CombinedText
stringlengths
4
3.42M
class Shfmt < Formula desc "Autoformat shell script source code" homepage "https://github.com/mvdan/sh" url "https://github.com/mvdan/sh/archive/v3.4.2.tar.gz" sha256 "2000656613bc4165fb1d419bedec08fcb23a625274f4505e303d18b204d8f5ee" license "BSD-3-Clause" head "https://github.com/mvdan/sh.git", branch: "master" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "0de39f63c01876ea44edaf5f1db58ca6bad15ba851de3bc1065b0b71b2f9ee22" sha256 cellar: :any_skip_relocation, arm64_big_sur: "f90de59d503c1c39372f8020bdd9433a15bd543a4e27e5937f74a12972c18e92" sha256 cellar: :any_skip_relocation, monterey: "eae6fc1c573d7624cc282b24580272e2d77397b90340b4e5f1129d44aadcbdbd" sha256 cellar: :any_skip_relocation, big_sur: "a7fb4f0b937883ff6367db892986823efc894d67ea77514fd88a8d49d95c87d1" sha256 cellar: :any_skip_relocation, catalina: "41d8f6bf716a000fa3c5f36720d4c22e23951cba71b619716fe5e792eee7ab38" sha256 cellar: :any_skip_relocation, x86_64_linux: "c13c9a6d768d8fda58e741ff1148baa2d5ca1d9ae9d96bb2441a818f045285b8" end depends_on "go" => :build depends_on "scdoc" => :build def install ENV["CGO_ENABLED"] = "0" (buildpath/"src/mvdan.cc").mkpath ln_sf buildpath, buildpath/"src/mvdan.cc/sh" system "go", "build", "-a", "-tags", "production brew", "-ldflags", "-w -s -extldflags '-static' -X main.version=#{version}", "-o", "#{bin}/shfmt", "./cmd/shfmt" man1.mkpath system "scdoc < ./cmd/shfmt/shfmt.1.scd > #{man1}/shfmt.1" end test do assert_match version.to_s, shell_output("#{bin}/shfmt --version") (testpath/"test").write "\t\techo foo" system "#{bin}/shfmt", testpath/"test" end end shfmt: update 3.4.2 bottle. class Shfmt < Formula desc "Autoformat shell script source code" homepage "https://github.com/mvdan/sh" url "https://github.com/mvdan/sh/archive/v3.4.2.tar.gz" sha256 "2000656613bc4165fb1d419bedec08fcb23a625274f4505e303d18b204d8f5ee" license "BSD-3-Clause" head "https://github.com/mvdan/sh.git", branch: "master" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "3d16adb18028a2bf572104d383a081d513ec3c608e2ea9dfd44fccf20c1e7b0f" sha256 cellar: :any_skip_relocation, arm64_big_sur: "3eaff57d43b2b12b276a866e693fc76597091b6580b484cb27beb0f5b7a30f43" sha256 cellar: :any_skip_relocation, monterey: "b4508d0a67b4a5802fa2cb9875687ec933c2369395521b23b89faf4e7eb53cad" sha256 cellar: :any_skip_relocation, big_sur: "b6765390c7387bb16bfa4fb63bb75bedf346bd2f42e70b2042c88230e668bd70" sha256 cellar: :any_skip_relocation, catalina: "ab7bb4cf991a41eecda3fca4bef473dd711a62b89d906f3861515b8ec1386c98" sha256 cellar: :any_skip_relocation, x86_64_linux: "8ed1ad0c691990dd7bc6bc1665f5c47f6815b73ad28e7d97bce07af69b28f962" end depends_on "go" => :build depends_on "scdoc" => :build def install ENV["CGO_ENABLED"] = "0" (buildpath/"src/mvdan.cc").mkpath ln_sf buildpath, buildpath/"src/mvdan.cc/sh" system "go", "build", "-a", "-tags", "production brew", "-ldflags", "-w -s -extldflags '-static' -X main.version=#{version}", "-o", "#{bin}/shfmt", "./cmd/shfmt" man1.mkpath system "scdoc < ./cmd/shfmt/shfmt.1.scd > #{man1}/shfmt.1" end test do assert_match version.to_s, shell_output("#{bin}/shfmt --version") (testpath/"test").write "\t\techo foo" system "#{bin}/shfmt", testpath/"test" end end
class SqlTranslator < Formula desc "Manipulate structured data definitions (SQL and more)" homepage "https://github.com/dbsrgits/sql-translator/" url "https://cpan.metacpan.org/authors/id/I/IL/ILMARI/SQL-Translator-1.60.tar.gz" sha256 "6bb0cb32ca25da69df65e5de71f679f3ca90044064526fa336cabd342f220e87" bottle do cellar :any_skip_relocation sha256 "2c32a4d89ab652bf3c56459c9f8c5d73d602aefea3f8e9a9970153cedeca8c5e" => :catalina sha256 "5b56cd85c30deb2c7852d0090c55f2d168ec9420c0c25d9c5513a8fb89aac711" => :mojave sha256 "b3af3df936b1c03d50a9d9209e8aef974e59449179e11a2b5bc78e1f59338114" => :high_sierra end uses_from_macos "perl" resource "File::ShareDir::Install" do url "https://cpan.metacpan.org/authors/id/E/ET/ETHER/File-ShareDir-Install-0.13.tar.gz" sha256 "45befdf0d95cbefe7c25a1daf293d85f780d6d2576146546e6828aad26e580f9" end resource "Package::Variant" do url "https://cpan.metacpan.org/authors/id/M/MS/MSTROUT/Package-Variant-1.003002.tar.gz" sha256 "b2ed849d2f4cdd66467512daa3f143266d6df810c5fae9175b252c57bc1536dc" end resource "strictures" do url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/strictures-2.000006.tar.gz" sha256 "09d57974a6d1b2380c802870fed471108f51170da81458e2751859f2714f8d57" end def install ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" resources.each do |r| r.stage do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make" system "make", "install" end end system "perl", "Makefile.PL", "--defaultdeps", "INSTALL_BASE=#{libexec}", "INSTALLSITESCRIPT=#{bin}", "INSTALLSITEMAN1DIR=#{man1}", "INSTALLSITEMAN3DIR=#{man3}" system "make", "install" # Disable dynamic selection of perl which may cause segfault when an # incompatible perl is picked up. # https://github.com/Homebrew/homebrew-core/issues/4936 inreplace Dir["#{bin}/*"], "#!/usr/bin/env perl", "#!/usr/bin/perl" bin.env_script_all_files libexec/"bin", :PERL5LIB => ENV["PERL5LIB"] end test do command = "#{bin}/sqlt -f MySQL -t PostgreSQL --no-comments -" sql_input = "create table sqlt ( id int AUTO_INCREMENT );" sql_output = <<~EOS CREATE TABLE "sqlt" ( "id" serial ); EOS assert_equal sql_output, pipe_output(command, sql_input) end end sql-translator: Fix test for Linuxbrew (#19926) class SqlTranslator < Formula desc "Manipulate structured data definitions (SQL and more)" homepage "https://github.com/dbsrgits/sql-translator/" url "https://cpan.metacpan.org/authors/id/I/IL/ILMARI/SQL-Translator-1.60.tar.gz" sha256 "6bb0cb32ca25da69df65e5de71f679f3ca90044064526fa336cabd342f220e87" bottle do cellar :any_skip_relocation sha256 "2c32a4d89ab652bf3c56459c9f8c5d73d602aefea3f8e9a9970153cedeca8c5e" => :catalina sha256 "5b56cd85c30deb2c7852d0090c55f2d168ec9420c0c25d9c5513a8fb89aac711" => :mojave sha256 "b3af3df936b1c03d50a9d9209e8aef974e59449179e11a2b5bc78e1f59338114" => :high_sierra end uses_from_macos "perl" resource "File::ShareDir::Install" do url "https://cpan.metacpan.org/authors/id/E/ET/ETHER/File-ShareDir-Install-0.13.tar.gz" sha256 "45befdf0d95cbefe7c25a1daf293d85f780d6d2576146546e6828aad26e580f9" end resource "Package::Variant" do url "https://cpan.metacpan.org/authors/id/M/MS/MSTROUT/Package-Variant-1.003002.tar.gz" sha256 "b2ed849d2f4cdd66467512daa3f143266d6df810c5fae9175b252c57bc1536dc" end resource "strictures" do url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/strictures-2.000006.tar.gz" sha256 "09d57974a6d1b2380c802870fed471108f51170da81458e2751859f2714f8d57" end unless OS.mac? resource "Moo" do url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/Moo-2.003006.tar.gz" sha256 "bcb2092ab18a45005b5e2e84465ebf3a4999d8e82a43a09f5a94d859ae7f2472" end resource "Module::Runtime" do url "https://cpan.metacpan.org/authors/id/Z/ZE/ZEFRAM/Module-Runtime-0.016.tar.gz" sha256 "68302ec646833547d410be28e09676db75006f4aa58a11f3bdb44ffe99f0f024" end resource "Sub::Quote" do url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/Sub-Quote-2.006006.tar.gz" sha256 "6e4e2af42388fa6d2609e0e82417de7cc6be47223f576592c656c73c7524d89d" end resource "Try::Tiny" do url "https://cpan.metacpan.org/authors/id/E/ET/ETHER/Try-Tiny-0.30.tar.gz" sha256 "da5bd0d5c903519bbf10bb9ba0cb7bcac0563882bcfe4503aee3fb143eddef6b" end resource "Import::Into" do url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/Import-Into-1.002005.tar.gz" sha256 "bd9e77a3fb662b40b43b18d3280cd352edf9fad8d94283e518181cc1ce9f0567" end resource "Role::Tiny" do url "https://cpan.metacpan.org/authors/id/H/HA/HAARG/Role-Tiny-2.001004.tar.gz" sha256 "92ba5712850a74102c93c942eb6e7f62f7a4f8f483734ed289d08b324c281687" end resource "Class::Method::Modifiers" do url "https://cpan.metacpan.org/authors/id/E/ET/ETHER/Class-Method-Modifiers-2.13.tar.gz" sha256 "ab5807f71018a842de6b7a4826d6c1f24b8d5b09fcce5005a3309cf6ea40fd63" end resource "DBI" do url "https://cpan.metacpan.org/authors/id/T/TI/TIMB/DBI-1.643.tar.gz" sha256 "8a2b993db560a2c373c174ee976a51027dd780ec766ae17620c20393d2e836fa" end resource "Carp::Clan" do url "https://cpan.metacpan.org/authors/id/E/ET/ETHER/Carp-Clan-6.08.tar.gz" sha256 "c75f92e34422cc5a65ab05d155842b701452434e9aefb649d6e2289c47ef6708" end resource "Parse::RecDescent" do url "https://cpan.metacpan.org/authors/id/J/JT/JTBRAUN/Parse-RecDescent-1.967015.tar.gz" sha256 "1943336a4cb54f1788a733f0827c0c55db4310d5eae15e542639c9dd85656e37" end end def install ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5" resources.each do |r| r.stage do system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}" system "make" system "make", "install" end end system "perl", "Makefile.PL", "--defaultdeps", "INSTALL_BASE=#{libexec}", "INSTALLSITESCRIPT=#{bin}", "INSTALLSITEMAN1DIR=#{man1}", "INSTALLSITEMAN3DIR=#{man3}" system "make", "install" # Disable dynamic selection of perl which may cause segfault when an # incompatible perl is picked up. # https://github.com/Homebrew/homebrew-core/issues/4936 inreplace Dir["#{bin}/*"], "#!/usr/bin/env perl", "#!/usr/bin/perl" if OS.mac? bin.env_script_all_files libexec/"bin", :PERL5LIB => ENV["PERL5LIB"] end test do command = "#{bin}/sqlt -f MySQL -t PostgreSQL --no-comments -" sql_input = "create table sqlt ( id int AUTO_INCREMENT );" sql_output = <<~EOS CREATE TABLE "sqlt" ( "id" serial ); EOS assert_equal sql_output, pipe_output(command, sql_input) end end
# encoding: UTF-8 module AnnotationsHelper def get_annotations (project, doc, options = {}) if doc.present? hdenotations = doc.hdenotations(project, options) hrelations = doc.hrelations(project, options) hmodifications = doc.hmodifications(project, options) text = doc.body if (options[:encoding] == 'ascii') asciitext = get_ascii_text (text) sequence_alignment = SequenceAlignment.new(text, asciitext, [["Ξ”", "delta"], [" ", " "], ["βˆ’", "-"], ["–", "-"], ["β€²", "'"], ["’", "'"]]) # sequence_alignment = Aligner.new(text, asciitext) hdenotations = sequence_alignment.transform_denotations(hdenotations) # hdenotations = adjust_denotations(hdenotations, asciitext) text = asciitext end if (options[:discontinuous_annotation] == 'bag') # TODO: convert to hash representation hdenotations, hrelations = bag_denotations(hdenotations, hrelations) end annotations = Hash.new # if doc.sourcedb == 'PudMed' # annotations[:pmdoc_id] = doc.sourceid # elsif doc.sourcedb == 'PMC' # annotations[:pmcdoc_id] = doc.sourceid # annotations[:div_id] = doc.serial # end # project if project.present? annotations[:project] = project[:name] end # doc annotations[:source_db] = doc.sourcedb annotations[:source_id] = doc.sourceid annotations[:division_id] = doc.serial annotations[:section] = doc.section annotations[:text] = text # doc.relational_models annotations[:denotations] = hdenotations if hdenotations annotations[:relations] = hrelations if hrelations annotations[:modifications] = hmodifications if hmodifications annotations else nil end end def get_annotations_for_json(project, doc, options = {}) if doc.present? text = doc.body annotations = Hash.new if doc.has_divs? annotations[:target] =Rails.application.routes.url_helpers.doc_sourcedb_sourceid_divs_show_path(doc.sourcedb, doc.sourceid, doc.serial, :only_path => false) else annotations[:target] = Rails.application.routes.url_helpers.doc_sourcedb_sourceid_show_path(doc.sourcedb, doc.sourceid, :only_path => false) end if (options[:encoding] == 'ascii') asciitext = get_ascii_text(text) text = asciitext end annotations[:text] = text # project if project.present? get_annotation_relational_models(doc, project, text, asciitext, annotations, options) elsif doc.projects.present? annotations[:tracks] = Array.new i = 0 project_names = options[:projects].split(',') if options[:projects].present? doc.projects.name_in(project_names).each do |project| annotations[:tracks][i] = Hash.new get_annotation_relational_models(doc, project, text, asciitext, annotations[:tracks][i], options) i += 1 end end if options[:doc_spans].present? annotations[:text] = doc.text(options[:params]) if annotations[:tracks].present? annotations[:tracks].each do |track| if track[:denotations].present? track[:denotations] = set_denotations_begin_end(track[:denotations], options) end end elsif annotations[:denotations].present? annotations[:denotations] = set_denotations_begin_end(annotations[:denotations], options) end end if options.present? && options[:params].present? && options[:params][:begin].present? context_size_value = options[:params][:context_size].to_i end_value = options[:params][:end].to_i - options[:params][:begin].to_i + context_size_value begin_value = 0 + context_size_value annotations[:focus] = {begin: begin_value, end: end_value} end annotations else nil end end def set_denotations_begin_end(denotations, options) denotations.each do |d| d[:span][:begin] -= options[:params][:begin].to_i d[:span][:end] -= options[:params][:begin].to_i if options[:params][:context_size].present? d[:span][:begin] += options[:params][:context_size].to_i d[:span][:end] += options[:params][:context_size].to_i end end return denotations end def get_annotation_relational_models(doc, project, text, asciitext, annotations, options) annotations[:project] = project_path(project.name, :only_path => false) hrelations = doc.hrelations(project, options) hmodifications = doc.hmodifications(project, options) hdenotations = doc.hdenotations(project, options) if options[:encoding] == 'ascii' sequence_alignment = SequenceAlignment.new(text, asciitext, [["Ξ”", "delta"], [" ", " "], ["βˆ’", "-"], ["–", "-"], ["β€²", "'"], ["’", "'"]]) hdenotations = sequence_alignment.transform_denotations(hdenotations) end if options[:discontinuous_annotation] == 'bag' hdenotations, hrelations = bag_denotations(hdenotations, hrelations) end # doc.relational_models annotations[:denotations] = hdenotations if hdenotations annotations[:relations] = hrelations if hrelations annotations[:modifications] = hmodifications if hmodifications annotations end def bag_denotations (denotations, relations) tomerge = Hash.new new_relations = Array.new relations.each do |ra| if ra[:pred] == '_lexChain' tomerge[ra[:obj]] = ra[:subj] else new_relations << ra end end idx = Hash.new denotations.each_with_index {|ca, i| idx[ca[:id]] = i} mergedto = Hash.new tomerge.each do |from, to| to = mergedto[to] if mergedto.has_key?(to) fca = denotations[idx[from]] tca = denotations[idx[to]] tca[:span] = [tca[:span]] unless tca[:span].respond_to?('push') tca[:span].push (fca[:span]) denotations.delete_at(idx[from]) mergedto[from] = to end return denotations, new_relations end def project_annotations_zip_link_helper(project) if project.annotations_zip_downloadable == true file_path = project.annotations_zip_path if File.exist?(file_path) == true zip_created_at = File.ctime(file_path) # when ZIP file exists html = link_to "#{project.name}.zip", "/annotations/#{project.name}.zip", :class => 'button' html += content_tag :span, "#{zip_created_at.strftime("#{t('controllers.shared.last_modified_at')}:%Y-%m-%d %T")}", :class => 'zip_time_stamp' if zip_created_at < project.annotations_updated_at html += link_to t('controllers.annotations.update_zip'), project_annotations_path(project.name, :delay => true, :update => true), :class => 'button', :confirm => t('controllers.annotations.confirm_create_zip') end html else # when ZIP file deos not exists delayed_job_tasks = ActiveRecord::Base.connection.execute('SELECT * FROM delayed_jobs').select{|delayed_job| delayed_job['handler'].include?(project.name) && delayed_job['handler'].include?('save_annotation_zip')} if delayed_job_tasks.blank? # when delayed_job exists link_to t('controllers.annotations.create_zip'), project_annotations_path(project.name, :delay => true), :class => 'button', :confirm => t('controllers.annotations.confirm_create_zip') else # delayed_job does not exists t('views.shared.zip.delayed_job_present') end end end end def annotations_destroy_all_helper(doc, project) # TODO should be instance method if doc annotations = doc.denotations.where("project_id = ?", project.id) ActiveRecord::Base.transaction do begin annotations.destroy_all rescue => e flash[:notice] = e end end end end def annotations_url_helper if params[:div_id].present? if params[:action] == 'spans' spans_annotations_project_sourcedb_sourceid_divs_docs_url(@project.name, @doc.sourcedb, @doc.sourceid, @doc.serial, params[:begin], params[:end]) else annotations_project_sourcedb_sourceid_divs_docs_url(@project.name, @doc.sourcedb, @doc.sourceid, @doc.serial) end else if params[:action] == 'spans' spans_annotations_project_sourcedb_sourceid_docs_url(@project.name, @doc.sourcedb, @doc.sourceid, params[:begin], params[:end]) else annotations_project_sourcedb_sourceid_docs_url(@project.name, @doc.sourcedb, @doc.sourceid) end end end def annotations_form_action_helper if params[:id].present? annotations_project_doc_path(@project.name, @doc.id) else if params[:div_id].present? generate_annotatons_project_sourcedb_sourceid_divs_docs_path(@project.name, @doc.sourcedb, @doc.sourceid, @doc.serial) else generate_annotatons_project_sourcedb_sourceid_docs_path(@project.name, @doc.sourcedb, @doc.sourceid) end end end def get_doc_info (doc_uri) source_db = (doc_uri =~ %r|/sourcedb/([^/]+)|)? $1 : nil source_id = (doc_uri =~ %r|/sourceid/([^/]+)|)? $1 : nil div_id = (doc_uri =~ %r|/divs/([^/]+)|)? $1 : nil docinfo = (div_id == nil)? "#{source_db}-#{source_id}" : "#{source_db}-#{source_id}-#{div_id}" end end Fixed project zip # encoding: UTF-8 module AnnotationsHelper def get_annotations (project, doc, options = {}) if doc.present? hdenotations = doc.hdenotations(project, options) hrelations = doc.hrelations(project, options) hmodifications = doc.hmodifications(project, options) text = doc.body if (options[:encoding] == 'ascii') asciitext = get_ascii_text (text) sequence_alignment = SequenceAlignment.new(text, asciitext, [["Ξ”", "delta"], [" ", " "], ["βˆ’", "-"], ["–", "-"], ["β€²", "'"], ["’", "'"]]) # sequence_alignment = Aligner.new(text, asciitext) hdenotations = sequence_alignment.transform_denotations(hdenotations) # hdenotations = adjust_denotations(hdenotations, asciitext) text = asciitext end if (options[:discontinuous_annotation] == 'bag') # TODO: convert to hash representation hdenotations, hrelations = bag_denotations(hdenotations, hrelations) end annotations = Hash.new # if doc.sourcedb == 'PudMed' # annotations[:pmdoc_id] = doc.sourceid # elsif doc.sourcedb == 'PMC' # annotations[:pmcdoc_id] = doc.sourceid # annotations[:div_id] = doc.serial # end # project if project.present? annotations[:project] = project[:name] end # doc annotations[:source_db] = doc.sourcedb annotations[:source_id] = doc.sourceid annotations[:division_id] = doc.serial annotations[:section] = doc.section annotations[:text] = text # doc.relational_models annotations[:denotations] = hdenotations if hdenotations annotations[:relations] = hrelations if hrelations annotations[:modifications] = hmodifications if hmodifications annotations else nil end end def get_annotations_for_json(project, doc, options = {}) if doc.present? text = doc.body annotations = Hash.new if doc.has_divs? annotations[:target] =Rails.application.routes.url_helpers.doc_sourcedb_sourceid_divs_show_path(doc.sourcedb, doc.sourceid, doc.serial, :only_path => false) else annotations[:target] = Rails.application.routes.url_helpers.doc_sourcedb_sourceid_show_path(doc.sourcedb, doc.sourceid, :only_path => false) end if (options[:encoding] == 'ascii') asciitext = get_ascii_text(text) text = asciitext end annotations[:text] = text # project if project.present? get_annotation_relational_models(doc, project, text, asciitext, annotations, options) elsif doc.projects.present? annotations[:tracks] = Array.new i = 0 project_names = options[:projects].split(',') if options[:projects].present? doc.projects.name_in(project_names).each do |project| annotations[:tracks][i] = Hash.new get_annotation_relational_models(doc, project, text, asciitext, annotations[:tracks][i], options) i += 1 end end if options[:doc_spans].present? annotations[:text] = doc.text(options[:params]) if annotations[:tracks].present? annotations[:tracks].each do |track| if track[:denotations].present? track[:denotations] = set_denotations_begin_end(track[:denotations], options) end end elsif annotations[:denotations].present? annotations[:denotations] = set_denotations_begin_end(annotations[:denotations], options) end end if options.present? && options[:params].present? && options[:params][:begin].present? context_size_value = options[:params][:context_size].to_i end_value = options[:params][:end].to_i - options[:params][:begin].to_i + context_size_value begin_value = 0 + context_size_value annotations[:focus] = {begin: begin_value, end: end_value} end annotations else nil end end def set_denotations_begin_end(denotations, options) denotations.each do |d| d[:span][:begin] -= options[:params][:begin].to_i d[:span][:end] -= options[:params][:begin].to_i if options[:params][:context_size].present? d[:span][:begin] += options[:params][:context_size].to_i d[:span][:end] += options[:params][:context_size].to_i end end return denotations end def get_annotation_relational_models(doc, project, text, asciitext, annotations, options) annotations[:project] = Rails.application.routes.url_helpers.project_path(project.name, :only_path => false) hrelations = doc.hrelations(project, options) hmodifications = doc.hmodifications(project, options) hdenotations = doc.hdenotations(project, options) if options[:encoding] == 'ascii' sequence_alignment = SequenceAlignment.new(text, asciitext, [["Ξ”", "delta"], [" ", " "], ["βˆ’", "-"], ["–", "-"], ["β€²", "'"], ["’", "'"]]) hdenotations = sequence_alignment.transform_denotations(hdenotations) end if options[:discontinuous_annotation] == 'bag' hdenotations, hrelations = bag_denotations(hdenotations, hrelations) end # doc.relational_models annotations[:denotations] = hdenotations if hdenotations annotations[:relations] = hrelations if hrelations annotations[:modifications] = hmodifications if hmodifications annotations end def bag_denotations (denotations, relations) tomerge = Hash.new new_relations = Array.new relations.each do |ra| if ra[:pred] == '_lexChain' tomerge[ra[:obj]] = ra[:subj] else new_relations << ra end end idx = Hash.new denotations.each_with_index {|ca, i| idx[ca[:id]] = i} mergedto = Hash.new tomerge.each do |from, to| to = mergedto[to] if mergedto.has_key?(to) fca = denotations[idx[from]] tca = denotations[idx[to]] tca[:span] = [tca[:span]] unless tca[:span].respond_to?('push') tca[:span].push (fca[:span]) denotations.delete_at(idx[from]) mergedto[from] = to end return denotations, new_relations end def project_annotations_zip_link_helper(project) if project.annotations_zip_downloadable == true file_path = project.annotations_zip_path if File.exist?(file_path) == true zip_created_at = File.ctime(file_path) # when ZIP file exists html = link_to "#{project.name}.zip", "/annotations/#{project.name}.zip", :class => 'button' html += content_tag :span, "#{zip_created_at.strftime("#{t('controllers.shared.last_modified_at')}:%Y-%m-%d %T")}", :class => 'zip_time_stamp' if zip_created_at < project.annotations_updated_at html += link_to t('controllers.annotations.update_zip'), project_annotations_path(project.name, :delay => true, :update => true), :class => 'button', :confirm => t('controllers.annotations.confirm_create_zip') end html else # when ZIP file deos not exists delayed_job_tasks = ActiveRecord::Base.connection.execute('SELECT * FROM delayed_jobs').select{|delayed_job| delayed_job['handler'].include?(project.name) && delayed_job['handler'].include?('save_annotation_zip')} if delayed_job_tasks.blank? # when delayed_job exists link_to t('controllers.annotations.create_zip'), project_annotations_path(project.name, :delay => true), :class => 'button', :confirm => t('controllers.annotations.confirm_create_zip') else # delayed_job does not exists t('views.shared.zip.delayed_job_present') end end end end def annotations_destroy_all_helper(doc, project) # TODO should be instance method if doc annotations = doc.denotations.where("project_id = ?", project.id) ActiveRecord::Base.transaction do begin annotations.destroy_all rescue => e flash[:notice] = e end end end end def annotations_url_helper if params[:div_id].present? if params[:action] == 'spans' spans_annotations_project_sourcedb_sourceid_divs_docs_url(@project.name, @doc.sourcedb, @doc.sourceid, @doc.serial, params[:begin], params[:end]) else annotations_project_sourcedb_sourceid_divs_docs_url(@project.name, @doc.sourcedb, @doc.sourceid, @doc.serial) end else if params[:action] == 'spans' spans_annotations_project_sourcedb_sourceid_docs_url(@project.name, @doc.sourcedb, @doc.sourceid, params[:begin], params[:end]) else annotations_project_sourcedb_sourceid_docs_url(@project.name, @doc.sourcedb, @doc.sourceid) end end end def annotations_form_action_helper if params[:id].present? annotations_project_doc_path(@project.name, @doc.id) else if params[:div_id].present? generate_annotatons_project_sourcedb_sourceid_divs_docs_path(@project.name, @doc.sourcedb, @doc.sourceid, @doc.serial) else generate_annotatons_project_sourcedb_sourceid_docs_path(@project.name, @doc.sourcedb, @doc.sourceid) end end end def get_doc_info (doc_uri) source_db = (doc_uri =~ %r|/sourcedb/([^/]+)|)? $1 : nil source_id = (doc_uri =~ %r|/sourceid/([^/]+)|)? $1 : nil div_id = (doc_uri =~ %r|/divs/([^/]+)|)? $1 : nil docinfo = (div_id == nil)? "#{source_db}-#{source_id}" : "#{source_db}-#{source_id}-#{div_id}" end end
class Siege < Formula desc "HTTP regression testing and benchmarking utility" homepage "https://www.joedog.org/siege-home/" url "http://download.joedog.org/siege/siege-4.0.2.tar.gz" sha256 "7efb81f9547bef0e693bdd51348a205ad691e1d72c36041f4608099ba0326c47" bottle do sha256 "d028c4d472199f55ac0a5db390f0c2600c76af1e3ca74f3fbf2657dfa4d79a7c" => :high_sierra sha256 "727ee17ca64eb752916cf8318d0cda9a56b094d358b46b04b33d66872373f843" => :sierra sha256 "787e7394cc038b1a06d164faebbb0b02a37f32757abbf80da223d46b0f0091e5" => :el_capitan sha256 "932fce124172f3b1e25bfcbe673feffccf1a86ea97f00564ecaeb01f4950d3bb" => :yosemite sha256 "6575d3bc644e7acecbeab9b7c8fed77c7c523a709e9b2184501b2d40c7eb8d5f" => :mavericks end depends_on "openssl" def install # To avoid unnecessary warning due to hardcoded path, create the folder first (prefix/"etc").mkdir system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--localstatedir=#{var}", "--with-ssl=#{Formula["openssl"].opt_prefix}" system "make", "install" end def caveats; <<-EOS.undent macOS has only 16K ports available that won't be released until socket TIME_WAIT is passed. The default timeout for TIME_WAIT is 15 seconds. Consider reducing in case of available port bottleneck. You can check whether this is a problem with netstat: # sysctl net.inet.tcp.msl net.inet.tcp.msl: 15000 # sudo sysctl -w net.inet.tcp.msl=1000 net.inet.tcp.msl: 15000 -> 1000 Run siege.config to create the ~/.siegerc config file. EOS end test do system "#{bin}/siege", "--concurrent=1", "--reps=1", "https://www.google.com/" end end siege 4.0.4 Closes #18811. Signed-off-by: JCount <33ebc4a6b11670639e02eb2b884714d9703346eb@gmail.com> class Siege < Formula desc "HTTP regression testing and benchmarking utility" homepage "https://www.joedog.org/siege-home/" url "http://download.joedog.org/siege/siege-4.0.4.tar.gz" sha256 "8f7dcf18bd722bb9cc92bc3ea4b59836b4a2f8d8f01d4a94c8d181f56d91ea6f" bottle do sha256 "d028c4d472199f55ac0a5db390f0c2600c76af1e3ca74f3fbf2657dfa4d79a7c" => :high_sierra sha256 "727ee17ca64eb752916cf8318d0cda9a56b094d358b46b04b33d66872373f843" => :sierra sha256 "787e7394cc038b1a06d164faebbb0b02a37f32757abbf80da223d46b0f0091e5" => :el_capitan sha256 "932fce124172f3b1e25bfcbe673feffccf1a86ea97f00564ecaeb01f4950d3bb" => :yosemite sha256 "6575d3bc644e7acecbeab9b7c8fed77c7c523a709e9b2184501b2d40c7eb8d5f" => :mavericks end depends_on "openssl" def install # To avoid unnecessary warning due to hardcoded path, create the folder first (prefix/"etc").mkdir system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--localstatedir=#{var}", "--with-ssl=#{Formula["openssl"].opt_prefix}" system "make", "install" end def caveats; <<-EOS.undent macOS has only 16K ports available that won't be released until socket TIME_WAIT is passed. The default timeout for TIME_WAIT is 15 seconds. Consider reducing in case of available port bottleneck. You can check whether this is a problem with netstat: # sysctl net.inet.tcp.msl net.inet.tcp.msl: 15000 # sudo sysctl -w net.inet.tcp.msl=1000 net.inet.tcp.msl: 15000 -> 1000 Run siege.config to create the ~/.siegerc config file. EOS end test do system "#{bin}/siege", "--concurrent=1", "--reps=1", "https://www.google.com/" end end
class SwiftProtobuf < Formula desc "Plugin and runtime library for using protobuf with Swift" homepage "https://github.com/apple/swift-protobuf" url "https://github.com/apple/swift-protobuf/archive/1.20.2.tar.gz" sha256 "3fb50bd4d293337f202d917b6ada22f9548a0a0aed9d9a4d791e6fbd8a246ebb" license "Apache-2.0" head "https://github.com/apple/swift-protobuf.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "36e84496c7f16bf9f318f899fa2ed3423ca4a302450d1e68d476a03d175099f2" sha256 cellar: :any_skip_relocation, arm64_big_sur: "b790680a423626fe077f0f8bc8d24601a07edec2947a4343ff0586493dd1e661" sha256 cellar: :any_skip_relocation, monterey: "362254db2dfe04119a6d32d1a80e22633af98f36fe1d5184afd3a38ac15e7bcc" sha256 cellar: :any_skip_relocation, big_sur: "37265f340278ef0cb6f9ee90f2dfd4f74e6e6f4caa0f16950c50330fb376759a" sha256 cellar: :any_skip_relocation, catalina: "34c6d2be247e52e95a0add0bc40346332b31f666819be89c6a3d269422614eef" sha256 x86_64_linux: "5d48da7672dfa9401ad037cc5a3b4bbe4434b830c33d0ec7ceadb91c63f0ffff" end depends_on xcode: ["8.3", :build] depends_on "protobuf" uses_from_macos "swift" def install system "swift", "build", "--disable-sandbox", "-c", "release" bin.install ".build/release/protoc-gen-swift" doc.install "Documentation/PLUGIN.md" end test do (testpath/"test.proto").write <<~EOS syntax = "proto3"; enum Flavor { CHOCOLATE = 0; VANILLA = 1; } message IceCreamCone { int32 scoops = 1; Flavor flavor = 2; } EOS system Formula["protobuf"].opt_bin/"protoc", "test.proto", "--swift_out=." assert_predicate testpath/"test.pb.swift", :exist? end end swift-protobuf: update 1.20.2 bottle. class SwiftProtobuf < Formula desc "Plugin and runtime library for using protobuf with Swift" homepage "https://github.com/apple/swift-protobuf" url "https://github.com/apple/swift-protobuf/archive/1.20.2.tar.gz" sha256 "3fb50bd4d293337f202d917b6ada22f9548a0a0aed9d9a4d791e6fbd8a246ebb" license "Apache-2.0" head "https://github.com/apple/swift-protobuf.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "bf4961d3753d541afa22d0c41ac2c53ab3e7a99e798d8890dd8959f5873bfba4" sha256 cellar: :any_skip_relocation, arm64_big_sur: "1e4dcad6041c37ee285949f43dda5194c2661d11682ac046c4f626e32234811a" sha256 cellar: :any_skip_relocation, monterey: "b92430ab9f117dc5e5e1f43572acbf5b5ba269709370d5fbe086620d77c96b14" sha256 cellar: :any_skip_relocation, big_sur: "69c57badc90be8d7f1067f858cfcc93105b6185406fbe57fb79a66a07cfbb4bf" sha256 cellar: :any_skip_relocation, catalina: "2fbca410cd4fe40f3a17951edddbe4f7ebbbc1b081f15abac1f1c50a8d60a76f" sha256 x86_64_linux: "c0d820d16f2973953d8c392dcb287b91259e2e885a9b5e0eee14e0976ff952c0" end depends_on xcode: ["8.3", :build] depends_on "protobuf" uses_from_macos "swift" def install system "swift", "build", "--disable-sandbox", "-c", "release" bin.install ".build/release/protoc-gen-swift" doc.install "Documentation/PLUGIN.md" end test do (testpath/"test.proto").write <<~EOS syntax = "proto3"; enum Flavor { CHOCOLATE = 0; VANILLA = 1; } message IceCreamCone { int32 scoops = 1; Flavor flavor = 2; } EOS system Formula["protobuf"].opt_bin/"protoc", "test.proto", "--swift_out=." assert_predicate testpath/"test.pb.swift", :exist? end end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def spell_check_button button_to_function('Check Spelling', "var f=this.form;var speller = new spellChecker();speller.textInputs=$$('#'+f.id + ' .spell_check');speller.openChecker();") + help_popup("If you have any problems with the spell check, please email spell_check_problems@simspilot.org . " ) end def show_whats_new ["schools","login", "main"].include? params[:controller] or params[:controller]=="students" && params[:action] == "search" end def li_link_to(name, options = {}, html_options = {}, *rest) content_tag :li,(link_to(name,options,html_options) + rest.join(" ")) end def li_link_to_if_authorized(name, options = {}, html_options = {}, *rest) r= link_to_if_authorized(name, options, html_options, *rest) content_tag :li,((r + rest.join(" ").html_safe).html_safe) if r.present? end def link_to_if_authorized(name, options = {}, html_options = {}, *rest) #TODO Test then Refactor!!! This is a spike. # hsh = ::ActionController::Routing::Routes.recognize_path url.gsub(/\?.*$/,''), :method=> :get if options.is_a?String url = options url = "/"+url.split("/")[3..-1].join("/").split('?').first unless url=~ /^\// hsh = ::Rails.application.routes.recognize_path url, :method => :get else if options[:controller].present? #Without a leading / url_for will assume it is in the current namespace options[:controller]="/#{options[:controller]}" unless options[:controller][0] =='/' hsh=options url=hsh else url = url_for(options) hsh = ::Rails.application.routes.recognize_path url end end ctrl = "#{hsh[:controller]}Controller".camelize.constantize link_to(name, url, html_options) if current_user.authorized_for?(ctrl.controller_path) end def link_to_if_present(name, path) link_to(name,path) if File.exist?("#{Rails.root}/public/#{path}") end def breadcrumbs s = [link_to('Home', root_path)] s << link_to_if_current_or_condition('School Selection', schools_path, session[:school_id]) s << link_to_if_current_or_condition('Student Selection', students_path, session[:selected_student]) s << link_to_if_current_or_condition('Student Search', [current_school,:student_search], session[:search]) #357 TODO add a test , if district admin had a student selected breadcrumb breaks when they do a new student s << link_to_if_current_or_condition(current_student, student_path(current_student), session[:selected_student]) if session[:selected_student] && !current_student.new_record? s.compact.join(' -> ').html_safe end def link_to_if_current_or_condition(title, path,conditions=nil) link_to_unless_current(title,path) if conditions || path == request.path end def if_student_selected if current_student yield end end def link_to_remote_degrades(name, options = {}, html_options = {}) html_options[:href] = url_for(options[:url]) unless html_options.has_key?(:href) link_to_remote(name, options, html_options) end def render_with_empty(options ={}) if options[:collection].size >0 render options else options[:empty].html_safe end end def yes_or_no(bool) if bool "Yes" else "No" end end def help_popup(msg) content_tag(:span, "?", :class=>"help-question", :onmouseover=>"return overlib('#{escape_javascript(msg)}');", :onmouseout => "return nd();").html_safe unless msg.blank? end def spinner(suffix = nil) image_tag "spinner.gif", :id => "spinner#{suffix}", :style => "display:none" end def link_to_remote_if(condition, name, options = {}, html_options = {}, &block) condition ? link_to_remote_degrades(name, options, html_options ) : name end def link_to_with_icon(name, url, suffix="") ext_match = /\.\w+$/ ext = (name.match ext_match) file = "#{name.split(ext_match).first.to_s.gsub(/_/," ")}#{suffix}" icon= ext.blank? ? "icon_htm.gif" : "icon_#{ext[0][1..-1].downcase}.gif" icon = "icon_htm.gif" unless File.exist?(File.join(Rails.public_path,"images",icon)) blank={} blank[:target]="_blank" unless url=="#" link_to "#{image_tag(icon, :class=>"menu_icon")} #{file}".html_safe, url, blank end def plus_minus_li( title, &blk) id = title.gsub(/ /, '_') content = with_output_buffer(&blk) content_tag(:li, :class => "plus_minus", :id => "li#{id}") do link_to_function(title, "toggle_visibility('ul#{id}'); $('li#{id}').style.listStyleImage =( $('ul#{id}').style.display != 'none' ? \"url('/images/minus-8.png')\" : \"url('/images/plus-8.png')\") ") + content_tag(:ul, content, :id => "ul#{id}") end end def description(obj, name="Description") "<div class='fake_label'>#{name}</div><table class='description'><tr><td>#{obj.description}</td></tr></table>".html_safe if obj end def labelled_form_for(record_or_name_or_array, *args, &proc) @spell_check_fields ||= [] options = args.extract_options! content_tag(:div, :class => 'new_form') do content_tag(:div, '', :id => "global_spell_container", :style => "background-color: #ddd") + form_for(record_or_name_or_array, *(args << options.merge(:builder => LabelFormBuilder)), &proc) end end def restrict_to_principals?(student) current_district.restrict_free_lunch? && !student.principals.include?(current_user) end def style_display_none_unless(cond) 'style="display:none;"'.html_safe unless cond end end fix breadcrumb order # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def spell_check_button button_to_function('Check Spelling', "var f=this.form;var speller = new spellChecker();speller.textInputs=$$('#'+f.id + ' .spell_check');speller.openChecker();") + help_popup("If you have any problems with the spell check, please email spell_check_problems@simspilot.org . " ) end def show_whats_new ["schools","login", "main"].include? params[:controller] or params[:controller]=="students" && params[:action] == "search" end def li_link_to(name, options = {}, html_options = {}, *rest) content_tag :li,(link_to(name,options,html_options) + rest.join(" ")) end def li_link_to_if_authorized(name, options = {}, html_options = {}, *rest) r= link_to_if_authorized(name, options, html_options, *rest) content_tag :li,((r + rest.join(" ").html_safe).html_safe) if r.present? end def link_to_if_authorized(name, options = {}, html_options = {}, *rest) #TODO Test then Refactor!!! This is a spike. # hsh = ::ActionController::Routing::Routes.recognize_path url.gsub(/\?.*$/,''), :method=> :get if options.is_a?String url = options url = "/"+url.split("/")[3..-1].join("/").split('?').first unless url=~ /^\// hsh = ::Rails.application.routes.recognize_path url, :method => :get else if options[:controller].present? #Without a leading / url_for will assume it is in the current namespace options[:controller]="/#{options[:controller]}" unless options[:controller][0] =='/' hsh=options url=hsh else url = url_for(options) hsh = ::Rails.application.routes.recognize_path url end end ctrl = "#{hsh[:controller]}Controller".camelize.constantize link_to(name, url, html_options) if current_user.authorized_for?(ctrl.controller_path) end def link_to_if_present(name, path) link_to(name,path) if File.exist?("#{Rails.root}/public/#{path}") end def breadcrumbs s = [link_to('Home', root_path)] s << link_to_if_current_or_condition('School Selection', schools_path, session[:school_id]) s << link_to_if_current_or_condition('Student Search', [current_school,:student_search], session[:search]) s << link_to_if_current_or_condition('Student Selection', students_path, session[:selected_student]) #357 TODO add a test , if district admin had a student selected breadcrumb breaks when they do a new student s << link_to_if_current_or_condition(current_student, student_path(current_student), session[:selected_student]) if session[:selected_student] && !current_student.new_record? s.compact.join(' -> ').html_safe end def link_to_if_current_or_condition(title, path,conditions=nil) link_to_unless_current(title,path) if conditions || path == request.path end def if_student_selected if current_student yield end end def link_to_remote_degrades(name, options = {}, html_options = {}) html_options[:href] = url_for(options[:url]) unless html_options.has_key?(:href) link_to_remote(name, options, html_options) end def render_with_empty(options ={}) if options[:collection].size >0 render options else options[:empty].html_safe end end def yes_or_no(bool) if bool "Yes" else "No" end end def help_popup(msg) content_tag(:span, "?", :class=>"help-question", :onmouseover=>"return overlib('#{escape_javascript(msg)}');", :onmouseout => "return nd();").html_safe unless msg.blank? end def spinner(suffix = nil) image_tag "spinner.gif", :id => "spinner#{suffix}", :style => "display:none" end def link_to_remote_if(condition, name, options = {}, html_options = {}, &block) condition ? link_to_remote_degrades(name, options, html_options ) : name end def link_to_with_icon(name, url, suffix="") ext_match = /\.\w+$/ ext = (name.match ext_match) file = "#{name.split(ext_match).first.to_s.gsub(/_/," ")}#{suffix}" icon= ext.blank? ? "icon_htm.gif" : "icon_#{ext[0][1..-1].downcase}.gif" icon = "icon_htm.gif" unless File.exist?(File.join(Rails.public_path,"images",icon)) blank={} blank[:target]="_blank" unless url=="#" link_to "#{image_tag(icon, :class=>"menu_icon")} #{file}".html_safe, url, blank end def plus_minus_li( title, &blk) id = title.gsub(/ /, '_') content = with_output_buffer(&blk) content_tag(:li, :class => "plus_minus", :id => "li#{id}") do link_to_function(title, "toggle_visibility('ul#{id}'); $('li#{id}').style.listStyleImage =( $('ul#{id}').style.display != 'none' ? \"url('/images/minus-8.png')\" : \"url('/images/plus-8.png')\") ") + content_tag(:ul, content, :id => "ul#{id}") end end def description(obj, name="Description") "<div class='fake_label'>#{name}</div><table class='description'><tr><td>#{obj.description}</td></tr></table>".html_safe if obj end def labelled_form_for(record_or_name_or_array, *args, &proc) @spell_check_fields ||= [] options = args.extract_options! content_tag(:div, :class => 'new_form') do content_tag(:div, '', :id => "global_spell_container", :style => "background-color: #ddd") + form_for(record_or_name_or_array, *(args << options.merge(:builder => LabelFormBuilder)), &proc) end end def restrict_to_principals?(student) current_district.restrict_free_lunch? && !student.principals.include?(current_user) end def style_display_none_unless(cond) 'style="display:none;"'.html_safe unless cond end end
class Sleef < Formula desc "SIMD library for evaluating elementary functions" homepage "https://sleef.org" url "https://github.com/shibatch/sleef/archive/3.5.1.tar.gz" sha256 "415ee9b1bcc5816989d3d4d92afd0cd3f9ee89cbd5a33eb008e69751e40438ab" license "BSL-1.0" head "https://github.com/shibatch/sleef.git" bottle do cellar :any sha256 "87ddfa37e9405dfc66c35295295e5f09e497fb1bc8c07c9e0f38560aeb46398f" => :catalina sha256 "f9e95775f5e41924f42eae7c4ae1f567229a49989e1f8a380d55355e37680d9c" => :mojave sha256 "353ca63589a038009ad9b39dadcf3ef4c46153f738fcfb07d58a25dfc37e945a" => :high_sierra end depends_on "cmake" => :build def install mkdir "build" do system "cmake", "..", "-DBUILD_TESTS=OFF", *std_cmake_args system "make", "install" end end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <math.h> #include <sleef.h> int main() { double a = M_PI / 6; printf("%.3f\\n", Sleef_sin_u10(a)); } EOS system ENV.cc, "test.c", "-o", "test", "-I#{include}", "-L#{lib}", "-lsleef" assert_equal "0.500\n", shell_output("./test") end end sleef: update 3.5.1 bottle. class Sleef < Formula desc "SIMD library for evaluating elementary functions" homepage "https://sleef.org" url "https://github.com/shibatch/sleef/archive/3.5.1.tar.gz" sha256 "415ee9b1bcc5816989d3d4d92afd0cd3f9ee89cbd5a33eb008e69751e40438ab" license "BSL-1.0" head "https://github.com/shibatch/sleef.git" bottle do cellar :any sha256 "87ddfa37e9405dfc66c35295295e5f09e497fb1bc8c07c9e0f38560aeb46398f" => :catalina sha256 "f9e95775f5e41924f42eae7c4ae1f567229a49989e1f8a380d55355e37680d9c" => :mojave sha256 "353ca63589a038009ad9b39dadcf3ef4c46153f738fcfb07d58a25dfc37e945a" => :high_sierra sha256 "c53bbb4cfca5a7cc75d077b966150c3672c168e54bde6c5fa75874da21a6f1e2" => :x86_64_linux end depends_on "cmake" => :build def install mkdir "build" do system "cmake", "..", "-DBUILD_TESTS=OFF", *std_cmake_args system "make", "install" end end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <math.h> #include <sleef.h> int main() { double a = M_PI / 6; printf("%.3f\\n", Sleef_sin_u10(a)); } EOS system ENV.cc, "test.c", "-o", "test", "-I#{include}", "-L#{lib}", "-lsleef" assert_equal "0.500\n", shell_output("./test") end end
class SwiftProtobuf < Formula desc "Plugin and runtime library for using protobuf with Swift" homepage "https://github.com/apple/swift-protobuf" url "https://github.com/apple/swift-protobuf/archive/1.18.0.tar.gz" sha256 "e7afc0d07e0d8970269ca04948cec36ecac85f4526c29ff2c211fc016bde27d6" license "Apache-2.0" revision 1 head "https://github.com/apple/swift-protobuf.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "5a1c709bf25fa4c7d02cdbcb5ff481fa8d0ba37897a03c6f1a58b1d38248bc32" sha256 cellar: :any_skip_relocation, big_sur: "ae0390c500b0ca6e9665f23c8e4a0224f790ed232184d530bf9c8c772f068f89" sha256 cellar: :any_skip_relocation, catalina: "172f3e61a551548eeb7d93ae2fb001b0b99c38cc440c905aa72d907037730a4e" sha256 x86_64_linux: "0b7c5288ec35491c7a435cd5cae5deb553221c6ee1d50946af12271f9f264fbe" end depends_on xcode: ["8.3", :build] depends_on "protobuf" uses_from_macos "swift" def install system "swift", "build", "--disable-sandbox", "-c", "release" bin.install ".build/release/protoc-gen-swift" doc.install "Documentation/PLUGIN.md" end test do (testpath/"test.proto").write <<~EOS syntax = "proto3"; enum Flavor { CHOCOLATE = 0; VANILLA = 1; } message IceCreamCone { int32 scoops = 1; Flavor flavor = 2; } EOS system Formula["protobuf"].opt_bin/"protoc", "test.proto", "--swift_out=." assert_predicate testpath/"test.pb.swift", :exist? end end swift-protobuf: update 1.18.0_1 bottle. class SwiftProtobuf < Formula desc "Plugin and runtime library for using protobuf with Swift" homepage "https://github.com/apple/swift-protobuf" url "https://github.com/apple/swift-protobuf/archive/1.18.0.tar.gz" sha256 "e7afc0d07e0d8970269ca04948cec36ecac85f4526c29ff2c211fc016bde27d6" license "Apache-2.0" revision 1 head "https://github.com/apple/swift-protobuf.git", branch: "main" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "5a5c84ddd827e0126c615d5dd274beda8d257d1bf63b27ceb3c615bd12eaa0ef" sha256 cellar: :any_skip_relocation, arm64_big_sur: "5a1c709bf25fa4c7d02cdbcb5ff481fa8d0ba37897a03c6f1a58b1d38248bc32" sha256 cellar: :any_skip_relocation, monterey: "81496b6246fa89194d7ffa490ae303332ffc6dcd2f2efd7786a25a3a82202651" sha256 cellar: :any_skip_relocation, big_sur: "ae0390c500b0ca6e9665f23c8e4a0224f790ed232184d530bf9c8c772f068f89" sha256 cellar: :any_skip_relocation, catalina: "172f3e61a551548eeb7d93ae2fb001b0b99c38cc440c905aa72d907037730a4e" sha256 x86_64_linux: "0b7c5288ec35491c7a435cd5cae5deb553221c6ee1d50946af12271f9f264fbe" end depends_on xcode: ["8.3", :build] depends_on "protobuf" uses_from_macos "swift" def install system "swift", "build", "--disable-sandbox", "-c", "release" bin.install ".build/release/protoc-gen-swift" doc.install "Documentation/PLUGIN.md" end test do (testpath/"test.proto").write <<~EOS syntax = "proto3"; enum Flavor { CHOCOLATE = 0; VANILLA = 1; } message IceCreamCone { int32 scoops = 1; Flavor flavor = 2; } EOS system Formula["protobuf"].opt_bin/"protoc", "test.proto", "--swift_out=." assert_predicate testpath/"test.pb.swift", :exist? end end
class Smali < Formula desc "Assembler/disassembler for Android's Java VM implementation" homepage "https://github.com/JesusFreke/smali" url "https://github.com/JesusFreke/smali/archive/v2.5.0.tar.gz" sha256 "849e56645769cd2b8d83b0078efecbbbac57db4d0030f12cece58fd571cd30e9" license "BSD-3-Clause" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "f067f72f005ce05fa14b9b32cad7129ba29c6dde59af5494461471eec4c46c9e" sha256 cellar: :any_skip_relocation, big_sur: "c795c4245df42dd3bf881fa5b9e034e55186efb517cf5a72c6fc7c603283bc89" sha256 cellar: :any_skip_relocation, catalina: "2a17c236e4dea10abb4cfc8383abd72204dfa925e72ab10bf6aaaa02875af266" sha256 cellar: :any_skip_relocation, mojave: "39f6422066f4b61496c4ce287f37a7ee1069926eea698a6dbd15a131e14a7616" sha256 cellar: :any_skip_relocation, high_sierra: "7b90641feb3ce88a706bee6c8b5ca3a231f4d3c2ce138d7fabe5d470574d77f3" end depends_on "gradle" => :build depends_on "openjdk" def install system "gradle", "build", "--no-daemon" %w[smali baksmali].each do |name| jarfile = "#{name}-#{version}-dev-fat.jar" libexec.install "#{name}/build/libs/#{jarfile}" bin.write_jar_script libexec/jarfile, name end end test do # From examples/HelloWorld/HelloWorld.smali in Smali project repo. # See https://bitbucket.org/JesusFreke/smali/src/2d8cbfe6bc2d8ff2fcd7a0bf432cc808d842da4a/examples/HelloWorld/HelloWorld.smali?at=master (testpath/"input.smali").write <<~EOS .class public LHelloWorld; .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const-string v1, "Hello World!" invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method EOS system bin/"smali", "assemble", "-o", "classes.dex", "input.smali" system bin/"baksmali", "disassemble", "-o", pwd, "classes.dex" assert_match "Hello World!", File.read("HelloWorld.smali") end end smali: update 2.5.0 bottle. class Smali < Formula desc "Assembler/disassembler for Android's Java VM implementation" homepage "https://github.com/JesusFreke/smali" url "https://github.com/JesusFreke/smali/archive/v2.5.0.tar.gz" sha256 "849e56645769cd2b8d83b0078efecbbbac57db4d0030f12cece58fd571cd30e9" license "BSD-3-Clause" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "d6f9288dfc3b4e54513d0b93b7a3f2320d63240f3c376df1a8d968eae6770c8e" sha256 cellar: :any_skip_relocation, big_sur: "8b49cc2d62cb4dccf995436cc465b04240a4f1dbb6bc557cb904eccd3040f2c5" sha256 cellar: :any_skip_relocation, catalina: "44ec49c4790ec596a434e4e6770e2a6ac8ee605dabdea1ca10381e5e83cf1fe7" sha256 cellar: :any_skip_relocation, mojave: "c43896dd00d7576c2bb4299f8e14ec99d8dab8b3138d5a5319b23c91ea216b09" end depends_on "gradle" => :build depends_on "openjdk" def install system "gradle", "build", "--no-daemon" %w[smali baksmali].each do |name| jarfile = "#{name}-#{version}-dev-fat.jar" libexec.install "#{name}/build/libs/#{jarfile}" bin.write_jar_script libexec/jarfile, name end end test do # From examples/HelloWorld/HelloWorld.smali in Smali project repo. # See https://bitbucket.org/JesusFreke/smali/src/2d8cbfe6bc2d8ff2fcd7a0bf432cc808d842da4a/examples/HelloWorld/HelloWorld.smali?at=master (testpath/"input.smali").write <<~EOS .class public LHelloWorld; .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const-string v1, "Hello World!" invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method EOS system bin/"smali", "assemble", "-o", "classes.dex", "input.smali" system bin/"baksmali", "disassemble", "-o", pwd, "classes.dex" assert_match "Hello World!", File.read("HelloWorld.smali") end end
class TerraformDocs < Formula desc "Tool to generate documentation from Terraform modules" homepage "https://github.com/terraform-docs/terraform-docs" url "https://github.com/terraform-docs/terraform-docs/archive/v0.16.0.tar.gz" sha256 "e370fd106ca74caebc8632834cc28412a3a6a160952392da71f213515bba2085" license "MIT" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "1f2f4cf6fcf375be8963c87892a9949fd415f3bd7d91cf7c2e6ecbd51525aaf8" sha256 cellar: :any_skip_relocation, arm64_big_sur: "4019590722af255f89f39cb67f6a032bd5ccc2fb50f8949c7928215b215cf6f7" sha256 cellar: :any_skip_relocation, monterey: "2feecfdf034d99b6b9de4d20d377d91d546c800fdcf3efb32ab8fc74936af84b" sha256 cellar: :any_skip_relocation, big_sur: "a8bd7087f7d1b8f351c44cef6ddfe5a8adcdc06999665f0f46b0d9753d2e50f0" sha256 cellar: :any_skip_relocation, catalina: "434ec046eb696cc5a6eded18b8afca8e346e7009165d9a8e12e88ffb3fc3811e" sha256 cellar: :any_skip_relocation, mojave: "dae4a1d6f4dd664f8388a19a55d037b9a63e76f1ee704b1e4ec993892234bd83" sha256 cellar: :any_skip_relocation, x86_64_linux: "b66e3b532c81e093416f3b7e2af35295b8f9887ef1d662fe836a7b1f0ac7dbab" end depends_on "go" => :build def install system "make", "build" cpu = Hardware::CPU.intel? ? "amd64" : Hardware::CPU.arch.to_s os = OS.kernel_name.downcase bin.install "bin/#{os}-#{cpu}/terraform-docs" prefix.install_metafiles end test do (testpath/"main.tf").write <<~EOS /** * Module usage: * * module "foo" { * source = "github.com/foo/baz" * subnet_ids = "${join(",", subnet.*.id)}" * } */ variable "subnet_ids" { description = "a comma-separated list of subnet IDs" } variable "security_group_ids" { default = "sg-a, sg-b" } variable "amis" { default = { "us-east-1" = "ami-8f7687e2" "us-west-1" = "ami-bb473cdb" "us-west-2" = "ami-84b44de4" "eu-west-1" = "ami-4e6ffe3d" "eu-central-1" = "ami-b0cc23df" "ap-northeast-1" = "ami-095dbf68" "ap-southeast-1" = "ami-cf03d2ac" "ap-southeast-2" = "ami-697a540a" } } // The VPC ID. output "vpc_id" { value = "vpc-5c1f55fd" } EOS system "#{bin}/terraform-docs", "json", testpath end end terraform-docs: update 0.16.0 bottle. class TerraformDocs < Formula desc "Tool to generate documentation from Terraform modules" homepage "https://github.com/terraform-docs/terraform-docs" url "https://github.com/terraform-docs/terraform-docs/archive/v0.16.0.tar.gz" sha256 "e370fd106ca74caebc8632834cc28412a3a6a160952392da71f213515bba2085" license "MIT" bottle do sha256 cellar: :any_skip_relocation, arm64_ventura: "26fd4d4865b9a169773dbb811b2e1cafe1262a36b86394ac767b317069742a18" sha256 cellar: :any_skip_relocation, arm64_monterey: "1f2f4cf6fcf375be8963c87892a9949fd415f3bd7d91cf7c2e6ecbd51525aaf8" sha256 cellar: :any_skip_relocation, arm64_big_sur: "4019590722af255f89f39cb67f6a032bd5ccc2fb50f8949c7928215b215cf6f7" sha256 cellar: :any_skip_relocation, monterey: "2feecfdf034d99b6b9de4d20d377d91d546c800fdcf3efb32ab8fc74936af84b" sha256 cellar: :any_skip_relocation, big_sur: "a8bd7087f7d1b8f351c44cef6ddfe5a8adcdc06999665f0f46b0d9753d2e50f0" sha256 cellar: :any_skip_relocation, catalina: "434ec046eb696cc5a6eded18b8afca8e346e7009165d9a8e12e88ffb3fc3811e" sha256 cellar: :any_skip_relocation, mojave: "dae4a1d6f4dd664f8388a19a55d037b9a63e76f1ee704b1e4ec993892234bd83" sha256 cellar: :any_skip_relocation, x86_64_linux: "b66e3b532c81e093416f3b7e2af35295b8f9887ef1d662fe836a7b1f0ac7dbab" end depends_on "go" => :build def install system "make", "build" cpu = Hardware::CPU.intel? ? "amd64" : Hardware::CPU.arch.to_s os = OS.kernel_name.downcase bin.install "bin/#{os}-#{cpu}/terraform-docs" prefix.install_metafiles end test do (testpath/"main.tf").write <<~EOS /** * Module usage: * * module "foo" { * source = "github.com/foo/baz" * subnet_ids = "${join(",", subnet.*.id)}" * } */ variable "subnet_ids" { description = "a comma-separated list of subnet IDs" } variable "security_group_ids" { default = "sg-a, sg-b" } variable "amis" { default = { "us-east-1" = "ami-8f7687e2" "us-west-1" = "ami-bb473cdb" "us-west-2" = "ami-84b44de4" "eu-west-1" = "ami-4e6ffe3d" "eu-central-1" = "ami-b0cc23df" "ap-northeast-1" = "ami-095dbf68" "ap-southeast-1" = "ami-cf03d2ac" "ap-southeast-2" = "ami-697a540a" } } // The VPC ID. output "vpc_id" { value = "vpc-5c1f55fd" } EOS system "#{bin}/terraform-docs", "json", testpath end end
module ApplicationHelper def default_meta_tags { site: 'Freshness', reverse: true, title: 'Index page', description: "The index page of Freshness showing two search functions", keywords: %w[food fresh preservation search web], canonical: 'https://obscure-mesa-98847.herokuapp.com', icon: image_url('apple.ico'), author: 'https://www.linkedin.com/in/saki-tanda-26b0b8141/', og: { title: 'Freshness', type: 'website', url: 'https://obscure-mesa-98847.herokuapp.com', image: image_url('logo10101010101010101010.png'), site_name: 'Freshness', description: "Freshness provides the food preservation methods for you to keep food fresh as long as you can. Let's reduce food waste for global environment by using Freshness!" }, fb: { app_id: '110529839531578' } } end end modify fb module ApplicationHelper def default_meta_tags { site: 'Freshness', reverse: true, title: 'Index page', description: "The index page of Freshness showing two search functions", keywords: %w[food fresh preservation search web], canonical: 'https://obscure-mesa-98847.herokuapp.com', icon: image_url('apple.ico'), author: 'https://www.linkedin.com/in/saki-tanda-26b0b8141/', og: { title: 'Freshness', type: 'website', url: 'https://obscure-mesa-98847.herokuapp.com', image: image_url('logo10.png'), site_name: 'Freshness', description: "Freshness provides the food preservation methods for you to keep food fresh as long as you can. Let's reduce food waste for global environment by using Freshness!" }, fb: { app_id: '110529839531578' } } end end
class Smpeg < Formula desc "SDL MPEG Player Library" homepage "https://icculus.org/smpeg/" url "svn://svn.icculus.org/smpeg/tags/release_0_4_5/", revision: "399" livecheck do url "https://svn.icculus.org/smpeg/tags/" regex(%r{href=.*?release[._-]v?([01](?:[._]\d+)+)/}i) end bottle do rebuild 1 sha256 cellar: :any, arm64_big_sur: "1078558dafa6125c781a6b50242fc8def024f36dc3d8f4c1ae719c05779f12c2" sha256 cellar: :any, big_sur: "1b667d8cc8548a25b1a5c16e706f9fba9a0a4a3380c1674ba64444abb3d18837" sha256 cellar: :any, catalina: "929cb2fe89f7525acbf38a269bde8aaf07f7b2d406007ee9df2d21051a0ccba6" sha256 cellar: :any, mojave: "6e826bd49ceb171cc36877c0498d8ccfc3c614f39b684728e0c307b69942d58c" sha256 cellar: :any, high_sierra: "2779c8aba2aed376076e53fc9e2e694e8b5fabca0096ae91eed786b73ef3704f" sha256 cellar: :any, sierra: "9ac1a1c83a9861b8762ab711d709e67bf020204fb1c1b5907b244d83ced4ab2c" sha256 cellar: :any, el_capitan: "a4bf36f39959150e1f0cd83c8f58761ce59acdee50f591a1f695665b7517728a" end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "sdl" def install args = %W[ --prefix=#{prefix} --with-sdl-prefix=#{Formula["sdl"].opt_prefix} --disable-dependency-tracking --disable-debug --disable-gtk-player --disable-gtktest --disable-opengl-player --disable-sdltest ] system "./autogen.sh" system "./configure", *args system "make" # Install script is not +x by default for some reason chmod 0755, "./install-sh" system "make", "install" # Not present since we do not build with gtk+ rm_f "#{man1}/gtv.1" end test do system "#{bin}/plaympeg", "--version" end end smpeg: update 0.4.5 bottle. class Smpeg < Formula desc "SDL MPEG Player Library" homepage "https://icculus.org/smpeg/" url "svn://svn.icculus.org/smpeg/tags/release_0_4_5/", revision: "399" livecheck do url "https://svn.icculus.org/smpeg/tags/" regex(%r{href=.*?release[._-]v?([01](?:[._]\d+)+)/}i) end bottle do rebuild 1 sha256 cellar: :any, arm64_big_sur: "1078558dafa6125c781a6b50242fc8def024f36dc3d8f4c1ae719c05779f12c2" sha256 cellar: :any, big_sur: "1b667d8cc8548a25b1a5c16e706f9fba9a0a4a3380c1674ba64444abb3d18837" sha256 cellar: :any, catalina: "929cb2fe89f7525acbf38a269bde8aaf07f7b2d406007ee9df2d21051a0ccba6" sha256 cellar: :any, mojave: "6e826bd49ceb171cc36877c0498d8ccfc3c614f39b684728e0c307b69942d58c" sha256 cellar: :any, high_sierra: "2779c8aba2aed376076e53fc9e2e694e8b5fabca0096ae91eed786b73ef3704f" sha256 cellar: :any, sierra: "9ac1a1c83a9861b8762ab711d709e67bf020204fb1c1b5907b244d83ced4ab2c" sha256 cellar: :any, el_capitan: "a4bf36f39959150e1f0cd83c8f58761ce59acdee50f591a1f695665b7517728a" sha256 cellar: :any_skip_relocation, x86_64_linux: "2eee39cbdbaa936ede8e1ebab1eb651974104dfafb5200f6516da3461cb1b7ad" end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "sdl" def install args = %W[ --prefix=#{prefix} --with-sdl-prefix=#{Formula["sdl"].opt_prefix} --disable-dependency-tracking --disable-debug --disable-gtk-player --disable-gtktest --disable-opengl-player --disable-sdltest ] system "./autogen.sh" system "./configure", *args system "make" # Install script is not +x by default for some reason chmod 0755, "./install-sh" system "make", "install" # Not present since we do not build with gtk+ rm_f "#{man1}/gtv.1" end test do system "#{bin}/plaympeg", "--version" end end
class VulkanHeaders < Formula desc "Vulkan Header files and API registry" homepage "https://github.com/KhronosGroup/Vulkan-Headers" url "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.1.121.tar.gz" sha256 "d49a50f1dd5c74896367553efffeb19c699ce1c1b30d66dc396fcb8e295a1e4a" bottle do cellar :any_skip_relocation sha256 "e8053f8eade915e4a55726481d02ab078b4c3015b1dc1580e5c10bd4ad38a248" => :mojave sha256 "e8053f8eade915e4a55726481d02ab078b4c3015b1dc1580e5c10bd4ad38a248" => :high_sierra sha256 "31235b912c10762f1881a8671f899c458e17aa39d4dbd49b087d517b784e40fb" => :sierra end depends_on "cmake" => :build def install system "cmake", ".", *std_cmake_args system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <vulkan/vulkan_core.h> int main() { printf("vulkan version %d", VK_VERSION_1_0); return 0; } EOS system ENV.cc, "test.c", "-o", "test" system "./test" end end vulkan-headers: update 1.1.121 bottle. class VulkanHeaders < Formula desc "Vulkan Header files and API registry" homepage "https://github.com/KhronosGroup/Vulkan-Headers" url "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.1.121.tar.gz" sha256 "d49a50f1dd5c74896367553efffeb19c699ce1c1b30d66dc396fcb8e295a1e4a" bottle do cellar :any_skip_relocation sha256 "e002846360df87635225ea84914143dc6f462f0c982b17181bb988c1e7f07122" => :mojave sha256 "e002846360df87635225ea84914143dc6f462f0c982b17181bb988c1e7f07122" => :high_sierra sha256 "5fa450745ddfd6ea10e03fabdea86aadb531f5394c05bb401e38729a56983cef" => :sierra end depends_on "cmake" => :build def install system "cmake", ".", *std_cmake_args system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <vulkan/vulkan_core.h> int main() { printf("vulkan version %d", VK_VERSION_1_0); return 0; } EOS system ENV.cc, "test.c", "-o", "test" system "./test" end end
module ApplicationHelper def cancel_link(url = {action: :index}) content_tag("li", class: "cancel") do link_to t("cancel"), url end end def basic_map(&block) @map = core_map("map") do |map, page| page << map.add_layer(MapLayers::OPENCYCLEMAP) page << map.add_layer(MapLayers::OSM_MAPNIK) page << map.add_controls([OpenLayers::Control::PZ.new, OpenLayers::Control::Navigation.new, OpenLayers::Control::LayerSwitcher.new]) format = MapLayers::JsVar.new("format") page.assign(format, OpenLayers::Format::GeoJSON.new(internalProjection: googleproj, externalProjection: projection)) format_plain = MapLayers::JsVar.new("format_plain") page.assign(format_plain, OpenLayers::Format::GeoJSON.new) yield(map, page) if block_given? end end def tiny_display_map(object, geometry_url, &block) zoom = 16 html_id = "tinymap_#{object.id}" @map = core_map(html_id) do |map, page| page << map.add_layer(MapLayers::OPENCYCLEMAP) format = MapLayers::JsVar.new("format") page.assign(format, OpenLayers::Format::GeoJSON.new(internalProjection: googleproj, externalProjection: projection)) format_plain = MapLayers::JsVar.new("format_plain") page.assign(format_plain, OpenLayers::Format::GeoJSON.new) if object.location.geometry_type == RGeo::Feature::Point page << map.setCenter(OpenLayers::LonLat.new(object.location.x,object.location.y).transform(projection, map.getProjectionObject()),zoom); markerlayer = MapLayers::JsVar.new('markerlayer') icon = MapLayers::JsVar.new('icon') page.assign(markerlayer, OpenLayers::Layer::Markers.new( "Location", { projection: projection })) page << map.addLayer(markerlayer) page.assign(icon, OpenLayers::Icon.new('/openlayers/img/marker-blue.png')) page << markerlayer.addMarker(OpenLayers::Marker.new(OpenLayers::LonLat.new(object.location.x, object.location.y).transform(projection, map.getProjectionObject()), icon)) else bbox = RGeo::Cartesian::BoundingBox.new(object.location.factory) bbox.add(object.location) page << map.zoomToExtent(OpenLayers::Bounds.new(bbox.min_x, bbox.min_y, bbox.max_x, bbox.max_y).transform(projection, map.getProjectionObject())) locationlayer = MapLayers::JsVar.new('locationlayer') protocol = OpenLayers::Protocol::HTTP.new( url: geometry_url, format: :format_plain ) page.assign(locationlayer, OpenLayers::Layer::Vector.new( "Location", protocol: protocol, projection: projection, strategies: [OpenLayers::Strategy::Fixed.new() ])) page << map.addLayer(locationlayer) end yield(map, page, html_id) if block_given? end end def display_bbox_map(start_location, geometry_bbox_url, &block) map = basic_map do |map, page| if start_location.geometry_type == RGeo::Feature::Point page << map.setCenter(OpenLayers::LonLat.new(start_location.x, start_location.y).transform(projection, map.getProjectionObject()),start_location.z); else bbox = RGeo::Cartesian::BoundingBox.new(start_location.factory) bbox.add(start_location) page << map.zoomToExtent(OpenLayers::Bounds.new(bbox.min_x, bbox.min_y, bbox.max_x, bbox.max_y).transform(projection, map.getProjectionObject())) end vectorlayer = MapLayers::JsVar.new("vectorlayer") protocol = OpenLayers::Protocol::HTTP.new( url: geometry_bbox_url, format: :format_plain ) page.assign(vectorlayer, OpenLayers::Layer::Vector.new("Issues", protocol: protocol, projection: projection, strategies: [OpenLayers::Strategy::BBOX.new()])) page << map.add_layer(vectorlayer) yield(map, page) if block_given? end end def projection OpenLayers::Projection.new("EPSG:4326") end def googleproj OpenLayers::Projection.new("EPSG:900913") end def user_groups(user = nil) user ||= current_user return [] if user.nil? user.groups end # Generate link to user or group profiles def link_to_profile(item) case item when User link_to item.name, user_profile_path(item) when Group link_to item.name, group_profile_path(item) end end protected def core_map(html_id, &block) map = MapLayers::Map.new(html_id, {theme: "/openlayers/theme/default/style.css", projection: googleproj, displayProjection: projection, controls: [] }) do |map, page| yield(map, page) if block_given? end end end Refactor the adding of formats module ApplicationHelper def cancel_link(url = {action: :index}) content_tag("li", class: "cancel") do link_to t("cancel"), url end end def basic_map(&block) @map = core_map("map") do |map, page| page << map.add_layer(MapLayers::OPENCYCLEMAP) page << map.add_layer(MapLayers::OSM_MAPNIK) page << map.add_controls([OpenLayers::Control::PZ.new, OpenLayers::Control::Navigation.new, OpenLayers::Control::LayerSwitcher.new]) add_formats(page) yield(map, page) if block_given? end end def tiny_display_map(object, geometry_url, &block) zoom = 16 html_id = "tinymap_#{object.id}" @map = core_map(html_id) do |map, page| page << map.add_layer(MapLayers::OPENCYCLEMAP) add_formats(page) if object.location.geometry_type == RGeo::Feature::Point page << map.setCenter(OpenLayers::LonLat.new(object.location.x,object.location.y).transform(projection, map.getProjectionObject()),zoom); markerlayer = MapLayers::JsVar.new('markerlayer') icon = MapLayers::JsVar.new('icon') page.assign(markerlayer, OpenLayers::Layer::Markers.new( "Location", { projection: projection })) page << map.addLayer(markerlayer) page.assign(icon, OpenLayers::Icon.new('/openlayers/img/marker-blue.png')) page << markerlayer.addMarker(OpenLayers::Marker.new(OpenLayers::LonLat.new(object.location.x, object.location.y).transform(projection, map.getProjectionObject()), icon)) else bbox = RGeo::Cartesian::BoundingBox.new(object.location.factory) bbox.add(object.location) page << map.zoomToExtent(OpenLayers::Bounds.new(bbox.min_x, bbox.min_y, bbox.max_x, bbox.max_y).transform(projection, map.getProjectionObject())) locationlayer = MapLayers::JsVar.new('locationlayer') protocol = OpenLayers::Protocol::HTTP.new( url: geometry_url, format: :format_plain ) page.assign(locationlayer, OpenLayers::Layer::Vector.new( "Location", protocol: protocol, projection: projection, strategies: [OpenLayers::Strategy::Fixed.new() ])) page << map.addLayer(locationlayer) end yield(map, page, html_id) if block_given? end end def display_bbox_map(start_location, geometry_bbox_url, &block) map = basic_map do |map, page| if start_location.geometry_type == RGeo::Feature::Point page << map.setCenter(OpenLayers::LonLat.new(start_location.x, start_location.y).transform(projection, map.getProjectionObject()),start_location.z); else bbox = RGeo::Cartesian::BoundingBox.new(start_location.factory) bbox.add(start_location) page << map.zoomToExtent(OpenLayers::Bounds.new(bbox.min_x, bbox.min_y, bbox.max_x, bbox.max_y).transform(projection, map.getProjectionObject())) end vectorlayer = MapLayers::JsVar.new("vectorlayer") protocol = OpenLayers::Protocol::HTTP.new( url: geometry_bbox_url, format: :format_plain ) page.assign(vectorlayer, OpenLayers::Layer::Vector.new("Issues", protocol: protocol, projection: projection, strategies: [OpenLayers::Strategy::BBOX.new()])) page << map.add_layer(vectorlayer) yield(map, page) if block_given? end end def projection OpenLayers::Projection.new("EPSG:4326") end def googleproj OpenLayers::Projection.new("EPSG:900913") end def user_groups(user = nil) user ||= current_user return [] if user.nil? user.groups end # Generate link to user or group profiles def link_to_profile(item) case item when User link_to item.name, user_profile_path(item) when Group link_to item.name, group_profile_path(item) end end protected def core_map(html_id, &block) map = MapLayers::Map.new(html_id, {theme: "/openlayers/theme/default/style.css", projection: googleproj, displayProjection: projection, controls: [] }) do |map, page| yield(map, page) if block_given? end end def add_formats(page) format = MapLayers::JsVar.new("format") page.assign(format, OpenLayers::Format::GeoJSON.new(internalProjection: googleproj, externalProjection: projection)) format_plain = MapLayers::JsVar.new("format_plain") page.assign(format_plain, OpenLayers::Format::GeoJSON.new) end end
require 'formula' class Sntop < Formula url 'ftp://ftp.freebsd.org/pub/FreeBSD/ports/distfiles/sntop-1.4.3.tar.gz' homepage 'http://sntop.sourceforge.net/' md5 '0e99c64ea5a1bad6c1a32ac0dc2e9dd9' version 'v1.4.3' depends_on 'fping' def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--sysconfdir=#{etc}" bin.mkpath system "make install" end def caveats <<-EOS.undent sntop uses fping by default. fping can only be run by root by default so either use sudo to run sntop or setuid root fping. Alternatively, run sntop using standard ping (sntop -p). EOS end end sntop: style nits require 'formula' class Sntop < Formula homepage 'http://sntop.sourceforge.net/' url 'ftp://ftp.freebsd.org/pub/FreeBSD/ports/distfiles/sntop-1.4.3.tar.gz' md5 '0e99c64ea5a1bad6c1a32ac0dc2e9dd9' depends_on 'fping' def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--sysconfdir=#{etc}" bin.mkpath system "make install" end def caveats; <<-EOS.undent sntop uses fping by default. fping can only be run by root by default so either use sudo to run sntop or setuid root fping. Alternatively, run sntop using standard ping (sntop -p). EOS end end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper ## Menu helpers def menu home = menu_element("Home", home_path) people = menu_element("People", people_path) if Forum.count == 1 forum = menu_element("Forum", forum_path(Forum.find(:first))) else forum = menu_element("Forums", forums_path) end resources = menu_element("Resources", "http://docs.insoshi.com/") if logged_in? and not admin_view? profile = menu_element("Profile", person_path(current_person)) requests = menu_element("Requests", reqs_path) categories = menu_element("Categories", categories_path) messages = menu_element("Messages", messages_path) # blog = menu_element("Blog", blog_path(current_person.blog)) photos = menu_element("Photos", photos_path) # contacts = menu_element("Contacts", # person_connections_path(current_person)) # links = [home, profile, contacts, messages, blog, people, forum] events = menu_element("Events", events_path) links = [home, profile, requests, people, messages, forum, categories] # TODO: remove 'unless production?' once events are ready. links.push(events) #unless production? elsif logged_in? and admin_view? home = menu_element("Home", home_path) categories = menu_element("Categories", categories_path) people = menu_element("People", admin_people_path) events = menu_element("Events", events_path) forums = menu_element(inflect("Forum", Forum.count), admin_forums_path) preferences = menu_element("Prefs", admin_preferences_path) links = [home, categories, people, forums, preferences] else events = menu_element("Events", events_path) links = [home, people, events] end if global_prefs.about.blank? links else links.push(menu_element("About", about_url)) end end def menu_element(content, address) { :content => content, :href => address } end def menu_link_to(link, options = {}) link_to(link[:content], link[:href], options) end def menu_li(link, options = {}) klass = "n-#{link[:content].downcase}" klass += " active" if current_page?(link[:href]) content_tag(:li, menu_link_to(link, options), :class => klass) end # Return true if the user is viewing the site in admin view. def admin_view? params[:controller] =~ /admin/ and admin? end def admin? logged_in? and current_person.admin? end # Set the input focus for a specific id # Usage: <%= set_focus_to 'form_field_label' %> def set_focus_to(id) javascript_tag("$('#{id}').focus()"); end # Display text by sanitizing and formatting. # The html_options, if present, allow the syntax # display("foo", :class => "bar") # => '<p class="bar">foo</p>' def display(text, html_options = nil) begin if html_options html_options = html_options.stringify_keys tag_opts = tag_options(html_options) else tag_opts = nil end processed_text = format(sanitize(text)) rescue # Sometimes Markdown throws exceptions, so rescue gracefully. processed_text = content_tag(:p, sanitize(text)) end add_tag_options(processed_text, tag_opts) end # Output a column div. # The current two-column layout has primary & secondary columns. # The options hash is handled so that the caller can pass options to # content_tag. # The LEFT, RIGHT, and FULL constants are defined in # config/initializers/global_constants.rb def column_div(options = {}, &block) klass = options.delete(:type) == :primary ? "col1" : "col2" # Allow callers to pass in additional classes. options[:class] = "#{klass} #{options[:class]}".strip content = content_tag(:div, capture(&block), options) concat(content, block.binding) end def email_link(person, options = {}) reply = options[:replying_to] if reply path = reply_message_path(reply) else path = new_person_message_path(person) end img = image_tag("icons/email.gif") action = reply.nil? ? "Send a message" : "Send reply" opts = { :class => 'email-link' } str = link_to(img, path, opts) str << "&nbsp;" str << link_to_unless_current(action, path, opts) end # Return a formatting note (depends on the presence of a Markdown library) def formatting_note if markdown? %(HTML and #{link_to("Markdown", "http://daringfireball.net/projects/markdown/basics", :popup => true)} formatting supported) else "HTML formatting supported" end end private def inflect(word, number) number > 1 ? word.pluralize : word end def add_tag_options(text, options) text.gsub("<p>", "<p#{options}>") end # Format text using BlueCloth (or RDiscount) if available. def format(text) if text.nil? "" elsif defined?(RDiscount) RDiscount.new(text).to_html elsif defined?(BlueCloth) BlueCloth.new(text).to_html elsif no_paragraph_tag?(text) content_tag :p, text else text end end # Is a Markdown library present? def markdown? defined?(RDiscount) or defined?(BlueCloth) end # Return true if the text *doesn't* start with a paragraph tag. def no_paragraph_tag?(text) text !~ /^\<p/ end end keep events in dev mode for now # Methods added to this helper will be available to all templates in the application. module ApplicationHelper ## Menu helpers def menu home = menu_element("Home", home_path) people = menu_element("People", people_path) if Forum.count == 1 forum = menu_element("Forum", forum_path(Forum.find(:first))) else forum = menu_element("Forums", forums_path) end resources = menu_element("Resources", "http://docs.insoshi.com/") if logged_in? and not admin_view? profile = menu_element("Profile", person_path(current_person)) requests = menu_element("Requests", reqs_path) categories = menu_element("Categories", categories_path) messages = menu_element("Messages", messages_path) # blog = menu_element("Blog", blog_path(current_person.blog)) photos = menu_element("Photos", photos_path) # contacts = menu_element("Contacts", # person_connections_path(current_person)) # links = [home, profile, contacts, messages, blog, people, forum] events = menu_element("Events", events_path) links = [home, profile, requests, people, messages, forum, categories] # TODO: remove 'unless production?' once events are ready. links.push(events) #unless production? elsif logged_in? and admin_view? home = menu_element("Home", home_path) categories = menu_element("Categories", categories_path) people = menu_element("People", admin_people_path) events = menu_element("Events", events_path) forums = menu_element(inflect("Forum", Forum.count), admin_forums_path) preferences = menu_element("Prefs", admin_preferences_path) links = [home, categories, people, forums, preferences] else links = [home, people] end if global_prefs.about.blank? links else links.push(menu_element("About", about_url)) end end def menu_element(content, address) { :content => content, :href => address } end def menu_link_to(link, options = {}) link_to(link[:content], link[:href], options) end def menu_li(link, options = {}) klass = "n-#{link[:content].downcase}" klass += " active" if current_page?(link[:href]) content_tag(:li, menu_link_to(link, options), :class => klass) end # Return true if the user is viewing the site in admin view. def admin_view? params[:controller] =~ /admin/ and admin? end def admin? logged_in? and current_person.admin? end # Set the input focus for a specific id # Usage: <%= set_focus_to 'form_field_label' %> def set_focus_to(id) javascript_tag("$('#{id}').focus()"); end # Display text by sanitizing and formatting. # The html_options, if present, allow the syntax # display("foo", :class => "bar") # => '<p class="bar">foo</p>' def display(text, html_options = nil) begin if html_options html_options = html_options.stringify_keys tag_opts = tag_options(html_options) else tag_opts = nil end processed_text = format(sanitize(text)) rescue # Sometimes Markdown throws exceptions, so rescue gracefully. processed_text = content_tag(:p, sanitize(text)) end add_tag_options(processed_text, tag_opts) end # Output a column div. # The current two-column layout has primary & secondary columns. # The options hash is handled so that the caller can pass options to # content_tag. # The LEFT, RIGHT, and FULL constants are defined in # config/initializers/global_constants.rb def column_div(options = {}, &block) klass = options.delete(:type) == :primary ? "col1" : "col2" # Allow callers to pass in additional classes. options[:class] = "#{klass} #{options[:class]}".strip content = content_tag(:div, capture(&block), options) concat(content, block.binding) end def email_link(person, options = {}) reply = options[:replying_to] if reply path = reply_message_path(reply) else path = new_person_message_path(person) end img = image_tag("icons/email.gif") action = reply.nil? ? "Send a message" : "Send reply" opts = { :class => 'email-link' } str = link_to(img, path, opts) str << "&nbsp;" str << link_to_unless_current(action, path, opts) end # Return a formatting note (depends on the presence of a Markdown library) def formatting_note if markdown? %(HTML and #{link_to("Markdown", "http://daringfireball.net/projects/markdown/basics", :popup => true)} formatting supported) else "HTML formatting supported" end end private def inflect(word, number) number > 1 ? word.pluralize : word end def add_tag_options(text, options) text.gsub("<p>", "<p#{options}>") end # Format text using BlueCloth (or RDiscount) if available. def format(text) if text.nil? "" elsif defined?(RDiscount) RDiscount.new(text).to_html elsif defined?(BlueCloth) BlueCloth.new(text).to_html elsif no_paragraph_tag?(text) content_tag :p, text else text end end # Is a Markdown library present? def markdown? defined?(RDiscount) or defined?(BlueCloth) end # Return true if the text *doesn't* start with a paragraph tag. def no_paragraph_tag?(text) text !~ /^\<p/ end end
class Sntop < Formula desc "Curses-based utility that polls hosts to determine connectivity" homepage "https://sntop.sourceforge.io/" url "https://downloads.sourceforge.net/project/sntop/sntop/1.4.3/sntop-1.4.3.tar.gz" sha256 "943a5af1905c3ae7ead064e531cde6e9b3dc82598bbda26ed4a43788d81d6d89" license "GPL-2.0" livecheck do url :stable regex(%r{url=.*?/sntop[._-]v?(\d+(?:\.\d+)+)\.t}i) end bottle do rebuild 1 sha256 arm64_monterey: "88c1bf529d00acd5093a911407aae68da341df753371f81d319862e9bafe2407" sha256 arm64_big_sur: "0674ad1a5387fadc27e9132d36bef2178e3ea821e9e05fadcc3a4d97b90a5758" sha256 monterey: "339487a2777504f99d3a3d9b9ae4f9d10de35d4e694a1708784e55ca2c586e09" sha256 big_sur: "ea8df8c0dbf95ed5686009df6bd7742d6f4a4a2e4c6132a02e6273ccfd21cc67" sha256 catalina: "886a981f2c95a8a17d4bfb44c27d99cde66faeb4f2942d1c43757e8d702509c6" sha256 mojave: "d010bc2fa761320d0d0f4948d5f95392d892e7bd7815418e9881ec90049d4036" sha256 high_sierra: "c22d769ddb8599acf3f03db2ef85eef5ee28e41f9ec3011e9b23f6168ceb0a76" sha256 sierra: "f15c15a4e2251e86e55c3bd2c75f660448e38efe9b0b57edd6d3e9301377929c" sha256 el_capitan: "c3f19036cf2d42ce9fa07ed6db6264b3e52ba475827903972877a8131eae60e9" end depends_on "fping" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--sysconfdir=#{etc}" etc.mkpath bin.mkpath man1.mkpath system "make", "install" end def caveats <<~EOS sntop uses fping by default and fping can only be run by root by default. You can run `sudo sntop` (or `sntop -p` which uses standard ping). You should be certain that you trust any software you grant root privileges. EOS end test do system "#{bin}/sntop", "--version" end end sntop: fix build on Linux Closes #99613. Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com> Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com> class Sntop < Formula desc "Curses-based utility that polls hosts to determine connectivity" homepage "https://sntop.sourceforge.io/" url "https://downloads.sourceforge.net/project/sntop/sntop/1.4.3/sntop-1.4.3.tar.gz" sha256 "943a5af1905c3ae7ead064e531cde6e9b3dc82598bbda26ed4a43788d81d6d89" license "GPL-2.0" livecheck do url :stable regex(%r{url=.*?/sntop[._-]v?(\d+(?:\.\d+)+)\.t}i) end bottle do rebuild 1 sha256 arm64_monterey: "88c1bf529d00acd5093a911407aae68da341df753371f81d319862e9bafe2407" sha256 arm64_big_sur: "0674ad1a5387fadc27e9132d36bef2178e3ea821e9e05fadcc3a4d97b90a5758" sha256 monterey: "339487a2777504f99d3a3d9b9ae4f9d10de35d4e694a1708784e55ca2c586e09" sha256 big_sur: "ea8df8c0dbf95ed5686009df6bd7742d6f4a4a2e4c6132a02e6273ccfd21cc67" sha256 catalina: "886a981f2c95a8a17d4bfb44c27d99cde66faeb4f2942d1c43757e8d702509c6" sha256 mojave: "d010bc2fa761320d0d0f4948d5f95392d892e7bd7815418e9881ec90049d4036" sha256 high_sierra: "c22d769ddb8599acf3f03db2ef85eef5ee28e41f9ec3011e9b23f6168ceb0a76" sha256 sierra: "f15c15a4e2251e86e55c3bd2c75f660448e38efe9b0b57edd6d3e9301377929c" sha256 el_capitan: "c3f19036cf2d42ce9fa07ed6db6264b3e52ba475827903972877a8131eae60e9" end depends_on "fping" uses_from_macos "ncurses" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}", "--sysconfdir=#{etc}" etc.mkpath bin.mkpath man1.mkpath system "make", "install" end def caveats <<~EOS sntop uses fping by default and fping can only be run by root by default. You can run `sudo sntop` (or `sntop -p` which uses standard ping). You should be certain that you trust any software you grant root privileges. EOS end test do system "#{bin}/sntop", "--version" end end
module ApplicationHelper def stacks @stacks ||= Stacks.all end end Fix #stacks helper module ApplicationHelper def stacks @stacks ||= Stack.all end end
require "mkmf" require "os" lib_path = [] if OS.bits == 64 lib_path << File.expand_path("lib/x64", __dir__) else lib_path << File.expand_path("lib/x86", __dir__) end dir_config("xf_sdk", [], lib_path) have_library("msc") or raise "Library msc not found." have_library("dl") or raise "Library dl not found." have_library("pthread") or raise "Library pthread not found." create_makefile("xf_sdk/xf_sdk") fix bug that on some systems, rpath is not set require "mkmf" require "os" libs_path = [] lib_path = if OS.bits == 64 File.expand_path("lib/x64", __dir__) else File.expand_path("lib/x86", __dir__) end if RbConfig::CONFIG["RPATHFLAG"].to_s.empty? $LDFLAGS << " -Wl,-rpath,#{lib_path}" end libs_path << lib_path dir_config("xf_sdk", [], libs_path) have_library("msc") or raise "Library msc not found." have_library("dl") or raise "Library dl not found." have_library("pthread") or raise "Library pthread not found." create_makefile("xf_sdk/xf_sdk")
class Socat < Formula desc "SOcket CAT: netcat on steroids" homepage "http://www.dest-unreach.org/socat/" url "http://www.dest-unreach.org/socat/download/socat-1.7.4.2.tar.gz" sha256 "a38f507dea8aaa8f260f54ebc1de1a71e5adca416219f603cda3e3002960173c" license "GPL-2.0" livecheck do url "http://www.dest-unreach.org/socat/download/" regex(/href=.*?socat[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any, arm64_monterey: "a1d69b34c205acecf9cd848a83884675e730920749ed3d5b2cb3d2770d4566bd" sha256 cellar: :any, arm64_big_sur: "1d355658a55eb44cb6ffe1fa8dc140883359467080e13be0d4237cf181c05dc0" sha256 cellar: :any, monterey: "b6fb68ad1092c12e0ccac75526ab19bb3714adc1605eb4a3757c238a2430c71a" sha256 cellar: :any, big_sur: "2249d3b3852d95fc683e27292e26967b0e3a13d60e59a99181445f941a343a32" sha256 cellar: :any, catalina: "f2a0d0d0bca542cb0f4b700d42dc244e82b8da9be2d5aff8d98b8a7fef77c9fe" sha256 cellar: :any, mojave: "531f3ea55671c8d01165c3a314b24cef873c51442a1729fe2e9ce14ff908aebb" sha256 cellar: :any_skip_relocation, x86_64_linux: "78a1e71516e40d992644374d24b33013d23b2e92e7c000783f3d5fd517282994" end depends_on "openssl@1.1" depends_on "readline" # Fix `error: use of undeclared identifier 'TCP_INFO'` # Remove in the next release patch :DATA def install system "./configure", *std_configure_args, "--mandir=#{man}" system "make", "install" end test do output = pipe_output("#{bin}/socat - tcp:www.google.com:80", "GET / HTTP/1.0\r\n\r\n") assert_match "HTTP/1.0", output.lines.first end end __END__ diff --git a/filan.c b/filan.c index 3465f7c..77c22a4 100644 --- a/filan.c +++ b/filan.c @@ -905,6 +905,7 @@ int tcpan(int fd, FILE *outfile) { #if WITH_TCP int tcpan2(int fd, FILE *outfile) { +#ifdef TCP_INFO struct tcp_info tcpinfo; socklen_t tcpinfolen = sizeof(tcpinfo); int result; @@ -930,6 +931,8 @@ int tcpan2(int fd, FILE *outfile) { // fprintf(outfile, "%s={%u}\t", "TCPI_", tcpinfo.tcpi_); return 0; +#endif + return -1; } #endif /* WITH_TCP */ socat: update 1.7.4.2 bottle. class Socat < Formula desc "SOcket CAT: netcat on steroids" homepage "http://www.dest-unreach.org/socat/" url "http://www.dest-unreach.org/socat/download/socat-1.7.4.2.tar.gz" sha256 "a38f507dea8aaa8f260f54ebc1de1a71e5adca416219f603cda3e3002960173c" license "GPL-2.0" livecheck do url "http://www.dest-unreach.org/socat/download/" regex(/href=.*?socat[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any, arm64_monterey: "bebff01d4a9da5539be0c56064458506ef3c2e098e66e3ecdd81a56b953b18bc" sha256 cellar: :any, arm64_big_sur: "ab41a0fff966fe7d766604de9392c18fb5fb1bbe938fcb13ed2861ba9d7e65bb" sha256 cellar: :any, monterey: "7de63a881d222435b6ea2f416a93f758f265feb87573b2bd8045b6fc383196ee" sha256 cellar: :any, big_sur: "4ee020dff0b50603598022a6d924fffdf105fd175772fbbd84efdd52397ac023" sha256 cellar: :any, catalina: "e45f83eee32c323aca752b3a63075b8d65b4eff1814bcce3cd5fdd01c7a526f7" sha256 cellar: :any_skip_relocation, x86_64_linux: "1f1932cc4004c5f6234de385b59e36ce686d6e7e152526d9b47dd9fd9bfd13c4" end depends_on "openssl@1.1" depends_on "readline" # Fix `error: use of undeclared identifier 'TCP_INFO'` # Remove in the next release patch :DATA def install system "./configure", *std_configure_args, "--mandir=#{man}" system "make", "install" end test do output = pipe_output("#{bin}/socat - tcp:www.google.com:80", "GET / HTTP/1.0\r\n\r\n") assert_match "HTTP/1.0", output.lines.first end end __END__ diff --git a/filan.c b/filan.c index 3465f7c..77c22a4 100644 --- a/filan.c +++ b/filan.c @@ -905,6 +905,7 @@ int tcpan(int fd, FILE *outfile) { #if WITH_TCP int tcpan2(int fd, FILE *outfile) { +#ifdef TCP_INFO struct tcp_info tcpinfo; socklen_t tcpinfolen = sizeof(tcpinfo); int result; @@ -930,6 +931,8 @@ int tcpan2(int fd, FILE *outfile) { // fprintf(outfile, "%s={%u}\t", "TCPI_", tcpinfo.tcpi_); return 0; +#endif + return -1; } #endif /* WITH_TCP */
require 'github/markdown' require 'rouge' module ApplicationHelper def login_link case ENV['OMNIAUTH'] when "cas" then link_to "Sign in with PLOS ID", user_omniauth_authorize_path(:cas), :id => "sign_in" when "github" then link_to "Sign in with Github", user_omniauth_authorize_path(:github), :id => "sign_in" when "orcid" then link_to "Sign in with ORCID", user_omniauth_authorize_path(:orcid), :id => "sign_in" when "persona" then form_tag "/users/auth/persona/callback", id: "persona_form", class: "navbar-form" do hidden_field_tag('assertion') + button_tag("Sign in with Persona", id: "sign_in_button", class: "btn btn-link persona") end.html_safe else link_to "Sign in not configured", "#", :id => "sign_in" end end def icon(icon, text = nil, html_options = {}) text, html_options = nil, text if text.is_a?(Hash) content_class = "fa fa-#{icon}" content_class << " #{html_options[:class]}" if html_options.key?(:class) html_options[:class] = content_class html = content_tag(:i, nil, html_options) html << ' ' << text.to_s unless text.blank? html end def markdown(text) text = GitHub::Markdown.render_gfm(text) syntax_highlighter(text).html_safe end def syntax_highlighter(html) formatter = Rouge::Formatters::HTML.new(:css_class => 'hll') lexer = Rouge::Lexers::Shell.new doc = Nokogiri::HTML::DocumentFragment.parse(html) doc.search("//pre").each { |pre| pre.replace formatter.format(lexer.lex(pre.text)) } doc.to_s end def state_label(state) case state when "working" then '<span class="label label-success">working</span>' when "inactive" then '<span class="label label-info">inactive</span>' when "disabled" then '<span class="label label-warning">disabled</span>' when "available" then '<span class="label label-default">available</span>' when "retired" then '<span class="label label-primary">retired</span>' else state end end def level_label(level) case level when 1 then '<span class="label label-info">Info</span>' when 2 then '<span class="label label-warning">Warn</span>' when 3 then '<span class="label label-danger">Error</span>' when 4 then '<span class="label label-fatal">Fatal</span>' else '<span class="label label-default">Other</span>' end end def worker_label(status) case status when "working" then "panel-success" when "waiting" then "panel-default" else "panel-warning" end end def status_label(name, status) case status when "OK" then name else "<span class='label label-warning'>#{name}</span>" end end def number_hiding_zero(number) (number.nil? || number == 0 ? "" : number_with_delimiter(number)) end def sources Source.order("group_id, title") end def publishers Publisher.order("name") end def notifications %w(Net::HTTPUnauthorized Net::HTTPForbidden Net::HTTPRequestTimeOut Net::HTTPGatewayTimeOut Net::HTTPConflict Net::HTTPServiceUnavailable - Faraday::ResourceNotFound ActiveRecord::RecordInvalid - Net::HTTPTooManyRequests ActiveJobError TooManyErrorsBySourceError AgentInactiveError - EventCountDecreasingError EventCountIncreasingTooFastError ApiResponseTooSlowError HtmlRatioTooHighError WorkNotUpdatedError SourceNotUpdatedError CitationMilestoneAlert) end def author_format(author) author = [author] if author.is_a?(Hash) authors = Array(author).map do |a| if author.is_a?(Hash) name = a.fetch("given", nil).to_s + " " + a.fetch("family", nil).to_s a["ORCID"].present? ? "<a href=\"/works/#{a["ORCID"]}\">#{name}</a>" : name else nil end end.compact fa = case authors.length when 0, 1, 2 then authors.join(" & ") when 3, 4, 5, 6, 7 then authors[0..-2].join(", ") + " & " + authors.last else authors[0..5].join(", ") + " … & " + authors.last end fa.html_safe end def date_format(work) if work.day :long elsif work.month :month else :year end end def date_from_iso8601(date) DateTime.parse(date).to_s(:short) end def description_with_link(report) if report.name == 'work_statistics_report' h(report.description) #+ link_to("Download", work_statistics_report_path, :class => 'pull-right') else h(report.description) end end def work_notifications %w(EventCountDecreasingError EventCountIncreasingTooFastError ApiResponseTooSlowError HtmlRatioTooHighError WorkNotUpdatedError CitationMilestoneAlert) end def documents %w(Installation Deployment Setup - Sources API Rake Notifications Styleguide - Releases Roadmap Contributors) end def roles %w(user staff admin) end end author helper was swallowing metadata require 'github/markdown' require 'rouge' module ApplicationHelper def login_link case ENV['OMNIAUTH'] when "cas" then link_to "Sign in with PLOS ID", user_omniauth_authorize_path(:cas), :id => "sign_in" when "github" then link_to "Sign in with Github", user_omniauth_authorize_path(:github), :id => "sign_in" when "orcid" then link_to "Sign in with ORCID", user_omniauth_authorize_path(:orcid), :id => "sign_in" when "persona" then form_tag "/users/auth/persona/callback", id: "persona_form", class: "navbar-form" do hidden_field_tag('assertion') + button_tag("Sign in with Persona", id: "sign_in_button", class: "btn btn-link persona") end.html_safe else link_to "Sign in not configured", "#", :id => "sign_in" end end def icon(icon, text = nil, html_options = {}) text, html_options = nil, text if text.is_a?(Hash) content_class = "fa fa-#{icon}" content_class << " #{html_options[:class]}" if html_options.key?(:class) html_options[:class] = content_class html = content_tag(:i, nil, html_options) html << ' ' << text.to_s unless text.blank? html end def markdown(text) text = GitHub::Markdown.render_gfm(text) syntax_highlighter(text).html_safe end def syntax_highlighter(html) formatter = Rouge::Formatters::HTML.new(:css_class => 'hll') lexer = Rouge::Lexers::Shell.new doc = Nokogiri::HTML::DocumentFragment.parse(html) doc.search("//pre").each { |pre| pre.replace formatter.format(lexer.lex(pre.text)) } doc.to_s end def state_label(state) case state when "working" then '<span class="label label-success">working</span>' when "inactive" then '<span class="label label-info">inactive</span>' when "disabled" then '<span class="label label-warning">disabled</span>' when "available" then '<span class="label label-default">available</span>' when "retired" then '<span class="label label-primary">retired</span>' else state end end def level_label(level) case level when 1 then '<span class="label label-info">Info</span>' when 2 then '<span class="label label-warning">Warn</span>' when 3 then '<span class="label label-danger">Error</span>' when 4 then '<span class="label label-fatal">Fatal</span>' else '<span class="label label-default">Other</span>' end end def worker_label(status) case status when "working" then "panel-success" when "waiting" then "panel-default" else "panel-warning" end end def status_label(name, status) case status when "OK" then name else "<span class='label label-warning'>#{name}</span>" end end def number_hiding_zero(number) (number.nil? || number == 0 ? "" : number_with_delimiter(number)) end def sources Source.order("group_id, title") end def publishers Publisher.order("name") end def notifications %w(Net::HTTPUnauthorized Net::HTTPForbidden Net::HTTPRequestTimeOut Net::HTTPGatewayTimeOut Net::HTTPConflict Net::HTTPServiceUnavailable - Faraday::ResourceNotFound ActiveRecord::RecordInvalid - Net::HTTPTooManyRequests ActiveJobError TooManyErrorsBySourceError AgentInactiveError - EventCountDecreasingError EventCountIncreasingTooFastError ApiResponseTooSlowError HtmlRatioTooHighError WorkNotUpdatedError SourceNotUpdatedError CitationMilestoneAlert) end def author_format(author) author = [author] if author.is_a?(Hash) authors = Array(author).map do |a| name = a.fetch("given", nil).to_s + " " + a.fetch("family", nil).to_s a["ORCID"].present? ? "<a href=\"/works/#{a["ORCID"]}\">#{name}</a>" : name end.compact fa = case authors.length when 0, 1, 2 then authors.join(" & ") when 3, 4, 5, 6, 7 then authors[0..-2].join(", ") + " & " + authors.last else authors[0..5].join(", ") + " … & " + authors.last end fa.html_safe end def date_format(work) if work.day :long elsif work.month :month else :year end end def date_from_iso8601(date) DateTime.parse(date).to_s(:short) end def description_with_link(report) if report.name == 'work_statistics_report' h(report.description) #+ link_to("Download", work_statistics_report_path, :class => 'pull-right') else h(report.description) end end def work_notifications %w(EventCountDecreasingError EventCountIncreasingTooFastError ApiResponseTooSlowError HtmlRatioTooHighError WorkNotUpdatedError CitationMilestoneAlert) end def documents %w(Installation Deployment Setup - Sources API Rake Notifications Styleguide - Releases Roadmap Contributors) end def roles %w(user staff admin) end end
class Socat < Formula desc "netcat on steroids" homepage "http://www.dest-unreach.org/socat/" url "http://www.dest-unreach.org/socat/download/socat-1.7.3.0.tar.gz" sha256 "f8de4a2aaadb406a2e475d18cf3b9f29e322d4e5803d8106716a01fd4e64b186" bottle do cellar :any revision 1 sha256 "6be41d4d90cd2d56119a2474f80ee5b289efcdbd73b48a9d024b2667bd4214e4" => :el_capitan sha256 "a989fcc760a1e05a53b4193ec49d16d84072b29311366b2f5c38af4490338fef" => :yosemite sha256 "dc80a1cfabde2f6abdf4a898bd92d4f8ff9a90a0464e61f5862bde0cb2f1ffe3" => :mavericks sha256 "1956257e901dbb67a3286950059c7edca5cb08e435fa87b038cc3ef306def1ea" => :mountain_lion end devel do url "http://www.dest-unreach.org/socat/download/socat-2.0.0-b8.tar.bz2" sha256 "c804579db998fb697431c82829ae03e6a50f342bd41b8810332a5d0661d893ea" version "2.0.0-b8" end depends_on "readline" depends_on "openssl" def install ENV.enable_warnings # -w causes build to fail system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do assert_match "HTTP/1.0", pipe_output("#{bin}/socat - tcp:www.google.com:80", "GET / HTTP/1.0\r\n\r\n") end end socat: update 1.7.3.0 bottle. Closes Homebrew/homebrew#45177. class Socat < Formula desc "netcat on steroids" homepage "http://www.dest-unreach.org/socat/" url "http://www.dest-unreach.org/socat/download/socat-1.7.3.0.tar.gz" sha256 "f8de4a2aaadb406a2e475d18cf3b9f29e322d4e5803d8106716a01fd4e64b186" bottle do cellar :any revision 1 sha256 "f611b1af13a4ffd67edb2e051112b65d5ae72c04fd1a6cdb1bd17fdc37dfed92" => :el_capitan sha256 "a989fcc760a1e05a53b4193ec49d16d84072b29311366b2f5c38af4490338fef" => :yosemite sha256 "dc80a1cfabde2f6abdf4a898bd92d4f8ff9a90a0464e61f5862bde0cb2f1ffe3" => :mavericks sha256 "1956257e901dbb67a3286950059c7edca5cb08e435fa87b038cc3ef306def1ea" => :mountain_lion end devel do url "http://www.dest-unreach.org/socat/download/socat-2.0.0-b8.tar.bz2" sha256 "c804579db998fb697431c82829ae03e6a50f342bd41b8810332a5d0661d893ea" version "2.0.0-b8" end depends_on "readline" depends_on "openssl" def install ENV.enable_warnings # -w causes build to fail system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do assert_match "HTTP/1.0", pipe_output("#{bin}/socat - tcp:www.google.com:80", "GET / HTTP/1.0\r\n\r\n") end end
module ApplicationHelper def parse_date(str) str ||= '' # Date.parse barfs on nil str == '' ? nil : Date.parse(str) end def build_alert_classes(alert_type = :info) classes = 'alert alert-dismissable ' case alert_type.to_sym when :alert, :danger, :error, :validation_errors classes += 'alert-danger' when :warning, :todo classes += 'alert-warning' when :notice, :success classes += 'alert-success' when :info classes += 'alert-info' end classes end # Produces a cache key for uniquely identifying cached fragments. def cache_key_for(klass, identifier = "all") count = klass.count max_updated_at = klass.maximum(:updated_at).try(:utc).try(:to_s, :number) "#{klass.name.downcase.pluralize}/#{identifier}-#{count}-#{max_updated_at}" end def required_field_help_text asterisk = content_tag :span, '*', class: ['red'] text = content_tag :em, 'denotes a required field' content_tag :div, asterisk + ' '.html_safe + text, class: ['margin-bottom'] end # # Returns an image uri for a given member. # # Falls back to Gravatar # def avatar_uri(member, size = 150) return unless member if member.preferred_avatar_uri.present? # Some avatars support different sizes # http://graph.facebook.com/12345678/picture?width=150&height=150 uri = URI.parse(member.preferred_avatar_uri) uri.query = "&width=#{size}&height=#{size}" if uri.host == 'graph.facebook.com' # TODO: Assess twitter - https://dev.twitter.com/overview/general/user-profile-images-and-banners # TODO: Assess flickr - https://www.flickr.com/services/api/misc.buddyicons.html return uri.to_s end Gravatar.new(member.email).image_url(size: size, default: :identicon) end # Returns a string with the quantity and the right pluralization for a # given collection and model. def localize_plural(collection, model) size = collection.size model_name = model.model_name.human(count: size) "#{size} #{model_name}" end def show_inactive_tickbox_path(type, owner, show_all) all = show_all ? '' : 1 if owner if type == 'plantings' plantings_by_owner_path(owner: owner.slug, all: all) elsif type == 'gardens' gardens_by_owner_path(owner: owner.slug, all: all) end elsif type == 'plantings' plantings_path(all: all) elsif type == 'gardens' gardens_path(all: all) end end def title(type, owner, crop, planting) if owner t(".title.owner_#{type}", owner: owner.login_name) elsif crop t(".title.crop_#{type}", crop: crop.name) elsif planting t(".title.planting_#{type}", planting: planting.to_s) else t(".title.default") end end def og_description(description) strip_tags(description).split(' ')[0..20].join(' ') end end Simplifying show_inactive_tickbox_path method module ApplicationHelper def parse_date(str) str ||= '' # Date.parse barfs on nil str == '' ? nil : Date.parse(str) end def build_alert_classes(alert_type = :info) classes = 'alert alert-dismissable ' case alert_type.to_sym when :alert, :danger, :error, :validation_errors classes += 'alert-danger' when :warning, :todo classes += 'alert-warning' when :notice, :success classes += 'alert-success' when :info classes += 'alert-info' end classes end # Produces a cache key for uniquely identifying cached fragments. def cache_key_for(klass, identifier = "all") count = klass.count max_updated_at = klass.maximum(:updated_at).try(:utc).try(:to_s, :number) "#{klass.name.downcase.pluralize}/#{identifier}-#{count}-#{max_updated_at}" end def required_field_help_text asterisk = content_tag :span, '*', class: ['red'] text = content_tag :em, 'denotes a required field' content_tag :div, asterisk + ' '.html_safe + text, class: ['margin-bottom'] end # # Returns an image uri for a given member. # # Falls back to Gravatar # def avatar_uri(member, size = 150) return unless member if member.preferred_avatar_uri.present? # Some avatars support different sizes # http://graph.facebook.com/12345678/picture?width=150&height=150 uri = URI.parse(member.preferred_avatar_uri) uri.query = "&width=#{size}&height=#{size}" if uri.host == 'graph.facebook.com' # TODO: Assess twitter - https://dev.twitter.com/overview/general/user-profile-images-and-banners # TODO: Assess flickr - https://www.flickr.com/services/api/misc.buddyicons.html return uri.to_s end Gravatar.new(member.email).image_url(size: size, default: :identicon) end # Returns a string with the quantity and the right pluralization for a # given collection and model. def localize_plural(collection, model) size = collection.size model_name = model.model_name.human(count: size) "#{size} #{model_name}" end def show_inactive_tickbox_path(type, owner, show_all) all = show_all ? '' : 1 if owner return plantings_by_owner_path(owner: owner.slug, all: all) if type == 'plantings' return gardens_by_owner_path(owner: owner.slug, all: all) if type == 'gardens' end return plantings_path(all: all) if type == 'plantings' return gardens_path(all: all) if type == 'gardens' end def title(type, owner, crop, planting) if owner t(".title.owner_#{type}", owner: owner.login_name) elsif crop t(".title.crop_#{type}", crop: crop.name) elsif planting t(".title.planting_#{type}", planting: planting.to_s) else t(".title.default") end end def og_description(description) strip_tags(description).split(' ')[0..20].join(' ') end end
class Stern < Formula desc "Tail multiple Kubernetes pods & their containers" homepage "https://github.com/stern/stern" url "https://github.com/stern/stern/archive/v1.19.0.tar.gz" sha256 "1f19f9ec21f07317ce53b333b9633b6b91392f5af6b0fff2657ee1b2a0bae707" license "Apache-2.0" head "https://github.com/stern/stern.git" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "2d4eb663c230a5531461272845ebe49b682126aeb271d048a39e336c2a7ecd4f" sha256 cellar: :any_skip_relocation, big_sur: "1cdc09acfdb8ddb9dc2f3865bd330e2dce44743ee9979e8cacc7a89e804e34d3" sha256 cellar: :any_skip_relocation, catalina: "d693aab66a01eef79db5962b1dad628ce53d3061732cd86c06faa76b3000144d" sha256 cellar: :any_skip_relocation, mojave: "e0d9f83aa8ed11f4e1136f37ce1b6671d4ef29b98dee49634a1d50f22a962069" end depends_on "go" => :build def install system "go", "build", "-ldflags", "-s -w -X github.com/stern/stern/cmd.version=#{version}", *std_go_args # Install shell completion output = Utils.safe_popen_read("#{bin}/stern", "--completion=bash") (bash_completion/"stern").write output output = Utils.safe_popen_read("#{bin}/stern", "--completion=zsh") (zsh_completion/"_stern").write output end test do assert_match "version: #{version}", shell_output("#{bin}/stern --version") end end stern: update 1.19.0 bottle. class Stern < Formula desc "Tail multiple Kubernetes pods & their containers" homepage "https://github.com/stern/stern" url "https://github.com/stern/stern/archive/v1.19.0.tar.gz" sha256 "1f19f9ec21f07317ce53b333b9633b6b91392f5af6b0fff2657ee1b2a0bae707" license "Apache-2.0" head "https://github.com/stern/stern.git" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "b274de5c5f3c9cf97aa64a6375d05103ec241becee3e6cbd02fe9a9407bed551" sha256 cellar: :any_skip_relocation, big_sur: "9815b17dd2796aa4040207fe40731d4a9e1fe19cd581175f18a160f6162bfff2" sha256 cellar: :any_skip_relocation, catalina: "4474cdd9d0ba47b09a4fd4a837d0c5c00d451b1f96290ebefedcb1837f0dc947" sha256 cellar: :any_skip_relocation, mojave: "96b38e3a0d220d9278aef074196f576964a9f62173f00cf5a6c9cbb138129dff" end depends_on "go" => :build def install system "go", "build", "-ldflags", "-s -w -X github.com/stern/stern/cmd.version=#{version}", *std_go_args # Install shell completion output = Utils.safe_popen_read("#{bin}/stern", "--completion=bash") (bash_completion/"stern").write output output = Utils.safe_popen_read("#{bin}/stern", "--completion=zsh") (zsh_completion/"_stern").write output end test do assert_match "version: #{version}", shell_output("#{bin}/stern --version") end end
module ApplicationHelper def messages_tab? params[:controller] == 'messages' end def profile_tab? params[:controller] == 'users' && params['action'] == 'profile' end def ad_tab? params[:controller] == 'users' && params['action'] == 'listads' end def meta_description general = t('nlt.meta_description') specific = content_for(:meta_description) if content_for?(:meta_description) content = specific ? "#{specific}. #{general}" : general tag :meta, name: 'description', content: content end def escape_privacy_data text if text text = text.gsub(/([\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+)/, ' ') text = text.gsub(/([9|6])+([0-9\s*]{8,})/, ' ') text = text.gsub(/whatsapp/, ' ') text = text.gsub(/whatsupp/, ' ') text = text.gsub(/whatsap/, ' ') text = text.gsub(/whatsap/, ' ') text = text.gsub(/watsap/, ' ') text = text.gsub(/guasap/, ' ') text = text.gsub(/wuassap/, ' ') text = text.gsub(/wuasap/, ' ') text = text.gsub(/wassap/, ' ') text = text.gsub(/wasap/, ' ') text = text.gsub(/guassapp/, ' ') text = text.gsub(/guassap/, ' ') text = text.gsub(/guasapp/, ' ') text = text.gsub(/guasap/, ' ') text = text.gsub(/guasp/, ' ') text end end def i18n_to_localeapp_in_locale(locale) langs = { gl: 20650, pt: 20648, nl: 24068, it: 20649, fr: 20646, eu: 20651, en: 20647, de: 20645, ca: 20644 } langs[locale] end def localized_url(locale) url_for(params.merge(locale: locale, only_path: false)) end def errors_for(object) errs = object.errors return unless errs.any? content_tag(:div, id: 'error_explanation') do header = content_tag(:h2, t('nlt.save_failed')) list = content_tag(:ul) do errs.full_messages.map { |m| content_tag(:li, m) }.join("\n").html_safe end header + list end end def link_to_change_location(place, name = nil) title = name || place link_to title, location_change_path(location: place) end end Fix Rails/OutputSafety offenses module ApplicationHelper def messages_tab? params[:controller] == 'messages' end def profile_tab? params[:controller] == 'users' && params['action'] == 'profile' end def ad_tab? params[:controller] == 'users' && params['action'] == 'listads' end def meta_description general = t('nlt.meta_description') specific = content_for(:meta_description) if content_for?(:meta_description) content = specific ? "#{specific}. #{general}" : general tag :meta, name: 'description', content: content end def escape_privacy_data text if text text = text.gsub(/([\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+)/, ' ') text = text.gsub(/([9|6])+([0-9\s*]{8,})/, ' ') text = text.gsub(/whatsapp/, ' ') text = text.gsub(/whatsupp/, ' ') text = text.gsub(/whatsap/, ' ') text = text.gsub(/whatsap/, ' ') text = text.gsub(/watsap/, ' ') text = text.gsub(/guasap/, ' ') text = text.gsub(/wuassap/, ' ') text = text.gsub(/wuasap/, ' ') text = text.gsub(/wassap/, ' ') text = text.gsub(/wasap/, ' ') text = text.gsub(/guassapp/, ' ') text = text.gsub(/guassap/, ' ') text = text.gsub(/guasapp/, ' ') text = text.gsub(/guasap/, ' ') text = text.gsub(/guasp/, ' ') text end end def i18n_to_localeapp_in_locale(locale) langs = { gl: 20650, pt: 20648, nl: 24068, it: 20649, fr: 20646, eu: 20651, en: 20647, de: 20645, ca: 20644 } langs[locale] end def localized_url(locale) url_for(params.merge(locale: locale, only_path: false)) end def errors_for(object) errs = object.errors return unless errs.any? content_tag(:div, id: 'error_explanation') do header = content_tag(:h2, t('nlt.save_failed')) list = content_tag(:ul) do safe_join(errs.full_messages.map { |m| content_tag(:li, m) }, "\n") end header + list end end def link_to_change_location(place, name = nil) title = name || place link_to title, location_change_path(location: place) end end
class Stgit < Formula desc "Push/pop utility built on top of Git" homepage "https://github.com/ctmarinas/stgit" url "https://github.com/ctmarinas/stgit/archive/v0.21.tar.gz" sha256 "ba1ccbbc15beccc4648ae3b3a198693be7e6b1b1e330f45605654d56095dac0d" head "https://github.com/ctmarinas/stgit.git" bottle do cellar :any_skip_relocation sha256 "736d0fb7ba2e2f09acb9f3c12e7a232d975c1f20306b1d6b56dbc8fa9622bb0e" => :catalina sha256 "a8c5a52941bb5c524f97bddf295dbf65b79ec74b4ec5a0d0ebcdb25429e1e03d" => :mojave sha256 "a8c5a52941bb5c524f97bddf295dbf65b79ec74b4ec5a0d0ebcdb25429e1e03d" => :high_sierra end def install ENV["PYTHON"] = "python" # overrides 'python2' built into makefile system "make", "prefix=#{prefix}", "all" system "make", "prefix=#{prefix}", "install" end test do system "git", "init" (testpath/"test").write "test" system "git", "add", "test" system "git", "commit", "--message", "Initial commit", "test" system "#{bin}/stg", "init" system "#{bin}/stg", "log" end end stgit: python@2 and fix test Closes #16831. Signed-off-by: Dawid Dziurla <c4a7db180859322ef5630a1dfc2805b5bc97fc25@gmail.com> class Stgit < Formula desc "Push/pop utility built on top of Git" homepage "https://github.com/ctmarinas/stgit" url "https://github.com/ctmarinas/stgit/archive/v0.21.tar.gz" sha256 "ba1ccbbc15beccc4648ae3b3a198693be7e6b1b1e330f45605654d56095dac0d" head "https://github.com/ctmarinas/stgit.git" bottle do cellar :any_skip_relocation sha256 "736d0fb7ba2e2f09acb9f3c12e7a232d975c1f20306b1d6b56dbc8fa9622bb0e" => :catalina sha256 "a8c5a52941bb5c524f97bddf295dbf65b79ec74b4ec5a0d0ebcdb25429e1e03d" => :mojave sha256 "a8c5a52941bb5c524f97bddf295dbf65b79ec74b4ec5a0d0ebcdb25429e1e03d" => :high_sierra end depends_on "python@2" unless OS.mac? def install ENV["PYTHON"] = "python" # overrides 'python2' built into makefile system "make", "prefix=#{prefix}", "all" system "make", "prefix=#{prefix}", "install" end test do if ENV["CI"] system "git", "config", "--global", "user.email", "you@example.com" system "git", "config", "--global", "user.name", "Your Name" end system "git", "init" (testpath/"test").write "test" system "git", "add", "test" system "git", "commit", "--message", "Initial commit", "test" system "#{bin}/stg", "init" system "#{bin}/stg", "log" end end
# frozen_string_literal: true # # = Application Helpers # # These methods are available to all templates in the application: # ################################################################################ module ApplicationHelper include AutocompleteHelper include DescriptionHelper include ExporterHelper include FooterHelper include JavascriptHelper include LocalizationHelper include MapHelper include ObjectLinkHelper include TabsHelper include ThumbnailHelper include VersionHelper def safe_empty "".html_safe end def safe_br "<br/>".html_safe end def safe_nbsp "&nbsp;".html_safe end # Return escaped HTML. # # "<i>X</i>" --> "&lt;i&gt;X&lt;/i&gt;" def escape_html(html) h(html.to_str) end # Call link_to with query params added. def link_with_query(name = nil, options = nil, html_options = nil) link_to(name, add_query_param(options), html_options) end # Take a query which can be coerced into a different model, and create a link # to the results of that coerced query. Return +nil+ if not coercable. def link_to_coerced_query(query, model) link = coerced_query_link(query, model) return nil unless link link_to(*link) end # Convert @links in index views into a list of tabs for RHS tab set. def create_links(links) return [] unless links links.reject(&:nil?).map { |str, url| link_to(str, url) } end # Create an in-line white-space element approximately the given width in # pixels. It should be non-line-breakable, too. def indent(count = 10) "<span style='margin-left:#{count}px'>&nbsp;</span>".html_safe end def content_tag_if(condition, name, content_or_options_with_block = nil, options = nil, escape = true, &block) return unless condition content_tag(name, content_or_options_with_block, options, escape, &block) end def content_tag_unless(condition, name, content_or_options_with_block = nil, options = nil, escape = true, &block) content_tag_if(!condition, name, content_or_options_with_block, options, escape, &block) end # Wrap an html object in '<span title="blah">' tag. This has the effect of # giving it context help (mouse-over popup) in most modern browsers. # # <%= add_context_help(link, "Click here to do something.") %> # def add_context_help(object, help) content_tag(:span, object, title: help, data: { toggle: "tooltip" }) end # Add something to the header from within view. This can be called as many # times as necessary -- the application layout will mash them all together # and stick them at the end of the <tt>&gt;head&lt;/tt> section. # # <% # add_header(GMap.header) # adds GMap general header # gmap = make_map(@locations) # add_header(finish_map(gmap)) # adds map-specific header # %> # def add_header(str) @header ||= safe_empty @header += str end # Create a table out of a list of Arrays. # # make_table([[1,2],[3,4]]) # # Produces: # # <table> # <tr> # <td>1</td> # <td>2</td> # </tr> # <tr> # <td>3</td> # <td>4</td> # </tr> # </table> # def make_table(rows, table_opts = {}, tr_opts = {}, td_opts = {}) content_tag(:table, table_opts) do rows.map do |row| make_row(row, tr_opts, td_opts) + make_line(row, td_opts) end.safe_join end end def make_row(row, tr_opts = {}, td_opts = {}) content_tag(:tr, tr_opts) do if !row.is_a?(Array) row else row.map do |cell| make_cell(cell, td_opts) end.safe_join end end end def make_cell(cell, td_opts = {}) content_tag(:td, cell.to_s, td_opts) end def make_line(_row, td_opts) colspan = td_opts[:colspan] if colspan content_tag(:tr, class: "MatrixLine") do content_tag(:td, tag(:hr), class: "MatrixLine", colspan: colspan) end else safe_empty end end # Take URL that got us to this page and add one or more parameters to it. # Returns new URL. # # link_to("Next Page", reload_with_args(page: 2)) # def reload_with_args(new_args) uri = request.url.sub(%r{^\w+:/+[^/]+}, "") add_args_to_url(uri, new_args) end # Take an arbitrary URL and change the parameters. Returns new URL. Should # even handle the fancy "/object/id" case. (Note: use +nil+ to mean delete # -- i.e. <tt>add_args_to_url(url, old_arg: nil)</tt> deletes the # parameter named +old_arg+ from +url+.) # # url = url_for(action: "blah", ...) # new_url = add_args_to_url(url, arg1: :val1, arg2: :val2, ...) # def add_args_to_url(url, new_args) new_args = new_args.clone args = {} # Garbage in, garbage out... return url unless url.valid_encoding? # Parse parameters off of current URL. addr, parms = url.split("?") for arg in parms ? parms.split("&") : [] var, val = arg.split("=") next unless var && var != "" var = CGI.unescape(var) # See note below about precedence in case of redundancy. args[var] = val unless args.key?(var) end # Deal with the special "/xxx/id" case. if %r{/(\d+)$}.match?(addr) new_id = new_args[:id] || new_args["id"] addr.sub!(/\d+$/, new_id.to_s) if new_id new_args.delete(:id) new_args.delete("id") end # Merge in new arguments, deleting where new values are nil. for var in new_args.keys val = new_args[var] var = var.to_s if val.nil? args.delete(var) elsif val.is_a?(ActiveRecord::Base) args[var] = val.id.to_s else args[var] = CGI.escape(val.to_s) end end # Put it back together. return addr if args.keys.empty? addr + "?" + args.keys.sort.map do |k| CGI.escape(k) + "=" + (args[k] || "") end.join("&") end # Returns URL to return to after deleting an object. Can't just return to # the index, because we'd prefer to return to the correct page in the index, # but to do that we need to know the id of next object. def url_after_delete(object) return nil unless object id = get_next_id(object) args = { controller: object.show_controller, action: object.index_action } args[:id] = id if id url_for(add_query_param(args)) end def get_next_id(object) query = passed_query return nil unless query return nil unless query.model.to_s == object.class.name idx = query.index(object) return nil unless idx query.result_ids[idx + 1] || query.result_ids[idx - 1] end # Override Rails method of the same name. Just calls our # Textile#textilize_without_paragraph method on the given string. def textilize_without_paragraph(str, do_object_links = false) Textile.textilize_without_paragraph(str, do_object_links) end # Override Rails method of the same name. Just calls our Textile#textilize # method on the given string. def textilize(str, do_object_links = false) Textile.textilize(str, do_object_links) end # Create stylable file input field with client-side size validation. def custom_file_field(obj, attr, opts = {}) max_size = MO.image_upload_max_size max_size_in_mb = (max_size.to_f / 1024 / 1024).round file_field = file_field( obj, attr, opts.merge( max_upload_msg: :validate_image_file_too_big.l(max: max_size_in_mb), max_upload_size: max_size ) ) content_tag(:span, :select_file.t + file_field, class: "file-field btn") + content_tag(:span, :no_file_selected.t) end def date_select_opts(obj = nil) start_year = 20.years.ago.year init_value = obj.try(&:when).try(&:year) start_year = init_value if init_value && init_value < start_year { start_year: start_year, end_year: Time.zone.now.year, order: [:day, :month, :year] } end # contents of the <title> in html header def title_tag_contents(action_name) if @title.present? @title.strip_html.html_safe elsif TranslationString.where(tag: "title_for_#{action_name}").present? :"title_for_#{action_name}".t else action_name.tr("_", " ").titleize end end # button to destroy object # Used instead of link because DESTROY link requires js # Sample usage: # destroy_button(object: article) # destroy_button(object: term, name: :destroy_glossary_term) def destroy_button(object:, name: :DESTROY) button_to( name.t, { action: "destroy", id: object.id }, method: :delete, data: { confirm: "Are you sure?" } ) end end Add documentation at top of ApplicationHelper # frozen_string_literal: true # # = Application Helpers # # Methods available to all templates in the application: # # safe_br # <br/>,html_safe # safe_empty # safe_nbsp # escape_html # Return escaped HTML # link_to_coerced_query # link to query coerced into different model # link_with_query # link_to with query params # create_link # convert links into list of tabs # indent # in-lined white-space element of n pixels # content_tag_if # content_tag_unless # add content_help # help text viewable on mouse-over # add_header # add to html header from within view # make_table # make table from list of arrays # reload_with_args # add args to url that got us to this page # add_args_to_url # change params of arbitrary url # url_after_delete # url to return to after deleting object # get_next_id # textilize_without_paragraph # override Rails method of same name # textilize # override Rails method of same name # custom_file_field # stylable file input field with # # client-side size validation # date_select_opts # title_tag_contents # text to put in html header <title> # destroy_button # button to destroy object # module ApplicationHelper include AutocompleteHelper include DescriptionHelper include ExporterHelper include FooterHelper include JavascriptHelper include LocalizationHelper include MapHelper include ObjectLinkHelper include TabsHelper include ThumbnailHelper include VersionHelper def safe_empty "".html_safe end def safe_br "<br/>".html_safe end def safe_nbsp "&nbsp;".html_safe end # Return escaped HTML. # # "<i>X</i>" --> "&lt;i&gt;X&lt;/i&gt;" def escape_html(html) h(html.to_str) end # Call link_to with query params added. def link_with_query(name = nil, options = nil, html_options = nil) link_to(name, add_query_param(options), html_options) end # Take a query which can be coerced into a different model, and create a link # to the results of that coerced query. Return +nil+ if not coercable. def link_to_coerced_query(query, model) link = coerced_query_link(query, model) return nil unless link link_to(*link) end # Convert @links in index views into a list of tabs for RHS tab set. def create_links(links) return [] unless links links.reject(&:nil?).map { |str, url| link_to(str, url) } end # Create an in-line white-space element approximately the given width in # pixels. It should be non-line-breakable, too. def indent(count = 10) "<span style='margin-left:#{count}px'>&nbsp;</span>".html_safe end def content_tag_if(condition, name, content_or_options_with_block = nil, options = nil, escape = true, &block) return unless condition content_tag(name, content_or_options_with_block, options, escape, &block) end def content_tag_unless(condition, name, content_or_options_with_block = nil, options = nil, escape = true, &block) content_tag_if(!condition, name, content_or_options_with_block, options, escape, &block) end # Wrap an html object in '<span title="blah">' tag. This has the effect of # giving it context help (mouse-over popup) in most modern browsers. # # <%= add_context_help(link, "Click here to do something.") %> # def add_context_help(object, help) content_tag(:span, object, title: help, data: { toggle: "tooltip" }) end # Add something to the header from within view. This can be called as many # times as necessary -- the application layout will mash them all together # and stick them at the end of the <tt>&gt;head&lt;/tt> section. # # <% # add_header(GMap.header) # adds GMap general header # gmap = make_map(@locations) # add_header(finish_map(gmap)) # adds map-specific header # %> # def add_header(str) @header ||= safe_empty @header += str end # Create a table out of a list of Arrays. # # make_table([[1,2],[3,4]]) # # Produces: # # <table> # <tr> # <td>1</td> # <td>2</td> # </tr> # <tr> # <td>3</td> # <td>4</td> # </tr> # </table> # def make_table(rows, table_opts = {}, tr_opts = {}, td_opts = {}) content_tag(:table, table_opts) do rows.map do |row| make_row(row, tr_opts, td_opts) + make_line(row, td_opts) end.safe_join end end def make_row(row, tr_opts = {}, td_opts = {}) content_tag(:tr, tr_opts) do if !row.is_a?(Array) row else row.map do |cell| make_cell(cell, td_opts) end.safe_join end end end def make_cell(cell, td_opts = {}) content_tag(:td, cell.to_s, td_opts) end def make_line(_row, td_opts) colspan = td_opts[:colspan] if colspan content_tag(:tr, class: "MatrixLine") do content_tag(:td, tag(:hr), class: "MatrixLine", colspan: colspan) end else safe_empty end end # Take URL that got us to this page and add one or more parameters to it. # Returns new URL. # # link_to("Next Page", reload_with_args(page: 2)) # def reload_with_args(new_args) uri = request.url.sub(%r{^\w+:/+[^/]+}, "") add_args_to_url(uri, new_args) end # Take an arbitrary URL and change the parameters. Returns new URL. Should # even handle the fancy "/object/id" case. (Note: use +nil+ to mean delete # -- i.e. <tt>add_args_to_url(url, old_arg: nil)</tt> deletes the # parameter named +old_arg+ from +url+.) # # url = url_for(action: "blah", ...) # new_url = add_args_to_url(url, arg1: :val1, arg2: :val2, ...) # def add_args_to_url(url, new_args) new_args = new_args.clone args = {} # Garbage in, garbage out... return url unless url.valid_encoding? # Parse parameters off of current URL. addr, parms = url.split("?") for arg in parms ? parms.split("&") : [] var, val = arg.split("=") next unless var && var != "" var = CGI.unescape(var) # See note below about precedence in case of redundancy. args[var] = val unless args.key?(var) end # Deal with the special "/xxx/id" case. if %r{/(\d+)$}.match?(addr) new_id = new_args[:id] || new_args["id"] addr.sub!(/\d+$/, new_id.to_s) if new_id new_args.delete(:id) new_args.delete("id") end # Merge in new arguments, deleting where new values are nil. for var in new_args.keys val = new_args[var] var = var.to_s if val.nil? args.delete(var) elsif val.is_a?(ActiveRecord::Base) args[var] = val.id.to_s else args[var] = CGI.escape(val.to_s) end end # Put it back together. return addr if args.keys.empty? addr + "?" + args.keys.sort.map do |k| CGI.escape(k) + "=" + (args[k] || "") end.join("&") end # Returns URL to return to after deleting an object. Can't just return to # the index, because we'd prefer to return to the correct page in the index, # but to do that we need to know the id of next object. def url_after_delete(object) return nil unless object id = get_next_id(object) args = { controller: object.show_controller, action: object.index_action } args[:id] = id if id url_for(add_query_param(args)) end def get_next_id(object) query = passed_query return nil unless query return nil unless query.model.to_s == object.class.name idx = query.index(object) return nil unless idx query.result_ids[idx + 1] || query.result_ids[idx - 1] end # Override Rails method of the same name. Just calls our # Textile#textilize_without_paragraph method on the given string. def textilize_without_paragraph(str, do_object_links = false) Textile.textilize_without_paragraph(str, do_object_links) end # Override Rails method of the same name. Just calls our Textile#textilize # method on the given string. def textilize(str, do_object_links = false) Textile.textilize(str, do_object_links) end # Create stylable file input field with client-side size validation. def custom_file_field(obj, attr, opts = {}) max_size = MO.image_upload_max_size max_size_in_mb = (max_size.to_f / 1024 / 1024).round file_field = file_field( obj, attr, opts.merge( max_upload_msg: :validate_image_file_too_big.l(max: max_size_in_mb), max_upload_size: max_size ) ) content_tag(:span, :select_file.t + file_field, class: "file-field btn") + content_tag(:span, :no_file_selected.t) end def date_select_opts(obj = nil) start_year = 20.years.ago.year init_value = obj.try(&:when).try(&:year) start_year = init_value if init_value && init_value < start_year { start_year: start_year, end_year: Time.zone.now.year, order: [:day, :month, :year] } end # contents of the <title> in html header def title_tag_contents(action_name) if @title.present? @title.strip_html.html_safe elsif TranslationString.where(tag: "title_for_#{action_name}").present? :"title_for_#{action_name}".t else action_name.tr("_", " ").titleize end end # button to destroy object # Used instead of link because DESTROY link requires js # Sample usage: # destroy_button(object: article) # destroy_button(object: term, name: :destroy_glossary_term) def destroy_button(object:, name: :DESTROY) button_to( name.t, { action: "destroy", id: object.id }, method: :delete, data: { confirm: "Are you sure?" } ) end end
class Storm < Formula desc "Distributed realtime computation system to process data streams" homepage "https://storm.apache.org" url "https://www.apache.org/dyn/closer.cgi?path=storm/apache-storm-1.2.1/apache-storm-1.2.1.tar.gz" sha256 "7b4a7b7d384f328c193c0942f0348ef5711e793d06a247d5bef9a9b8d7c3ed9c" bottle :unneeded conflicts_with "stormssh", :because => "both install 'storm' binary" def install libexec.install Dir["*"] bin.install_symlink libexec/"bin/storm" end test do system bin/"storm", "version" end end storm 1.2.2 (#28588) class Storm < Formula desc "Distributed realtime computation system to process data streams" homepage "https://storm.apache.org" url "https://www.apache.org/dyn/closer.cgi?path=storm/apache-storm-1.2.2/apache-storm-1.2.2.tar.gz" sha256 "e97e92ea13998c95ee37565bdf4d6f6a379deb259ec76cb0178cd356502e657f" bottle :unneeded conflicts_with "stormssh", :because => "both install 'storm' binary" def install libexec.install Dir["*"] bin.install_symlink libexec/"bin/storm" end test do system bin/"storm", "version" end end
module ApplicationHelper include Storcs::Formatter def sortable(column, title = nil) title ||= t(column, :default => column.titleize) direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc" link_to title, params.merge(:sort => column, :direction => direction) end def sortable_css_class(column) column == sort_column ? "current #{sort_direction}" : "sortable" end def sortable_th(column, title = nil, html_options = {}) content_tag :th, {:class => sortable_css_class(column)}.merge(html_options) do sortable(column,title) end end def progress_bar(pcts, options={}) #width width = 120 if options[:width].present? && options[:width].is_a?(Integer) width = options[:width] end width = width.to_f #percents calculations pcts = [pcts, pcts] unless pcts.is_a?(Array) pcts = pcts.collect(&:round) pcts[1] = pcts[1] - pcts[0] pcts.map! do |pct| pct * width / 100 end pcts << (width - pcts[1] - pcts[0]) legend = options[:legend] || '' o = %(<table class="progress" style="width:#{width + 30}px;"><tr>) o << %(<td class="closed" style="width:#{pcts[0]}px;"></td>) if pcts[0] > 0 o << %(<td class="done" style="width:#{pcts[1]}px;"></td>) if pcts[1] > 0 o << %(<td class="todo" style="width:#{pcts[2]}px;"></td>) if pcts[2] > 0 o << %(<td class="legend" style="width:30px">#{legend}</td>) o << %(</tr></table>) o.html_safe end def show_version "<i>Cartoque v#{Cartocs::VERSION}</i>".html_safe end # see ancestry wiki on github # usage: <%= f.select :parent_id, @categories %> # # @categories = ancestry_options(Category.scoped.arrange(:order => 'name'){|i| "#{'-'*i.depth} #{i.name}"}) def ancestry_options(items, &block) result = [] items.map do |item, sub_items| result << [ yield(item), item.id ] #recursive call result += ancestry_options(sub_items) {|i| "#{'-'*i.depth} #{i.name}" } end result end def tabular_errors(object) if object.errors.any? html = <<-EOF <tr id="error_explanation"><td colspan="2"> <h2>#{pluralize(object.errors.count, "erreur")} :</h2> <ul> #{object.errors.full_messages.map do |msg| "<li>"+msg+"</li>" end.join(" ")} </ul> </td></tr> EOF html.html_safe end end def action_links(&block) content_tag(:div, :class => "actions") do capture(&block) end end def links_for(application) html = "" if application.identifier? html << link_to("R", (URI.parse(APP_CONFIG[:redmine_url])+"/projects/#{application.identifier}").to_s, :title => "Redmine #{application.identifier}", :class => "link-to-redmine") end content_tag(:span, html.html_safe, :class => "links") end def display_machine(machine) content_tag(:span, :class => "machine-link") do link_to(machine.name, machine) + content_tag(:span, :class => "machine-details") do [ machine.operating_system, (machine.nb_proc && machine.nb_proc > 0 ? machine.cores : ""), (machine.memory? ? "#{machine.ram}G" : ""), (machine.disk_size && machine.disk_size > 0 ? machine.disks : "") ].reject(&:blank?).join(" | ") end end end def context_li(text, url, options = {}) current = options.delete(:current) if current content_tag :li, text, :class => "current" else content_tag :li, link_to(text, url, options) end end def link_to_servername(name) link_to name, machine_path(Machine.identifier_for(name)) end def link_to_server_if_exists(name) s = Machine.find_by_name(name) s ? link_to(name, s) : server_missing(name) end def server_missing(name) name + " " + link_to("+", new_machine_path(:machine => { :name => name }), :class => "action create-machine", :title => t(:"helpers.submit.create")) end def link_to_rack(rack) return "" if rack.blank? link_to rack, machines_path(:by_rack => rack.id) end def link_to_remove_fields(name, f, options = {}) if options.delete(:confirm) js = "if (confirm('#{t(:text_are_you_sure)}')) remove_fields(this)" else js = "remove_fields(this)" end f.hidden_field(:_destroy) + link_to_function(name, js, {:class => "link-delete"}.merge(options)).html_safe end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", :class => "link-add") end def request_from_pdfkit? request.env["Rack-Middleware-PDFKit"] == "true" end end Added reference for pdfkit + asset pipeline problems module ApplicationHelper include Storcs::Formatter def sortable(column, title = nil) title ||= t(column, :default => column.titleize) direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc" link_to title, params.merge(:sort => column, :direction => direction) end def sortable_css_class(column) column == sort_column ? "current #{sort_direction}" : "sortable" end def sortable_th(column, title = nil, html_options = {}) content_tag :th, {:class => sortable_css_class(column)}.merge(html_options) do sortable(column,title) end end def progress_bar(pcts, options={}) #width width = 120 if options[:width].present? && options[:width].is_a?(Integer) width = options[:width] end width = width.to_f #percents calculations pcts = [pcts, pcts] unless pcts.is_a?(Array) pcts = pcts.collect(&:round) pcts[1] = pcts[1] - pcts[0] pcts.map! do |pct| pct * width / 100 end pcts << (width - pcts[1] - pcts[0]) legend = options[:legend] || '' o = %(<table class="progress" style="width:#{width + 30}px;"><tr>) o << %(<td class="closed" style="width:#{pcts[0]}px;"></td>) if pcts[0] > 0 o << %(<td class="done" style="width:#{pcts[1]}px;"></td>) if pcts[1] > 0 o << %(<td class="todo" style="width:#{pcts[2]}px;"></td>) if pcts[2] > 0 o << %(<td class="legend" style="width:30px">#{legend}</td>) o << %(</tr></table>) o.html_safe end def show_version "<i>Cartoque v#{Cartocs::VERSION}</i>".html_safe end # see ancestry wiki on github # usage: <%= f.select :parent_id, @categories %> # # @categories = ancestry_options(Category.scoped.arrange(:order => 'name'){|i| "#{'-'*i.depth} #{i.name}"}) def ancestry_options(items, &block) result = [] items.map do |item, sub_items| result << [ yield(item), item.id ] #recursive call result += ancestry_options(sub_items) {|i| "#{'-'*i.depth} #{i.name}" } end result end def tabular_errors(object) if object.errors.any? html = <<-EOF <tr id="error_explanation"><td colspan="2"> <h2>#{pluralize(object.errors.count, "erreur")} :</h2> <ul> #{object.errors.full_messages.map do |msg| "<li>"+msg+"</li>" end.join(" ")} </ul> </td></tr> EOF html.html_safe end end def action_links(&block) content_tag(:div, :class => "actions") do capture(&block) end end def links_for(application) html = "" if application.identifier? html << link_to("R", (URI.parse(APP_CONFIG[:redmine_url])+"/projects/#{application.identifier}").to_s, :title => "Redmine #{application.identifier}", :class => "link-to-redmine") end content_tag(:span, html.html_safe, :class => "links") end def display_machine(machine) content_tag(:span, :class => "machine-link") do link_to(machine.name, machine) + content_tag(:span, :class => "machine-details") do [ machine.operating_system, (machine.nb_proc && machine.nb_proc > 0 ? machine.cores : ""), (machine.memory? ? "#{machine.ram}G" : ""), (machine.disk_size && machine.disk_size > 0 ? machine.disks : "") ].reject(&:blank?).join(" | ") end end end def context_li(text, url, options = {}) current = options.delete(:current) if current content_tag :li, text, :class => "current" else content_tag :li, link_to(text, url, options) end end def link_to_servername(name) link_to name, machine_path(Machine.identifier_for(name)) end def link_to_server_if_exists(name) s = Machine.find_by_name(name) s ? link_to(name, s) : server_missing(name) end def server_missing(name) name + " " + link_to("+", new_machine_path(:machine => { :name => name }), :class => "action create-machine", :title => t(:"helpers.submit.create")) end def link_to_rack(rack) return "" if rack.blank? link_to rack, machines_path(:by_rack => rack.id) end def link_to_remove_fields(name, f, options = {}) if options.delete(:confirm) js = "if (confirm('#{t(:text_are_you_sure)}')) remove_fields(this)" else js = "remove_fields(this)" end f.hidden_field(:_destroy) + link_to_function(name, js, {:class => "link-delete"}.merge(options)).html_safe end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", :class => "link-add") end #for more information on pdfkit + asset pipeline: #http://www.mobalean.com/blog/2011/08/02/pdf-generation-and-heroku def request_from_pdfkit? request.env["Rack-Middleware-PDFKit"] == "true" end end
class Tfsec < Formula desc "Static analysis security scanner for your terraform code" homepage "https://tfsec.dev/" url "https://github.com/aquasecurity/tfsec/archive/v0.59.0.tar.gz" sha256 "0bf6488b8b4dac7c83b1175eb7d6b6786b41ca892f1678ff0b16597e45466fdd" license "MIT" head "https://github.com/aquasecurity/tfsec.git", branch: "master" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "0ca9dec8fe964ff78bddd70a0a16b1c8da885f66334e6e67b2e99b0d28bb686a" sha256 cellar: :any_skip_relocation, arm64_big_sur: "3e7e22286faf406a19de0982d6529582b02638a3b1586f1a62cd4ab75842ccba" sha256 cellar: :any_skip_relocation, monterey: "ae2339de2b93dc8c79ee30d6b872e4366dc0435e3cbba8316a4b646bb5fb5be5" sha256 cellar: :any_skip_relocation, big_sur: "6426b7f76b2589c7ff809fd08688cafc5992e1bdb9982a0d22fa91725b1b640c" sha256 cellar: :any_skip_relocation, catalina: "8fefe4a41cf07358f6d99b16217acde729c26d9847bdf92e6b858779bd42b094" sha256 cellar: :any_skip_relocation, x86_64_linux: "7786254fc9f2dcd94388ef31bb2068f9f22576f9d17ab67c60b3b51537400433" end depends_on "go" => :build def install system "scripts/install.sh", "v#{version}" bin.install "tfsec" end test do (testpath/"good/brew-validate.tf").write <<~EOS resource "aws_alb_listener" "my-alb-listener" { port = "443" protocol = "HTTPS" } EOS (testpath/"bad/brew-validate.tf").write <<~EOS resource "aws_security_group_rule" "world" { description = "A security group triggering tfsec AWS006." type = "ingress" cidr_blocks = ["0.0.0.0/0"] } EOS good_output = shell_output("#{bin}/tfsec #{testpath}/good") assert_match "No problems detected!", good_output bad_output = shell_output("#{bin}/tfsec #{testpath}/bad 2>&1", 1) assert_match "1 potential problems detected.", bad_output end end tfsec 0.60.0 Closes #89719. Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com> Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com> class Tfsec < Formula desc "Static analysis security scanner for your terraform code" homepage "https://tfsec.dev/" url "https://github.com/aquasecurity/tfsec/archive/v0.60.0.tar.gz" sha256 "64d6ec30942bfc071c3dbc4a6dd0e50a1b1ef4e63bbfbc441a76a7882c595fa8" license "MIT" head "https://github.com/aquasecurity/tfsec.git", branch: "master" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "0ca9dec8fe964ff78bddd70a0a16b1c8da885f66334e6e67b2e99b0d28bb686a" sha256 cellar: :any_skip_relocation, arm64_big_sur: "3e7e22286faf406a19de0982d6529582b02638a3b1586f1a62cd4ab75842ccba" sha256 cellar: :any_skip_relocation, monterey: "ae2339de2b93dc8c79ee30d6b872e4366dc0435e3cbba8316a4b646bb5fb5be5" sha256 cellar: :any_skip_relocation, big_sur: "6426b7f76b2589c7ff809fd08688cafc5992e1bdb9982a0d22fa91725b1b640c" sha256 cellar: :any_skip_relocation, catalina: "8fefe4a41cf07358f6d99b16217acde729c26d9847bdf92e6b858779bd42b094" sha256 cellar: :any_skip_relocation, x86_64_linux: "7786254fc9f2dcd94388ef31bb2068f9f22576f9d17ab67c60b3b51537400433" end depends_on "go" => :build def install system "scripts/install.sh", "v#{version}" bin.install "tfsec" end test do (testpath/"good/brew-validate.tf").write <<~EOS resource "aws_alb_listener" "my-alb-listener" { port = "443" protocol = "HTTPS" } EOS (testpath/"bad/brew-validate.tf").write <<~EOS resource "aws_security_group_rule" "world" { description = "A security group triggering tfsec AWS006." type = "ingress" cidr_blocks = ["0.0.0.0/0"] } EOS good_output = shell_output("#{bin}/tfsec #{testpath}/good") assert_match "No problems detected!", good_output bad_output = shell_output("#{bin}/tfsec #{testpath}/bad 2>&1", 1) assert_match "1 potential problems detected.", bad_output end end
class Tfsec < Formula desc "Static analysis powered security scanner for your terraform code" homepage "https://github.com/tfsec/tfsec" url "https://github.com/tfsec/tfsec/archive/v0.38.5.tar.gz" sha256 "b00f7135ed4d4cdc2c7a1b4abd92929a6aca74c6e7d3994499f9ece8d2f01f87" license "MIT" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "20529c26bbc31284830b732ec67b7651758a7777934d43b1bdc4dacc14e64ccc" sha256 cellar: :any_skip_relocation, big_sur: "edd789c52bd15229a798a5106d49cace01fe2f8f91c6100e1d7fc9200fc642ce" sha256 cellar: :any_skip_relocation, catalina: "e977e169ced7e9f3d51c72d03b25cfa1789a3c4a9c87c62924b2d39b6004fd68" sha256 cellar: :any_skip_relocation, mojave: "ea24b99c2530e0cff04a76da294c83a115c2235d8273d7ad0ae65f700f4f5037" end depends_on "go" => :build resource "testfile" do url "https://raw.githubusercontent.com/tfsec/tfsec/2d9b76a/example/brew-validate.tf" sha256 "3ef5c46e81e9f0b42578fd8ddce959145cd043f87fd621a12140e99681f1128a" end def install system "scripts/install.sh", "v#{version}" bin.install "tfsec" end test do resource("testfile").stage do assert_match "No problems detected!", shell_output("#{bin}/tfsec .") end end end tfsec: update 0.38.5 bottle. class Tfsec < Formula desc "Static analysis powered security scanner for your terraform code" homepage "https://github.com/tfsec/tfsec" url "https://github.com/tfsec/tfsec/archive/v0.38.5.tar.gz" sha256 "b00f7135ed4d4cdc2c7a1b4abd92929a6aca74c6e7d3994499f9ece8d2f01f87" license "MIT" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "c2d76a9d9e659e9fd82b180812c0d43b89f660758e1d4805d268063eea621e13" sha256 cellar: :any_skip_relocation, big_sur: "07115c8b22a51af5b756fb16c07cb8e378e6a32dfd295a444e66f4adf81b2f29" sha256 cellar: :any_skip_relocation, catalina: "c81446c95004f15ad87a0c7a756a00c7d4b29702959de792f8d6cac994071133" sha256 cellar: :any_skip_relocation, mojave: "2fe5cfcca6719169343848c95f5a09695de0a5bbdad98068107ff5630f6ad623" end depends_on "go" => :build resource "testfile" do url "https://raw.githubusercontent.com/tfsec/tfsec/2d9b76a/example/brew-validate.tf" sha256 "3ef5c46e81e9f0b42578fd8ddce959145cd043f87fd621a12140e99681f1128a" end def install system "scripts/install.sh", "v#{version}" bin.install "tfsec" end test do resource("testfile").stage do assert_match "No problems detected!", shell_output("#{bin}/tfsec .") end end end
module ApplicationHelper # The traditional "3 days ago" result isn't good enough. Examples of when you might like to know a commit happened: # 10 minutes ago # 10:15am # 1 hour ago (4:15pm) # Monday, 4:10pm # Last Monday (Dec 3rd), 4:10pm # Dec 24th, 2010 # TODO: currently appearing in UTC, that's no good. def as_commit_time(commit_time) now = Time.now relative = (now - commit_time).to_i timetoday = commit_time.strftime('%l:%M%p').downcase.strip day = commit_time.strftime("%A").strip date = "#{commit_time.strftime("%b").strip} #{commit_time.strftime("%e").strip}" # TODO: This could be nicer around midnight, but not important. if now.day == commit_time.day case relative when 0..59 then "#{relative.to_s} seconds ago" when 60..3599 then "#{(relative/60).to_i} minutes ago" when 1.hours..2.hours then "an hour ago (#{timetoday})" when 2.hours..5.hours then "#{(relative/3600).to_i} hours ago (#{timetoday})" else "#{timetoday}" end elsif now.day == commit_time.day+1 "Yesterday at #{timetoday}" elsif commit_time > 1.week.ago "#{day} at #{timetoday}" elsif 2.weeks.ago < commit_time && commit_time < 1.week.ago "Last #{day} (#{date}) at #{timetoday}" elsif now.year == commit_time.year "#{date} at #{timetoday}" else "#{date}, #{commit_time.year}" end end def as_length_of_build(start, stop) # TECHNICAL_DEBT: we should add stop_times for all builds, and then update the DB if stop == nil stop = Time.now end seconds = (stop - start).to_i minutes = (seconds / 60).to_i hours = (minutes / 60).to_i if hours > 0 "#{hours}h #{minutes % 60}m" elsif minutes > 0 "#{minutes}m #{seconds % 60}s" else "#{seconds}s" end end def revision_link(url, revision) return if url.nil? or revision.nil? # TECHNICAL_DEBT: github only link_to(revision[0..8], url + "/commit/" + revision) end def bootstrap_status(build) type = case build.status when :fail :important when :killed :warning when :success :success when :running :notice end "<span class='label #{type}'>#{ build.status }" end def as_action_timestamp(time) time.strftime("%T.%3N") end def trigger_project_button(project, options={}) name = options[:name] || "Trigger build" flash = options[:flash] || "Submitting..." twitter_bootstrap_form_for [project, Build.new], :remote => true do |f| f.submit name, :disable_with => flash end end def project_link_to(project) return unless project link_to project.github_project_name, github_project_path(project) end # TECHNICAL_DEBT: these shouldn't even exist, never mind being two separate functions. def build_link_to(build, project=nil) return if build.nil? || build.build_num.nil? project = project || build.the_project begin link = github_project_path(project) + "/" + build.build_num.to_s rescue return "" # new projects may have no builds available yet end # TECHNICAL_DEBT: kill this function - this puts the word build where it shouldnt be. link_to build.build_num.to_s, build_path(:project => build.project, :id => build.build_num) end def build_absolute_link_to(build, options={}) project = build.the_project begin text = options[:text] || build.build_num.to_s anchor = github_project_path(project) + "/" + build.build_num.to_s rescue return "" # new projects may have no builds available yet end link_to text, build_url(:project => project, :id => build.build_num.to_s) end end Handle empty start_time. module ApplicationHelper # The traditional "3 days ago" result isn't good enough. Examples of when you might like to know a commit happened: # 10 minutes ago # 10:15am # 1 hour ago (4:15pm) # Monday, 4:10pm # Last Monday (Dec 3rd), 4:10pm # Dec 24th, 2010 # TODO: currently appearing in UTC, that's no good. def as_commit_time(commit_time) return if commit_time.nil? now = Time.now relative = (now - commit_time).to_i timetoday = commit_time.strftime('%l:%M%p').downcase.strip day = commit_time.strftime("%A").strip date = "#{commit_time.strftime("%b").strip} #{commit_time.strftime("%e").strip}" # TODO: This could be nicer around midnight, but not important. if now.day == commit_time.day case relative when 0..59 then "#{relative.to_s} seconds ago" when 60..3599 then "#{(relative/60).to_i} minutes ago" when 1.hours..2.hours then "an hour ago (#{timetoday})" when 2.hours..5.hours then "#{(relative/3600).to_i} hours ago (#{timetoday})" else "#{timetoday}" end elsif now.day == commit_time.day+1 "Yesterday at #{timetoday}" elsif commit_time > 1.week.ago "#{day} at #{timetoday}" elsif 2.weeks.ago < commit_time && commit_time < 1.week.ago "Last #{day} (#{date}) at #{timetoday}" elsif now.year == commit_time.year "#{date} at #{timetoday}" else "#{date}, #{commit_time.year}" end end def as_length_of_build(start, stop) # TECHNICAL_DEBT: we should add stop_times for all builds, and then update the DB if stop == nil stop = Time.now end seconds = (stop - start).to_i minutes = (seconds / 60).to_i hours = (minutes / 60).to_i if hours > 0 "#{hours}h #{minutes % 60}m" elsif minutes > 0 "#{minutes}m #{seconds % 60}s" else "#{seconds}s" end end def revision_link(url, revision) return if url.nil? or revision.nil? # TECHNICAL_DEBT: github only link_to(revision[0..8], url + "/commit/" + revision) end def bootstrap_status(build) type = case build.status when :fail :important when :killed :warning when :success :success when :running :notice end "<span class='label #{type}'>#{ build.status }" end def as_action_timestamp(time) time.strftime("%T.%3N") end def trigger_project_button(project, options={}) name = options[:name] || "Trigger build" flash = options[:flash] || "Submitting..." twitter_bootstrap_form_for [project, Build.new], :remote => true do |f| f.submit name, :disable_with => flash end end def project_link_to(project) return unless project link_to project.github_project_name, github_project_path(project) end # TECHNICAL_DEBT: these shouldn't even exist, never mind being two separate functions. def build_link_to(build, project=nil) return if build.nil? || build.build_num.nil? project = project || build.the_project begin link = github_project_path(project) + "/" + build.build_num.to_s rescue return "" # new projects may have no builds available yet end # TECHNICAL_DEBT: kill this function - this puts the word build where it shouldnt be. link_to build.build_num.to_s, build_path(:project => build.project, :id => build.build_num) end def build_absolute_link_to(build, options={}) project = build.the_project begin text = options[:text] || build.build_num.to_s anchor = github_project_path(project) + "/" + build.build_num.to_s rescue return "" # new projects may have no builds available yet end link_to text, build_url(:project => project, :id => build.build_num.to_s) end end
class Tnote < Formula desc "Small note-taking program for the terminal" homepage "http://tnote.sourceforge.net/" url "https://downloads.sourceforge.net/project/tnote/tnote/tnote-0.2.1/tnote-0.2.1.tar.gz" sha256 "451e0e352cb279725c5e12ad1c1377be63c7113f3fe568fb6213ede478ba6a87" bottle do cellar :any_skip_relocation sha256 "63b2c1aea236fd24d2fa5c315bd0772b009d63018b9c18379a5e782f65debfea" => :el_capitan sha256 "de7e2e72f85a8c42133329f77d242aa0b8a6c9cb2edbb305d843a6e7be1ea3b0" => :yosemite sha256 "8e3a2baf4185b131e0223e6b0fe113890ace15b6a9c67b5f7a4068b3d767c4e6" => :mavericks end depends_on :python if MacOS.version <= :snow_leopard def install ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages" system "python", *Language::Python.setup_install_args(libexec) bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"]) man1.install Dir[libexec/"share/man/man1/*"] end test do ENV["EDITOR"] = "/bin/cat" system bin/"tnote", "--nocol", "-a", "test" end end tnote: update 0.2.1 bottle. class Tnote < Formula desc "Small note-taking program for the terminal" homepage "http://tnote.sourceforge.net/" url "https://downloads.sourceforge.net/project/tnote/tnote/tnote-0.2.1/tnote-0.2.1.tar.gz" sha256 "451e0e352cb279725c5e12ad1c1377be63c7113f3fe568fb6213ede478ba6a87" bottle do cellar :any_skip_relocation sha256 "6665cd2351aff6cf025483f711b9620667a2d32e275230cb80d5d790477c5e3f" => :sierra sha256 "63b2c1aea236fd24d2fa5c315bd0772b009d63018b9c18379a5e782f65debfea" => :el_capitan sha256 "de7e2e72f85a8c42133329f77d242aa0b8a6c9cb2edbb305d843a6e7be1ea3b0" => :yosemite sha256 "8e3a2baf4185b131e0223e6b0fe113890ace15b6a9c67b5f7a4068b3d767c4e6" => :mavericks end depends_on :python if MacOS.version <= :snow_leopard def install ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages" system "python", *Language::Python.setup_install_args(libexec) bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"]) man1.install Dir[libexec/"share/man/man1/*"] end test do ENV["EDITOR"] = "/bin/cat" system bin/"tnote", "--nocol", "-a", "test" end end
# frozen_string_literal: true module ApplicationHelper def related_media_card index, media, &block data = {} data["link"] = resource_path(media) classes = ["c-related-media-item"] if ![MediaContent::TYPE_VIDEO, MediaContent::TYPE_VIDEO_COLLECTION].include?(media.type) biggest = media.first_item.biggest_size picture_url = biggest.url classes << "-vertical" if biggest.is_vertical? styles = "background-image: url('#{biggest.url}')" else classes << "js-video-thumbnail" data["video-provider"] = media.video_provider data["video-id"] = media.video_id end content_tag :div, id: index, class: classes.join(" "), data: data, style: styles do yield end end def resource_users resource user_ids = [0] if resource.publications.any? resource.publications.each do |item| item.users.each do |user| user_ids.push(user.id) end end end if resource.activities.any? resource.activities.each do |item| item.users.each do |user| user_ids.push(user.id) end end end user_ids = user_ids.uniq User.where(id: user_ids).order_by_fullname end end Refactor the Media content users method # frozen_string_literal: true module ApplicationHelper def related_media_card index, media, &block data = {} data["link"] = resource_path(media) classes = ["c-related-media-item"] if ![MediaContent::TYPE_VIDEO, MediaContent::TYPE_VIDEO_COLLECTION].include?(media.type) biggest = media.first_item.biggest_size picture_url = biggest.url classes << "-vertical" if biggest.is_vertical? styles = "background-image: url('#{biggest.url}')" else classes << "js-video-thumbnail" data["video-provider"] = media.video_provider data["video-id"] = media.video_id end content_tag :div, id: index, class: classes.join(" "), data: data, style: styles do yield end end end
class Tokei < Formula desc "Program that allows you to count code, quickly" homepage "https://github.com/Aaronepower/tokei" url "https://github.com/Aaronepower/tokei/archive/v7.0.3.tar.gz" sha256 "47848921f7f04fdd1ef515b2db25b931f97471f4b178c7914b3646251bcd8086" bottle do rebuild 1 sha256 "573fad477decddf656f666848a3da572a8d903ff8b5352f712fb6535f52c83d2" => :high_sierra sha256 "fbc0cf15f958c8e4a5aeaf8b270aefbe97f2f2058e3c6a3dbc9b3268f032de38" => :sierra sha256 "ecb70caf0becbd065ebb3f23d8fa188e072c20b279f385e4bf118276eda53c12" => :el_capitan end depends_on "rust" => :build def install system "cargo", "install", "--root", prefix, "--features", "all" end test do (testpath/"lib.rs").write <<~EOS #[cfg(test)] mod tests { #[test] fn test() { println!("It works!"); } } EOS system bin/"tokei", "lib.rs" end end tokei: update 7.0.3 bottle for Linuxbrew. Closes Linuxbrew/homebrew-core#8854. Signed-off-by: Michka Popoff <7b0496f66f66ee22a38826c310c38b415671b832@gmail.com> class Tokei < Formula desc "Program that allows you to count code, quickly" homepage "https://github.com/Aaronepower/tokei" url "https://github.com/Aaronepower/tokei/archive/v7.0.3.tar.gz" sha256 "47848921f7f04fdd1ef515b2db25b931f97471f4b178c7914b3646251bcd8086" bottle do rebuild 1 sha256 "573fad477decddf656f666848a3da572a8d903ff8b5352f712fb6535f52c83d2" => :high_sierra sha256 "fbc0cf15f958c8e4a5aeaf8b270aefbe97f2f2058e3c6a3dbc9b3268f032de38" => :sierra sha256 "ecb70caf0becbd065ebb3f23d8fa188e072c20b279f385e4bf118276eda53c12" => :el_capitan sha256 "4e72893d655fd7595e40d477a675fd02e342df140b12eacd69911522983e6875" => :x86_64_linux end depends_on "rust" => :build def install system "cargo", "install", "--root", prefix, "--features", "all" end test do (testpath/"lib.rs").write <<~EOS #[cfg(test)] mod tests { #[test] fn test() { println!("It works!"); } } EOS system bin/"tokei", "lib.rs" end end
require "google_chart" module ApplicationHelper def protocol (Rails.env == "production" ? "https" : "http") + "://" end def page_title(title=nil) if title then @page_title = title else [h(@page_title), "NotreBudget.com"].reject(&:blank?).join(" &mdash; ") end end def body_classes [controller.controller_name, controller.action_name] * " " end def render_flash_messages %w(notice error).map do |key| next if flash[key.to_sym].blank? content_tag(:p, h(flash[key.to_sym]), :class => key) end.join("\n") end def calendar year, month, day = current_date.year, current_date.month, current_date.day first_of_month = Date.new(year, month, 1) first_sunday = first_of_month - first_of_month.wday last_of_month = Date.new(year, month, 1) >> 1 last_saturday = last_of_month + (6 - last_of_month.wday) returning([]) do |buffer| buffer << %q(<table cellspacing="0" cellpadding="0">) buffer << %Q(<caption>#{month_name(month)} #{year}</caption>) buffer << %q(<thead>) buffer << %q(<tr>) %w(Dim Lun Mar Mer Jeu Ven Sam).each do |dayname| buffer << %q(<th>) buffer << dayname buffer << %q(</th>) end buffer << %q(</tr>) buffer << %q(</thead>) buffer << %q(<tbody>) (first_sunday .. last_saturday).step(7) do |week| buffer << %q(<tr>) (week ... (week+7)).each do |date| classes = [] classes << "today" if date == current_date classes << "outside" if date.month != month buffer << content_tag(:td, content_tag(:a, date.day, :href => "#"), :id => "date_#{date}", :class => classes.join(" ")) end buffer << %q(</tr>) end buffer << %q(</tbody>) buffer << %q(</table>) end.join("\n") end DAY_NAMES = %w(dimanche lundi mardi mercredi jeudi vendredi samedi) def render_current_date "#{DAY_NAMES[current_date.wday]} le #{current_date.day}" end MONTH_NAMES = %w(Janvier FΓ©vrier Mars Avril Mai Juin Juillet AoΓ»t September Octobre Novembre DΓ©cembre) def month_name(month) MONTH_NAMES[month - 1] end def amount(value, default="") value && value.nonzero? ? "%0.2f"%value : default end def when_logged_in?(&block) return nil unless logged_in? concat(capture(&block), block.binding) end def when_not_logged_in?(&block) return nil if logged_in? concat(capture(&block), block.binding) end def jquery_files if Rails.env == "development" then ["jquery.js", "jquery-ui.js"] else ["jquery.min.js", "jquery-ui.min.js"] end end FRENCH_DAY_NAMES = %w(Dim Lun Mar Mer Jeu Ven Sam) FRENCH_MONTH_NAMES = %w(Jan FΓ©v Mar Avr Mai Jui Jui AoΓ» Sep Oct Nov Dec) def i18n_date(date) "%s %d" % [FRENCH_DAY_NAMES[date.wday], date.day] end def format_money(amount) "%.2f" % amount end def pie_chart(data, options={}) options.reverse_merge!(:size => "320x200", :title => "Pie Chart") GoogleChart::PieChart.new(options[:size], options[:title], false) do |pc| data.each do |line| pc.data line.first, line.last.to_f end return image_tag(pc.to_url(options[:extras] || {}), :size => options[:size]) end end def line_chart(data, options={}) options.reverse_merge!(:size => "320x200", :title => "Pie Chart") GoogleChart::LineChart.new(options[:size], options[:title]) do |lc| data.each do |label, (points, color)| lc.data label, points, color end labels = dates_for_period.map {|d| d.strftime("%b")} lc.axis :x, :labels => labels lc.axis :y, :range => [0, data.map(&:last).map(&:first).flatten.compact.max] return image_tag(lc.to_url(options[:extras] || {}), :size => options[:size]) end end def account_spending_history(account, dates) period = (dates.sort.first .. (dates.sort.last >> 1)) debits = current_family.transfers.in_debit_accounts(account).within_period(period).group_amounts_by_period.all debits = debits.index_by {|dt| Date.parse(dt.period)} credits = current_family.transfers.in_credit_accounts(account).within_period(period).group_amounts_by_period.all credits = credits.index_by {|dt| Date.parse(dt.period)} real_amounts = dates.inject([]) do |memo, date| debit_amount = debits[date] credit_amount = credits[date] debit_amount = debit_amount.amount if debit_amount credit_amount = credit_amount.amount if credit_amount debit_amount = 0 unless debit_amount credit_amount = 0 unless credit_amount memo << @account.normalize_amount(debit_amount, credit_amount) end budget_amounts = dates.inject([]) do |memo, date| memo << current_family.budgets.find_or_initialize_by_account_id_and_starting_on(account.id, date).amount end GoogleChart::BarChart.new("600x200", "DΓ©penses rΓ©elles pour #{h(account.name)}") do |lc| lc.data "BudgΓ©tΓ©", budget_amounts, "cc9999" lc.data "RΓ©el", real_amounts, "9999cc" lc.axis :x, :labels => dates.map {|d| d.strftime("%b")} lc.axis :y, :range => [0, (debits.to_a + credits.to_a).map(&:last).map(&:amount).max] return image_tag(lc.to_url(:chbh => "16,2,8"), :size => "600x200") end end end Changed bar chart title require "google_chart" module ApplicationHelper def protocol (Rails.env == "production" ? "https" : "http") + "://" end def page_title(title=nil) if title then @page_title = title else [h(@page_title), "NotreBudget.com"].reject(&:blank?).join(" &mdash; ") end end def body_classes [controller.controller_name, controller.action_name] * " " end def render_flash_messages %w(notice error).map do |key| next if flash[key.to_sym].blank? content_tag(:p, h(flash[key.to_sym]), :class => key) end.join("\n") end def calendar year, month, day = current_date.year, current_date.month, current_date.day first_of_month = Date.new(year, month, 1) first_sunday = first_of_month - first_of_month.wday last_of_month = Date.new(year, month, 1) >> 1 last_saturday = last_of_month + (6 - last_of_month.wday) returning([]) do |buffer| buffer << %q(<table cellspacing="0" cellpadding="0">) buffer << %Q(<caption>#{month_name(month)} #{year}</caption>) buffer << %q(<thead>) buffer << %q(<tr>) %w(Dim Lun Mar Mer Jeu Ven Sam).each do |dayname| buffer << %q(<th>) buffer << dayname buffer << %q(</th>) end buffer << %q(</tr>) buffer << %q(</thead>) buffer << %q(<tbody>) (first_sunday .. last_saturday).step(7) do |week| buffer << %q(<tr>) (week ... (week+7)).each do |date| classes = [] classes << "today" if date == current_date classes << "outside" if date.month != month buffer << content_tag(:td, content_tag(:a, date.day, :href => "#"), :id => "date_#{date}", :class => classes.join(" ")) end buffer << %q(</tr>) end buffer << %q(</tbody>) buffer << %q(</table>) end.join("\n") end DAY_NAMES = %w(dimanche lundi mardi mercredi jeudi vendredi samedi) def render_current_date "#{DAY_NAMES[current_date.wday]} le #{current_date.day}" end MONTH_NAMES = %w(Janvier FΓ©vrier Mars Avril Mai Juin Juillet AoΓ»t September Octobre Novembre DΓ©cembre) def month_name(month) MONTH_NAMES[month - 1] end def amount(value, default="") value && value.nonzero? ? "%0.2f"%value : default end def when_logged_in?(&block) return nil unless logged_in? concat(capture(&block), block.binding) end def when_not_logged_in?(&block) return nil if logged_in? concat(capture(&block), block.binding) end def jquery_files if Rails.env == "development" then ["jquery.js", "jquery-ui.js"] else ["jquery.min.js", "jquery-ui.min.js"] end end FRENCH_DAY_NAMES = %w(Dim Lun Mar Mer Jeu Ven Sam) FRENCH_MONTH_NAMES = %w(Jan FΓ©v Mar Avr Mai Jui Jui AoΓ» Sep Oct Nov Dec) def i18n_date(date) "%s %d" % [FRENCH_DAY_NAMES[date.wday], date.day] end def format_money(amount) "%.2f" % amount end def pie_chart(data, options={}) options.reverse_merge!(:size => "320x200", :title => "Pie Chart") GoogleChart::PieChart.new(options[:size], options[:title], false) do |pc| data.each do |line| pc.data line.first, line.last.to_f end return image_tag(pc.to_url(options[:extras] || {}), :size => options[:size]) end end def line_chart(data, options={}) options.reverse_merge!(:size => "320x200", :title => "Pie Chart") GoogleChart::LineChart.new(options[:size], options[:title]) do |lc| data.each do |label, (points, color)| lc.data label, points, color end labels = dates_for_period.map {|d| d.strftime("%b")} lc.axis :x, :labels => labels lc.axis :y, :range => [0, data.map(&:last).map(&:first).flatten.compact.max] return image_tag(lc.to_url(options[:extras] || {}), :size => options[:size]) end end def account_spending_history(account, dates) period = (dates.sort.first .. (dates.sort.last >> 1)) debits = current_family.transfers.in_debit_accounts(account).within_period(period).group_amounts_by_period.all debits = debits.index_by {|dt| Date.parse(dt.period)} credits = current_family.transfers.in_credit_accounts(account).within_period(period).group_amounts_by_period.all credits = credits.index_by {|dt| Date.parse(dt.period)} real_amounts = dates.inject([]) do |memo, date| debit_amount = debits[date] credit_amount = credits[date] debit_amount = debit_amount.amount if debit_amount credit_amount = credit_amount.amount if credit_amount debit_amount = 0 unless debit_amount credit_amount = 0 unless credit_amount memo << @account.normalize_amount(debit_amount, credit_amount) end budget_amounts = dates.inject([]) do |memo, date| memo << current_family.budgets.find_or_initialize_by_account_id_and_starting_on(account.id, date).amount end GoogleChart::BarChart.new("600x200", "BudgΓ©tΓ© vs RΓ©el pour #{h(account.name)}") do |lc| lc.data "BudgΓ©tΓ©", budget_amounts, "cc9999" lc.data "RΓ©el", real_amounts, "9999cc" lc.axis :x, :labels => dates.map {|d| d.strftime("%b")} lc.axis :y, :range => [0, (debits.to_a + credits.to_a).map(&:last).map(&:amount).max] return image_tag(lc.to_url(:chbh => "16,2,8"), :size => "600x200") end end end
class Tokei < Formula desc "Program that allows you to count code, quickly." homepage "https://github.com/Aaronepower/tokei" url "https://github.com/Aaronepower/tokei/archive/v6.1.2.tar.gz" sha256 "736bab89800c397acc3be961af12b80acc2ca71dc990792fff8935018a2f0698" bottle do sha256 "9ec430a5d41ffd3dea4001842c269193190adcc4968cb405754a65cb5bd5e955" => :sierra sha256 "9e3ec9a5dd0aaf6289871c9fcdcd37139349871e95931b6febe306e5388b932e" => :el_capitan sha256 "4747f489aaa9701939e7c25039b1137c2c53fcc19358e47c80c1717aa9ddde42" => :yosemite end depends_on "rust" => :build def install system "cargo", "build", "--release" bin.install "target/release/tokei" end test do (testpath/"lib.rs").write <<-EOS.undent #[cfg(test)] mod tests { #[test] fn test() { println!("It works!"); } } EOS system bin/"tokei", "lib.rs" end end tokei: update 6.1.2 bottle. class Tokei < Formula desc "Program that allows you to count code, quickly." homepage "https://github.com/Aaronepower/tokei" url "https://github.com/Aaronepower/tokei/archive/v6.1.2.tar.gz" sha256 "736bab89800c397acc3be961af12b80acc2ca71dc990792fff8935018a2f0698" bottle do sha256 "53ccc42b89ad19fad28ce1e043d5776f10ea32d8aad6d2810198612d2ff64c69" => :high_sierra sha256 "9ec430a5d41ffd3dea4001842c269193190adcc4968cb405754a65cb5bd5e955" => :sierra sha256 "9e3ec9a5dd0aaf6289871c9fcdcd37139349871e95931b6febe306e5388b932e" => :el_capitan sha256 "4747f489aaa9701939e7c25039b1137c2c53fcc19358e47c80c1717aa9ddde42" => :yosemite end depends_on "rust" => :build def install system "cargo", "build", "--release" bin.install "target/release/tokei" end test do (testpath/"lib.rs").write <<-EOS.undent #[cfg(test)] mod tests { #[test] fn test() { println!("It works!"); } } EOS system bin/"tokei", "lib.rs" end end
require 'digest/md5' require 'uri' module ApplicationHelper COLOR_SCHEMES = { 1 => 'white', 2 => 'dark', 3 => 'solarized-light', 4 => 'solarized-dark', 5 => 'monokai', } COLOR_SCHEMES.default = 'white' # Helper method to access the COLOR_SCHEMES # # The keys are the `color_scheme_ids` # The values are the `name` of the scheme. # # The preview images are `name-scheme-preview.png` # The stylesheets should use the css class `.name` def color_schemes COLOR_SCHEMES.freeze end # Check if a particular controller is the current one # # args - One or more controller names to check # # Examples # # # On TreeController # current_controller?(:tree) # => true # current_controller?(:commits) # => false # current_controller?(:commits, :tree) # => true def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end # Check if a particular action is the current one # # args - One or more action names to check # # Examples # # # On Projects#new # current_action?(:new) # => true # current_action?(:create) # => false # current_action?(:new, :create) # => true def current_action?(*args) args.any? { |v| v.to_s.downcase == action_name } end def project_icon(project_id, options = {}) project = if project_id.is_a?(Project) project = project_id else Project.find_with_namespace(project_id) end if project.avatar_url image_tag project.avatar_url, options else # generated icon project_identicon(project, options) end end def project_identicon(project, options = {}) allowed_colors = { red: 'FFEBEE', purple: 'F3E5F5', indigo: 'E8EAF6', blue: 'E3F2FD', teal: 'E0F2F1', orange: 'FBE9E7', gray: 'EEEEEE' } options[:class] ||= '' options[:class] << ' identicon' bg_key = project.id % 7 style = "background-color: ##{ allowed_colors.values[bg_key] }; color: #555" content_tag(:div, class: options[:class], style: style) do project.name[0, 1].upcase end end def avatar_icon(user_email = '', size = nil) user = User.find_by(email: user_email) if user user.avatar_url(size) || default_avatar else gravatar_icon(user_email, size) end end def gravatar_icon(user_email = '', size = nil) GravatarService.new.execute(user_email, size) || default_avatar end def default_avatar image_path('no_avatar.png') end def last_commit(project) if project.repo_exists? time_ago_with_tooltip(project.repository.commit.committed_date) else 'Never' end rescue 'Never' end def grouped_options_refs repository = @project.repository options = [ ['Branches', repository.branch_names], ['Tags', VersionSorter.rsort(repository.tag_names)] ] # If reference is commit id - we should add it to branch/tag selectbox if(@ref && !options.flatten.include?(@ref) && @ref =~ /\A[0-9a-zA-Z]{6,52}\z/) options << ['Commit', [@ref]] end grouped_options_for_select(options, @ref || @project.default_branch) end def emoji_autocomplete_source # should be an array of strings # so to_s can be called, because it is sufficient and to_json is too slow Emoji.names.to_s end def app_theme Gitlab::Theme.css_class_by_id(current_user.try(:theme_id)) end def theme_type Gitlab::Theme.type_css_class_by_id(current_user.try(:theme_id)) end def user_color_scheme_class COLOR_SCHEMES[current_user.try(:color_scheme_id)] if defined?(current_user) end # Define whenever show last push event # with suggestion to create MR def show_last_push_widget?(event) # Skip if event is not about added or modified non-master branch return false unless event && event.last_push_to_non_root? && !event.rm_ref? project = event.project # Skip if project repo is empty or MR disabled return false unless project && !project.empty_repo? && project.merge_requests_enabled # Skip if user already created appropriate MR return false if project.merge_requests.where(source_branch: event.branch_name).opened.any? # Skip if user removed branch right after that return false unless project.repository.branch_names.include?(event.branch_name) true end def hexdigest(string) Digest::SHA1.hexdigest string end def simple_sanitize(str) sanitize(str, tags: %w(a span)) end def body_data_page path = controller.controller_path.split('/') namespace = path.first if path.second [namespace, controller.controller_name, controller.action_name].compact.join(':') end # shortcut for gitlab config def gitlab_config Gitlab.config.gitlab end # shortcut for gitlab extra config def extra_config Gitlab.config.extra end def search_placeholder if @project && @project.persisted? 'Search in this project' elsif @snippet || @snippets || @show_snippets 'Search snippets' elsif @group && @group.persisted? 'Search in this group' else 'Search' end end def broadcast_message BroadcastMessage.current end def time_ago_with_tooltip(date, placement = 'top', html_class = 'time_ago') capture_haml do haml_tag :time, date.to_s, class: html_class, datetime: date.getutc.iso8601, title: date.stamp('Aug 21, 2011 9:23pm'), data: { toggle: 'tooltip', placement: placement } haml_tag :script, "$('." + html_class + "').timeago().tooltip()" end.html_safe end def render_markup(file_name, file_content) GitHub::Markup.render(file_name, file_content). force_encoding(file_content.encoding).html_safe rescue RuntimeError simple_format(file_content) end def markup?(filename) Gitlab::MarkdownHelper.markup?(filename) end def gitlab_markdown?(filename) Gitlab::MarkdownHelper.gitlab_markdown?(filename) end # Overrides ActionView::Helpers::UrlHelper#link_to to add `rel="nofollow"` to # external links def link_to(name = nil, options = nil, html_options = {}) if options.kind_of?(String) if options[0] != '/' && options[0] != '#' html_options = add_nofollow(options, html_options) end end super end # Add `"rel=nofollow"` to external links # # link - String link to check # html_options - Hash of `html_options` passed to `link_to` # # Returns `html_options`, adding `rel: nofollow` for external links def add_nofollow(link, html_options = {}) uri = URI(link) if uri && uri.absolute? && uri.host != Gitlab.config.gitlab.host rel = html_options.fetch(:rel, '') html_options[:rel] = (rel + ' nofollow').strip end html_options end def escaped_autolink(text) auto_link ERB::Util.html_escape(text), link: :urls end def promo_host 'about.gitlab.com' end def promo_url 'https://' + promo_host end def page_filter_path(options = {}) without = options.delete(:without) exist_opts = { state: params[:state], scope: params[:scope], label_name: params[:label_name], milestone_id: params[:milestone_id], assignee_id: params[:assignee_id], author_id: params[:author_id], sort: params[:sort], } options = exist_opts.merge(options) if without.present? without.each do |key| options.delete(key) end end path = request.path path << "?#{options.to_param}" path end def outdated_browser? browser.ie? && browser.version.to_i < 10 end def path_to_key(key, admin = false) if admin admin_user_key_path(@user, key) else profile_key_path(key) end end def nav_sidebar_class if nav_menu_collapsed? "page-sidebar-collapsed" else "page-sidebar-expanded" end end end Use `start_with?` instead of String slicing to check for external links [ci skip] require 'digest/md5' require 'uri' module ApplicationHelper COLOR_SCHEMES = { 1 => 'white', 2 => 'dark', 3 => 'solarized-light', 4 => 'solarized-dark', 5 => 'monokai', } COLOR_SCHEMES.default = 'white' # Helper method to access the COLOR_SCHEMES # # The keys are the `color_scheme_ids` # The values are the `name` of the scheme. # # The preview images are `name-scheme-preview.png` # The stylesheets should use the css class `.name` def color_schemes COLOR_SCHEMES.freeze end # Check if a particular controller is the current one # # args - One or more controller names to check # # Examples # # # On TreeController # current_controller?(:tree) # => true # current_controller?(:commits) # => false # current_controller?(:commits, :tree) # => true def current_controller?(*args) args.any? { |v| v.to_s.downcase == controller.controller_name } end # Check if a particular action is the current one # # args - One or more action names to check # # Examples # # # On Projects#new # current_action?(:new) # => true # current_action?(:create) # => false # current_action?(:new, :create) # => true def current_action?(*args) args.any? { |v| v.to_s.downcase == action_name } end def project_icon(project_id, options = {}) project = if project_id.is_a?(Project) project = project_id else Project.find_with_namespace(project_id) end if project.avatar_url image_tag project.avatar_url, options else # generated icon project_identicon(project, options) end end def project_identicon(project, options = {}) allowed_colors = { red: 'FFEBEE', purple: 'F3E5F5', indigo: 'E8EAF6', blue: 'E3F2FD', teal: 'E0F2F1', orange: 'FBE9E7', gray: 'EEEEEE' } options[:class] ||= '' options[:class] << ' identicon' bg_key = project.id % 7 style = "background-color: ##{ allowed_colors.values[bg_key] }; color: #555" content_tag(:div, class: options[:class], style: style) do project.name[0, 1].upcase end end def avatar_icon(user_email = '', size = nil) user = User.find_by(email: user_email) if user user.avatar_url(size) || default_avatar else gravatar_icon(user_email, size) end end def gravatar_icon(user_email = '', size = nil) GravatarService.new.execute(user_email, size) || default_avatar end def default_avatar image_path('no_avatar.png') end def last_commit(project) if project.repo_exists? time_ago_with_tooltip(project.repository.commit.committed_date) else 'Never' end rescue 'Never' end def grouped_options_refs repository = @project.repository options = [ ['Branches', repository.branch_names], ['Tags', VersionSorter.rsort(repository.tag_names)] ] # If reference is commit id - we should add it to branch/tag selectbox if(@ref && !options.flatten.include?(@ref) && @ref =~ /\A[0-9a-zA-Z]{6,52}\z/) options << ['Commit', [@ref]] end grouped_options_for_select(options, @ref || @project.default_branch) end def emoji_autocomplete_source # should be an array of strings # so to_s can be called, because it is sufficient and to_json is too slow Emoji.names.to_s end def app_theme Gitlab::Theme.css_class_by_id(current_user.try(:theme_id)) end def theme_type Gitlab::Theme.type_css_class_by_id(current_user.try(:theme_id)) end def user_color_scheme_class COLOR_SCHEMES[current_user.try(:color_scheme_id)] if defined?(current_user) end # Define whenever show last push event # with suggestion to create MR def show_last_push_widget?(event) # Skip if event is not about added or modified non-master branch return false unless event && event.last_push_to_non_root? && !event.rm_ref? project = event.project # Skip if project repo is empty or MR disabled return false unless project && !project.empty_repo? && project.merge_requests_enabled # Skip if user already created appropriate MR return false if project.merge_requests.where(source_branch: event.branch_name).opened.any? # Skip if user removed branch right after that return false unless project.repository.branch_names.include?(event.branch_name) true end def hexdigest(string) Digest::SHA1.hexdigest string end def simple_sanitize(str) sanitize(str, tags: %w(a span)) end def body_data_page path = controller.controller_path.split('/') namespace = path.first if path.second [namespace, controller.controller_name, controller.action_name].compact.join(':') end # shortcut for gitlab config def gitlab_config Gitlab.config.gitlab end # shortcut for gitlab extra config def extra_config Gitlab.config.extra end def search_placeholder if @project && @project.persisted? 'Search in this project' elsif @snippet || @snippets || @show_snippets 'Search snippets' elsif @group && @group.persisted? 'Search in this group' else 'Search' end end def broadcast_message BroadcastMessage.current end def time_ago_with_tooltip(date, placement = 'top', html_class = 'time_ago') capture_haml do haml_tag :time, date.to_s, class: html_class, datetime: date.getutc.iso8601, title: date.stamp('Aug 21, 2011 9:23pm'), data: { toggle: 'tooltip', placement: placement } haml_tag :script, "$('." + html_class + "').timeago().tooltip()" end.html_safe end def render_markup(file_name, file_content) GitHub::Markup.render(file_name, file_content). force_encoding(file_content.encoding).html_safe rescue RuntimeError simple_format(file_content) end def markup?(filename) Gitlab::MarkdownHelper.markup?(filename) end def gitlab_markdown?(filename) Gitlab::MarkdownHelper.gitlab_markdown?(filename) end # Overrides ActionView::Helpers::UrlHelper#link_to to add `rel="nofollow"` to # external links def link_to(name = nil, options = nil, html_options = {}) if options.kind_of?(String) if !options.start_with?('#', '/') html_options = add_nofollow(options, html_options) end end super end # Add `"rel=nofollow"` to external links # # link - String link to check # html_options - Hash of `html_options` passed to `link_to` # # Returns `html_options`, adding `rel: nofollow` for external links def add_nofollow(link, html_options = {}) uri = URI(link) if uri && uri.absolute? && uri.host != Gitlab.config.gitlab.host rel = html_options.fetch(:rel, '') html_options[:rel] = (rel + ' nofollow').strip end html_options end def escaped_autolink(text) auto_link ERB::Util.html_escape(text), link: :urls end def promo_host 'about.gitlab.com' end def promo_url 'https://' + promo_host end def page_filter_path(options = {}) without = options.delete(:without) exist_opts = { state: params[:state], scope: params[:scope], label_name: params[:label_name], milestone_id: params[:milestone_id], assignee_id: params[:assignee_id], author_id: params[:author_id], sort: params[:sort], } options = exist_opts.merge(options) if without.present? without.each do |key| options.delete(key) end end path = request.path path << "?#{options.to_param}" path end def outdated_browser? browser.ie? && browser.version.to_i < 10 end def path_to_key(key, admin = false) if admin admin_user_key_path(@user, key) else profile_key_path(key) end end def nav_sidebar_class if nav_menu_collapsed? "page-sidebar-collapsed" else "page-sidebar-expanded" end end end
class Trino < Formula include Language::Python::Shebang desc "Distributed SQL query engine for big data" homepage "https://trino.io" url "https://search.maven.org/remotecontent?filepath=io/trino/trino-server/400/trino-server-400.tar.gz", using: :nounzip sha256 "3846515697f910c66f958bb7699a656bd5085fbbbddaff7c3f45b1597c6d7cba" license "Apache-2.0" livecheck do url "https://search.maven.org/remotecontent?filepath=io/trino/trino-server/" regex(%r{href=["']?v?(\d+(?:\.\d+)*)/?["' >]}i) end bottle do sha256 cellar: :any_skip_relocation, all: "2f4f7c7fb11acb58d36f2d18c45648fe32010ec771fccf8833e7cbfc99d50888" end depends_on "gnu-tar" => :build depends_on "openjdk" depends_on "python@3.10" resource "trino-src" do url "https://github.com/trinodb/trino/archive/refs/tags/400.tar.gz", using: :nounzip sha256 "d7bef0a1119805948e82d39bfbdd454a934a5d23a5064587d8efc5dc2d7e01d3" end resource "trino-cli" do url "https://search.maven.org/remotecontent?filepath=io/trino/trino-cli/400/trino-cli-400-executable.jar" sha256 "7b0188c8aae221c7931f0247a2781167a7ca38cddbaf464c1caf0276bcec087a" end def install # Manually extract tarball to avoid losing hardlinks which increases bottle # size from MBs to GBs. Remove once Homebrew is able to preserve hardlinks. # Ref: https://github.com/Homebrew/brew/pull/13154 libexec.mkpath system "tar", "-C", libexec.to_s, "--strip-components", "1", "-xzf", "trino-server-#{version}.tar.gz" # Manually untar, since macOS-bundled tar produces the error: # trino-363/plugin/trino-hive/src/test/resources/<truncated>.snappy.orc.crc: Failed to restore metadata # Remove when https://github.com/trinodb/trino/issues/8877 is fixed resource("trino-src").stage do |r| ENV.prepend_path "PATH", Formula["gnu-tar"].opt_libexec/"gnubin" system "tar", "-xzf", "trino-#{r.version}.tar.gz" (libexec/"etc").install Dir["trino-#{r.version}/core/docker/default/etc/*"] inreplace libexec/"etc/node.properties", "docker", tap.user.downcase inreplace libexec/"etc/node.properties", "/data/trino", var/"trino/data" inreplace libexec/"etc/jvm.config", %r{^-agentpath:/usr/lib/trino/bin/libjvmkill.so$\n}, "" end rewrite_shebang detected_python_shebang, libexec/"bin/launcher.py" (bin/"trino-server").write_env_script libexec/"bin/launcher", Language::Java.overridable_java_home_env resource("trino-cli").stage do libexec.install "trino-cli-#{version}-executable.jar" bin.write_jar_script libexec/"trino-cli-#{version}-executable.jar", "trino" end # Remove incompatible pre-built binaries libprocname_dirs = libexec.glob("bin/procname/*") # Keep the Linux-x86_64 directory to make bottles identical libprocname_dirs.reject! { |dir| dir.basename.to_s == "Linux-x86_64" } if build.bottle? libprocname_dirs.reject! { |dir| dir.basename.to_s == "#{OS.kernel_name}-#{Hardware::CPU.arch}" } libprocname_dirs.map(&:rmtree) end def post_install (var/"trino/data").mkpath end service do run [opt_bin/"trino-server", "run"] working_dir opt_libexec end test do port = free_port cp libexec/"etc/config.properties", testpath/"config.properties" inreplace testpath/"config.properties", "8080", port.to_s server = fork do exec bin/"trino-server", "run", "--verbose", "--data-dir", testpath, "--config", testpath/"config.properties" end sleep 30 query = "SELECT state FROM system.runtime.nodes" output = shell_output(bin/"trino --debug --server localhost:#{port} --execute '#{query}'") assert_match "\"active\"", output ensure Process.kill("TERM", server) Process.wait server end end trino: update 400 bottle. class Trino < Formula include Language::Python::Shebang desc "Distributed SQL query engine for big data" homepage "https://trino.io" url "https://search.maven.org/remotecontent?filepath=io/trino/trino-server/400/trino-server-400.tar.gz", using: :nounzip sha256 "3846515697f910c66f958bb7699a656bd5085fbbbddaff7c3f45b1597c6d7cba" license "Apache-2.0" livecheck do url "https://search.maven.org/remotecontent?filepath=io/trino/trino-server/" regex(%r{href=["']?v?(\d+(?:\.\d+)*)/?["' >]}i) end bottle do sha256 cellar: :any_skip_relocation, all: "fd49875b814971b71c80d6b7a77ee662fafd4b14976a4ccf70810cca9c823f73" end depends_on "gnu-tar" => :build depends_on "openjdk" depends_on "python@3.10" resource "trino-src" do url "https://github.com/trinodb/trino/archive/refs/tags/400.tar.gz", using: :nounzip sha256 "d7bef0a1119805948e82d39bfbdd454a934a5d23a5064587d8efc5dc2d7e01d3" end resource "trino-cli" do url "https://search.maven.org/remotecontent?filepath=io/trino/trino-cli/400/trino-cli-400-executable.jar" sha256 "7b0188c8aae221c7931f0247a2781167a7ca38cddbaf464c1caf0276bcec087a" end def install # Manually extract tarball to avoid losing hardlinks which increases bottle # size from MBs to GBs. Remove once Homebrew is able to preserve hardlinks. # Ref: https://github.com/Homebrew/brew/pull/13154 libexec.mkpath system "tar", "-C", libexec.to_s, "--strip-components", "1", "-xzf", "trino-server-#{version}.tar.gz" # Manually untar, since macOS-bundled tar produces the error: # trino-363/plugin/trino-hive/src/test/resources/<truncated>.snappy.orc.crc: Failed to restore metadata # Remove when https://github.com/trinodb/trino/issues/8877 is fixed resource("trino-src").stage do |r| ENV.prepend_path "PATH", Formula["gnu-tar"].opt_libexec/"gnubin" system "tar", "-xzf", "trino-#{r.version}.tar.gz" (libexec/"etc").install Dir["trino-#{r.version}/core/docker/default/etc/*"] inreplace libexec/"etc/node.properties", "docker", tap.user.downcase inreplace libexec/"etc/node.properties", "/data/trino", var/"trino/data" inreplace libexec/"etc/jvm.config", %r{^-agentpath:/usr/lib/trino/bin/libjvmkill.so$\n}, "" end rewrite_shebang detected_python_shebang, libexec/"bin/launcher.py" (bin/"trino-server").write_env_script libexec/"bin/launcher", Language::Java.overridable_java_home_env resource("trino-cli").stage do libexec.install "trino-cli-#{version}-executable.jar" bin.write_jar_script libexec/"trino-cli-#{version}-executable.jar", "trino" end # Remove incompatible pre-built binaries libprocname_dirs = libexec.glob("bin/procname/*") # Keep the Linux-x86_64 directory to make bottles identical libprocname_dirs.reject! { |dir| dir.basename.to_s == "Linux-x86_64" } if build.bottle? libprocname_dirs.reject! { |dir| dir.basename.to_s == "#{OS.kernel_name}-#{Hardware::CPU.arch}" } libprocname_dirs.map(&:rmtree) end def post_install (var/"trino/data").mkpath end service do run [opt_bin/"trino-server", "run"] working_dir opt_libexec end test do port = free_port cp libexec/"etc/config.properties", testpath/"config.properties" inreplace testpath/"config.properties", "8080", port.to_s server = fork do exec bin/"trino-server", "run", "--verbose", "--data-dir", testpath, "--config", testpath/"config.properties" end sleep 30 query = "SELECT state FROM system.runtime.nodes" output = shell_output(bin/"trino --debug --server localhost:#{port} --execute '#{query}'") assert_match "\"active\"", output ensure Process.kill("TERM", server) Process.wait server end end
# # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # # Methods added to this helper will be available to all templates in the application. module ApplicationHelper include TextHelper # Admins of the given context can see the User.name attribute, # but everyone else sees the User.short_name attribute. def context_user_name(context, user, last_name_first=false) return nil unless user return user.short_name if !context && user.respond_to?(:short_name) context_code = context context_code = context.asset_string if context.respond_to?(:asset_string) context_code ||= "no_context" user_id = user user_id = user.id if user.is_a?(User) || user.is_a?(OpenObject) Rails.cache.fetch(['context_user_name', context_code, user_id, last_name_first].cache_key, {:expires_in=>15.minutes}) do user = User.find_by_id(user_id) res = user.short_name || user.name res end end def keyboard_navigation(keys) content = "<ul class='navigation_list' tabindex='-1'>\n" keys.each do |hash| content += " <li>\n" content += " <span class='keycode'>#{hash[:key]}</span>\n" content += " <span class='colon'>:</span>\n" content += " <span class='description'>#{hash[:description]}</span>\n" content += " </li>\n" end content += "</ul>" content_for(:keyboard_navigation) { content } end def context_prefix(code) return "/{{ context_type_pluralized }}/{{ context_id }}" unless code split = code.split(/_/) id = split.pop type = split.join('_') "/#{type.pluralize}/#{id}" end def cached_context_short_name(code) return nil unless code @cached_context_names ||= {} @cached_context_names[code] ||= Rails.cache.fetch(['short_name_lookup', code].cache_key) do Context.find_by_asset_string(code).short_name rescue "" end end def css_size(val) res = val.to_f res = nil if res == 0 res = (res + 10).to_s + "px" if res && res.to_s == val res end def user_content(str, context_code, asset_string) str ||= "" return raw(str) unless str.match(/object|embed/) raise "context_code and asset_string required" if !str.blank? && (!context_code || !asset_string) return str if !context_code || !asset_string html = Nokogiri::HTML::DocumentFragment.parse(str) html.css('object,embed').each_with_index do |obj, idx| styles = {} params = {} obj.css('param').each do |param| params[param['key']] = param['value'] end (obj['style'] || '').split(/\;/).each do |attr| key, value = attr.split(/\:/).map(&:strip) styles[key] = value end width = css_size(obj['width']) width ||= css_size(params['width']) width ||= css_size(styles['width']) width ||= '400px' height = css_size(obj['height']) height ||= css_size(params['height']) height ||= css_size(styles['height']) height ||= '300px' url = "http://#{HostUrl.file_host(@domain_root_account || Account.default)}" ts, sig = @current_user && @current_user.access_verifier url += "/object_snippet/#{context_code}/#{asset_string}/#{idx}" url += "?user_id=#{(@current_user ? @current_user.id : nil)}&ts=#{ts}&verifier=#{sig}" child = Nokogiri::HTML::DocumentFragment.parse("<iframe class='user_content_iframe' src='#{url}' style='width: #{width}; height: #{height}' frameborder='0'></iframe>") obj.replace(child) end raw(html.to_s) end def lock_explanation(hash, type, context=nil) res = "This #{type} " hash ||= {} if hash[:lock_at] res += "was locked #{datetime_string(hash[:lock_at])}" elsif hash[:unlock_at] res += "is locked until #{datetime_string(hash[:unlock_at])}" elsif hash[:context_module] obj = hash[:context_module].is_a?(ContextModule) ? hash[:context_module] : OpenObject.new(hash[:context_module]) res += "hasn't been unlocked yet. It is part of the module <b>#{obj.name}</b>." if context res += "<br/><a href='#{context_url(context, :context_context_modules_url)}'>Visit the #{context.class.to_s.downcase} modules page for information on how to unlock this content.</a>" res += "<a href='#{context_url(context, :context_context_module_prerequisites_needing_finishing_url, obj.id, hash[:asset_string])}' style='display: none;' id='module_prerequisites_lookup_link'>&nbsp;</a>" jammit_js :prerequisites_lookup end else res += "is currently locked" end raw(res) end def avatar_image(user_id, height=50) if session["reported_#{user_id}"] image_tag "no_pic.gif" else image_tag(avatar_image_url(user_id || 0), :style => "height: #{height}px;", :alt => '') end end def avatar(user_id, context_code, height=50) link_to(avatar_image(user_id, height), "#{context_prefix(context_code)}/users/#{user_id}", :style => 'z-index: 2; position: relative;') end def slugify(text="") text.gsub(/[^\w]/, "_").downcase end def count_if_any(count=nil) if count && count > 0 "(#{count})" else "" end end # Used to generate context_specific urls, as in: # context_url(@context, :context_assignments_url) # context_url(@context, :controller => :assignments, :action => :show) def context_url(context, *opts) @context_url_lookup ||= {} context_name = (context ? context.class.base_ar_class : context.class).name.underscore lookup = [context ? context.id : nil, context_name, *opts] return @context_url_lookup[lookup] if @context_url_lookup[lookup] res = nil if opts.length > 1 || (opts[0].is_a? String) || (opts[0].is_a? Symbol) name = opts.shift.to_s name = name.sub(/context/, context_name) opts.unshift context.id opts.push({}) unless opts[-1].is_a?(Hash) ajax = opts[-1].delete :ajax rescue nil opts[-1][:only_path] = true res = self.send name, *opts elsif opts[0].is_a? Hash opts = opts[0] ajax = opts[0].delete :ajax rescue nil opts[:only_path] = true opts["#{context_name}_id"] = context.id res = self.url_for opts else res = context_name.to_s + opts.to_json.to_s end @context_url_lookup[lookup] = res end def hidden(include_style=false) include_style ? "style='display:none;'" : "display: none;" end # Helper for easily checking vender/plugins/adheres_to_policy.rb # policies from within a view. Caches the response, but basically # user calls object.grants_right?(user, nil, action) def can_do(object, user, action) return false unless object if object.is_a?(OpenObject) && object.type obj = object.temporary_instance if !obj obj = object.type.classify.constantize.new obj.instance_variable_set("@attributes", object.instance_variable_get("@table").with_indifferent_access) obj.instance_variable_set("@new_record", false) object.temporary_instance = obj end return can_do(obj, user, action) end if (object == @context || object.is_a?(Course)) && user == @current_user @context_all_permissions ||= {} @context_all_permissions[object.asset_string] ||= object.grants_rights?(user, session, nil) return @context_all_permissions[object.asset_string][action] end @permissions_lookup ||= {} lookup = [object ? object.asset_string : nil, user ? user.id : nil, action] return @permissions_lookup[lookup] if @permissions_lookup[lookup] != nil res = false begin res = object.grants_right?(user, session, action) rescue => e logger.warn "#{object.inspect} raised an error while granting rights. #{e.inspect}" if logger false end @permissions_lookup[lookup] = res end # Loads up the lists of files needed for the wiki_sidebar. Called from # within the cached code so won't be loaded unless needed. def load_wiki_sidebar return if @wiki_sidebar_data logger.warn "database lookups happening in view code instead of controller code for wiki sidebar (load_wiki_sidebar)" Folder.root_folders(@context) @wiki_sidebar_data = {} includes = [:default_wiki_wiki_pages, :active_assignments, :active_discussion_topics, :active_folders, :active_quizzes] includes.each{|i| @wiki_sidebar_data[i] = @context.send(i).scoped({:limit => 150}) if @context.respond_to?(i) } includes.each{|i| @wiki_sidebar_data[i] ||= [] } @wiki_sidebar_data[:root_folders] = @wiki_sidebar_data[:active_folders].select{|f| f.parent_folder_id == nil && f.visible? }.to_a.sort_by{|f| f.position || 999 } @wiki_sidebar_data end # js_block captures the content of what you pass it and render_js_blocks will # render all of the blocks that were captured by js_block inside of a <script> tag # if you are in the development environment it will also print out a javascript // comment # that shows the file and line number of where this block of javascript came from. def js_block(&block) js_blocks << { :file_and_line => block.to_s, :contents => capture(&block) } end def js_blocks; @js_blocks ||= []; end def render_js_blocks output = js_blocks.inject('') do |str, e| # print file and line number for debugging in development mode. value = "" value << "<!-- BEGIN SCRIPT BLOCK FROM: " + e[:file_and_line] + " --> \n" if Rails.env == "development" value << e[:contents] value << "<!-- END SCRIPT BLOCK FROM: " + e[:file_and_line] + " --> \n" if Rails.env == "development" str << value end raw(output) end def jammit_js_bundles; @jammit_js_bundles ||= []; end def jammit_js(*args) Array(args).flatten.each do |bundle| jammit_js_bundles << bundle unless jammit_js_bundles.include? bundle end end def jammit_css_bundles; @jammit_css_bundles ||= []; end def jammit_css(*args) Array(args).flatten.each do |bundle| jammit_css_bundles << bundle unless jammit_css_bundles.include? bundle end end def section_tabs @section_tabs ||= begin if @context Rails.cache.fetch([@context, @current_user, "section_tabs"].cache_key) do if @context.respond_to?(:tabs_available) && !@context.tabs_available(@current_user).empty? html = [] html << '<nav role="navigation"><ul id="section-tabs">' tabs = @context.tabs_available(@current_user).select do |tab| if (tab[:id] == @context.class::TAB_CHAT rescue false) tab[:href] && tab[:label] && feature_enabled?(:tinychat) elsif (tab[:id] == @context.class::TAB_COLLABORATIONS rescue false) tab[:href] && tab[:label] && Collaboration.any_collaborations_configured? elsif (tab[:id] == @context.class::TAB_CONFERENCES rescue false) tab[:href] && tab[:label] && feature_enabled?(:web_conferences) else tab[:href] && tab[:label] end end tabs.each do |tab| path = tab[:no_args] ? send(tab[:href]) : send(tab[:href], @context) html << "<li class='section #{"hidden" if tab[:hidden] || tab[:hidden_unused] }'>" + link_to(tab[:label], path, :class => tab[:label].to_css_class) + "</li>" if tab[:href] end html << "</ul></nav>" html.join("") end end end end raw(@section_tabs) end def sortable_tabs tabs = @context.tabs_available(@current_user) tabs.select do |tab| if (tab[:id] == @context.class::TAB_CHAT rescue false) feature_enabled?(:tinychat) elsif (tab[:id] == @context.class::TAB_COLLABORATIONS rescue false) Collaboration.any_collaborations_configured? elsif (tab[:id] == @context.class::TAB_CONFERENCES rescue false) feature_enabled?(:web_conferences) else tab[:id] != (@context.class::TAB_SETTINGS rescue nil) end end end def license_help_link @include_license_dialog = true link_to(image_tag('help.png'), '#', :class => 'license_help_link no-hover', :title => "Help with content licensing") end def equella_enabled? @equella_settings ||= @context.equella_settings if @context.respond_to?(:equella_settings) @equella_settings ||= @domain_root_account.equella_settings !!@equella_settings end def show_user_create_course_button(user) return false if user.nil? root_account = @domain_root_account || user.account.root_account || user.account # admins can always create courses return true if root_account.account_users.find_by_user_id(user.id) if root_account.settings[:teachers_can_create_courses] != false count = user.enrollments.scoped(:select=>'id', :conditions=>"enrollments.type IN ('TeacherEnrollment', 'DesignerEnrollment') AND (enrollments.workflow_state != 'deleted') AND root_account_id = #{root_account.id}").count return true if count > 0 end if root_account.settings[:students_can_create_courses] != false count = user.enrollments.scoped(:select=>'id', :conditions=>"enrollments.type IN ('StudentEnrollment', 'ObserverEnrollment') AND (enrollments.workflow_state != 'deleted') AND root_account_id = #{root_account.id}").count return true if count > 0 end if root_account.settings[:no_enrollments_can_create_courses] != false count = user.enrollments.scoped(:select=>'id', :conditions=>"enrollments.workflow_state != 'deleted' AND root_account_id = #{root_account.id}").count return true if count == 0 end false end def hash_get(hash, key, default=nil) if hash if hash[key.to_s] != nil hash[key.to_s] elsif hash[key.to_sym] != nil hash[key.to_sym] else default end else default end end def safe_cache_key(*args) key = args.cache_key if key.length > 200 key = Digest::MD5.hexdigest(key) end key end def inst_env global_inst_object = { :environment => Rails.env, :logPageViews => !@body_class_no_headers, :allowMediaComments => !!( Kaltura::ClientV3.config && @context && @context.respond_to?(:allow_media_comments?) && @context.allow_media_comments? ), :equellaEnabled => !!equella_enabled?, :filePreviewsEnabled => !!feature_enabled?(:scribd), :googleAnalyticsAccount => Setting.get_cached('google_analytics_key', nil), :http_status => @status, :error_id => @error && @error.id } global_inst_object[:errorURL] = ErrorLogging.javascript_error_url if Kaltura::ClientV3.config global_inst_object[:kalturaSettings] = Kaltura::ClientV3.config.slice('domain', 'resource_domain', 'partner_id', 'subpartner_id', 'player_ui_conf', 'player_cache_st', 'kcw_ui_conf', 'upload_ui_conf') end global_inst_object end def nbsp raw("&nbsp;") end # translate a URL intended for an iframe into an alternative URL, if one is # avavailable. Right now the only supported translation is for youtube # videos. Youtube video pages can no longer be embedded, but we can translate # the URL into the player iframe data. def iframe(src, html_options = {}) uri = URI.parse(src) rescue nil if uri query = Rack::Utils.parse_query(uri.query) if uri.host == 'www.youtube.com' && uri.path == '/watch' && query['v'].present? src = "http://www.youtube.com/embed/#{query['v']}" html_options.merge!({:title => 'Youtube video player', :width => 640, :height => 480, :frameborder => 0, :allowfullscreen => 'allowfullscreen'}) end end content_tag('iframe', '', { :src => src }.merge(html_options)) end end don't try to show avatars when they are not enabled; fixes #3966 Change-Id: Ie236b20177a405e104061ee3eacc3bdaf887c8a7 Reviewed-on: https://gerrit.instructure.com/2654 Tested-by: Hudson <dfb64870173313a9a7b56f814c8e3b33e268497a@instructure.com> Reviewed-by: Brian Palmer <3cb4e1df5ec4da2c7c4af7c52cec8cf340a55a10@instructure.com> # # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # # Methods added to this helper will be available to all templates in the application. module ApplicationHelper include TextHelper # Admins of the given context can see the User.name attribute, # but everyone else sees the User.short_name attribute. def context_user_name(context, user, last_name_first=false) return nil unless user return user.short_name if !context && user.respond_to?(:short_name) context_code = context context_code = context.asset_string if context.respond_to?(:asset_string) context_code ||= "no_context" user_id = user user_id = user.id if user.is_a?(User) || user.is_a?(OpenObject) Rails.cache.fetch(['context_user_name', context_code, user_id, last_name_first].cache_key, {:expires_in=>15.minutes}) do user = User.find_by_id(user_id) res = user.short_name || user.name res end end def keyboard_navigation(keys) content = "<ul class='navigation_list' tabindex='-1'>\n" keys.each do |hash| content += " <li>\n" content += " <span class='keycode'>#{hash[:key]}</span>\n" content += " <span class='colon'>:</span>\n" content += " <span class='description'>#{hash[:description]}</span>\n" content += " </li>\n" end content += "</ul>" content_for(:keyboard_navigation) { content } end def context_prefix(code) return "/{{ context_type_pluralized }}/{{ context_id }}" unless code split = code.split(/_/) id = split.pop type = split.join('_') "/#{type.pluralize}/#{id}" end def cached_context_short_name(code) return nil unless code @cached_context_names ||= {} @cached_context_names[code] ||= Rails.cache.fetch(['short_name_lookup', code].cache_key) do Context.find_by_asset_string(code).short_name rescue "" end end def css_size(val) res = val.to_f res = nil if res == 0 res = (res + 10).to_s + "px" if res && res.to_s == val res end def user_content(str, context_code, asset_string) str ||= "" return raw(str) unless str.match(/object|embed/) raise "context_code and asset_string required" if !str.blank? && (!context_code || !asset_string) return str if !context_code || !asset_string html = Nokogiri::HTML::DocumentFragment.parse(str) html.css('object,embed').each_with_index do |obj, idx| styles = {} params = {} obj.css('param').each do |param| params[param['key']] = param['value'] end (obj['style'] || '').split(/\;/).each do |attr| key, value = attr.split(/\:/).map(&:strip) styles[key] = value end width = css_size(obj['width']) width ||= css_size(params['width']) width ||= css_size(styles['width']) width ||= '400px' height = css_size(obj['height']) height ||= css_size(params['height']) height ||= css_size(styles['height']) height ||= '300px' url = "http://#{HostUrl.file_host(@domain_root_account || Account.default)}" ts, sig = @current_user && @current_user.access_verifier url += "/object_snippet/#{context_code}/#{asset_string}/#{idx}" url += "?user_id=#{(@current_user ? @current_user.id : nil)}&ts=#{ts}&verifier=#{sig}" child = Nokogiri::HTML::DocumentFragment.parse("<iframe class='user_content_iframe' src='#{url}' style='width: #{width}; height: #{height}' frameborder='0'></iframe>") obj.replace(child) end raw(html.to_s) end def lock_explanation(hash, type, context=nil) res = "This #{type} " hash ||= {} if hash[:lock_at] res += "was locked #{datetime_string(hash[:lock_at])}" elsif hash[:unlock_at] res += "is locked until #{datetime_string(hash[:unlock_at])}" elsif hash[:context_module] obj = hash[:context_module].is_a?(ContextModule) ? hash[:context_module] : OpenObject.new(hash[:context_module]) res += "hasn't been unlocked yet. It is part of the module <b>#{obj.name}</b>." if context res += "<br/><a href='#{context_url(context, :context_context_modules_url)}'>Visit the #{context.class.to_s.downcase} modules page for information on how to unlock this content.</a>" res += "<a href='#{context_url(context, :context_context_module_prerequisites_needing_finishing_url, obj.id, hash[:asset_string])}' style='display: none;' id='module_prerequisites_lookup_link'>&nbsp;</a>" jammit_js :prerequisites_lookup end else res += "is currently locked" end raw(res) end def avatar_image(user_id, height=50) if session["reported_#{user_id}"] image_tag "no_pic.gif" else image_tag(avatar_image_url(user_id || 0), :style => "height: #{height}px;", :alt => '') end end def avatar(user_id, context_code, height=50) if service_enabled?(:avatars) link_to(avatar_image(user_id, height), "#{context_prefix(context_code)}/users/#{user_id}", :style => 'z-index: 2; position: relative;') end end def slugify(text="") text.gsub(/[^\w]/, "_").downcase end def count_if_any(count=nil) if count && count > 0 "(#{count})" else "" end end # Used to generate context_specific urls, as in: # context_url(@context, :context_assignments_url) # context_url(@context, :controller => :assignments, :action => :show) def context_url(context, *opts) @context_url_lookup ||= {} context_name = (context ? context.class.base_ar_class : context.class).name.underscore lookup = [context ? context.id : nil, context_name, *opts] return @context_url_lookup[lookup] if @context_url_lookup[lookup] res = nil if opts.length > 1 || (opts[0].is_a? String) || (opts[0].is_a? Symbol) name = opts.shift.to_s name = name.sub(/context/, context_name) opts.unshift context.id opts.push({}) unless opts[-1].is_a?(Hash) ajax = opts[-1].delete :ajax rescue nil opts[-1][:only_path] = true res = self.send name, *opts elsif opts[0].is_a? Hash opts = opts[0] ajax = opts[0].delete :ajax rescue nil opts[:only_path] = true opts["#{context_name}_id"] = context.id res = self.url_for opts else res = context_name.to_s + opts.to_json.to_s end @context_url_lookup[lookup] = res end def hidden(include_style=false) include_style ? "style='display:none;'" : "display: none;" end # Helper for easily checking vender/plugins/adheres_to_policy.rb # policies from within a view. Caches the response, but basically # user calls object.grants_right?(user, nil, action) def can_do(object, user, action) return false unless object if object.is_a?(OpenObject) && object.type obj = object.temporary_instance if !obj obj = object.type.classify.constantize.new obj.instance_variable_set("@attributes", object.instance_variable_get("@table").with_indifferent_access) obj.instance_variable_set("@new_record", false) object.temporary_instance = obj end return can_do(obj, user, action) end if (object == @context || object.is_a?(Course)) && user == @current_user @context_all_permissions ||= {} @context_all_permissions[object.asset_string] ||= object.grants_rights?(user, session, nil) return @context_all_permissions[object.asset_string][action] end @permissions_lookup ||= {} lookup = [object ? object.asset_string : nil, user ? user.id : nil, action] return @permissions_lookup[lookup] if @permissions_lookup[lookup] != nil res = false begin res = object.grants_right?(user, session, action) rescue => e logger.warn "#{object.inspect} raised an error while granting rights. #{e.inspect}" if logger false end @permissions_lookup[lookup] = res end # Loads up the lists of files needed for the wiki_sidebar. Called from # within the cached code so won't be loaded unless needed. def load_wiki_sidebar return if @wiki_sidebar_data logger.warn "database lookups happening in view code instead of controller code for wiki sidebar (load_wiki_sidebar)" Folder.root_folders(@context) @wiki_sidebar_data = {} includes = [:default_wiki_wiki_pages, :active_assignments, :active_discussion_topics, :active_folders, :active_quizzes] includes.each{|i| @wiki_sidebar_data[i] = @context.send(i).scoped({:limit => 150}) if @context.respond_to?(i) } includes.each{|i| @wiki_sidebar_data[i] ||= [] } @wiki_sidebar_data[:root_folders] = @wiki_sidebar_data[:active_folders].select{|f| f.parent_folder_id == nil && f.visible? }.to_a.sort_by{|f| f.position || 999 } @wiki_sidebar_data end # js_block captures the content of what you pass it and render_js_blocks will # render all of the blocks that were captured by js_block inside of a <script> tag # if you are in the development environment it will also print out a javascript // comment # that shows the file and line number of where this block of javascript came from. def js_block(&block) js_blocks << { :file_and_line => block.to_s, :contents => capture(&block) } end def js_blocks; @js_blocks ||= []; end def render_js_blocks output = js_blocks.inject('') do |str, e| # print file and line number for debugging in development mode. value = "" value << "<!-- BEGIN SCRIPT BLOCK FROM: " + e[:file_and_line] + " --> \n" if Rails.env == "development" value << e[:contents] value << "<!-- END SCRIPT BLOCK FROM: " + e[:file_and_line] + " --> \n" if Rails.env == "development" str << value end raw(output) end def jammit_js_bundles; @jammit_js_bundles ||= []; end def jammit_js(*args) Array(args).flatten.each do |bundle| jammit_js_bundles << bundle unless jammit_js_bundles.include? bundle end end def jammit_css_bundles; @jammit_css_bundles ||= []; end def jammit_css(*args) Array(args).flatten.each do |bundle| jammit_css_bundles << bundle unless jammit_css_bundles.include? bundle end end def section_tabs @section_tabs ||= begin if @context Rails.cache.fetch([@context, @current_user, "section_tabs"].cache_key) do if @context.respond_to?(:tabs_available) && !@context.tabs_available(@current_user).empty? html = [] html << '<nav role="navigation"><ul id="section-tabs">' tabs = @context.tabs_available(@current_user).select do |tab| if (tab[:id] == @context.class::TAB_CHAT rescue false) tab[:href] && tab[:label] && feature_enabled?(:tinychat) elsif (tab[:id] == @context.class::TAB_COLLABORATIONS rescue false) tab[:href] && tab[:label] && Collaboration.any_collaborations_configured? elsif (tab[:id] == @context.class::TAB_CONFERENCES rescue false) tab[:href] && tab[:label] && feature_enabled?(:web_conferences) else tab[:href] && tab[:label] end end tabs.each do |tab| path = tab[:no_args] ? send(tab[:href]) : send(tab[:href], @context) html << "<li class='section #{"hidden" if tab[:hidden] || tab[:hidden_unused] }'>" + link_to(tab[:label], path, :class => tab[:label].to_css_class) + "</li>" if tab[:href] end html << "</ul></nav>" html.join("") end end end end raw(@section_tabs) end def sortable_tabs tabs = @context.tabs_available(@current_user) tabs.select do |tab| if (tab[:id] == @context.class::TAB_CHAT rescue false) feature_enabled?(:tinychat) elsif (tab[:id] == @context.class::TAB_COLLABORATIONS rescue false) Collaboration.any_collaborations_configured? elsif (tab[:id] == @context.class::TAB_CONFERENCES rescue false) feature_enabled?(:web_conferences) else tab[:id] != (@context.class::TAB_SETTINGS rescue nil) end end end def license_help_link @include_license_dialog = true link_to(image_tag('help.png'), '#', :class => 'license_help_link no-hover', :title => "Help with content licensing") end def equella_enabled? @equella_settings ||= @context.equella_settings if @context.respond_to?(:equella_settings) @equella_settings ||= @domain_root_account.equella_settings !!@equella_settings end def show_user_create_course_button(user) return false if user.nil? root_account = @domain_root_account || user.account.root_account || user.account # admins can always create courses return true if root_account.account_users.find_by_user_id(user.id) if root_account.settings[:teachers_can_create_courses] != false count = user.enrollments.scoped(:select=>'id', :conditions=>"enrollments.type IN ('TeacherEnrollment', 'DesignerEnrollment') AND (enrollments.workflow_state != 'deleted') AND root_account_id = #{root_account.id}").count return true if count > 0 end if root_account.settings[:students_can_create_courses] != false count = user.enrollments.scoped(:select=>'id', :conditions=>"enrollments.type IN ('StudentEnrollment', 'ObserverEnrollment') AND (enrollments.workflow_state != 'deleted') AND root_account_id = #{root_account.id}").count return true if count > 0 end if root_account.settings[:no_enrollments_can_create_courses] != false count = user.enrollments.scoped(:select=>'id', :conditions=>"enrollments.workflow_state != 'deleted' AND root_account_id = #{root_account.id}").count return true if count == 0 end false end def hash_get(hash, key, default=nil) if hash if hash[key.to_s] != nil hash[key.to_s] elsif hash[key.to_sym] != nil hash[key.to_sym] else default end else default end end def safe_cache_key(*args) key = args.cache_key if key.length > 200 key = Digest::MD5.hexdigest(key) end key end def inst_env global_inst_object = { :environment => Rails.env, :logPageViews => !@body_class_no_headers, :allowMediaComments => !!( Kaltura::ClientV3.config && @context && @context.respond_to?(:allow_media_comments?) && @context.allow_media_comments? ), :equellaEnabled => !!equella_enabled?, :filePreviewsEnabled => !!feature_enabled?(:scribd), :googleAnalyticsAccount => Setting.get_cached('google_analytics_key', nil), :http_status => @status, :error_id => @error && @error.id } global_inst_object[:errorURL] = ErrorLogging.javascript_error_url if Kaltura::ClientV3.config global_inst_object[:kalturaSettings] = Kaltura::ClientV3.config.slice('domain', 'resource_domain', 'partner_id', 'subpartner_id', 'player_ui_conf', 'player_cache_st', 'kcw_ui_conf', 'upload_ui_conf') end global_inst_object end def nbsp raw("&nbsp;") end # translate a URL intended for an iframe into an alternative URL, if one is # avavailable. Right now the only supported translation is for youtube # videos. Youtube video pages can no longer be embedded, but we can translate # the URL into the player iframe data. def iframe(src, html_options = {}) uri = URI.parse(src) rescue nil if uri query = Rack::Utils.parse_query(uri.query) if uri.host == 'www.youtube.com' && uri.path == '/watch' && query['v'].present? src = "http://www.youtube.com/embed/#{query['v']}" html_options.merge!({:title => 'Youtube video player', :width => 640, :height => 480, :frameborder => 0, :allowfullscreen => 'allowfullscreen'}) end end content_tag('iframe', '', { :src => src }.merge(html_options)) end end
class Trunk < Formula desc "Build, bundle & ship your Rust WASM application to the web" homepage "https://github.com/thedodd/trunk" url "https://github.com/thedodd/trunk/archive/v0.8.1.tar.gz" sha256 "94cb167f2370a2749bbac7b7b1c5a8ea1f9f49065ddcb2fba4bd7bb977080f76" license any_of: ["MIT", "Apache-2.0"] head "https://github.com/thedodd/trunk.git" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "37b5d7e5469b41fb586f996eb6f4ab94863a2780f986d4cd27b9c7f295078704" sha256 cellar: :any_skip_relocation, big_sur: "f3377776db1fd33651b9500ac625bfec0ea806c8a509d48605064a6d9ff1b64f" sha256 cellar: :any_skip_relocation, catalina: "ad77113d27d6c35a3a161423993e5d49ebf70ff5989b7691bd9559945c27791b" sha256 cellar: :any_skip_relocation, mojave: "f6e2954c9f2befbac069a567276168d8c17706fd5676e1deb3b89c829eed8de1" end depends_on "rust" => :build def install system "cargo", "install", *std_cargo_args end test do assert_match "ConfigOpts {\n", shell_output("#{bin}/trunk config show") end end trunk: update 0.8.1 bottle. class Trunk < Formula desc "Build, bundle & ship your Rust WASM application to the web" homepage "https://github.com/thedodd/trunk" url "https://github.com/thedodd/trunk/archive/v0.8.1.tar.gz" sha256 "94cb167f2370a2749bbac7b7b1c5a8ea1f9f49065ddcb2fba4bd7bb977080f76" license any_of: ["MIT", "Apache-2.0"] head "https://github.com/thedodd/trunk.git" bottle do sha256 cellar: :any_skip_relocation, big_sur: "6048e4ac198b442011f29daab363a5ad0e63cf0e2c0bdbc55393a74eba7aa8ec" sha256 cellar: :any_skip_relocation, arm64_big_sur: "fd4c0e014e8bc1c92b50b66971051a47c9545b17b1f0e49c39ea9f6bc56034af" sha256 cellar: :any_skip_relocation, catalina: "eb6f94ad5c40e7a6d93887a3b7379643592f5ccead01874a2be775fb6936b43f" sha256 cellar: :any_skip_relocation, mojave: "0e9519ffc6995c91a89e7a2fe103778cf6be65ca036070d2afef9670db648656" end depends_on "rust" => :build def install system "cargo", "install", *std_cargo_args end test do assert_match "ConfigOpts {\n", shell_output("#{bin}/trunk config show") end end
module ApplicationHelper def lepra_version @_lepra_version ||= File.read('VERSION') end def tr_text f, field, *opts haml = <<EOP %tr %td #{f.label field} %td #{f.text_field field, *opts} EOP Haml::Engine.new(haml).render end def tr_symbol f, field, *opts label = field.to_s.sub(/symbol_/,'').to_sym html = <<EOP <tr> <td> #{f.label label} </td> <td> #{f.text_field field, *opts} </td> </tr> EOP end def tr_number f, field, *opts html = <<EOP <tr> <td> #{f.label field} </td> <td> #{f.number_field field, *opts} </td> </tr> EOP html end def tr_check_box f, field, *opts html = <<EOP <tr> <td> #{f.label field} </td> <td> #{f.check_box field, *opts} </td> </tr> EOP html end def tr_boolean f, field, *opts haml = <<EOP %tr %td #{f.label field} %td #{radio_button_tag(field, "nil", :checked => true)} #{label_tag(field.to_s+'_', "unused")} #{radio_button_tag(field, true)} #{label_tag(field.to_s+'_true', "yes")} #{radio_button_tag(field, false)} #{label_tag(field.to_s+'_false', "no")} EOP Haml::Engine.new(haml).render end def tr_date f, field, *opts html = <<EOP <tr> <td> #{f.label field} </td> <td> #{f.text_field(field,*opts)} </td> </tr> EOP html end # require 'bluecloth' require 'maruku' def parse_markdown buf # BlueCloth.new(buf).to_html Maruku.new(buf).to_html end end Radio button works module ApplicationHelper def lepra_version @_lepra_version ||= File.read('VERSION') end def tr_text f, field, *opts haml = <<EOP %tr %td #{f.label field} %td #{f.text_field field, *opts} EOP Haml::Engine.new(haml).render end def tr_symbol f, field, *opts label = field.to_s.sub(/symbol_/,'').to_sym html = <<EOP <tr> <td> #{f.label label} </td> <td> #{f.text_field field, *opts} </td> </tr> EOP end def tr_number f, field, *opts html = <<EOP <tr> <td> #{f.label field} </td> <td> #{f.number_field field, *opts} </td> </tr> EOP html end def tr_check_box f, field, *opts html = <<EOP <tr> <td> #{f.label field} </td> <td> #{f.check_box field, *opts} </td> </tr> EOP html end def tr_boolean f, field, *opts haml = <<EOP %tr %td #{f.label field} %td #{f.radio_button field, ""} #{f.label field, "unused"} #{f.radio_button field, true} #{f.label field, "Yes"} #{f.radio_button field, false} #{f.label field, "No"} EOP Haml::Engine.new(haml).render end def tr_date f, field, *opts html = <<EOP <tr> <td> #{f.label field} </td> <td> #{f.text_field(field,*opts)} </td> </tr> EOP html end # require 'bluecloth' require 'maruku' def parse_markdown buf # BlueCloth.new(buf).to_html Maruku.new(buf).to_html end end
#!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' require 'zippy' require 'clik' require 'nokogiri' xml_dump_path = nil extra_args = cli '--xml-dump' => lambda { |path| xml_dump_path = path } opendocument_path = extra_args.first raise "usage: #$0 <OpenDocument file>" unless opendocument_path xml = nil Zippy.open(opendocument_path) do |zip| xml = zip['content.xml'] end doc = Nokogiri::XML::Document.parse(xml) if xml_dump_path File.open(xml_dump_path, "w") { |f| f.write doc.to_xml(indent: 2) } end text = doc.xpath('//office:text').first raise "no office:text found" unless text amend_start = nil amend_nodes = [] text.children.each_with_index do |node, i| if node.search("[text()='<Amend>']").size > 0 amend_start = i elsif node.search("[text()='</Amend>']").size > 0 if amend_start.nil? raise "amend end before amend start" end amend_end = i amend_nodes << text.children.slice(amend_start..amend_end) amend_start = nil end end p amend_nodes.length extract amendment meta data #!/usr/bin/env ruby require 'rubygems' require 'bundler/setup' require 'zippy' require 'clik' require 'nokogiri' xml_dump_path = nil def debug(values); end extra_args = cli '--xml-dump' => lambda { |path| xml_dump_path = path }, '-d --debug' => lambda { def debug(values) p values; end } opendocument_path = extra_args.first raise "usage: #$0 <OpenDocument file>" unless opendocument_path xml = nil Zippy.open(opendocument_path) do |zip| xml = zip['content.xml'] end doc = Nokogiri::XML::Document.parse(xml) if xml_dump_path File.open(xml_dump_path, "w") { |f| f.write doc.to_xml(indent: 2) } end text = doc.xpath('//office:text').first raise "no office:text found" unless text amend_start = nil amend_nodes = [] text.children.each_with_index do |node, i| if node.search("[text()='<Amend>']").size > 0 amend_start = i elsif node.search("[text()='</Amend>']").size > 0 if amend_start.nil? raise "amend end before amend start" end amend_end = i amend_nodes << text.children.slice(amend_start..amend_end) amend_start = nil end end puts "#{amend_nodes.length} amendments found" amend_nodes.each do |nodes| amend_text = nodes.map(&:text).join debug amend_text: amend_text amend_doc = Nokogiri::XML::Document.parse(amend_text) num_am = amend_doc.xpath("//NumAm").first.text doc_amend = amend_doc.xpath("//DocAmend").first.text article = amend_doc.xpath("//Article").first.text debug num_am: num_am, doc_amend: doc_amend, article: article end
require 'formula' class Tsuru < Formula url "https://s3.amazonaws.com/tsuru/tsuru-1.0.1.tar.gz" homepage "https://tsuru.io" sha256 "ca246f280c010f43ff816ee4a41df0c4e90eb555639d52d4c7ed5760a5a49069" depends_on 'go' def install system "bash", "-c", "test -n \"$(go version | awk '{print \$3}' | perl -ne 'print if /go1\.[0-4](\.[0-9]+)?$/')\" && echo ERROR: tsuru requires Go 1.5 or later, your version is: $(go version) && exit 1 || echo proceeding ..." system "bash", "-c", "GOPATH=\"$PWD\" go build -o tsuru github.com/tsuru/tsuru-client/tsuru" ENV['TSURU_PATH'] = "./tsuru" bin.install "tsuru" bash_completion.install "src/github.com/tsuru/tsuru-client/misc/bash-completion" => "tsuru" zsh_completion.install "src/github.com/tsuru/tsuru-client/misc/zsh-completion" => "tsuru" end devel do url "https://s3.amazonaws.com//tsuru/dist-src/tsuru-1.1.0-rc1.tar.gz" sha256 "6f7230a29a80de70e2523d149d0a6b37f3dcad61cfb7b7f5d46098cf441293cd" ENV['TSURU_DEVEL'] = "true" end end release tsuru client 1.1.0 require 'formula' class Tsuru < Formula url "https://s3.amazonaws.com/tsuru/tsuru-1.1.0.tar.gz" homepage "https://tsuru.io" sha256 "d5d0ed869fcd619abb4f0a1e4b4505be60936de5cb7a5c4e1dd64f6851d04ebd" depends_on 'go' def install system "bash", "-c", "test -n \"$(go version | awk '{print \$3}' | perl -ne 'print if /go1\.[0-4](\.[0-9]+)?$/')\" && echo ERROR: tsuru requires Go 1.5 or later, your version is: $(go version) && exit 1 || echo proceeding ..." system "bash", "-c", "GOPATH=\"$PWD\" go build -o tsuru github.com/tsuru/tsuru-client/tsuru" ENV['TSURU_PATH'] = "./tsuru" bin.install "tsuru" bash_completion.install "src/github.com/tsuru/tsuru-client/misc/bash-completion" => "tsuru" zsh_completion.install "src/github.com/tsuru/tsuru-client/misc/zsh-completion" => "tsuru" end end
module ApplicationHelper def title(page_title) content_for(:title) { page_title } end # Can return four different sizes from Twitter API # :original - size is undefined, whatever user uploaded # :mini - 24px by 24px # :normal - 48px by 48px # :bigger - 73px by 73px def mailer_unfollower_details(size, id, options={}) if options[:style] style = options[:style] end src = Twitter.user(id).profile_image_url(size) name = Twitter.user(id).name handle = '@' + Twitter.user(id).screen_name user_followers = Twitter.follower_ids(@user.uid.to_i).collection unfollower_status = if user_followers.include?(id) content_tag(:span, "Following", :class => 'status', :style => "font-size:8px;color:#777;padding:2px 5px;margin-top:2px;text-transform:uppercase;background-color:#EEE;border-radius:3px;") end details = content_tag(:li, name, :class => 'name', :style => "list-style:none;font-weight:500;color:#444;") + content_tag(:li, handle, :class => 'handle', :style => "list-style:none;color:#999;font-weight:300;margin-bottom:4px;") + unfollower_status content_tag(:img, nil, :src => src, :class => 'avatar', :style => style) + content_tag(:ul, details, :style => "padding:0;margin:0 2.5em 0 0;float:right;") end def mailer_unfollower_link(id, options={}) link_to mailer_unfollower_details(:normal, id, options), "http://twitter.com/#{Twitter.user(id).screen_name}", :target => '_blank', :style => "display:inline-block;text-decoration:none;" end # Can return four different sizes from Twitter API # :original - size is undefined, whatever user uploaded # :mini - 24px by 24px # :normal - 48px by 48px # :bigger - 73px by 73px def unfollower_details(size, id) src = Twitter.user(id).profile_image_url(size) name = Twitter.user(id).name handle = '@' + Twitter.user(id).screen_name current_user_followers = Twitter.follower_ids(current_user.uid.to_i).collection unfollower_status = if current_user_followers.include?(id) content_tag(:span, "Following", :class => 'status') end details = content_tag(:span, name, :class => 'name') + content_tag(:span, handle, :class => 'handle') + unfollower_status content_tag(:img, nil, :src => src, :class => 'avatar') + content_tag(:div, details) end def unfollower_link(id) link_to unfollower_details(:normal, id), "http://twitter.com/#{Twitter.user(id).screen_name}", :target => '_blank' end end Visual tweaks to unfollower mailer badges module ApplicationHelper def title(page_title) content_for(:title) { page_title } end # Can return four different sizes from Twitter API # :original - size is undefined, whatever user uploaded # :mini - 24px by 24px # :normal - 48px by 48px # :bigger - 73px by 73px def mailer_unfollower_details(size, id, options={}) if options[:style] style = options[:style] end src = Twitter.user(id).profile_image_url(size) name = Twitter.user(id).name handle = '@' + Twitter.user(id).screen_name user_followers = Twitter.follower_ids(@user.uid.to_i).collection unfollower_status = if user_followers.include?(id) content_tag(:span, "Following", :class => 'status', :style => "font-size:8px;color:#777;padding:2px 5px;margin-top:1px;text-transform:uppercase;background-color:#EEE;border-radius:3px;") end details = content_tag(:li, name, :class => 'name', :style => "font-size:12px;list-style:none;font-weight:500;color:#444;") + content_tag(:li, handle, :class => 'handle', :style => "font-size:12px;list-style:none;color:#999;font-weight:300;margin-bottom:4px;") + unfollower_status content_tag(:img, nil, :src => src, :class => 'avatar', :style => style) + content_tag(:ul, details, :style => "padding:0;margin:0 2.5em 0 0;float:right;") end def mailer_unfollower_link(id, options={}) link_to mailer_unfollower_details(:normal, id, options), "http://twitter.com/#{Twitter.user(id).screen_name}", :target => '_blank', :style => "display:inline-block;text-decoration:none;" end # Can return four different sizes from Twitter API # :original - size is undefined, whatever user uploaded # :mini - 24px by 24px # :normal - 48px by 48px # :bigger - 73px by 73px def unfollower_details(size, id) src = Twitter.user(id).profile_image_url(size) name = Twitter.user(id).name handle = '@' + Twitter.user(id).screen_name current_user_followers = Twitter.follower_ids(current_user.uid.to_i).collection unfollower_status = if current_user_followers.include?(id) content_tag(:span, "Following", :class => 'status') end details = content_tag(:span, name, :class => 'name') + content_tag(:span, handle, :class => 'handle') + unfollower_status content_tag(:img, nil, :src => src, :class => 'avatar') + content_tag(:div, details) end def unfollower_link(id) link_to unfollower_details(:normal, id), "http://twitter.com/#{Twitter.user(id).screen_name}", :target => '_blank' end end
class Twarc < Formula include Language::Python::Virtualenv desc "Command-line tool and Python library for archiving Twitter JSON" homepage "https://github.com/DocNow/twarc" url "https://files.pythonhosted.org/packages/f2/6d/2f70ad698ee6caf0e773f0636466085bfe1262009b655776263bd38b33e0/twarc-1.0.10.tar.gz" sha256 "e5592353f6a2d8e11296485ecf87cd1e868c078548afede2b95ee3ffd04ebf8b" bottle do cellar :any_skip_relocation sha256 "741afb86241a7459455ddd9dc24c1c28f0471cd2964852ae6c84f5872695a1bc" => :sierra sha256 "4c4f78f82f788ffbee6dda69cdc4b49b59fea089c38e19780f2b931cce2b9bbc" => :el_capitan sha256 "9c0021da9a40756c36a7894563f23a8eaa948e93d004123e37eee847439cb4a7" => :yosemite end depends_on :python if MacOS.version <= :snow_leopard resource "appdirs" do url "https://files.pythonhosted.org/packages/48/69/d87c60746b393309ca30761f8e2b49473d43450b150cb08f3c6df5c11be5/appdirs-1.4.3.tar.gz" sha256 "9e5896d1372858f8dd3344faf4e5014d21849c756c8d5701f78f8a103b372d92" end resource "funcsigs" do url "https://files.pythonhosted.org/packages/94/4a/db842e7a0545de1cdb0439bb80e6e42dfe82aaeaadd4072f2263a4fbed23/funcsigs-1.0.2.tar.gz" sha256 "a7bb0f2cf3a3fd1ab2732cb49eba4252c2af4240442415b4abce3b87022a8f50" end resource "mock" do url "https://files.pythonhosted.org/packages/0c/53/014354fc93c591ccc4abff12c473ad565a2eb24dcd82490fae33dbf2539f/mock-2.0.0.tar.gz" sha256 "b158b6df76edd239b8208d481dc46b6afd45a846b7812ff0ce58971cf5bc8bba" end resource "oauthlib" do url "https://files.pythonhosted.org/packages/fa/2e/25f25e6c69d97cf921f0a8f7d520e0ef336dd3deca0142c0b634b0236a90/oauthlib-2.0.2.tar.gz" sha256 "b3b9b47f2a263fe249b5b48c4e25a5bce882ff20a0ac34d553ce43cff55b53ac" end resource "packaging" do url "https://files.pythonhosted.org/packages/c6/70/bb32913de251017e266c5114d0a645f262fb10ebc9bf6de894966d124e35/packaging-16.8.tar.gz" sha256 "5d50835fdf0a7edf0b55e311b7c887786504efea1177abd7e69329a8e5ea619e" end resource "pbr" do url "https://files.pythonhosted.org/packages/35/a5/3d1beff9fc149b3da814419369a8c24ecf0d1410637fc91002989f433a1a/pbr-2.0.0.tar.gz" sha256 "0ccd2db529afd070df815b1521f01401d43de03941170f8a800e7531faba265d" end resource "py" do url "https://files.pythonhosted.org/packages/2a/a5/139ca93a9ffffd9fc1d3f14be375af3085f53cc490c508cf1c988b886baa/py-1.4.33.tar.gz" sha256 "1f9a981438f2acc20470b301a07a496375641f902320f70e31916fe3377385a9" end resource "pyparsing" do url "https://files.pythonhosted.org/packages/3c/ec/a94f8cf7274ea60b5413df054f82a8980523efd712ec55a59e7c3357cf7c/pyparsing-2.2.0.tar.gz" sha256 "0832bcf47acd283788593e7a0f542407bd9550a55a8a8435214a1960e04bcb04" end resource "pytest" do url "https://files.pythonhosted.org/packages/00/e9/f77dcd80bdb2e52760f38dbd904016da018ab4373898945da744e5e892e9/pytest-3.0.7.tar.gz" sha256 "b70696ebd1a5e6b627e7e3ac1365a4bc60aaf3495e843c1e70448966c5224cab" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/51/fc/39a3fbde6864942e8bb24c93663734b74e281b984d1b8c4f95d64b0c21f6/python-dateutil-2.6.0.tar.gz" sha256 "62a2f8df3d66f878373fd0072eacf4ee52194ba302e00082828e0d263b0418d2" end resource "requests" do url "https://files.pythonhosted.org/packages/16/09/37b69de7c924d318e51ece1c4ceb679bf93be9d05973bb30c35babd596e2/requests-2.13.0.tar.gz" sha256 "5722cd09762faa01276230270ff16af7acf7c5c45d623868d9ba116f15791ce8" end resource "requests-oauthlib" do url "https://files.pythonhosted.org/packages/80/14/ad120c720f86c547ba8988010d5186102030591f71f7099f23921ca47fe5/requests-oauthlib-0.8.0.tar.gz" sha256 "883ac416757eada6d3d07054ec7092ac21c7f35cb1d2cf82faf205637081f468" end resource "six" do url "https://files.pythonhosted.org/packages/b3/b2/238e2590826bfdd113244a40d9d3eb26918bd798fc187e2360a8367068db/six-1.10.0.tar.gz" sha256 "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a" end resource "unicodecsv" do url "https://files.pythonhosted.org/packages/6f/a4/691ab63b17505a26096608cc309960b5a6bdf39e4ba1a793d5f9b1a53270/unicodecsv-0.14.1.tar.gz" sha256 "018c08037d48649a0412063ff4eda26eaa81eff1546dbffa51fa5293276ff7fc" end def install virtualenv_install_with_resources end test do assert_equal "usage: twarc [-h] [--log LOG] [--consumer_key CONSUMER_KEY]", shell_output("#{bin}/twarc -h").chomp.split("\n").first end end twarc 1.1.0 Closes #12424. Signed-off-by: ilovezfs <fbd54dbbcf9e596abad4ccdc4dfc17f80ebeaee2@icloud.com> class Twarc < Formula include Language::Python::Virtualenv desc "Command-line tool and Python library for archiving Twitter JSON" homepage "https://github.com/DocNow/twarc" url "https://files.pythonhosted.org/packages/b6/48/2bdffb148b34d2ae1b2bb009ad6dbed95c1a2696953b62d31c754e74e084/twarc-1.1.0.tar.gz" sha256 "fd9d83a9d00e6fbedc4e99648713824321505ef038928ad354996df87f61209a" bottle do cellar :any_skip_relocation sha256 "741afb86241a7459455ddd9dc24c1c28f0471cd2964852ae6c84f5872695a1bc" => :sierra sha256 "4c4f78f82f788ffbee6dda69cdc4b49b59fea089c38e19780f2b931cce2b9bbc" => :el_capitan sha256 "9c0021da9a40756c36a7894563f23a8eaa948e93d004123e37eee847439cb4a7" => :yosemite end depends_on :python if MacOS.version <= :snow_leopard resource "appdirs" do url "https://files.pythonhosted.org/packages/48/69/d87c60746b393309ca30761f8e2b49473d43450b150cb08f3c6df5c11be5/appdirs-1.4.3.tar.gz" sha256 "9e5896d1372858f8dd3344faf4e5014d21849c756c8d5701f78f8a103b372d92" end resource "funcsigs" do url "https://files.pythonhosted.org/packages/94/4a/db842e7a0545de1cdb0439bb80e6e42dfe82aaeaadd4072f2263a4fbed23/funcsigs-1.0.2.tar.gz" sha256 "a7bb0f2cf3a3fd1ab2732cb49eba4252c2af4240442415b4abce3b87022a8f50" end resource "mock" do url "https://files.pythonhosted.org/packages/0c/53/014354fc93c591ccc4abff12c473ad565a2eb24dcd82490fae33dbf2539f/mock-2.0.0.tar.gz" sha256 "b158b6df76edd239b8208d481dc46b6afd45a846b7812ff0ce58971cf5bc8bba" end resource "oauthlib" do url "https://files.pythonhosted.org/packages/fa/2e/25f25e6c69d97cf921f0a8f7d520e0ef336dd3deca0142c0b634b0236a90/oauthlib-2.0.2.tar.gz" sha256 "b3b9b47f2a263fe249b5b48c4e25a5bce882ff20a0ac34d553ce43cff55b53ac" end resource "packaging" do url "https://files.pythonhosted.org/packages/c6/70/bb32913de251017e266c5114d0a645f262fb10ebc9bf6de894966d124e35/packaging-16.8.tar.gz" sha256 "5d50835fdf0a7edf0b55e311b7c887786504efea1177abd7e69329a8e5ea619e" end resource "pbr" do url "https://files.pythonhosted.org/packages/9b/cf/6c6f843ffc13aee42c5412c49e7aff7e860d006261dcafb5a5512fa27cd6/pbr-2.1.0.tar.gz" sha256 "f71359a7e2de2f5ea1eceea7c1e3222f2560ee48e21eef6f96957bb5c2ebb94a" end resource "py" do url "https://files.pythonhosted.org/packages/2a/a5/139ca93a9ffffd9fc1d3f14be375af3085f53cc490c508cf1c988b886baa/py-1.4.33.tar.gz" sha256 "1f9a981438f2acc20470b301a07a496375641f902320f70e31916fe3377385a9" end resource "pyparsing" do url "https://files.pythonhosted.org/packages/3c/ec/a94f8cf7274ea60b5413df054f82a8980523efd712ec55a59e7c3357cf7c/pyparsing-2.2.0.tar.gz" sha256 "0832bcf47acd283788593e7a0f542407bd9550a55a8a8435214a1960e04bcb04" end resource "pytest" do url "https://files.pythonhosted.org/packages/00/e9/f77dcd80bdb2e52760f38dbd904016da018ab4373898945da744e5e892e9/pytest-3.0.7.tar.gz" sha256 "b70696ebd1a5e6b627e7e3ac1365a4bc60aaf3495e843c1e70448966c5224cab" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/51/fc/39a3fbde6864942e8bb24c93663734b74e281b984d1b8c4f95d64b0c21f6/python-dateutil-2.6.0.tar.gz" sha256 "62a2f8df3d66f878373fd0072eacf4ee52194ba302e00082828e0d263b0418d2" end resource "requests" do url "https://files.pythonhosted.org/packages/16/09/37b69de7c924d318e51ece1c4ceb679bf93be9d05973bb30c35babd596e2/requests-2.13.0.tar.gz" sha256 "5722cd09762faa01276230270ff16af7acf7c5c45d623868d9ba116f15791ce8" end resource "requests-oauthlib" do url "https://files.pythonhosted.org/packages/80/14/ad120c720f86c547ba8988010d5186102030591f71f7099f23921ca47fe5/requests-oauthlib-0.8.0.tar.gz" sha256 "883ac416757eada6d3d07054ec7092ac21c7f35cb1d2cf82faf205637081f468" end resource "six" do url "https://files.pythonhosted.org/packages/b3/b2/238e2590826bfdd113244a40d9d3eb26918bd798fc187e2360a8367068db/six-1.10.0.tar.gz" sha256 "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a" end resource "unicodecsv" do url "https://files.pythonhosted.org/packages/6f/a4/691ab63b17505a26096608cc309960b5a6bdf39e4ba1a793d5f9b1a53270/unicodecsv-0.14.1.tar.gz" sha256 "018c08037d48649a0412063ff4eda26eaa81eff1546dbffa51fa5293276ff7fc" end def install virtualenv_install_with_resources end test do assert_equal "usage: twarc [-h] [--log LOG] [--consumer_key CONSUMER_KEY]", shell_output("#{bin}/twarc -h").chomp.split("\n").first end end
module ApplicationHelper def nice_date_times(datetime) return "" if datetime.nil? "#{datetime.strftime('%a')} #{datetime.day.ordinalize} #{datetime.strftime('%b %Y %H:%M')} " end def nice_dates(date) return "" if date.nil? "#{date.strftime('%a')} #{date.day.ordinalize} #{date.strftime('%b %Y')} " end def active(bool = true) bool ? '' : 'bg-warning' end def html_from_markdown(folder, file) folder_dir = Rails.root.join('markdown_pages').join(folder.to_s) if File.exist? folder_dir file_name = file.nil? ? 'default.md' : file + '.md' full_path = folder_dir.join file_name return "Sorry, we couldn't find that page. [File not found]" unless File.exist? full_path render_markdown File.read(full_path) else "Sorry, we couldn't find that page. [Folder not found]" end end def render_markdown(content) renderer = Redcarpet::Render::HTML.new markdown = Redcarpet::Markdown.new(renderer, autolink: true) markdown.render(content).html_safe end def options_from_collection_for_select_with_data(collection, value_method, text_method, selected = nil, data = {}) options = collection.map do |element| [element.send(text_method), element.send(value_method), data.map do |k, v| { "data-#{k}" => element.send(v) } end ].flatten end selected, disabled = extract_selected_and_disabled(selected) select_deselect = {} select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected) select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled) options_for_select(options, select_deselect) end def class_for_last_date(last_date) if last_date.nil? "table-light" elsif last_date < Time.zone.now - 30.days "table-danger" elsif last_date < Time.zone.now - 5.days "table-warning" else "table-success" end end def class_for_alert_colour(colour) return class_for_alert_colour(:unknown) if colour.nil? case colour.to_sym when :red then 'bg-danger' when :yellow then 'bg-warning' when :green then 'bg-success' else 'bg-secondary' end end def temperature_cell_colour(temperature) if temperature >= 19 'table-danger' elsif temperature < 18 'table-primary' else 'table-success' end end def class_for_alert_rating(rating) return class_for_alert_colour(:unknown) if rating.nil? if rating > 9 class_for_alert_colour(:green) elsif rating > 6 class_for_alert_colour(:yellow) else class_for_alert_colour(:red) end end def class_for_alert_subscription(status) case status when 'sent' 'bg-success' when 'pending' 'bg-warning' else 'bg-danger' end end def class_for_boolean(boolean) boolean ? 'bg-success' : 'bg-danger' end def class_for_enough_data(enough_data) case enough_data when :enough, 'enough' 'bg-success' when :minimum_might_not_be_accurate, 'minimum_might_not_be_accurate' 'bg-warning' else 'bg-danger' end end def fa_icon(icon_type) icon('fas', icon_type) end def fab_icon(icon_type) icon('fab', icon_type) end def alert_icon(alert, size = nil) alert.alert_type.fuel_type.nil? ? "calendar-alt #{size}" : "#{fuel_type_icon(alert.alert_type.fuel_type)} #{size}" end def fuel_type_icon(fuel_type) case fuel_type.to_sym when :electricity 'bolt' when :gas 'fire' end end def nav_link(link_text, link_path) content_tag(:li) do if current_page?(link_path) link_to link_text, link_path, class: 'nav-link active' else link_to link_text, link_path, class: 'nav-link' end end end def chart_tag(chart_type, index: 1, chart_config: {}) html_chart_data = chart_config.inject({}) do |collection, (data_item_key, data_item_value)| collection["chart-#{data_item_key.to_s.parameterize}"] = data_item_value collection end content_tag( :div, '', id: "chart_#{index}", class: 'analysis-chart', data: { "chart-index" => index, "chart-type" => chart_type }.merge(html_chart_data) ) end def label_is_energy_plus?(label) label.is_a?(String) && label.start_with?('Energy') && label.length > 6 end def label_is_temperature_plus?(label) label.start_with?('Temperature') && label.length > 11 end def tidy_label(current_label) if label_is_energy_plus?(current_label) current_label = sort_out_dates_when_tidying_labels(current_label) end current_label end def tidy_and_keep_label(current_label) label_bit = current_label.scan(/\d+|[A-Za-z]+/).shift label_bit + ' ' + sort_out_dates_when_tidying_labels(current_label) end def sort_out_dates_when_tidying_labels(current_label) date_to_and_from = current_label.scan(/\d+|[A-Za-z]+/).drop(1).each_slice(4).to_a if date_to_and_from.size > 1 && date_to_and_from[0][3] != date_to_and_from[1][3] date_to_and_from[0].delete_at(0) date_to_and_from[1].delete_at(0) end date_to_and_from.map { |bit| bit.join(' ') }.join(' - ') end def format_school_time(school_time) return school_time if school_time.blank? sprintf('%04d', school_time).insert(2, ':') end def table_headers_from_array(array) header = array[0] header.map do |column| html_class = column == header.first ? '' : 'text-center' [column, html_class] end end def table_body_from_array(array) array[1, array.length - 1] end def table_row_from_array(row) row.map do |column| html_class = column == row.first ? '' : 'text-right' [column, html_class] end end def y_n(boolean) boolean ? 'Yes' : 'No' end end Remove unused helper module ApplicationHelper def nice_date_times(datetime) return "" if datetime.nil? "#{datetime.strftime('%a')} #{datetime.day.ordinalize} #{datetime.strftime('%b %Y %H:%M')} " end def nice_dates(date) return "" if date.nil? "#{date.strftime('%a')} #{date.day.ordinalize} #{date.strftime('%b %Y')} " end def active(bool = true) bool ? '' : 'bg-warning' end def html_from_markdown(folder, file) folder_dir = Rails.root.join('markdown_pages').join(folder.to_s) if File.exist? folder_dir file_name = file.nil? ? 'default.md' : file + '.md' full_path = folder_dir.join file_name return "Sorry, we couldn't find that page. [File not found]" unless File.exist? full_path render_markdown File.read(full_path) else "Sorry, we couldn't find that page. [Folder not found]" end end def render_markdown(content) renderer = Redcarpet::Render::HTML.new markdown = Redcarpet::Markdown.new(renderer, autolink: true) markdown.render(content).html_safe end def options_from_collection_for_select_with_data(collection, value_method, text_method, selected = nil, data = {}) options = collection.map do |element| [element.send(text_method), element.send(value_method), data.map do |k, v| { "data-#{k}" => element.send(v) } end ].flatten end selected, disabled = extract_selected_and_disabled(selected) select_deselect = {} select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected) select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled) options_for_select(options, select_deselect) end def class_for_last_date(last_date) if last_date.nil? "table-light" elsif last_date < Time.zone.now - 30.days "table-danger" elsif last_date < Time.zone.now - 5.days "table-warning" else "table-success" end end def class_for_alert_colour(colour) return class_for_alert_colour(:unknown) if colour.nil? case colour.to_sym when :red then 'bg-danger' when :yellow then 'bg-warning' when :green then 'bg-success' else 'bg-secondary' end end def temperature_cell_colour(temperature) if temperature >= 19 'table-danger' elsif temperature < 18 'table-primary' else 'table-success' end end def class_for_alert_rating(rating) return class_for_alert_colour(:unknown) if rating.nil? if rating > 9 class_for_alert_colour(:green) elsif rating > 6 class_for_alert_colour(:yellow) else class_for_alert_colour(:red) end end def class_for_alert_subscription(status) case status when 'sent' 'bg-success' when 'pending' 'bg-warning' else 'bg-danger' end end def class_for_boolean(boolean) boolean ? 'bg-success' : 'bg-danger' end def fa_icon(icon_type) icon('fas', icon_type) end def fab_icon(icon_type) icon('fab', icon_type) end def alert_icon(alert, size = nil) alert.alert_type.fuel_type.nil? ? "calendar-alt #{size}" : "#{fuel_type_icon(alert.alert_type.fuel_type)} #{size}" end def fuel_type_icon(fuel_type) case fuel_type.to_sym when :electricity 'bolt' when :gas 'fire' end end def nav_link(link_text, link_path) content_tag(:li) do if current_page?(link_path) link_to link_text, link_path, class: 'nav-link active' else link_to link_text, link_path, class: 'nav-link' end end end def chart_tag(chart_type, index: 1, chart_config: {}) html_chart_data = chart_config.inject({}) do |collection, (data_item_key, data_item_value)| collection["chart-#{data_item_key.to_s.parameterize}"] = data_item_value collection end content_tag( :div, '', id: "chart_#{index}", class: 'analysis-chart', data: { "chart-index" => index, "chart-type" => chart_type }.merge(html_chart_data) ) end def label_is_energy_plus?(label) label.is_a?(String) && label.start_with?('Energy') && label.length > 6 end def label_is_temperature_plus?(label) label.start_with?('Temperature') && label.length > 11 end def tidy_label(current_label) if label_is_energy_plus?(current_label) current_label = sort_out_dates_when_tidying_labels(current_label) end current_label end def tidy_and_keep_label(current_label) label_bit = current_label.scan(/\d+|[A-Za-z]+/).shift label_bit + ' ' + sort_out_dates_when_tidying_labels(current_label) end def sort_out_dates_when_tidying_labels(current_label) date_to_and_from = current_label.scan(/\d+|[A-Za-z]+/).drop(1).each_slice(4).to_a if date_to_and_from.size > 1 && date_to_and_from[0][3] != date_to_and_from[1][3] date_to_and_from[0].delete_at(0) date_to_and_from[1].delete_at(0) end date_to_and_from.map { |bit| bit.join(' ') }.join(' - ') end def format_school_time(school_time) return school_time if school_time.blank? sprintf('%04d', school_time).insert(2, ':') end def table_headers_from_array(array) header = array[0] header.map do |column| html_class = column == header.first ? '' : 'text-center' [column, html_class] end end def table_body_from_array(array) array[1, array.length - 1] end def table_row_from_array(row) row.map do |column| html_class = column == row.first ? '' : 'text-right' [column, html_class] end end def y_n(boolean) boolean ? 'Yes' : 'No' end end
class Ufraw < Formula desc "Unidentified Flying RAW: RAW image processing utility" homepage "https://ufraw.sourceforge.io" url "https://downloads.sourceforge.net/project/ufraw/ufraw/ufraw-0.22/ufraw-0.22.tar.gz" sha256 "f7abd28ce587db2a74b4c54149bd8a2523a7ddc09bedf4f923246ff0ae09a25e" revision 2 bottle do sha256 "374d46188ae4127e29b0e8bd3da65341a68ba7473aebb4592873bda2621f31e9" => :mojave sha256 "73a19c1aa3644f1b53174226a8ee2853ad6354315859ac90b59739e884e4544b" => :high_sierra sha256 "74d32fc9213f4f8f9aa16249e17f5c23d6cb92c706bfe85a51f36ee5d05bd3a1" => :sierra sha256 "7f60c27241d80fbd9b2a2aa1ed5a8635de6a7326850321a7dcafd819fb7aa564" => :el_capitan sha256 "e894048c08cb563ebda3be58de6d89667f1c7ae6337738b03792ebe7306ce74d" => :yosemite end depends_on "pkg-config" => :build depends_on "libpng" depends_on "dcraw" depends_on "gettext" depends_on "glib" depends_on "jasper" depends_on "jpeg" depends_on "libtiff" depends_on "little-cms2" depends_on "exiv2" => :optional # jpeg 9 compatibility patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/b8ed064/ufraw/jpeg9.patch" sha256 "45de293a9b132eb675302ba8870f5b6216c51da8247cd096b24a5ab60ffbd7f9" end # Fix compilation with Xcode 9, see https://sourceforge.net/p/ufraw/bugs/419/ if MacOS.version >= :high_sierra patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/d5bf686c74/ufraw/high_sierra.patch" sha256 "60c67978cc84b5a118855bcaa552d5c5c3772b407046f1b9db9b74076a938f6e" end end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--without-gtk", "--without-gimp" system "make", "install" (share/"pixmaps").rmtree end test do assert_match version.to_s, shell_output("#{bin}/ufraw-batch --version 2>&1") end end ufraw: fix dependency order class Ufraw < Formula desc "Unidentified Flying RAW: RAW image processing utility" homepage "https://ufraw.sourceforge.io" url "https://downloads.sourceforge.net/project/ufraw/ufraw/ufraw-0.22/ufraw-0.22.tar.gz" sha256 "f7abd28ce587db2a74b4c54149bd8a2523a7ddc09bedf4f923246ff0ae09a25e" revision 2 bottle do sha256 "374d46188ae4127e29b0e8bd3da65341a68ba7473aebb4592873bda2621f31e9" => :mojave sha256 "73a19c1aa3644f1b53174226a8ee2853ad6354315859ac90b59739e884e4544b" => :high_sierra sha256 "74d32fc9213f4f8f9aa16249e17f5c23d6cb92c706bfe85a51f36ee5d05bd3a1" => :sierra sha256 "7f60c27241d80fbd9b2a2aa1ed5a8635de6a7326850321a7dcafd819fb7aa564" => :el_capitan sha256 "e894048c08cb563ebda3be58de6d89667f1c7ae6337738b03792ebe7306ce74d" => :yosemite end depends_on "pkg-config" => :build depends_on "dcraw" depends_on "gettext" depends_on "glib" depends_on "jasper" depends_on "jpeg" depends_on "libpng" depends_on "libtiff" depends_on "little-cms2" depends_on "exiv2" => :optional # jpeg 9 compatibility patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/b8ed064/ufraw/jpeg9.patch" sha256 "45de293a9b132eb675302ba8870f5b6216c51da8247cd096b24a5ab60ffbd7f9" end # Fix compilation with Xcode 9, see https://sourceforge.net/p/ufraw/bugs/419/ if MacOS.version >= :high_sierra patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/d5bf686c74/ufraw/high_sierra.patch" sha256 "60c67978cc84b5a118855bcaa552d5c5c3772b407046f1b9db9b74076a938f6e" end end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--without-gtk", "--without-gimp" system "make", "install" (share/"pixmaps").rmtree end test do assert_match version.to_s, shell_output("#{bin}/ufraw-batch --version 2>&1") end end
module ApplicationHelper def google_walking_directions(args) options = { languange: :en, alternative: :true, sensor: :false, mode: :walking } GoogleDirections.new(args[:start],args[:destination],options) end def google_biking_directions(args) options = { languange: :en, alternative: :true, sensor: :false, mode: :biking } GoogleDirections.new(args[:start],args[:destination],options) end def find_closest_bike(start_point) p station_list = get_station_list end # def find_closest_bike(args) # station_list = get_station_list # closest = station_list.first # station_list.each do |station| # if google_walking_directions(start: args[:start], destination: "#{station['latitude']},#{station['longitude']}").distance < google_walking_directions(start: args[:start], destination: "#{closest['latitude']},#{closest['longitude']}").distance && station.availableBikes > 1 # closest = station # end # end # closest # end # def find_closest_dock(args) # station_list = get_station_list # closest = station_list.first # station_list.each do |station| # if google_walking_directions(destination: args[:destination], start: "#{station.latitude},#{station.longitude}").distance < google_walking_directions(start: args[:destination], destination: "#{closest.latitude},#{closest.longitude}").distance && station.availableDocks > 1 # closest = station # end # end # closest # end def get_station_list uri = URI.parse("http://www.citibikenyc.com/stations/json") res = Net::HTTP.get_response(uri) json_response = JSON.parse(res.body) json_response["stationBeanList"] end end Finish this method - need to test it when I find internet module ApplicationHelper # def google_walking_directions(args) # options = { # languange: :en, # alternative: :true, # sensor: :false, # mode: :walking # } # GoogleDirections.new(args[:start],args[:destination],options) # end # def google_biking_directions(args) # options = { # languange: :en, # alternative: :true, # sensor: :false, # mode: :biking # } # GoogleDirections.new(args[:start],args[:destination],options) # end # def find_closest_bike(start_point) # p station_list = get_station_list # end # args = {start_point: start_point, looking_for: "availableBikes" or "availableDocks"} def find_closest(args) station_list = get_station_list location = Geocoder.search(args[:start_point]) #can maybe also use the GoogleDirections gem here? All we're doing here is getting the latitude and longitude stations_array = [] station_list.each do |station| distance = GeoDistance.distance(location[0].latitude, location[0].longitude, station["latitude"], station["longitude"]).miles.number stations_array << [station, distance] end get_closest_station(stations_array, args[:looking_for]) end # args = {stations_array: stations_array, looking_for: looking_for} def get_closest_station_bike(args) stations_array = args[:stations_array] stations_array.sort!{|a,b| a[1] <=> b[1]} stations_array.each do |station| return station[0,0] if (station[0,0][args[:looking_for])>2 end end def get_station_list uri = URI.parse("http://www.citibikenyc.com/stations/json") res = Net::HTTP.get_response(uri) json_response = JSON.parse(res.body) json_response["stationBeanList"] end end
class Ugrep < Formula desc "Ultra fast grep with query UI, fuzzy search, archive search, and more" homepage "https://github.com/Genivia/ugrep" url "https://github.com/Genivia/ugrep/archive/v3.1.12.tar.gz" sha256 "f783b8bcc628f792ba418f073b38f089a14d709cbd0438ee27a0cc437e0543ac" license "BSD-3-Clause" bottle do sha256 arm64_big_sur: "ffa4faa1f9d5c87d41377d05e593f59eb42f557b7b1a160e85ea7adc11c82ba1" sha256 big_sur: "41b9c6046211133c8529ec9e180227ebf30efe9f82f5d00585e67b63a3529e4f" sha256 catalina: "5754ce1be95575c050e70988db074897c9ac5691e9ad5d5929aa87b1b1163a92" sha256 mojave: "293e2835870b20bee8b486b0a9ff05169a2c77aa7157a0ab026e324f83d0ac81" end depends_on "pcre2" depends_on "xz" def install system "./configure", "--enable-color", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make" system "make", "install" end test do (testpath/"Hello.txt").write("Hello World!") assert_match "Hello World!", shell_output("#{bin}/ug 'Hello' '#{testpath}'").strip assert_match "Hello World!", shell_output("#{bin}/ugrep 'World' '#{testpath}'").strip end end ugrep 3.1.14 Closes #76152. Signed-off-by: Nanda H Krishna <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@nandahkrishna.com> Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com> class Ugrep < Formula desc "Ultra fast grep with query UI, fuzzy search, archive search, and more" homepage "https://github.com/Genivia/ugrep" url "https://github.com/Genivia/ugrep/archive/v3.1.14.tar.gz" sha256 "5fc446306d786641bce192f09a51f6126d6941aae54dbbbe85015ecd8659b220" license "BSD-3-Clause" bottle do sha256 arm64_big_sur: "ffa4faa1f9d5c87d41377d05e593f59eb42f557b7b1a160e85ea7adc11c82ba1" sha256 big_sur: "41b9c6046211133c8529ec9e180227ebf30efe9f82f5d00585e67b63a3529e4f" sha256 catalina: "5754ce1be95575c050e70988db074897c9ac5691e9ad5d5929aa87b1b1163a92" sha256 mojave: "293e2835870b20bee8b486b0a9ff05169a2c77aa7157a0ab026e324f83d0ac81" end depends_on "pcre2" depends_on "xz" def install system "./configure", "--enable-color", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make" system "make", "install" end test do (testpath/"Hello.txt").write("Hello World!") assert_match "Hello World!", shell_output("#{bin}/ug 'Hello' '#{testpath}'").strip assert_match "Hello World!", shell_output("#{bin}/ugrep 'World' '#{testpath}'").strip end end
module ApplicationHelper def display_repo_info if repo = Grit::Repo.new(".") last_commit = repo.commits.first content_tag('ul') do list = '' list << content_tag('li') { "commit: #{last_commit.id}" } list << content_tag('li') { "author: #{last_commit.author.name}" } list << content_tag('li') { "date: #{last_commit.authored_date}" } end end end # Sets the page title and outputs title if container is passed in. # eg. <%= title('Hello World', :h2) %> will return the following: # <h2>Hello World</h2> as well as setting the page title. def title(str, container = nil) @page_title = str content_tag(container, str) if container end # Outputs the corresponding flash message if any are set def flash_messages messages = [] %w(notice warning error).each do |msg| messages << content_tag(:div, html_escape(flash[msg.to_sym]), :id => "flash-#{msg}") unless flash[msg.to_sym].blank? end messages end # http://davidwparker.com/2008/11/12/simple-non-model-checkbox-in-rails/ def check_box_tag_new(name, value = "1", options = {}) html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) unless html_options["check"].nil? html_options["checked"] = "checked" if html_options["check"].to_i == 1 end tag :input, html_options end def pdf_footer(message) pdf.footer [pdf.margin_box.left, pdf.margin_box.bottom + 25] do pdf.stroke_horizontal_rule pdf.pad(10) do pdf.text message, :size => 16 end end end def partial_for(component) # dynamically find the partial for the class_name = component.class.name.underscore # return "#{class_name.pluralize}/sortable_#{class_name}" "#{class_name.pluralize}/#{class_name}" end def render_partial_for(component) class_name = component.class.name.underscore render :partial => "#{class_name.pluralize}/#{class_name}", :locals => { class_name.to_sym => component } end # # dom_for_id generates a dom id value for any object that returns an integer when sent an "id" message # # This helper is normally used with ActiveRecord objects. # # @model = Model.find(3) # dom_id_for(@model) # => "model_3" # dom_id_for(@model, :item) # => "item_model_3" # dom_id_for(@model, :item, :textarea) # => "item_textarea_model_3" # def dom_id_for(component, *optional_prefixes) prefix = '' optional_prefixes.each { |p| prefix << "#{p.to_s}_" } class_name = component.class.name.underscore id_string = component.id.to_s "#{prefix}#{class_name}_#{id_string}" end def dom_class_for(component) component.class.name.underscore end def edit_button_for_component(component, options={}) url = options[:url] || edit_url_for_component(component) update = options[:update] || dom_id_for(component, :item) method = options[:method] || :get complete = options[:complete] || nil button_to_remote('edit', :url => url, :update => update, :method => method, :complete => complete) end def delete_button_for_page_component(page, component) button_to_remote('delete', :confirm => "Delete #{component.class.human_name} named #{component.name}?", :html => {:class => 'delete'}, :url => { :action => 'delete_element', :dom_id => dom_id_for(page.element_for(component)), :element_id => page.element_for(component).id } ) end def edit_url_for_component(component) { :controller => component.class.name.pluralize.underscore, :action => :edit, :id => component.id } end def name_for_component(component) if RAILS_ENV == "development" "#{component.id}: #{component.name}" else "#{component.name}" end end def edit_menu_for_component(component, form) content_tag('div', :class => 'menu') do content_tag('ul') do list = '' list << content_tag('li') { name_for_component(component) } list << content_tag('li') { form.submit "Save" } list << content_tag('li') { form.submit "Cancel" } # list << content_tag('li') { yield dom_id_for(component, :delete, :item) } end end end def show_menu_for_component(component, options={}) content_tag('div', :class => 'menu') do content_tag('ul') do list = '' list << content_tag('li') { name_for_component(component) } list << content_tag('li') { edit_button_for_component(component, options) } # list << content_tag('li') { yield dom_id_for(component, :delete, :item) } end end end end simplify string building in menu_for helpers module ApplicationHelper def display_repo_info if repo = Grit::Repo.new(".") last_commit = repo.commits.first content_tag('ul') do list = '' list << content_tag('li') { "commit: #{last_commit.id}" } list << content_tag('li') { "author: #{last_commit.author.name}" } list << content_tag('li') { "date: #{last_commit.authored_date}" } end end end # Sets the page title and outputs title if container is passed in. # eg. <%= title('Hello World', :h2) %> will return the following: # <h2>Hello World</h2> as well as setting the page title. def title(str, container = nil) @page_title = str content_tag(container, str) if container end # Outputs the corresponding flash message if any are set def flash_messages messages = [] %w(notice warning error).each do |msg| messages << content_tag(:div, html_escape(flash[msg.to_sym]), :id => "flash-#{msg}") unless flash[msg.to_sym].blank? end messages end # http://davidwparker.com/2008/11/12/simple-non-model-checkbox-in-rails/ def check_box_tag_new(name, value = "1", options = {}) html_options = { "type" => "checkbox", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys) unless html_options["check"].nil? html_options["checked"] = "checked" if html_options["check"].to_i == 1 end tag :input, html_options end def pdf_footer(message) pdf.footer [pdf.margin_box.left, pdf.margin_box.bottom + 25] do pdf.stroke_horizontal_rule pdf.pad(10) do pdf.text message, :size => 16 end end end def partial_for(component) # dynamically find the partial for the class_name = component.class.name.underscore # return "#{class_name.pluralize}/sortable_#{class_name}" "#{class_name.pluralize}/#{class_name}" end def render_partial_for(component) class_name = component.class.name.underscore render :partial => "#{class_name.pluralize}/#{class_name}", :locals => { class_name.to_sym => component } end # # dom_for_id generates a dom id value for any object that returns an integer when sent an "id" message # # This helper is normally used with ActiveRecord objects. # # @model = Model.find(3) # dom_id_for(@model) # => "model_3" # dom_id_for(@model, :item) # => "item_model_3" # dom_id_for(@model, :item, :textarea) # => "item_textarea_model_3" # def dom_id_for(component, *optional_prefixes) prefix = '' optional_prefixes.each { |p| prefix << "#{p.to_s}_" } class_name = component.class.name.underscore id_string = component.id.to_s "#{prefix}#{class_name}_#{id_string}" end def dom_class_for(component) component.class.name.underscore end def edit_button_for_component(component, options={}) url = options[:url] || edit_url_for_component(component) update = options[:update] || dom_id_for(component, :item) method = options[:method] || :get complete = options[:complete] || nil button_to_remote('edit', :url => url, :update => update, :method => method, :complete => complete) end def delete_button_for_page_component(page, component) button_to_remote('delete', :confirm => "Delete #{component.class.human_name} named #{component.name}?", :html => {:class => 'delete'}, :url => { :action => 'delete_element', :dom_id => dom_id_for(page.element_for(component)), :element_id => page.element_for(component).id } ) end def edit_url_for_component(component) { :controller => component.class.name.pluralize.underscore, :action => :edit, :id => component.id } end def name_for_component(component) if RAILS_ENV == "development" "#{component.id}: #{component.name}" else "#{component.name}" end end def edit_menu_for_component(component, form) content_tag('div', :class => 'menu') do content_tag('ul') do list = content_tag('li') { name_for_component(component) } list << content_tag('li') { form.submit "Save" } list << content_tag('li') { form.submit "Cancel" } # list << content_tag('li') { yield dom_id_for(component, :delete, :item) } end end end def show_menu_for_component(component, options={}) content_tag('div', :class => 'menu') do content_tag('ul') do list = content_tag('li') { name_for_component(component) } list << content_tag('li') { edit_button_for_component(component, options) } # list << content_tag('li') { yield dom_id_for(component, :delete, :item) } end end end end
require "language/node" class Ungit < Formula desc "Easiest way to use Git. On any platform. Anywhere" homepage "https://github.com/FredrikNoren/ungit" url "https://registry.npmjs.org/ungit/-/ungit-1.5.12.tgz" sha256 "8a52eec719818d520d2e774cf032126b7a5edfc2bd80c777202100bb2049c4d8" license "MIT" livecheck do url :stable end bottle do cellar :any_skip_relocation sha256 "5a0ae95c279780e34b8ed8d020b16a12bb2e36fa9025752106c73b4152eb95d2" => :catalina sha256 "74b2dcbfa88409a1245d73714a28b3f3dc971ec9ff782a9c2b75fb6a1f6fb5a1" => :mojave sha256 "1497767027bbd94fccd041598063141e721365d0f92fa171542b3936ea0d2fa1" => :high_sierra end depends_on "node" def install system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink Dir["#{libexec}/bin/*"] end test do port = free_port fork do exec bin/"ungit", "--no-launchBrowser", "--port=#{port}" end sleep 8 assert_includes shell_output("curl -s 127.0.0.1:#{port}/"), "<title>ungit</title>" end end ungit: update 1.5.12 bottle. require "language/node" class Ungit < Formula desc "Easiest way to use Git. On any platform. Anywhere" homepage "https://github.com/FredrikNoren/ungit" url "https://registry.npmjs.org/ungit/-/ungit-1.5.12.tgz" sha256 "8a52eec719818d520d2e774cf032126b7a5edfc2bd80c777202100bb2049c4d8" license "MIT" livecheck do url :stable end bottle do cellar :any_skip_relocation sha256 "fc993795f40b280ea3cfc9178687d55d5ff85b945f8ea24eeebbf496bdc3611c" => :catalina sha256 "62cb99b06b418f103ad6c57128d577375e1ca214e60c2dde3392031ecdb94942" => :mojave sha256 "cc798c8c18069b63795b953566f1c4fc997ca48cfc81f1856e1d724d63972de3" => :high_sierra end depends_on "node" def install system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink Dir["#{libexec}/bin/*"] end test do port = free_port fork do exec bin/"ungit", "--no-launchBrowser", "--port=#{port}" end sleep 8 assert_includes shell_output("curl -s 127.0.0.1:#{port}/"), "<title>ungit</title>" end end
module ApplicationHelper include ActionView::Helpers::AssetTagHelper include ActionView::Helpers::UrlHelper include InputSanitizeHelper def module_page? controller_name == 'my_modules' end def experiment_page? controller_name == 'experiments' end def project_page? controller_name == 'projects' && action_name.in?(%w(show experiment_archive)) end def all_projects_page? controller_name == 'projects' && action_name.in?(%w(index archive)) end def display_tooltip(message, len = Constants::NAME_TRUNCATION_LENGTH) return '' unless message if message.strip.length > len sanitize_input("<div class='modal-tooltip'> \ #{truncate(message.strip, length: len)} \ <span class='modal-tooltiptext'> \ #{message.strip}</span></div>") else truncate(message.strip, length: len) end end def sample_types_page_project? controller_name == 'sample_types' && @my_module.nil? && @experiment.nil? end def sample_groups_page_project? controller_name == 'sample_groups' && @my_module.nil? && @experiment.nil? end def sample_types_page_my_module? controller_name == 'sample_types' && !@my_module.nil? end def sample_groups_page_my_module? controller_name == 'sample_groups' && !@my_module.nil? end def sample_groups_page_experiment? controller_name == 'sample_groups' && @my_module.nil? && !@experiment.nil? end def sample_types_page_expermient? controller_name == 'sample_types' && @my_module.nil? && !@experiment.nil? end def module_repository_page? controller_name == 'my_modules' && !@repository.nil? end def smart_annotation_notification(options = {}) title = options.fetch(:title) { :title_must_be_present } message = options.fetch(:message) { :message_must_be_present } new_text = options.fetch(:new_text) { :new_text_must_be_present } old_text = options[:old_text] || '' sa_user = /\[\@(.*?)~([0-9a-zA-Z]+)\]/ # fetch user ids from the previous text old_user_ids = [] old_text.gsub(sa_user) do |el| match = el.match(sa_user) old_user_ids << match[2].base62_decode end # fetch user ids from the new text new_user_ids = [] new_text.gsub(sa_user) do |el| match = el.match(sa_user) new_user_ids << match[2].base62_decode end # check if the user has been already mentioned annotated_users = [] new_user_ids.each do |el| annotated_users << el unless old_user_ids.include?(el) end # restrict the list of ids and generate notification annotated_users.uniq.each do |user_id| target_user = User.find_by_id(user_id) next unless target_user generate_annotation_notification(target_user, title, message) end end def generate_annotation_notification(target_user, title, message) notification = Notification.create( type_of: :assignment, title: sanitize_input(title), message: sanitize_input(message) ) if target_user.assignments_notification UserNotification.create(notification: notification, user: target_user) end end def smart_annotation_parser(text, team = nil) # sometimes happens that the "team" param gets wrong data: "{nil, []}" # so we have to check if the "team" param is kind of Team object team = nil unless team.is_a? Team new_text = smart_annotation_filter_resources(text) new_text = smart_annotation_filter_users(new_text, team) new_text end # Check if text have smart annotations of resources # and outputs a link to resource def smart_annotation_filter_resources(text) SmartAnnotations::TagToHtml.new(current_user, text).html end # Check if text have smart annotations of users # and outputs a popover with user information def smart_annotation_filter_users(text, team) sa_user = /\[\@(.*?)~([0-9a-zA-Z]+)\]/ new_text = text.gsub(sa_user) do |el| match = el.match(sa_user) user = User.find_by_id(match[2].base62_decode) next unless user team ||= current_team popover_for_user_name(user, team) end new_text end # Generate smart annotation link for one user object def popover_for_user_name(user, team = nil, skip_user_status = false) user_still_in_team = user.teams.include?(team) user_description = %(<div class='col-xs-4'> <img src='#{user_avatar_absolute_url(user, :thumb)}' alt='thumb'></div><div class='col-xs-8'> <div class='row'><div class='col-xs-9 text-left'><h5> #{user.full_name}</h5></div><div class='col-xs-3 text-right'> <span class='glyphicon glyphicon-remove' aria-hidden='true'></span> </div></div><div class='row'><div class='col-xs-12'> <p class='silver'>#{user.email}</p>) if user_still_in_team user_t = user.user_teams .where('user_teams.team_id = ?', team) .first user_description += %(<p> #{I18n.t('atwho.users.popover_html', role: user_t.role.capitalize, team: user_t.team.name, time: user_t.created_at.strftime('%B %Y'))} </p></div></div></div>) else user_description += %(<p></p></div></div></div>) end user_name = user.full_name # binding.pry unless skip_user_status || user_still_in_team user_name << " #{I18n.t('atwho.res.removed')}" end raw("<img src='#{user_avatar_absolute_url(user, :icon_small)}'" \ "alt='avatar' class='atwho-user-img-popover'" \ " ref='#{'missing-img' if missing_avatar(user, :icon_small)}'>") + raw('<a onClick="$(this).popover(\'show\')" ' \ 'class="atwho-user-popover" data-container="body" ' \ 'data-html="true" tabindex="0" data-trigger="focus" ' \ 'data-placement="top" data-toggle="popover" data-content="') + raw(user_description) + raw('" >') + user_name + raw('</a>') end # Dirty, dirty hack for displaying images in reports def user_avatar_absolute_url(user, style) prefix = '' if ENV['PAPERCLIP_STORAGE'].present? && ENV['MAIL_SERVER_URL'].present? && ENV['PAPERCLIP_STORAGE'] != 'filesystem' prefix = ENV['MAIL_SERVER_URL'] end # for development prefix = 'localhost:3000' if ENV['MAIL_SERVER_URL'] == 'localhost' if !prefix.empty? && !prefix.include?('http://') && !prefix.include?('https://') prefix = if respond_to?(:request) && request.ssl? "https://#{prefix}" else "http://#{prefix}" end end unless missing_avatar(user, style) return user.avatar(style, timeout: Constants::URL_LONG_EXPIRE_TIME) end url_for(prefix + "/images/#{style}/missing.png") end def missing_avatar(user, style) user.avatar(style) == '/images/icon_small/missing.png' || user.avatar(style) == '/images/thumb/missing.png' end end removes unneeded comment module ApplicationHelper include ActionView::Helpers::AssetTagHelper include ActionView::Helpers::UrlHelper include InputSanitizeHelper def module_page? controller_name == 'my_modules' end def experiment_page? controller_name == 'experiments' end def project_page? controller_name == 'projects' && action_name.in?(%w(show experiment_archive)) end def all_projects_page? controller_name == 'projects' && action_name.in?(%w(index archive)) end def display_tooltip(message, len = Constants::NAME_TRUNCATION_LENGTH) return '' unless message if message.strip.length > len sanitize_input("<div class='modal-tooltip'> \ #{truncate(message.strip, length: len)} \ <span class='modal-tooltiptext'> \ #{message.strip}</span></div>") else truncate(message.strip, length: len) end end def sample_types_page_project? controller_name == 'sample_types' && @my_module.nil? && @experiment.nil? end def sample_groups_page_project? controller_name == 'sample_groups' && @my_module.nil? && @experiment.nil? end def sample_types_page_my_module? controller_name == 'sample_types' && !@my_module.nil? end def sample_groups_page_my_module? controller_name == 'sample_groups' && !@my_module.nil? end def sample_groups_page_experiment? controller_name == 'sample_groups' && @my_module.nil? && !@experiment.nil? end def sample_types_page_expermient? controller_name == 'sample_types' && @my_module.nil? && !@experiment.nil? end def module_repository_page? controller_name == 'my_modules' && !@repository.nil? end def smart_annotation_notification(options = {}) title = options.fetch(:title) { :title_must_be_present } message = options.fetch(:message) { :message_must_be_present } new_text = options.fetch(:new_text) { :new_text_must_be_present } old_text = options[:old_text] || '' sa_user = /\[\@(.*?)~([0-9a-zA-Z]+)\]/ # fetch user ids from the previous text old_user_ids = [] old_text.gsub(sa_user) do |el| match = el.match(sa_user) old_user_ids << match[2].base62_decode end # fetch user ids from the new text new_user_ids = [] new_text.gsub(sa_user) do |el| match = el.match(sa_user) new_user_ids << match[2].base62_decode end # check if the user has been already mentioned annotated_users = [] new_user_ids.each do |el| annotated_users << el unless old_user_ids.include?(el) end # restrict the list of ids and generate notification annotated_users.uniq.each do |user_id| target_user = User.find_by_id(user_id) next unless target_user generate_annotation_notification(target_user, title, message) end end def generate_annotation_notification(target_user, title, message) notification = Notification.create( type_of: :assignment, title: sanitize_input(title), message: sanitize_input(message) ) if target_user.assignments_notification UserNotification.create(notification: notification, user: target_user) end end def smart_annotation_parser(text, team = nil) # sometimes happens that the "team" param gets wrong data: "{nil, []}" # so we have to check if the "team" param is kind of Team object team = nil unless team.is_a? Team new_text = smart_annotation_filter_resources(text) new_text = smart_annotation_filter_users(new_text, team) new_text end # Check if text have smart annotations of resources # and outputs a link to resource def smart_annotation_filter_resources(text) SmartAnnotations::TagToHtml.new(current_user, text).html end # Check if text have smart annotations of users # and outputs a popover with user information def smart_annotation_filter_users(text, team) sa_user = /\[\@(.*?)~([0-9a-zA-Z]+)\]/ new_text = text.gsub(sa_user) do |el| match = el.match(sa_user) user = User.find_by_id(match[2].base62_decode) next unless user team ||= current_team popover_for_user_name(user, team) end new_text end # Generate smart annotation link for one user object def popover_for_user_name(user, team = nil, skip_user_status = false) user_still_in_team = user.teams.include?(team) user_description = %(<div class='col-xs-4'> <img src='#{user_avatar_absolute_url(user, :thumb)}' alt='thumb'></div><div class='col-xs-8'> <div class='row'><div class='col-xs-9 text-left'><h5> #{user.full_name}</h5></div><div class='col-xs-3 text-right'> <span class='glyphicon glyphicon-remove' aria-hidden='true'></span> </div></div><div class='row'><div class='col-xs-12'> <p class='silver'>#{user.email}</p>) if user_still_in_team user_t = user.user_teams .where('user_teams.team_id = ?', team) .first user_description += %(<p> #{I18n.t('atwho.users.popover_html', role: user_t.role.capitalize, team: user_t.team.name, time: user_t.created_at.strftime('%B %Y'))} </p></div></div></div>) else user_description += %(<p></p></div></div></div>) end user_name = user.full_name unless skip_user_status || user_still_in_team user_name << " #{I18n.t('atwho.res.removed')}" end raw("<img src='#{user_avatar_absolute_url(user, :icon_small)}'" \ "alt='avatar' class='atwho-user-img-popover'" \ " ref='#{'missing-img' if missing_avatar(user, :icon_small)}'>") + raw('<a onClick="$(this).popover(\'show\')" ' \ 'class="atwho-user-popover" data-container="body" ' \ 'data-html="true" tabindex="0" data-trigger="focus" ' \ 'data-placement="top" data-toggle="popover" data-content="') + raw(user_description) + raw('" >') + user_name + raw('</a>') end # Dirty, dirty hack for displaying images in reports def user_avatar_absolute_url(user, style) prefix = '' if ENV['PAPERCLIP_STORAGE'].present? && ENV['MAIL_SERVER_URL'].present? && ENV['PAPERCLIP_STORAGE'] != 'filesystem' prefix = ENV['MAIL_SERVER_URL'] end # for development prefix = 'localhost:3000' if ENV['MAIL_SERVER_URL'] == 'localhost' if !prefix.empty? && !prefix.include?('http://') && !prefix.include?('https://') prefix = if respond_to?(:request) && request.ssl? "https://#{prefix}" else "http://#{prefix}" end end unless missing_avatar(user, style) return user.avatar(style, timeout: Constants::URL_LONG_EXPIRE_TIME) end url_for(prefix + "/images/#{style}/missing.png") end def missing_avatar(user, style) user.avatar(style) == '/images/icon_small/missing.png' || user.avatar(style) == '/images/thumb/missing.png' end end
require "language/node" class Ungit < Formula desc "The easiest way to use git. On any platform. Anywhere" homepage "https://github.com/FredrikNoren/ungit" url "https://registry.npmjs.org/ungit/-/ungit-1.4.44.tgz" sha256 "11f17f108dae85332d81e63efcb47517e0bddce64b3f97b9eff80dd9f80278b6" bottle do root_url "https://linuxbrew.bintray.com/bottles" cellar :any_skip_relocation sha256 "6c6e00aef5a25f4c9749bcc2448aee9f7b14726f55bc6a57dc708660e029b923" => :mojave sha256 "01c84b92d9b28e98e4ed1a842eeece5698283a394b9ee0d12acbae42b829843b" => :high_sierra sha256 "cb7474b30a4c5bce09262eade9a8cd3434bfc9cf770c49f4b5828c4ad63e3e27" => :sierra end depends_on "node" def install system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink Dir["#{libexec}/bin/*"] end test do begin require "nokogiri" pid = fork do exec bin/"ungit", "--no-launchBrowser", "--autoShutdownTimeout", "5000" # give it an idle timeout to make it exit end sleep 3 assert_match "ungit", Nokogiri::HTML(shell_output("curl -s 127.0.0.1:8448/")).at_css("title").text ensure Process.kill("TERM", pid) Process.wait(pid) end end end ungit: update 1.4.44 bottle. Closes #13181. Signed-off-by: Michka Popoff <7b0496f66f66ee22a38826c310c38b415671b832@gmail.com> require "language/node" class Ungit < Formula desc "The easiest way to use git. On any platform. Anywhere" homepage "https://github.com/FredrikNoren/ungit" url "https://registry.npmjs.org/ungit/-/ungit-1.4.44.tgz" sha256 "11f17f108dae85332d81e63efcb47517e0bddce64b3f97b9eff80dd9f80278b6" bottle do root_url "https://linuxbrew.bintray.com/bottles" cellar :any_skip_relocation sha256 "6c6e00aef5a25f4c9749bcc2448aee9f7b14726f55bc6a57dc708660e029b923" => :mojave sha256 "01c84b92d9b28e98e4ed1a842eeece5698283a394b9ee0d12acbae42b829843b" => :high_sierra sha256 "cb7474b30a4c5bce09262eade9a8cd3434bfc9cf770c49f4b5828c4ad63e3e27" => :sierra sha256 "c6faa90f5b9cf813a8151d0e83d80ffccf21e31cf1e4f7458f059fb031abae2d" => :x86_64_linux end depends_on "node" def install system "npm", "install", *Language::Node.std_npm_install_args(libexec) bin.install_symlink Dir["#{libexec}/bin/*"] end test do begin require "nokogiri" pid = fork do exec bin/"ungit", "--no-launchBrowser", "--autoShutdownTimeout", "5000" # give it an idle timeout to make it exit end sleep 3 assert_match "ungit", Nokogiri::HTML(shell_output("curl -s 127.0.0.1:8448/")).at_css("title").text ensure Process.kill("TERM", pid) Process.wait(pid) end end end
# frozen_string_literal: true module ApplicationHelper def home_link link_to current_account&.name || "Outage Master", root_path, class: "navbar-brand" end def notes_sort_order params.fetch(:sort_order, session.fetch(:sort_order, "desc")) end ## # Format object error messages that don't get attached to a specific # attribute. This always includes `:base`, but the caller can specify # other attributes. # The `bootstrap_form` gem has some helpers, but they don't quite do what # we need. def object_error_messages(resource, *attrs) attrs = [attrs] unless attrs.is_a? Array attrs |= [:base] return "" unless object_error_messages?(resource, *attrs) messages = resource.errors.to_hash(true).slice(*attrs).each_value.map do |msg_array| msg_array.map do |msg| content_tag(:li, msg) end end.join html = if block_given? yield messages else <<-HTML <div class="text-danger rails-bootstrap-forms-error-summary"> <ul>#{messages}</ul> </div> HTML end html.html_safe end def object_error_messages?(resource, *attrs) (resource.errors.keys & attrs).present? end end Fix for new Errors class # frozen_string_literal: true module ApplicationHelper def home_link link_to current_account&.name || "Outage Master", root_path, class: "navbar-brand" end def notes_sort_order params.fetch(:sort_order, session.fetch(:sort_order, "desc")) end ## # Format object error messages that don't get attached to a specific # attribute. This always includes `:base`, but the caller can specify # other attributes. # The `bootstrap_form` gem has some helpers, but they don't quite do what # we need. def object_error_messages(resource, *attrs) attrs = [attrs] unless attrs.is_a? Array attrs |= [:base] return "" unless object_error_messages?(resource, *attrs) messages = resource.errors.to_hash(true).slice(*attrs).each_value.map do |msg_array| msg_array.map do |msg| content_tag(:li, msg) end end.join html = if block_given? yield messages else <<-HTML <div class="text-danger rails-bootstrap-forms-error-summary"> <ul>#{messages}</ul> </div> HTML end html.html_safe end def object_error_messages?(resource, *attrs) (resource.errors.attribute_names & attrs).present? end end
require "language/go" # Please don't update this formula until the release is official via # mailing list or blog post. There's a history of GitHub tags moving around. # https://github.com/hashicorp/vault/issues/1051 class Vault < Formula desc "Secures, stores, and tightly controls access to secrets" homepage "https://vaultproject.io/" url "https://github.com/hashicorp/vault.git", :tag => "v0.6.4", :revision => "f4adc7fa960ed8e828f94bc6785bcdbae8d1b263" head "https://github.com/hashicorp/vault.git" bottle do cellar :any_skip_relocation sha256 "a0e956cad79a349755610aa3b2fd9c84abbd2fa7c3f0a6faef496880b04d07bf" => :sierra sha256 "ef2c6c35dd6d2765b099a5f46b7c815ad48c7f8e5a92875c0254b0063f6ef098" => :el_capitan sha256 "af8867dfa593c61bf441fccb3e30611364a13fcd5bfed4c297860f109ad4e560" => :yosemite end option "with-dynamic", "Build dynamic binary with CGO_ENABLED=1" depends_on "go" => :build go_resource "github.com/mitchellh/iochan" do url "https://github.com/mitchellh/iochan.git", :revision => "87b45ffd0e9581375c491fef3d32130bb15c5bd7" end go_resource "github.com/mitchellh/gox" do url "https://github.com/mitchellh/gox.git", :revision => "c9740af9c6574448fd48eb30a71f964014c7a837" end def install ENV["GOPATH"] = buildpath contents = buildpath.children - [buildpath/".brew_home"] (buildpath/"src/github.com/hashicorp/vault").install contents ENV.prepend_create_path "PATH", buildpath/"bin" Language::Go.stage_deps resources, buildpath/"src" cd "src/github.com/mitchellh/gox" do system "go", "install" end cd "src/github.com/hashicorp/vault" do target = build.with?("dynamic") ? "dev-dynamic" : "dev" system "make", target bin.install "bin/vault" prefix.install_metafiles end end test do pid = fork { exec bin/"vault", "server", "-dev" } sleep 1 ENV.append "VAULT_ADDR", "http://127.0.0.1:8200" system bin/"vault", "status" Process.kill("TERM", pid) end end vault: update 0.6.4 bottle. require "language/go" # Please don't update this formula until the release is official via # mailing list or blog post. There's a history of GitHub tags moving around. # https://github.com/hashicorp/vault/issues/1051 class Vault < Formula desc "Secures, stores, and tightly controls access to secrets" homepage "https://vaultproject.io/" url "https://github.com/hashicorp/vault.git", :tag => "v0.6.4", :revision => "f4adc7fa960ed8e828f94bc6785bcdbae8d1b263" head "https://github.com/hashicorp/vault.git" bottle do sha256 "a33d5e5517222e74a8f260af4ce5074da1e8e9771dbe0f66d3b318df96d8b45a" => :sierra sha256 "d90242f9c818ea5e905df1e4c85a076d00601436594b2d5db408513394873690" => :el_capitan sha256 "edf4396087bf7ac0d91179e5418c4cff783909eb917c4910f5f9d531e02c2caf" => :yosemite end option "with-dynamic", "Build dynamic binary with CGO_ENABLED=1" depends_on "go" => :build go_resource "github.com/mitchellh/iochan" do url "https://github.com/mitchellh/iochan.git", :revision => "87b45ffd0e9581375c491fef3d32130bb15c5bd7" end go_resource "github.com/mitchellh/gox" do url "https://github.com/mitchellh/gox.git", :revision => "c9740af9c6574448fd48eb30a71f964014c7a837" end def install ENV["GOPATH"] = buildpath contents = buildpath.children - [buildpath/".brew_home"] (buildpath/"src/github.com/hashicorp/vault").install contents ENV.prepend_create_path "PATH", buildpath/"bin" Language::Go.stage_deps resources, buildpath/"src" cd "src/github.com/mitchellh/gox" do system "go", "install" end cd "src/github.com/hashicorp/vault" do target = build.with?("dynamic") ? "dev-dynamic" : "dev" system "make", target bin.install "bin/vault" prefix.install_metafiles end end test do pid = fork { exec bin/"vault", "server", "-dev" } sleep 1 ENV.append "VAULT_ADDR", "http://127.0.0.1:8200" system bin/"vault", "status" Process.kill("TERM", pid) end end
require 'oily_png' class Renderer COLLISION_SOLID_COLOR = ChunkyPNG::Color::BLACK COLLISION_SEMISOLID_COLOR = ChunkyPNG::Color.rgba(127, 127, 127, 255) COLLISION_DAMAGE_COLOR = ChunkyPNG::Color.rgba(208, 32, 32, 255) COLLISION_WATER_COLOR = ChunkyPNG::Color.rgba(32, 32, 208, 255) COLLISION_CONVEYOR_COLOR = ChunkyPNG::Color.rgba(32, 208, 32, 255) class GFXImportError < StandardError ; end attr_reader :fs, :fill_color, :save_fill_color, :warp_fill_color, :secret_fill_color, :entrance_fill_color, :transition_fill_color, :line_color, :door_color, :door_center_color, :secret_door_color, :wall_pixels, :door_pixels, :secret_door_pixels def initialize(fs) @fs = fs end def render_room(folder, room, collision = false) rendered_layers = [] if collision rendered_layers << render_layer(folder, layers.first, room, collision) else room.z_ordered_layers.each do |layer| rendered_layers << render_layer(folder, layer, room, collision) end end if collision bg_color = ChunkyPNG::Color::WHITE else bg_color = ChunkyPNG::Color::BLACK end rendered_level = ChunkyPNG::Image.new(room.max_layer_width*SCREEN_WIDTH_IN_PIXELS, room.max_layer_height*SCREEN_HEIGHT_IN_PIXELS, bg_color) rendered_layers.each do |layer| rendered_level.compose!(layer) end if collision filename = "#{folder}/#{room.area_name}/Rendered Rooms/#{room.filename}_collision.png" else filename = "#{folder}/#{room.area_name}/Rendered Rooms/#{room.filename}.png" end FileUtils::mkdir_p(File.dirname(filename)) rendered_level.save(filename) puts "Wrote #{filename}" end def render_layer(folder, layer, room, collision = false) rendered_layer = ChunkyPNG::Image.new(layer.width*16*16, layer.height*16*12, ChunkyPNG::Color::TRANSPARENT) tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}.png" fs.load_overlay(AREA_INDEX_TO_OVERLAY_INDEX[room.area_index][room.sector_index]) if collision tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}_collision.png" tileset = render_collision_tileset(layer.collision_tileset_ram_pointer, tileset_filename) else tileset = get_tileset(layer.ram_pointer_to_tileset_for_layer, room.palette_offset, room.gfx_pages, layer.colors_per_palette, layer.collision_tileset_ram_pointer, tileset_filename) end layer.tiles.each_with_index do |tile, index_on_level| x_on_tileset = tile.index_on_tileset % 16 y_on_tileset = tile.index_on_tileset / 16 x_on_level = index_on_level % (layer.width*16) y_on_level = index_on_level / (layer.width*16) tile_gfx = tileset.crop(x_on_tileset*16, y_on_tileset*16, 16, 16) if tile.horizontal_flip tile_gfx.mirror! end if tile.vertical_flip tile_gfx.flip! end rendered_layer.compose!(tile_gfx, x_on_level*16, y_on_level*16) end # TODO: OPACITY return rendered_layer end def get_tileset(pointer_to_tileset_for_layer, palette_offset, gfx_pages, colors_per_palette, collision_tileset_offset, tileset_filename) if File.exist?(tileset_filename) ChunkyPNG::Image.from_file(tileset_filename) else render_tileset(pointer_to_tileset_for_layer, palette_offset, gfx_pages, colors_per_palette, collision_tileset_offset, tileset_filename) end end def ensure_tilesets_exist(folder, room, collision=false) room.layers.each do |layer| tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}.png" if !File.exist?(tileset_filename) render_tileset(layer.ram_pointer_to_tileset_for_layer, room.palette_offset, room.gfx_pages, layer.colors_per_palette, layer.collision_tileset_ram_pointer, tileset_filename) end if collision collision_tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}_collision.png" if !File.exist?(collision_tileset_filename) render_collision_tileset(layer.collision_tileset_ram_pointer, collision_tileset_filename) end end end end def render_tileset(tileset_offset, palette_offset, gfx_pages, colors_per_palette, collision_tileset_offset, output_filename=nil) if gfx_pages.empty? return render_collision_tileset(collision_tileset_offset, output_filename) end tileset = Tileset.new(tileset_offset, fs) rendered_tileset = ChunkyPNG::Image.new(Tileset::TILESET_WIDTH_IN_BLOCKS*16, Tileset::TILESET_HEIGHT_IN_BLOCKS*16, ChunkyPNG::Color::TRANSPARENT) palette_list = generate_palettes(palette_offset, 16) if gfx_pages.any?{|gfx| gfx.colors_per_palette == 256} palette_list_256 = generate_palettes(palette_offset, 256) end tileset.tiles.each_with_index do |tile, index_on_tileset| if tile.is_blank next end gfx = gfx_pages[tile.tile_page] if gfx.nil? next # TODO: figure out why this sometimes happens. end if tile.palette_index == 0xFF # TODO. 255 seems to have some special meaning besides an actual palette index. puts "Palette index is 0xFF, tileset #{output_filename}" next end if gfx.colors_per_palette == 16 palette = palette_list[tile.palette_index] else palette = palette_list_256[tile.palette_index] end if palette.nil? puts "Palette index #{tile.palette_index} out of range, tileset #{output_filename}" next # TODO: figure out why this sometimes happens. end graphic_tile = render_graphic_tile(gfx.file, palette, tile.index_on_tile_page) if tile.horizontal_flip graphic_tile.mirror! end if tile.vertical_flip graphic_tile.flip! end x_on_tileset = index_on_tileset % 16 y_on_tileset = index_on_tileset / 16 rendered_tileset.compose!(graphic_tile, x_on_tileset*16, y_on_tileset*16) end if output_filename FileUtils::mkdir_p(File.dirname(output_filename)) rendered_tileset.save(output_filename, :fast_rgba) puts "Wrote #{output_filename}" end return rendered_tileset end def render_graphic_tile(gfx_file, palette, tile_index_on_page) x_block_on_tileset = tile_index_on_page % 8 y_block_on_tileset = tile_index_on_page / 8 render_gfx(gfx_file, palette, x=x_block_on_tileset*16, y=y_block_on_tileset*16, width=16, height=16) end def render_gfx_page(gfx_file, palette, canvas_width=16) render_gfx(gfx_file, palette, x=0, y=0, width=canvas_width*8, height=canvas_width*8, canvas_width=canvas_width*8) end def render_gfx(gfx_file, palette, x, y, width, height, canvas_width=128) rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT) if gfx_file.nil? # Invalid graphics, render a red rectangle instead. rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color.rgba(255, 0, 0, 255)) return rendered_gfx end if palette.nil? # Invalid palette, use a dummy palette instead. palette = generate_palettes(nil, 256).first end if palette.length == 16 pixels_per_byte = 2 elsif palette.length == 256 pixels_per_byte = 1 else raise "Unknown palette length: #{palette.length}" end bytes_per_full_row = canvas_width / pixels_per_byte bytes_per_requested_row = width / pixels_per_byte offset = y*bytes_per_full_row + x/pixels_per_byte (0..height-1).each do |i| pixels_for_chunky = [] fs.read_by_file(gfx_file[:file_path], offset, bytes_per_requested_row, allow_reading_into_next_file_in_ram: true).each_byte do |byte| if pixels_per_byte == 2 pixels = [byte & 0b00001111, byte >> 4] # get the low 4 bits, then the high 4 bits (it's reversed). each is one pixel, two pixels total inside this byte. else pixels = [byte] end pixels.each do |pixel| if pixel == 0 # transparent pixels_for_chunky << ChunkyPNG::Color::TRANSPARENT else pixel_color = palette[pixel] pixels_for_chunky << pixel_color end end end rendered_gfx.replace_row!(i, pixels_for_chunky) offset += bytes_per_full_row end return rendered_gfx rescue NDSFileSystem::OffsetPastEndOfFileError rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color.rgba(255, 0, 0, 255)) return rendered_gfx end def render_gfx_1_dimensional_mode(gfx_file, palette) x = y = 0 width = height = canvas_width = 128 rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT) if gfx_file.nil? # Invalid graphics, render a red rectangle instead. rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color.rgba(255, 0, 0, 255)) return rendered_gfx end if palette.nil? # Invalid palette, use a dummy palette instead. palette = generate_palettes(nil, 16).first end if palette.length == 16 pixels_per_byte = 2 elsif palette.length == 256 pixels_per_byte = 1 raise "256-color palette in 1-dimensional mode" else raise "Unknown palette length: #{palette.length}" end bytes_per_block = 8*8 / pixels_per_byte offset = 0 (0..256-1).each do |block_num| pixels_for_chunky = [] fs.read_by_file(gfx_file[:file_path], offset, bytes_per_block, allow_reading_into_next_file_in_ram: true).each_byte do |byte| if pixels_per_byte == 2 pixels = [byte & 0b00001111, byte >> 4] # get the low 4 bits, then the high 4 bits (it's reversed). each is one pixel, two pixels total inside this byte. else pixels = [byte] end pixels.each do |pixel| if pixel == 0 # transparent pixels_for_chunky << ChunkyPNG::Color::TRANSPARENT else pixel_color = palette[pixel] pixels_for_chunky << pixel_color end end end pixels_for_chunky.each_with_index do |pixel, pixel_num| block_x = (block_num % 16) * 8 block_y = (block_num / 16) * 8 pixel_x = (pixel_num % 8) + block_x pixel_y = (pixel_num / 8) + block_y rendered_gfx[pixel_x, pixel_y] = pixel end offset += bytes_per_block end return rendered_gfx end def generate_palettes(palette_data_start_offset, colors_per_palette) if palette_data_start_offset.nil? # Invalid palette, use a dummy palette instead. palette = [ChunkyPNG::Color.rgba(0, 0, 0, 0)] + [ChunkyPNG::Color.rgba(255, 0, 0, 255)] * (colors_per_palette-1) palette_list = [palette] * 128 # 128 is the maximum number of palettes return palette_list end if colors_per_palette == 256 # color_offsets_per_palette_index: How many colors one index offsets by. This is always 16 for 16-color palettes. But for 256-color palettes it differs between DoS and PoR/OoE. In DoS one index only offsets by 16 colors, meaning you use indexes 0x00, 0x10, 0x20, etc. In PoR and OoE one index offsets by the full 256 colors, meaning you use indexes 0x00, 0x01, 0x02, etc color_offsets_per_palette_index = COLOR_OFFSETS_PER_256_PALETTE_INDEX else color_offsets_per_palette_index = 16 end number_of_palettes = fs.read(palette_data_start_offset+2,1).unpack("C*").first / (color_offsets_per_palette_index/16) palette_data_start_offset += 4 # Skip the first 4 bytes, as they contain the length of this palette page, not the palette data itself. palette_list = [] (0..number_of_palettes-1).each do |palette_index| # todo: cache palettes palette_data = fs.read(palette_data_start_offset + (2*color_offsets_per_palette_index)*palette_index, colors_per_palette*2, allow_length_to_exceed_end_of_file: true) palette = palette_data.unpack("v*").map do |color| # These two bytes hold the rgb data for the color in this format: # ?bbbbbgggggrrrrr # the ? is unknown. #unknown_bit = (color & 0b1000_0000_0000_0000) >> 15 blue_bits = (color & 0b0111_1100_0000_0000) >> 10 green_bits = (color & 0b0000_0011_1110_0000) >> 5 red_bits = color & 0b0000_0000_0001_1111 red = red_bits << 3 green = green_bits << 3 blue = blue_bits << 3 alpha = 255 ChunkyPNG::Color.rgba(red, green, blue, alpha) end palette_list << palette end palette_list end def export_palette_to_palette_swatches_file(palette, file_path) image = ChunkyPNG::Image.new(16, palette.size/16) palette.each_with_index do |color, i| x = i % 16 y = i / 16 image[x,y] = color end image.resample_nearest_neighbor!(image.width*16, image.height*16) # Make the color swatches 16 by 16 instead of a single pixel. image.save(file_path) end def import_palette_from_palette_swatches_file(file_path, colors_per_palette) image = ChunkyPNG::Image.from_file(file_path) if image.width != 16*16 || image.height != colors_per_palette raise GFXImportError.new("The palette file #{file_path} is not the right size, it must be a palette exported by DSVEdit.\n\nIf you want to generate a palette from an arbitrary file use \"Generate palette from file(s)\" instead.") end colors = [] (0..image.width-1).step(16) do |x| (0..image.height-1).step(16) do |y| colors << image[x,y] end end if colors.size > colors_per_palette raise GFXImportError.new("The number of colors in this file (#{file_path}) is greater than #{colors_per_palette}. Cannot import.") end return colors end def import_palette_from_file(file_path, colors_per_palette) image = ChunkyPNG::Image.from_file(file_path) colors = [ChunkyPNG::Color::TRANSPARENT] image.pixels.each do |pixel| colors << pixel unless colors.include?(pixel) end if colors.size > colors_per_palette raise GFXImportError.new("The number of colors in this file (#{file_path}) is greater than #{colors_per_palette}. Cannot import.") end return colors end def import_palette_from_multiple_files(file_paths, colors_per_palette) colors = [] file_paths.each do |file_path| colors += import_palette_from_file(file_path, colors_per_palette) end colors.uniq! if colors.size > colors_per_palette raise GFXImportError.new("The combined number of unique colors in these files is greater than #{colors_per_palette}. Cannot import.") end return colors end def save_palette(colors, palette_list_pointer, palette_index, colors_per_palette) if colors_per_palette == 256 color_offsets_per_palette_index = COLOR_OFFSETS_PER_256_PALETTE_INDEX else color_offsets_per_palette_index = 16 end specific_palette_pointer = palette_list_pointer + 4 + (2*color_offsets_per_palette_index)*palette_index new_palette_data = convert_chunky_color_list_to_palette_data(colors) fs.write(specific_palette_pointer, new_palette_data) end def convert_chunky_color_list_to_palette_data(chunky_colors) game_colors = [] chunky_colors.each do |chunky_color| red = ChunkyPNG::Color.r(chunky_color) green = ChunkyPNG::Color.g(chunky_color) blue = ChunkyPNG::Color.b(chunky_color) red_bits = red >> 3 green_bits = green >> 3 blue_bits = blue >> 3 bits = (blue_bits << 10) | (green_bits << 5) | red_bits game_colors << bits end return game_colors.pack("v*") end def import_gfx_page(input_filename, gfx, palette_list_pointer, colors_per_palette, palette_index) input_image = ChunkyPNG::Image.from_file(input_filename) if input_image.width != input_image.height || ![128, 256].include?(input_image.width) raise GFXImportError.new("Invalid image size. Image must be 128x128 or 256x256.") end colors = generate_palettes(palette_list_pointer, colors_per_palette)[palette_index] colors[0] = ChunkyPNG::Color::TRANSPARENT colors = colors.map{|color| color & 0b11111000111110001111100011111111} # Get rid of unnecessary bits so equality checks work correctly. gfx_data_bytes = [] input_image.pixels.each_with_index do |pixel, i| if pixel & 0xFF == 0 # Transparent color_index = 0 else pixel &= 0b11111000111110001111100011111111 color_index = colors.index(pixel) if color_index.nil? raise GFXImportError.new("The imported image uses different colors than the existing palette. Cannot import.") end if color_index < 0 || color_index > colors_per_palette-1 raise GFXImportError.new("Invalid color (this error shouldn't happen)") end end if i.even? || colors_per_palette == 256 gfx_data_bytes << color_index else gfx_data_bytes[-1] = (gfx_data_bytes[-1] | color_index << 4) end end fs.overwrite_file(gfx.file[:file_path], gfx_data_bytes.pack("C*")) gfx.canvas_width = input_image.width/8 gfx.write_to_rom() end def import_gfx_page_1_dimensional_mode(input_filename, gfx_file, palette_list_pointer, colors_per_palette, palette_index) input_image = ChunkyPNG::Image.from_file(input_filename) colors = generate_palettes(palette_list_pointer, colors_per_palette)[palette_index] colors[0] = ChunkyPNG::Color::TRANSPARENT colors = colors.map{|color| color & 0b11111000111110001111100011111111} # Get rid of unnecessary bits so equality checks work correctly. gfx_data_bytes = [] (0..256-1).each do |block_num| (0..64-1).each do |pixel_num| block_x = (block_num % 16) * 8 block_y = (block_num / 16) * 8 pixel_x = (pixel_num % 8) + block_x pixel_y = (pixel_num / 8) + block_y pixel = input_image[pixel_x,pixel_y] if pixel & 0xFF == 0 # Transparent color_index = 0 else pixel &= 0b11111000111110001111100011111111 color_index = colors.index(pixel) if color_index.nil? raise GFXImportError.new("The imported image uses different colors than the existing palette. Cannot import.") end if color_index < 0 || color_index > colors_per_palette-1 raise GFXImportError.new("Invalid color (this error shouldn't happen)") end end if pixel_num.even? || colors_per_palette == 256 gfx_data_bytes << color_index else gfx_data_bytes[-1] = (gfx_data_bytes[-1] | color_index << 4) end end end fs.write_by_file(gfx_file[:file_path], 0, gfx_data_bytes.pack("C*")) end def render_collision_tileset(collision_tileset_offset, output_filename=nil) if output_filename && File.exist?(output_filename) return ChunkyPNG::Image.from_file(output_filename) end collision_tileset = CollisionTileset.new(collision_tileset_offset, fs) rendered_tileset = ChunkyPNG::Image.new(Tileset::TILESET_WIDTH_IN_BLOCKS*16, Tileset::TILESET_HEIGHT_IN_BLOCKS*16, ChunkyPNG::Color::TRANSPARENT) collision_tileset.tiles.each_with_index do |tile, index_on_tileset| graphic_tile = render_collision_tile(tile) x_on_tileset = index_on_tileset % 16 y_on_tileset = index_on_tileset / 16 rendered_tileset.compose!(graphic_tile, x_on_tileset*16, y_on_tileset*16) end if output_filename FileUtils::mkdir_p(File.dirname(output_filename)) rendered_tileset.save(output_filename, :fast_rgba) puts "Wrote #{output_filename}" end return rendered_tileset end def render_collision_tile(tile) bg_color = ChunkyPNG::Color::TRANSPARENT if tile.is_water bg_color = COLLISION_WATER_COLOR end if tile.block_effect == :damage bg_color = COLLISION_DAMAGE_COLOR end graphic_tile = ChunkyPNG::Image.new(16, 16, bg_color) color = COLLISION_SOLID_COLOR case tile.block_shape when 0..1 # Full block. if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 15, stroke_color = color, fill_color = color) elsif tile.has_top graphic_tile.rect(0, 0, 15, 3, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) elsif tile.has_sides_and_bottom graphic_tile.polygon([0, 0, 7, 7, 15, 0, 15, 15, 0, 15], stroke_color = color, fill_color = color) end when 2 # Half-height block (top half). if tile.block_effect == :conveyor_belt_left if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 15, stroke_color = color, fill_color = color) graphic_tile.polygon([10, 1, 4, 7, 4, 8, 10, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) elsif tile.has_top graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) graphic_tile.polygon([5, 1, 3, 3, 3, 4, 5, 6, 5, 4, 12, 4, 12, 3, 5, 3], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) else graphic_tile.polygon([10, 1, 4, 7, 4, 8, 10, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) end else if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = color) elsif tile.has_top graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) end end when 3 # Half-height block (bottom half). if tile.block_effect == :conveyor_belt_right if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 15, stroke_color = color, fill_color = color) graphic_tile.polygon([5, 1, 11, 7, 11, 8, 5, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) elsif tile.has_top graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) graphic_tile.polygon([10, 1, 12, 3, 12, 4, 10, 6, 10, 4, 3, 4, 3, 3, 10, 3], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) else graphic_tile.polygon([5, 1, 11, 7, 11, 8, 5, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) end else if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 8, 15, 15, stroke_color = color, fill_color = color) elsif tile.has_top graphic_tile.rect(0, 8, 15, 15, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) end end when 4..15 # Slope. case tile.block_shape when 4 width = 16 x_offset = 0 when 8, 10 width = 2*16 x_offset = (tile.block_shape-8)*8 when 12..15 width = 4*16 x_offset = (tile.block_shape-12)*16 else puts "Unknown block shape: #{tile.block_shape}" graphic_tile.rect(1, 1, 14, 14, stroke_color = color, fill_color = ChunkyPNG::Color.rgba(0, 255, 0, 255)) return graphic_tile end if tile.vertical_flip x_end = width-1 y_end = 0 else x_end = 0 y_end = 15 end graphic_tile.polygon([0-x_offset, 0, width-1-x_offset, 15, x_end-x_offset, y_end], stroke_color = COLLISION_SOLID_COLOR, fill_color = COLLISION_SOLID_COLOR) if tile.horizontal_flip graphic_tile.mirror! end end return graphic_tile end def render_map(map, scale = 1) if map.tiles.any? map_width_in_blocks = map.tiles.map{|tile| tile.x_pos}.max + 1 map_height_in_blocks = map.tiles.map{|tile| tile.y_pos}.max + 1 else map_width_in_blocks = map_height_in_blocks = 0 end map_image_width = map_width_in_blocks*4 + 1 map_image_height = map_height_in_blocks*4 + 1 fill_img = ChunkyPNG::Image.new(map_image_width, map_image_height, ChunkyPNG::Color::TRANSPARENT) lines_img = ChunkyPNG::Image.new(map_image_width, map_image_height, ChunkyPNG::Color::TRANSPARENT) # 25 pixels per tile. But they overlap, so the left and top of a tile overlaps the right and bottom of other tiles. map.tiles.each do |tile| if tile.is_blank && !tile.left_door && !tile.left_wall && !tile.top_door && !tile.top_wall && !tile.right_door && !tile.right_wall && !tile.bottom_door && !tile.bottom_wall next end fill_tile, lines_tile = render_map_tile(tile) fill_img.compose!(fill_tile, tile.x_pos*4, tile.y_pos*4) lines_img.compose!(lines_tile, tile.x_pos*4, tile.y_pos*4) end img = fill_img img.compose!(lines_img, 0, 0) unless scale == 1 img.resample_nearest_neighbor!(map_image_width*scale, map_image_height*scale) end return img end def render_map_tile(tile) @fill_color ||= ChunkyPNG::Color.rgba(*MAP_FILL_COLOR) @save_fill_color ||= ChunkyPNG::Color.rgba(*MAP_SAVE_FILL_COLOR) @warp_fill_color ||= ChunkyPNG::Color.rgba(*MAP_WARP_FILL_COLOR) @secret_fill_color ||= ChunkyPNG::Color.rgba(*MAP_SECRET_FILL_COLOR) @entrance_fill_color ||= ChunkyPNG::Color.rgba(*MAP_ENTRANCE_FILL_COLOR) @transition_fill_color ||= ChunkyPNG::Color.rgba(0, 0, 0, 255) @line_color ||= ChunkyPNG::Color.rgba(*MAP_LINE_COLOR) @door_color ||= ChunkyPNG::Color.rgba(*MAP_DOOR_COLOR) @door_center_color ||= ChunkyPNG::Color.rgba(*MAP_DOOR_CENTER_PIXEL_COLOR) @secret_door_color ||= ChunkyPNG::Color.rgba(*MAP_SECRET_DOOR_COLOR) @wall_pixels ||= [line_color]*5 @door_pixels ||= [line_color, door_color, door_center_color, door_color, line_color] @secret_door_pixels ||= [line_color, secret_door_color, secret_door_color, secret_door_color, line_color] color = if tile.is_blank ChunkyPNG::Color::TRANSPARENT elsif tile.is_transition transition_fill_color elsif tile.is_entrance entrance_fill_color elsif tile.is_warp warp_fill_color elsif tile.is_secret secret_fill_color elsif tile.is_save save_fill_color else fill_color end fill_tile = ChunkyPNG::Image.new(5, 5, color) lines_tile = ChunkyPNG::Image.new(5, 5, ChunkyPNG::Color::TRANSPARENT) if tile.left_secret lines_tile.replace_column!(0, secret_door_pixels) elsif tile.left_wall lines_tile.replace_column!(0, wall_pixels) elsif tile.left_door lines_tile.replace_column!(0, door_pixels) end if tile.right_secret lines_tile.replace_column!(4, secret_door_pixels) elsif tile.right_wall lines_tile.replace_column!(4, wall_pixels) elsif tile.right_door lines_tile.replace_column!(4, door_pixels) end if tile.top_secret lines_tile.replace_row!(0, secret_door_pixels) elsif tile.top_wall lines_tile.replace_row!(0, wall_pixels) elsif tile.top_door lines_tile.replace_row!(0, door_pixels) end if tile.bottom_secret lines_tile.replace_row!(4, secret_door_pixels) elsif tile.bottom_wall lines_tile.replace_row!(4, wall_pixels) elsif tile.bottom_door lines_tile.replace_row!(4, door_pixels) end return [fill_tile, lines_tile] end def ensure_sprite_exists(folder, sprite_info, frame_to_render) sprite_filename = "%08X %08X %08X %02X" % [sprite_info.sprite.sprite_pointer, sprite_info.gfx_file_pointers.first, sprite_info.palette_pointer, sprite_info.palette_offset] output_path = "#{folder}/#{sprite_filename}_frame#{frame_to_render}.png" if !File.exist?(output_path) FileUtils::mkdir_p(File.dirname(output_path)) rendered_frames, _ = render_sprite(sprite_info, frame_to_render: frame_to_render) rendered_frames.first.save(output_path, :fast_rgba) puts "Wrote #{output_path}" end return output_path end def render_sprite(sprite_info, frame_to_render: nil, render_hitboxes: false, override_part_palette_index: nil, one_dimensional_mode: false) gfx_file_pointers = sprite_info.gfx_file_pointers palette_pointer = sprite_info.palette_pointer palette_offset = sprite_info.palette_offset sprite = sprite_info.sprite gfx_with_blanks = [] gfx_file_pointers.each do |gfx_file_pointer| gfx = GfxWrapper.new(gfx_file_pointer, fs) gfx_with_blanks << gfx blanks_needed = (gfx.canvas_width/0x10 - 1) * 3 gfx_with_blanks += [nil]*blanks_needed end if gfx_with_blanks.first.render_mode == 1 palettes = generate_palettes(palette_pointer, 16) dummy_palette = generate_palettes(nil, 16).first elsif gfx_with_blanks.first.render_mode == 2 palettes = generate_palettes(palette_pointer, 256) dummy_palette = generate_palettes(nil, 256).first else raise NotImplementedError.new("Unknown render mode.") end rendered_gfx_files_by_palette = Hash.new{|h, k| h[k] = {}} rendered_parts = {} if frame_to_render frame = sprite.frames[frame_to_render] if frame.nil? raise "Invalid frame to render: #{frame_to_render}" end frames = [frame] else frames = sprite.frames end parts_and_hitboxes = (sprite.parts + sprite.hitboxes) min_x = parts_and_hitboxes.map{|item| item.x_pos}.min min_y = parts_and_hitboxes.map{|item| item.y_pos}.min max_x = parts_and_hitboxes.map{|item| item.x_pos + item.width}.max max_y = parts_and_hitboxes.map{|item| item.y_pos + item.height}.max full_width = max_x - min_x full_height = max_y - min_y sprite.parts.each_with_index do |part, part_index| if part.gfx_page_index >= gfx_with_blanks.length puts "GFX page index too large (#{part.gfx_page_index+1} pages needed, have #{gfx_with_blanks.length})" # Invalid gfx page index, so just render a big red square. first_canvas_width = gfx_with_blanks.first.canvas_width rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] ||= render_gfx(nil, nil, 0, 0, first_canvas_width*8, first_canvas_width*8, canvas_width=first_canvas_width*8) else gfx_page = gfx_with_blanks[part.gfx_page_index] gfx_file = gfx_page.file canvas_width = gfx_page.canvas_width if override_part_palette_index # For weapons (which always use the first palette) and skeletally animated enemies (which have their palette specified in the skeleton file). palette = palettes[override_part_palette_index+palette_offset] else palette = palettes[part.palette_index+palette_offset] end if one_dimensional_mode rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] ||= render_gfx_1_dimensional_mode(gfx_file, palette || dummy_palette) else rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] ||= render_gfx(gfx_file, palette || dummy_palette, 0, 0, canvas_width*8, canvas_width*8, canvas_width=canvas_width*8) end end rendered_gfx_file = rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] rendered_parts[part_index] ||= render_sprite_part(part, rendered_gfx_file) end hitbox_color = ChunkyPNG::Color.rgba(255, 0, 0, 128) rendered_frames = [] frames.each do |frame| rendered_frame = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::TRANSPARENT) frame.part_indexes.reverse.each do |part_index| part = sprite.parts[part_index] part_gfx = rendered_parts[part_index] x = part.x_pos - min_x y = part.y_pos - min_y rendered_frame.compose!(part_gfx, x, y) end if render_hitboxes puts frame.hitboxes.size frame.hitboxes.each do |hitbox| x = hitbox.x_pos - min_x y = hitbox.y_pos - min_y rendered_frame.rect(x, y, x + hitbox.width, y + hitbox.height, stroke_color = hitbox_color, fill_color = ChunkyPNG::Color::TRANSPARENT) end end rendered_frames << rendered_frame end return [rendered_frames, min_x, min_y, rendered_parts, gfx_with_blanks, palettes, full_width, full_height] end def render_sprite_part(part, rendered_gfx_file) part_gfx = rendered_gfx_file.crop(part.gfx_x_offset, part.gfx_y_offset, part.width, part.height) if part.horizontal_flip part_gfx.mirror! end if part.vertical_flip part_gfx.flip! end return part_gfx end def render_icon_by_item_type(item_type_index, item_index, mode=:item) item_type = ITEM_TYPES[item_type_index] format = item_type[:format] format_length = format.inject(0){|sum, attr| sum += attr[0]} pointer = item_type[:list_pointer] + item_index*format_length item = Item.new(item_index, item_type, fs) if mode == :item icon_index, palette_index = EXTRACT_ICON_INDEX_AND_PALETTE_INDEX.call(item["Icon"]) else icon_index = item["Icon"] if item_type_index == 0 palette_index = 2 else palette_index = 1 end end render_icon(icon_index, palette_index, mode) end def render_icon_by_global_id(global_id) ITEM_TYPES.each do |item_type| format = item_type[:format] format_length = format.inject(0){|sum, attr| sum += attr[0]} base_pointer = item_type[:list_pointer] item_type[:count].times do |item_index| pointer = base_pointer+item_index*format_length item = Item.new(item_index, item_type, fs) if item["Item ID"] == global_id icon_index, palette_index = EXTRACT_ICON_INDEX_AND_PALETTE_INDEX.call(item["Icon"]) return render_icon(icon_index, palette_index, mode=:item) end end end raise "Could not find item with global ID: %04X" % global_id end def render_icon(icon_index, palette_index, mode=:item) return nil if icon_index == 0 icon_width = mode == :item ? 16 : 32 icon_height = icon_width icons_per_row = 128 / icon_width icons_per_column = 128 / icon_height icons_per_page = 128*128 / icon_width / icon_width gfx_page_index = icon_index / icons_per_page filename = mode == :item ? "item" : "rune" gfx_files = fs.files.values.select do |file| file[:file_path] =~ /\/sc\/f_#{filename}\d+\.dat/ end palette_pointer = mode == :item ? ITEM_ICONS_PALETTE_POINTER : GLYPH_ICONS_PALETTE_POINTER palettes = generate_palettes(palette_pointer, 16) if mode == :item gfx_page_image = render_gfx_1_dimensional_mode(gfx_files[gfx_page_index], palettes[palette_index]) else gfx_page_image = render_gfx_page(gfx_files[gfx_page_index], palettes[palette_index]) end x_pos = ((icon_index % icons_per_page) % icons_per_row) * icon_width y_pos = ((icon_index % icons_per_page) / icons_per_column) * icon_height item_image = gfx_page_image.crop(x_pos, y_pos, icon_width, icon_height) return item_image end def inspect; to_s; end end Fix icons require 'oily_png' class Renderer COLLISION_SOLID_COLOR = ChunkyPNG::Color::BLACK COLLISION_SEMISOLID_COLOR = ChunkyPNG::Color.rgba(127, 127, 127, 255) COLLISION_DAMAGE_COLOR = ChunkyPNG::Color.rgba(208, 32, 32, 255) COLLISION_WATER_COLOR = ChunkyPNG::Color.rgba(32, 32, 208, 255) COLLISION_CONVEYOR_COLOR = ChunkyPNG::Color.rgba(32, 208, 32, 255) class GFXImportError < StandardError ; end attr_reader :fs, :fill_color, :save_fill_color, :warp_fill_color, :secret_fill_color, :entrance_fill_color, :transition_fill_color, :line_color, :door_color, :door_center_color, :secret_door_color, :wall_pixels, :door_pixels, :secret_door_pixels def initialize(fs) @fs = fs end def render_room(folder, room, collision = false) rendered_layers = [] if collision rendered_layers << render_layer(folder, layers.first, room, collision) else room.z_ordered_layers.each do |layer| rendered_layers << render_layer(folder, layer, room, collision) end end if collision bg_color = ChunkyPNG::Color::WHITE else bg_color = ChunkyPNG::Color::BLACK end rendered_level = ChunkyPNG::Image.new(room.max_layer_width*SCREEN_WIDTH_IN_PIXELS, room.max_layer_height*SCREEN_HEIGHT_IN_PIXELS, bg_color) rendered_layers.each do |layer| rendered_level.compose!(layer) end if collision filename = "#{folder}/#{room.area_name}/Rendered Rooms/#{room.filename}_collision.png" else filename = "#{folder}/#{room.area_name}/Rendered Rooms/#{room.filename}.png" end FileUtils::mkdir_p(File.dirname(filename)) rendered_level.save(filename) puts "Wrote #{filename}" end def render_layer(folder, layer, room, collision = false) rendered_layer = ChunkyPNG::Image.new(layer.width*16*16, layer.height*16*12, ChunkyPNG::Color::TRANSPARENT) tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}.png" fs.load_overlay(AREA_INDEX_TO_OVERLAY_INDEX[room.area_index][room.sector_index]) if collision tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}_collision.png" tileset = render_collision_tileset(layer.collision_tileset_ram_pointer, tileset_filename) else tileset = get_tileset(layer.ram_pointer_to_tileset_for_layer, room.palette_offset, room.gfx_pages, layer.colors_per_palette, layer.collision_tileset_ram_pointer, tileset_filename) end layer.tiles.each_with_index do |tile, index_on_level| x_on_tileset = tile.index_on_tileset % 16 y_on_tileset = tile.index_on_tileset / 16 x_on_level = index_on_level % (layer.width*16) y_on_level = index_on_level / (layer.width*16) tile_gfx = tileset.crop(x_on_tileset*16, y_on_tileset*16, 16, 16) if tile.horizontal_flip tile_gfx.mirror! end if tile.vertical_flip tile_gfx.flip! end rendered_layer.compose!(tile_gfx, x_on_level*16, y_on_level*16) end # TODO: OPACITY return rendered_layer end def get_tileset(pointer_to_tileset_for_layer, palette_offset, gfx_pages, colors_per_palette, collision_tileset_offset, tileset_filename) if File.exist?(tileset_filename) ChunkyPNG::Image.from_file(tileset_filename) else render_tileset(pointer_to_tileset_for_layer, palette_offset, gfx_pages, colors_per_palette, collision_tileset_offset, tileset_filename) end end def ensure_tilesets_exist(folder, room, collision=false) room.layers.each do |layer| tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}.png" if !File.exist?(tileset_filename) render_tileset(layer.ram_pointer_to_tileset_for_layer, room.palette_offset, room.gfx_pages, layer.colors_per_palette, layer.collision_tileset_ram_pointer, tileset_filename) end if collision collision_tileset_filename = "#{folder}/#{room.area_name}/Tilesets/#{layer.tileset_filename}_collision.png" if !File.exist?(collision_tileset_filename) render_collision_tileset(layer.collision_tileset_ram_pointer, collision_tileset_filename) end end end end def render_tileset(tileset_offset, palette_offset, gfx_pages, colors_per_palette, collision_tileset_offset, output_filename=nil) if gfx_pages.empty? return render_collision_tileset(collision_tileset_offset, output_filename) end tileset = Tileset.new(tileset_offset, fs) rendered_tileset = ChunkyPNG::Image.new(Tileset::TILESET_WIDTH_IN_BLOCKS*16, Tileset::TILESET_HEIGHT_IN_BLOCKS*16, ChunkyPNG::Color::TRANSPARENT) palette_list = generate_palettes(palette_offset, 16) if gfx_pages.any?{|gfx| gfx.colors_per_palette == 256} palette_list_256 = generate_palettes(palette_offset, 256) end tileset.tiles.each_with_index do |tile, index_on_tileset| if tile.is_blank next end gfx = gfx_pages[tile.tile_page] if gfx.nil? next # TODO: figure out why this sometimes happens. end if tile.palette_index == 0xFF # TODO. 255 seems to have some special meaning besides an actual palette index. puts "Palette index is 0xFF, tileset #{output_filename}" next end if gfx.colors_per_palette == 16 palette = palette_list[tile.palette_index] else palette = palette_list_256[tile.palette_index] end if palette.nil? puts "Palette index #{tile.palette_index} out of range, tileset #{output_filename}" next # TODO: figure out why this sometimes happens. end graphic_tile = render_graphic_tile(gfx.file, palette, tile.index_on_tile_page) if tile.horizontal_flip graphic_tile.mirror! end if tile.vertical_flip graphic_tile.flip! end x_on_tileset = index_on_tileset % 16 y_on_tileset = index_on_tileset / 16 rendered_tileset.compose!(graphic_tile, x_on_tileset*16, y_on_tileset*16) end if output_filename FileUtils::mkdir_p(File.dirname(output_filename)) rendered_tileset.save(output_filename, :fast_rgba) puts "Wrote #{output_filename}" end return rendered_tileset end def render_graphic_tile(gfx_file, palette, tile_index_on_page) x_block_on_tileset = tile_index_on_page % 8 y_block_on_tileset = tile_index_on_page / 8 render_gfx(gfx_file, palette, x=x_block_on_tileset*16, y=y_block_on_tileset*16, width=16, height=16) end def render_gfx_page(gfx_file, palette, canvas_width=16) render_gfx(gfx_file, palette, x=0, y=0, width=canvas_width*8, height=canvas_width*8, canvas_width=canvas_width*8) end def render_gfx(gfx_file, palette, x, y, width, height, canvas_width=128) rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT) if gfx_file.nil? # Invalid graphics, render a red rectangle instead. rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color.rgba(255, 0, 0, 255)) return rendered_gfx end if palette.nil? # Invalid palette, use a dummy palette instead. palette = generate_palettes(nil, 256).first end if palette.length == 16 pixels_per_byte = 2 elsif palette.length == 256 pixels_per_byte = 1 else raise "Unknown palette length: #{palette.length}" end bytes_per_full_row = canvas_width / pixels_per_byte bytes_per_requested_row = width / pixels_per_byte offset = y*bytes_per_full_row + x/pixels_per_byte (0..height-1).each do |i| pixels_for_chunky = [] fs.read_by_file(gfx_file[:file_path], offset, bytes_per_requested_row, allow_reading_into_next_file_in_ram: true).each_byte do |byte| if pixels_per_byte == 2 pixels = [byte & 0b00001111, byte >> 4] # get the low 4 bits, then the high 4 bits (it's reversed). each is one pixel, two pixels total inside this byte. else pixels = [byte] end pixels.each do |pixel| if pixel == 0 # transparent pixels_for_chunky << ChunkyPNG::Color::TRANSPARENT else pixel_color = palette[pixel] pixels_for_chunky << pixel_color end end end rendered_gfx.replace_row!(i, pixels_for_chunky) offset += bytes_per_full_row end return rendered_gfx rescue NDSFileSystem::OffsetPastEndOfFileError rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color.rgba(255, 0, 0, 255)) return rendered_gfx end def render_gfx_1_dimensional_mode(gfx_file, palette) x = y = 0 width = height = canvas_width = 128 rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color::TRANSPARENT) if gfx_file.nil? # Invalid graphics, render a red rectangle instead. rendered_gfx = ChunkyPNG::Image.new(width, height, ChunkyPNG::Color.rgba(255, 0, 0, 255)) return rendered_gfx end if palette.nil? # Invalid palette, use a dummy palette instead. palette = generate_palettes(nil, 16).first end if palette.length == 16 pixels_per_byte = 2 elsif palette.length == 256 pixels_per_byte = 1 raise "256-color palette in 1-dimensional mode" else raise "Unknown palette length: #{palette.length}" end bytes_per_block = 8*8 / pixels_per_byte offset = 0 (0..256-1).each do |block_num| pixels_for_chunky = [] fs.read_by_file(gfx_file[:file_path], offset, bytes_per_block, allow_reading_into_next_file_in_ram: true).each_byte do |byte| if pixels_per_byte == 2 pixels = [byte & 0b00001111, byte >> 4] # get the low 4 bits, then the high 4 bits (it's reversed). each is one pixel, two pixels total inside this byte. else pixels = [byte] end pixels.each do |pixel| if pixel == 0 # transparent pixels_for_chunky << ChunkyPNG::Color::TRANSPARENT else pixel_color = palette[pixel] pixels_for_chunky << pixel_color end end end pixels_for_chunky.each_with_index do |pixel, pixel_num| block_x = (block_num % 16) * 8 block_y = (block_num / 16) * 8 pixel_x = (pixel_num % 8) + block_x pixel_y = (pixel_num / 8) + block_y rendered_gfx[pixel_x, pixel_y] = pixel end offset += bytes_per_block end return rendered_gfx end def generate_palettes(palette_data_start_offset, colors_per_palette) if palette_data_start_offset.nil? # Invalid palette, use a dummy palette instead. palette = [ChunkyPNG::Color.rgba(0, 0, 0, 0)] + [ChunkyPNG::Color.rgba(255, 0, 0, 255)] * (colors_per_palette-1) palette_list = [palette] * 128 # 128 is the maximum number of palettes return palette_list end if colors_per_palette == 256 # color_offsets_per_palette_index: How many colors one index offsets by. This is always 16 for 16-color palettes. But for 256-color palettes it differs between DoS and PoR/OoE. In DoS one index only offsets by 16 colors, meaning you use indexes 0x00, 0x10, 0x20, etc. In PoR and OoE one index offsets by the full 256 colors, meaning you use indexes 0x00, 0x01, 0x02, etc color_offsets_per_palette_index = COLOR_OFFSETS_PER_256_PALETTE_INDEX else color_offsets_per_palette_index = 16 end number_of_palettes = fs.read(palette_data_start_offset+2,1).unpack("C*").first / (color_offsets_per_palette_index/16) palette_data_start_offset += 4 # Skip the first 4 bytes, as they contain the length of this palette page, not the palette data itself. palette_list = [] (0..number_of_palettes-1).each do |palette_index| # todo: cache palettes palette_data = fs.read(palette_data_start_offset + (2*color_offsets_per_palette_index)*palette_index, colors_per_palette*2, allow_length_to_exceed_end_of_file: true) palette = palette_data.unpack("v*").map do |color| # These two bytes hold the rgb data for the color in this format: # ?bbbbbgggggrrrrr # the ? is unknown. #unknown_bit = (color & 0b1000_0000_0000_0000) >> 15 blue_bits = (color & 0b0111_1100_0000_0000) >> 10 green_bits = (color & 0b0000_0011_1110_0000) >> 5 red_bits = color & 0b0000_0000_0001_1111 red = red_bits << 3 green = green_bits << 3 blue = blue_bits << 3 alpha = 255 ChunkyPNG::Color.rgba(red, green, blue, alpha) end palette_list << palette end palette_list end def export_palette_to_palette_swatches_file(palette, file_path) image = ChunkyPNG::Image.new(16, palette.size/16) palette.each_with_index do |color, i| x = i % 16 y = i / 16 image[x,y] = color end image.resample_nearest_neighbor!(image.width*16, image.height*16) # Make the color swatches 16 by 16 instead of a single pixel. image.save(file_path) end def import_palette_from_palette_swatches_file(file_path, colors_per_palette) image = ChunkyPNG::Image.from_file(file_path) if image.width != 16*16 || image.height != colors_per_palette raise GFXImportError.new("The palette file #{file_path} is not the right size, it must be a palette exported by DSVEdit.\n\nIf you want to generate a palette from an arbitrary file use \"Generate palette from file(s)\" instead.") end colors = [] (0..image.width-1).step(16) do |x| (0..image.height-1).step(16) do |y| colors << image[x,y] end end if colors.size > colors_per_palette raise GFXImportError.new("The number of colors in this file (#{file_path}) is greater than #{colors_per_palette}. Cannot import.") end return colors end def import_palette_from_file(file_path, colors_per_palette) image = ChunkyPNG::Image.from_file(file_path) colors = [ChunkyPNG::Color::TRANSPARENT] image.pixels.each do |pixel| colors << pixel unless colors.include?(pixel) end if colors.size > colors_per_palette raise GFXImportError.new("The number of colors in this file (#{file_path}) is greater than #{colors_per_palette}. Cannot import.") end return colors end def import_palette_from_multiple_files(file_paths, colors_per_palette) colors = [] file_paths.each do |file_path| colors += import_palette_from_file(file_path, colors_per_palette) end colors.uniq! if colors.size > colors_per_palette raise GFXImportError.new("The combined number of unique colors in these files is greater than #{colors_per_palette}. Cannot import.") end return colors end def save_palette(colors, palette_list_pointer, palette_index, colors_per_palette) if colors_per_palette == 256 color_offsets_per_palette_index = COLOR_OFFSETS_PER_256_PALETTE_INDEX else color_offsets_per_palette_index = 16 end specific_palette_pointer = palette_list_pointer + 4 + (2*color_offsets_per_palette_index)*palette_index new_palette_data = convert_chunky_color_list_to_palette_data(colors) fs.write(specific_palette_pointer, new_palette_data) end def convert_chunky_color_list_to_palette_data(chunky_colors) game_colors = [] chunky_colors.each do |chunky_color| red = ChunkyPNG::Color.r(chunky_color) green = ChunkyPNG::Color.g(chunky_color) blue = ChunkyPNG::Color.b(chunky_color) red_bits = red >> 3 green_bits = green >> 3 blue_bits = blue >> 3 bits = (blue_bits << 10) | (green_bits << 5) | red_bits game_colors << bits end return game_colors.pack("v*") end def import_gfx_page(input_filename, gfx, palette_list_pointer, colors_per_palette, palette_index) input_image = ChunkyPNG::Image.from_file(input_filename) if input_image.width != input_image.height || ![128, 256].include?(input_image.width) raise GFXImportError.new("Invalid image size. Image must be 128x128 or 256x256.") end colors = generate_palettes(palette_list_pointer, colors_per_palette)[palette_index] colors[0] = ChunkyPNG::Color::TRANSPARENT colors = colors.map{|color| color & 0b11111000111110001111100011111111} # Get rid of unnecessary bits so equality checks work correctly. gfx_data_bytes = [] input_image.pixels.each_with_index do |pixel, i| if pixel & 0xFF == 0 # Transparent color_index = 0 else pixel &= 0b11111000111110001111100011111111 color_index = colors.index(pixel) if color_index.nil? raise GFXImportError.new("The imported image uses different colors than the existing palette. Cannot import.") end if color_index < 0 || color_index > colors_per_palette-1 raise GFXImportError.new("Invalid color (this error shouldn't happen)") end end if i.even? || colors_per_palette == 256 gfx_data_bytes << color_index else gfx_data_bytes[-1] = (gfx_data_bytes[-1] | color_index << 4) end end fs.overwrite_file(gfx.file[:file_path], gfx_data_bytes.pack("C*")) gfx.canvas_width = input_image.width/8 gfx.write_to_rom() end def import_gfx_page_1_dimensional_mode(input_filename, gfx_file, palette_list_pointer, colors_per_palette, palette_index) input_image = ChunkyPNG::Image.from_file(input_filename) colors = generate_palettes(palette_list_pointer, colors_per_palette)[palette_index] colors[0] = ChunkyPNG::Color::TRANSPARENT colors = colors.map{|color| color & 0b11111000111110001111100011111111} # Get rid of unnecessary bits so equality checks work correctly. gfx_data_bytes = [] (0..256-1).each do |block_num| (0..64-1).each do |pixel_num| block_x = (block_num % 16) * 8 block_y = (block_num / 16) * 8 pixel_x = (pixel_num % 8) + block_x pixel_y = (pixel_num / 8) + block_y pixel = input_image[pixel_x,pixel_y] if pixel & 0xFF == 0 # Transparent color_index = 0 else pixel &= 0b11111000111110001111100011111111 color_index = colors.index(pixel) if color_index.nil? raise GFXImportError.new("The imported image uses different colors than the existing palette. Cannot import.") end if color_index < 0 || color_index > colors_per_palette-1 raise GFXImportError.new("Invalid color (this error shouldn't happen)") end end if pixel_num.even? || colors_per_palette == 256 gfx_data_bytes << color_index else gfx_data_bytes[-1] = (gfx_data_bytes[-1] | color_index << 4) end end end fs.write_by_file(gfx_file[:file_path], 0, gfx_data_bytes.pack("C*")) end def render_collision_tileset(collision_tileset_offset, output_filename=nil) if output_filename && File.exist?(output_filename) return ChunkyPNG::Image.from_file(output_filename) end collision_tileset = CollisionTileset.new(collision_tileset_offset, fs) rendered_tileset = ChunkyPNG::Image.new(Tileset::TILESET_WIDTH_IN_BLOCKS*16, Tileset::TILESET_HEIGHT_IN_BLOCKS*16, ChunkyPNG::Color::TRANSPARENT) collision_tileset.tiles.each_with_index do |tile, index_on_tileset| graphic_tile = render_collision_tile(tile) x_on_tileset = index_on_tileset % 16 y_on_tileset = index_on_tileset / 16 rendered_tileset.compose!(graphic_tile, x_on_tileset*16, y_on_tileset*16) end if output_filename FileUtils::mkdir_p(File.dirname(output_filename)) rendered_tileset.save(output_filename, :fast_rgba) puts "Wrote #{output_filename}" end return rendered_tileset end def render_collision_tile(tile) bg_color = ChunkyPNG::Color::TRANSPARENT if tile.is_water bg_color = COLLISION_WATER_COLOR end if tile.block_effect == :damage bg_color = COLLISION_DAMAGE_COLOR end graphic_tile = ChunkyPNG::Image.new(16, 16, bg_color) color = COLLISION_SOLID_COLOR case tile.block_shape when 0..1 # Full block. if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 15, stroke_color = color, fill_color = color) elsif tile.has_top graphic_tile.rect(0, 0, 15, 3, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) elsif tile.has_sides_and_bottom graphic_tile.polygon([0, 0, 7, 7, 15, 0, 15, 15, 0, 15], stroke_color = color, fill_color = color) end when 2 # Half-height block (top half). if tile.block_effect == :conveyor_belt_left if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 15, stroke_color = color, fill_color = color) graphic_tile.polygon([10, 1, 4, 7, 4, 8, 10, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) elsif tile.has_top graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) graphic_tile.polygon([5, 1, 3, 3, 3, 4, 5, 6, 5, 4, 12, 4, 12, 3, 5, 3], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) else graphic_tile.polygon([10, 1, 4, 7, 4, 8, 10, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) end else if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = color) elsif tile.has_top graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) end end when 3 # Half-height block (bottom half). if tile.block_effect == :conveyor_belt_right if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 0, 15, 15, stroke_color = color, fill_color = color) graphic_tile.polygon([5, 1, 11, 7, 11, 8, 5, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) elsif tile.has_top graphic_tile.rect(0, 0, 15, 7, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) graphic_tile.polygon([10, 1, 12, 3, 12, 4, 10, 6, 10, 4, 3, 4, 3, 3, 10, 3], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) else graphic_tile.polygon([5, 1, 11, 7, 11, 8, 5, 14], stroke_color = COLLISION_CONVEYOR_COLOR, fill_color = COLLISION_CONVEYOR_COLOR) end else if tile.has_top && tile.has_sides_and_bottom graphic_tile.rect(0, 8, 15, 15, stroke_color = color, fill_color = color) elsif tile.has_top graphic_tile.rect(0, 8, 15, 15, stroke_color = color, fill_color = COLLISION_SEMISOLID_COLOR) end end when 4..15 # Slope. case tile.block_shape when 4 width = 16 x_offset = 0 when 8, 10 width = 2*16 x_offset = (tile.block_shape-8)*8 when 12..15 width = 4*16 x_offset = (tile.block_shape-12)*16 else puts "Unknown block shape: #{tile.block_shape}" graphic_tile.rect(1, 1, 14, 14, stroke_color = color, fill_color = ChunkyPNG::Color.rgba(0, 255, 0, 255)) return graphic_tile end if tile.vertical_flip x_end = width-1 y_end = 0 else x_end = 0 y_end = 15 end graphic_tile.polygon([0-x_offset, 0, width-1-x_offset, 15, x_end-x_offset, y_end], stroke_color = COLLISION_SOLID_COLOR, fill_color = COLLISION_SOLID_COLOR) if tile.horizontal_flip graphic_tile.mirror! end end return graphic_tile end def render_map(map, scale = 1) if map.tiles.any? map_width_in_blocks = map.tiles.map{|tile| tile.x_pos}.max + 1 map_height_in_blocks = map.tiles.map{|tile| tile.y_pos}.max + 1 else map_width_in_blocks = map_height_in_blocks = 0 end map_image_width = map_width_in_blocks*4 + 1 map_image_height = map_height_in_blocks*4 + 1 fill_img = ChunkyPNG::Image.new(map_image_width, map_image_height, ChunkyPNG::Color::TRANSPARENT) lines_img = ChunkyPNG::Image.new(map_image_width, map_image_height, ChunkyPNG::Color::TRANSPARENT) # 25 pixels per tile. But they overlap, so the left and top of a tile overlaps the right and bottom of other tiles. map.tiles.each do |tile| if tile.is_blank && !tile.left_door && !tile.left_wall && !tile.top_door && !tile.top_wall && !tile.right_door && !tile.right_wall && !tile.bottom_door && !tile.bottom_wall next end fill_tile, lines_tile = render_map_tile(tile) fill_img.compose!(fill_tile, tile.x_pos*4, tile.y_pos*4) lines_img.compose!(lines_tile, tile.x_pos*4, tile.y_pos*4) end img = fill_img img.compose!(lines_img, 0, 0) unless scale == 1 img.resample_nearest_neighbor!(map_image_width*scale, map_image_height*scale) end return img end def render_map_tile(tile) @fill_color ||= ChunkyPNG::Color.rgba(*MAP_FILL_COLOR) @save_fill_color ||= ChunkyPNG::Color.rgba(*MAP_SAVE_FILL_COLOR) @warp_fill_color ||= ChunkyPNG::Color.rgba(*MAP_WARP_FILL_COLOR) @secret_fill_color ||= ChunkyPNG::Color.rgba(*MAP_SECRET_FILL_COLOR) @entrance_fill_color ||= ChunkyPNG::Color.rgba(*MAP_ENTRANCE_FILL_COLOR) @transition_fill_color ||= ChunkyPNG::Color.rgba(0, 0, 0, 255) @line_color ||= ChunkyPNG::Color.rgba(*MAP_LINE_COLOR) @door_color ||= ChunkyPNG::Color.rgba(*MAP_DOOR_COLOR) @door_center_color ||= ChunkyPNG::Color.rgba(*MAP_DOOR_CENTER_PIXEL_COLOR) @secret_door_color ||= ChunkyPNG::Color.rgba(*MAP_SECRET_DOOR_COLOR) @wall_pixels ||= [line_color]*5 @door_pixels ||= [line_color, door_color, door_center_color, door_color, line_color] @secret_door_pixels ||= [line_color, secret_door_color, secret_door_color, secret_door_color, line_color] color = if tile.is_blank ChunkyPNG::Color::TRANSPARENT elsif tile.is_transition transition_fill_color elsif tile.is_entrance entrance_fill_color elsif tile.is_warp warp_fill_color elsif tile.is_secret secret_fill_color elsif tile.is_save save_fill_color else fill_color end fill_tile = ChunkyPNG::Image.new(5, 5, color) lines_tile = ChunkyPNG::Image.new(5, 5, ChunkyPNG::Color::TRANSPARENT) if tile.left_secret lines_tile.replace_column!(0, secret_door_pixels) elsif tile.left_wall lines_tile.replace_column!(0, wall_pixels) elsif tile.left_door lines_tile.replace_column!(0, door_pixels) end if tile.right_secret lines_tile.replace_column!(4, secret_door_pixels) elsif tile.right_wall lines_tile.replace_column!(4, wall_pixels) elsif tile.right_door lines_tile.replace_column!(4, door_pixels) end if tile.top_secret lines_tile.replace_row!(0, secret_door_pixels) elsif tile.top_wall lines_tile.replace_row!(0, wall_pixels) elsif tile.top_door lines_tile.replace_row!(0, door_pixels) end if tile.bottom_secret lines_tile.replace_row!(4, secret_door_pixels) elsif tile.bottom_wall lines_tile.replace_row!(4, wall_pixels) elsif tile.bottom_door lines_tile.replace_row!(4, door_pixels) end return [fill_tile, lines_tile] end def ensure_sprite_exists(folder, sprite_info, frame_to_render) sprite_filename = "%08X %08X %08X %02X" % [sprite_info.sprite.sprite_pointer, sprite_info.gfx_file_pointers.first, sprite_info.palette_pointer, sprite_info.palette_offset] output_path = "#{folder}/#{sprite_filename}_frame#{frame_to_render}.png" if !File.exist?(output_path) FileUtils::mkdir_p(File.dirname(output_path)) rendered_frames, _ = render_sprite(sprite_info, frame_to_render: frame_to_render) rendered_frames.first.save(output_path, :fast_rgba) puts "Wrote #{output_path}" end return output_path end def render_sprite(sprite_info, frame_to_render: nil, render_hitboxes: false, override_part_palette_index: nil, one_dimensional_mode: false) gfx_file_pointers = sprite_info.gfx_file_pointers palette_pointer = sprite_info.palette_pointer palette_offset = sprite_info.palette_offset sprite = sprite_info.sprite gfx_with_blanks = [] gfx_file_pointers.each do |gfx_file_pointer| gfx = GfxWrapper.new(gfx_file_pointer, fs) gfx_with_blanks << gfx blanks_needed = (gfx.canvas_width/0x10 - 1) * 3 gfx_with_blanks += [nil]*blanks_needed end if gfx_with_blanks.first.render_mode == 1 palettes = generate_palettes(palette_pointer, 16) dummy_palette = generate_palettes(nil, 16).first elsif gfx_with_blanks.first.render_mode == 2 palettes = generate_palettes(palette_pointer, 256) dummy_palette = generate_palettes(nil, 256).first else raise NotImplementedError.new("Unknown render mode.") end rendered_gfx_files_by_palette = Hash.new{|h, k| h[k] = {}} rendered_parts = {} if frame_to_render frame = sprite.frames[frame_to_render] if frame.nil? raise "Invalid frame to render: #{frame_to_render}" end frames = [frame] else frames = sprite.frames end parts_and_hitboxes = (sprite.parts + sprite.hitboxes) min_x = parts_and_hitboxes.map{|item| item.x_pos}.min min_y = parts_and_hitboxes.map{|item| item.y_pos}.min max_x = parts_and_hitboxes.map{|item| item.x_pos + item.width}.max max_y = parts_and_hitboxes.map{|item| item.y_pos + item.height}.max full_width = max_x - min_x full_height = max_y - min_y sprite.parts.each_with_index do |part, part_index| if part.gfx_page_index >= gfx_with_blanks.length puts "GFX page index too large (#{part.gfx_page_index+1} pages needed, have #{gfx_with_blanks.length})" # Invalid gfx page index, so just render a big red square. first_canvas_width = gfx_with_blanks.first.canvas_width rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] ||= render_gfx(nil, nil, 0, 0, first_canvas_width*8, first_canvas_width*8, canvas_width=first_canvas_width*8) else gfx_page = gfx_with_blanks[part.gfx_page_index] gfx_file = gfx_page.file canvas_width = gfx_page.canvas_width if override_part_palette_index # For weapons (which always use the first palette) and skeletally animated enemies (which have their palette specified in the skeleton file). palette = palettes[override_part_palette_index+palette_offset] else palette = palettes[part.palette_index+palette_offset] end if one_dimensional_mode rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] ||= render_gfx_1_dimensional_mode(gfx_file, palette || dummy_palette) else rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] ||= render_gfx(gfx_file, palette || dummy_palette, 0, 0, canvas_width*8, canvas_width*8, canvas_width=canvas_width*8) end end rendered_gfx_file = rendered_gfx_files_by_palette[part.palette_index+palette_offset][part.gfx_page_index] rendered_parts[part_index] ||= render_sprite_part(part, rendered_gfx_file) end hitbox_color = ChunkyPNG::Color.rgba(255, 0, 0, 128) rendered_frames = [] frames.each do |frame| rendered_frame = ChunkyPNG::Image.new(full_width, full_height, ChunkyPNG::Color::TRANSPARENT) frame.part_indexes.reverse.each do |part_index| part = sprite.parts[part_index] part_gfx = rendered_parts[part_index] x = part.x_pos - min_x y = part.y_pos - min_y rendered_frame.compose!(part_gfx, x, y) end if render_hitboxes puts frame.hitboxes.size frame.hitboxes.each do |hitbox| x = hitbox.x_pos - min_x y = hitbox.y_pos - min_y rendered_frame.rect(x, y, x + hitbox.width, y + hitbox.height, stroke_color = hitbox_color, fill_color = ChunkyPNG::Color::TRANSPARENT) end end rendered_frames << rendered_frame end return [rendered_frames, min_x, min_y, rendered_parts, gfx_with_blanks, palettes, full_width, full_height] end def render_sprite_part(part, rendered_gfx_file) part_gfx = rendered_gfx_file.crop(part.gfx_x_offset, part.gfx_y_offset, part.width, part.height) if part.horizontal_flip part_gfx.mirror! end if part.vertical_flip part_gfx.flip! end return part_gfx end def render_icon_by_item_type(item_type_index, item_index, mode=:item) item_type = ITEM_TYPES[item_type_index] format = item_type[:format] format_length = format.inject(0){|sum, attr| sum += attr[0]} pointer = item_type[:list_pointer] + item_index*format_length item = GenericEditable.new(item_index, item_type, fs) if mode == :item icon_index, palette_index = EXTRACT_ICON_INDEX_AND_PALETTE_INDEX.call(item["Icon"]) else icon_index = item["Icon"] if item_type_index == 0 palette_index = 2 else palette_index = 1 end end render_icon(icon_index, palette_index, mode) end def render_icon_by_global_id(global_id) ITEM_TYPES.each do |item_type| format = item_type[:format] format_length = format.inject(0){|sum, attr| sum += attr[0]} base_pointer = item_type[:list_pointer] item_type[:count].times do |item_index| pointer = base_pointer+item_index*format_length item = GenericEditable.new(item_index, item_type, fs) if item["Item ID"] == global_id icon_index, palette_index = EXTRACT_ICON_INDEX_AND_PALETTE_INDEX.call(item["Icon"]) return render_icon(icon_index, palette_index, mode=:item) end end end raise "Could not find item with global ID: %04X" % global_id end def render_icon(icon_index, palette_index, mode=:item) return nil if icon_index == 0 icon_width = mode == :item ? 16 : 32 icon_height = icon_width icons_per_row = 128 / icon_width icons_per_column = 128 / icon_height icons_per_page = 128*128 / icon_width / icon_width gfx_page_index = icon_index / icons_per_page filename = mode == :item ? "item" : "rune" gfx_files = fs.files.values.select do |file| file[:file_path] =~ /\/sc\/f_#{filename}\d+\.dat/ end palette_pointer = mode == :item ? ITEM_ICONS_PALETTE_POINTER : GLYPH_ICONS_PALETTE_POINTER palettes = generate_palettes(palette_pointer, 16) if mode == :item gfx_page_image = render_gfx_1_dimensional_mode(gfx_files[gfx_page_index], palettes[palette_index]) else gfx_page_image = render_gfx_page(gfx_files[gfx_page_index], palettes[palette_index]) end x_pos = ((icon_index % icons_per_page) % icons_per_row) * icon_width y_pos = ((icon_index % icons_per_page) / icons_per_column) * icon_height item_image = gfx_page_image.crop(x_pos, y_pos, icon_width, icon_height) return item_image end def inspect; to_s; end end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper # Required for truncate_html require 'rexml/parsers/pullparser' def side_column_links str = "<h3 class=\"head\">#{link_to 'Place Dictionary', '#nogo', {:hreflang => 'Manages geographical features.'}}</h3>\n<ul>\n" str += "<li>#{link_to 'Home', root_path, {:hreflang => 'Search and navigate through places.'}}</li>\n" str += "<li>#{link_to 'Help', '#wiki=/access/wiki/site/c06fa8cf-c49c-4ebc-007f-482de5382105/thl%20place%20dictionary%20end%20user%20manual.html', {:hreflang => 'End User Manual'}}</li>" str += "<li>#{link_to 'Edit', admin_root_path, {:hreflang => 'Manage places.'}}</li>\n" if logged_in? str += "<li>#{link_to 'Editing Help', '#wiki=/access/wiki/site/c06fa8cf-c49c-4ebc-007f-482de5382105/thl%20place%20dictionary%20editorial%20manual.html', {:hreflang => 'Editorial Manual'}}</li>" if logged_in? str += "<li>#{link_to 'Feature Thesaurus', "#iframe=#{SubjectsIntegration::Feature.get_url('20')}", {:hreflang => 'Feature Thesaurus'}}</li>" if defined?(SubjectsIntegration) str += "</ul>" return str.html_safe end # # # def blank_label; '-'; end def breadcrumb_separator "<span class=\"icon shanticon-arrow3-right\"></span>" end def page_header_title if @feature.nil? ts('app.short') else name = @feature.prioritized_name(current_view) name.nil? ? @feature.pid : name.name end end # # Creates a breadcrumb trail to the feature # def f_breadcrumb if @feature.nil? content_tag :ol, "<li>#{link_to(ts('home.this'), root_path)}</li>".html_safe, class: 'breadcrumb' else list = @feature.closest_ancestors_by_perspective(current_perspective).collect do |r| name = r.prioritized_name(current_view) name = name.nil? ? r.pid : name.name link_to(name, feature_path(r.fid)) end list = [link_to("#{ts('app.short')}:", root_path)] + list[0...list.size-1].collect{|e| "#{e}#{breadcrumb_separator}".html_safe} + [list.last] content_tag :ol, list.collect{|e| "<li>#{e}</li>"}.join.html_safe, class: 'breadcrumb' end # content_tag :div, acts_as_family_tree_breadcrumb(feature, breadcrumb_separator) {|r| f_link(r, feature_path(r.fid), {}, {:s => true})}, :class => "breadcrumbs" end # # Creates a breadcrumb trail to the feature name # def fname_breadcrumb(feature_name) acts_as_family_tree_breadcrumb(feature_name) {|r| fname_label(r)} end def concise_fname_breadcrumb(feature_name) label = "" feature_name.all_parents.size.times { label << "> "} label << fname_label(feature_name) label.html_safe end # # Accepts an instance of an ActsAsFamilyTree node and creates a breadcrumb trail from it's ancestors # Can pass a block for item formatting # def acts_as_family_tree_breadcrumb(aaft_instance, sep=' &gt; ') if aaft_instance.parent.nil? grandparent = aaft_instance.all_parent_relations.collect(&:parent_node).detect(&:parent) trail = grandparent.nil? ? [aaft_instance] : grandparent.all_parents + [grandparent, aaft_instance] else trail = aaft_instance.all_parents + [aaft_instance] end trail.collect do |r| block_given? ? yield(r) : r.to_s end.join(sep) end # # Returns the blank_label method output # if the path to the value is invalid or blank # Can specify a different default value by supplying a block # # def_if_blank(feature_name, :type, :name) # def_if_blank(feature_name, :type, :name){'-'} # def def_if_blank(*resource_path) default = block_given? ? yield : blank_label obj = resource_path.shift resource_path.each do |method| return default if ! obj.respond_to?(method) current = obj.send(method) return default if current.to_s.blank? obj = current end obj end # # # def formatted_date(*dates) sep = block_given? ? yield : ' - ' dates.compact.collect {|date| date.to_formatted_s(:us_date)}.join(sep) end # # # def f_label(feature, html_attrs={}) html_attrs[:class] = html_attrs[:class].blank? ? 'feature_name' : "#{html_attrs[:class]} feature_name" html_attrs[:title] ||= h(feature.name) content_tag(:span, fname_labels(feature), html_attrs) end # # # def f_link(feature, url, html_attrs={}, options={}) html_attrs[:class] = html_attrs[:class].blank? ? 'feature_name' : "#{html_attrs[:class]} feature_name" html_attrs[:title] ||= h(feature.name) # url = url_for iframe_feature_path(feature.id) if current_page?(Rails.application.routes.recognize_path iframe_feature_path(feature.id)) name = fname_labels(feature) name = name.s if !options[:s].nil? && options[:s] link_to(name, url, html_attrs) end # # This should be getting the class from the writing system, not language # def fname_labels(feature) #return feature.pid if feature.names.empty? #items = apply_name_preference feature.names.sort #items.collect do |item| # fname_label(item) #end.join(' | ') name = feature.prioritized_name(current_view) if name.nil? feature.pid else fname_label(name) end end def fname_label(feature_name) css_class=feature_name.writing_system.nil? ? nil : feature_name.writing_system.code content_tag(:span, h(feature_name.to_s), {:class=>css_class}) end def description_title(d) title = d.title.blank? ? "Essay" : d.title authors = d.authors.empty? ? "" : " <span class='by'> by </span><span class='content_by'>#{join_with_and(d.authors.collect(&:fullname))}</span><span class='by'> in </span><span class='content_by'>#{d.language.name}</span>" date = " <span class='last_updated'>(#{h(d.updated_at.to_date.to_formatted_s(:long))})</span>" "#{title}#{authors}#{date}".html_safe end def description_simple_title(d) d.title.blank? ? "Essay" : d.title end # # # def note_popup_link_for(object, options={}) unless options[:association_type].blank? if object.respond_to?(:association_notes_for) && object.association_notes_for(options[:association_type]).length > 0 notes = object.association_notes_for(options[:association_type]) link_url = polymorphic_url([object, :association_notes], :association_type => options[:association_type]) end else if object.respond_to?(:notes) && object.public_notes.length > 0 notes = object.public_notes link_url = polymorphic_url([object, :notes]) end end unless notes.nil? link_title = notes.collect{|n| (n.title.nil? ? 'Note' : n.title) + (" by #{n.authors.collect(&:fullname).join(", ").s}" if n.authors.length > 0).to_s}.join(', ') link_classes = "draggable-pop no-view-alone overflow-y-auto height-350" ("<span class='has-draggable-popups note-popup-link'>(" + link_to("", link_url, :class => "note-popup-link-icon "+link_classes, :title => h(link_title)) + link_to("See Note", link_url, :class => "note-popup-link-text "+link_classes, :title => h(link_title)) + ")</span>").html_safe else "" end end # # # def note_popup_link_list_for(object, options={}) unless options[:association_type].blank? if object.respond_to?(:association_notes_for) && object.association_notes_for(options[:association_type]).length > 0 notes = object.association_notes_for(options[:association_type]) end else if object.respond_to?(:notes) && object.public_notes.length > 0 notes = object.public_notes link_url = polymorphic_url([object, :notes]) end end if !notes.nil? && notes.length > 0 # Wrapping this in a <p /> makes its font size incorrect, so for now, we'll achieve the top margin with # a <br />. ('<br /> <strong>Notes:</strong> <ul class="note-popup-link-list">' + notes.collect{|n| "<li>#{note_popup_link(n)}</li>" }.join() + '</ul>').html_safe end end # # # def note_popup_link(note) note_title = note.title.nil? ? "Note" : note.title note_authors = " by #{note.authors.collect(&:fullname).join(", ").s}" if note.authors.length > 0 note_date = " (#{formatted_date(note.updated_at)})" link_title = "#{note_title}#{note_authors}#{note_date}" link_url = polymorphic_url([note.notable, note]) link_classes = "draggable-pop no-view-alone overflow-y-auto height-350" "<span class='has-draggable-popups'> #{link_to(link_title, link_url, :class => link_classes, :title => h(note_title))} </span>".html_safe end # # # def time_units_for(object, options={}) if object.respond_to?(:time_units) if object.time_units.size > 0 time_units_list = object.time_units_ordered_by_date.collect{|tu| "#{tu}#{note_popup_link_for(tu)}" }.reject{|str| str.blank?}.join("; ") "<span class='time-units'>(#{time_units_list})</span>".html_safe end end end # # Allows for specification of what model names should be displayed as to users (e.g. "location" instead of "shape") # def model_display_name(str) names = { 'association_note' => Note.model_name.human, 'description' => Description.model_name.human, 'feature' => Feature.model_name.human, 'feature_geo_code' => FeatureGeoCode.model_name.human, 'feature_name' => FeatureName.model_name.human, 'time_unit' => 'date' } names[str].nil? ? str : names[str] end # # # def yes_no(value) (value.nil? || value==0 || value=='false' || value == false) ? ts(:negation) : ts(:affirmation) end # # # def highlight(string) ('<span class="highlight">' + string + '</span>').html_safe end def custom_secondary_tabs(current_tab_id=:place) @tab_options ||= {} if @tab_options[:entity].blank? tabs = {} else tabs = custom_secondary_tabs_list end current_tab_id = :place unless (tabs.keys << :home).include? current_tab_id tabs = tabs.sort_by{ |t| t[1][:index] }.collect{|tab_id, tab| remove_tab = false if tab[:url].blank? && !@tab_options[:entity].blank? entity = @tab_options[:entity] url = nil count = nil case tab_id when :place url = feature_path(entity.fid) when :descriptions if entity.descriptions.empty? remove_tab = true else url = feature_description_path(entity.fid, entity.descriptions.first) count = entity.descriptions.size end when :related url = related_feature_path(entity.fid) count = entity.all_relations.size end else tab_url = tab[:url] end title = count.nil? ? tab[:title] : "#{tab[:title]} <span class=\"badge\">#{count}</span>" remove_tab ? nil : [tab_id, title, url, tab[:shanticon]] }.reject{|t| t.nil?} tabs end # TODO: Add rules here based on language of name and perspective. def apply_name_preference(names) return [] if names.empty? filtered = [] # FIXME: This should be cleaned up; most direct implementation to get something working latin_names = names.select {|n| !n.writing_system.blank? and n.writing_system.is_latin?} latin_names.each do |name| unless name.language.blank? filtered << name if name.language.is_english? if name.language.is_chinese? related_name = name.relations.select {|r| !r.phonetic_system.blank? and r.phonetic_system.is_pinyin? } filtered << related_name.first.child_node unless related_name.empty? end if name.language.is_nepali? related_name = name.relations.select {|r| !r.phonetic_system.blank? and r.phonetic_system.is_ind_transcrip? } filtered << related_name.first.child_node unless related_name.empty? filtered << name if name.is_original? and related_name.empty? end if name.language.is_tibetan? related_name = name.relations.select {|r| !r.phonetic_system.blank? and r.phonetic_system.is_thl_simple_transcrip? } filtered << related_name.first.child_node unless related_name.empty? end end end # TODO: improve fallback. For now names transcript in latin script are better than nothing. if filtered.empty? latin_names else filtered.uniq # in case any dupes get added end end def join_with_and(list) size = list.size case size when 0 then nil when 1 then list.first when 2 then list.join(' and ') when 3 then [list[0..size-2].join(', '), list[size-1]].join(', and ') end.s end # Custom HTML truncate for PD descriptions, which don't always validate def truncate_html(input, len = 30, extension = "...") #output = input #output.gsub!(/<\/p>\s*<p>/iu, "<br /><br />") #output = sanitize(input, :tags => %w(br h1 h2 h3 h4 h5 h6 ul ol li)) #output.gsub!(/<br.*?>/, "\v") # We need to be able to call .s on the input, but not on the extension, so we # have to use a modified version of truncate() instead of truncate() itself. # output = truncate(input, :length => len, :omission => extension) l = len - extension.size # Temporarily removing .s, as it takes a while to run on long strings #output = (chars.length > len ? chars[0...l].s + extension : input).to_s #output = input.size > len ? input[0...l] + extension : input output = strip_tags(input).strip! #output.gsub!(/\v/, "<br />") return (output.size < len ? output : (output[0...l] + extension)).html_safe end # HTML truncate for valid HTML, requires REXML::Parsers::PullParser def truncate_well_formed_html(input, len = 30, extension = "...") def attrs_to_s(attrs) return '' if attrs.empty? attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ') end p = REXML::Parsers::PullParser.new(input) tags = [] new_len = len results = '' while p.has_next? && new_len > 0 p_e = p.pull case p_e.event_type when :start_element tags.push p_e[0] results << "<#{tags.last} #{attrs_to_s(p_e[1])}>" when :end_element results << "</#{tags.pop}>" when :text results << p_e[0].first(new_len) new_len -= p_e[0].length end end tags.reverse.each do |tag| results << "</#{tag}>" end (results.to_s + (input.length > len ? extension : '')).html_safe end # Override the default page_entries_info from will_paginate def page_entries_info(collection, options = {}) entry_name = options[:entry_name] || (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) (if collection.total_pages < 2 case collection.size when 0; "No #{entry_name.pluralize} found" when 1; "Displaying <b>1</b> #{entry_name}" else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}" end else %{Showing #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b>} % [ collection.offset + 1, collection.offset + collection.length, collection.total_entries ] end).html_safe end def pictures_url(feature) pictures_associated_medium_path(feature.fid) end def videos_url(feature) videos_associated_medium_path(feature.fid) end def documents_url(feature) documents_associated_medium_path(feature.fid) end def object_authorized?(o) current_user.object_authorized?(o) end end Fixes error on truncate_html # Methods added to this helper will be available to all templates in the application. module ApplicationHelper # Required for truncate_html require 'rexml/parsers/pullparser' def side_column_links str = "<h3 class=\"head\">#{link_to 'Place Dictionary', '#nogo', {:hreflang => 'Manages geographical features.'}}</h3>\n<ul>\n" str += "<li>#{link_to 'Home', root_path, {:hreflang => 'Search and navigate through places.'}}</li>\n" str += "<li>#{link_to 'Help', '#wiki=/access/wiki/site/c06fa8cf-c49c-4ebc-007f-482de5382105/thl%20place%20dictionary%20end%20user%20manual.html', {:hreflang => 'End User Manual'}}</li>" str += "<li>#{link_to 'Edit', admin_root_path, {:hreflang => 'Manage places.'}}</li>\n" if logged_in? str += "<li>#{link_to 'Editing Help', '#wiki=/access/wiki/site/c06fa8cf-c49c-4ebc-007f-482de5382105/thl%20place%20dictionary%20editorial%20manual.html', {:hreflang => 'Editorial Manual'}}</li>" if logged_in? str += "<li>#{link_to 'Feature Thesaurus', "#iframe=#{SubjectsIntegration::Feature.get_url('20')}", {:hreflang => 'Feature Thesaurus'}}</li>" if defined?(SubjectsIntegration) str += "</ul>" return str.html_safe end # # # def blank_label; '-'; end def breadcrumb_separator "<span class=\"icon shanticon-arrow3-right\"></span>" end def page_header_title if @feature.nil? ts('app.short') else name = @feature.prioritized_name(current_view) name.nil? ? @feature.pid : name.name end end # # Creates a breadcrumb trail to the feature # def f_breadcrumb if @feature.nil? content_tag :ol, "<li>#{link_to(ts('home.this'), root_path)}</li>".html_safe, class: 'breadcrumb' else list = @feature.closest_ancestors_by_perspective(current_perspective).collect do |r| name = r.prioritized_name(current_view) name = name.nil? ? r.pid : name.name link_to(name, feature_path(r.fid)) end list = [link_to("#{ts('app.short')}:", root_path)] + list[0...list.size-1].collect{|e| "#{e}#{breadcrumb_separator}".html_safe} + [list.last] content_tag :ol, list.collect{|e| "<li>#{e}</li>"}.join.html_safe, class: 'breadcrumb' end # content_tag :div, acts_as_family_tree_breadcrumb(feature, breadcrumb_separator) {|r| f_link(r, feature_path(r.fid), {}, {:s => true})}, :class => "breadcrumbs" end # # Creates a breadcrumb trail to the feature name # def fname_breadcrumb(feature_name) acts_as_family_tree_breadcrumb(feature_name) {|r| fname_label(r)} end def concise_fname_breadcrumb(feature_name) label = "" feature_name.all_parents.size.times { label << "> "} label << fname_label(feature_name) label.html_safe end # # Accepts an instance of an ActsAsFamilyTree node and creates a breadcrumb trail from it's ancestors # Can pass a block for item formatting # def acts_as_family_tree_breadcrumb(aaft_instance, sep=' &gt; ') if aaft_instance.parent.nil? grandparent = aaft_instance.all_parent_relations.collect(&:parent_node).detect(&:parent) trail = grandparent.nil? ? [aaft_instance] : grandparent.all_parents + [grandparent, aaft_instance] else trail = aaft_instance.all_parents + [aaft_instance] end trail.collect do |r| block_given? ? yield(r) : r.to_s end.join(sep) end # # Returns the blank_label method output # if the path to the value is invalid or blank # Can specify a different default value by supplying a block # # def_if_blank(feature_name, :type, :name) # def_if_blank(feature_name, :type, :name){'-'} # def def_if_blank(*resource_path) default = block_given? ? yield : blank_label obj = resource_path.shift resource_path.each do |method| return default if ! obj.respond_to?(method) current = obj.send(method) return default if current.to_s.blank? obj = current end obj end # # # def formatted_date(*dates) sep = block_given? ? yield : ' - ' dates.compact.collect {|date| date.to_formatted_s(:us_date)}.join(sep) end # # # def f_label(feature, html_attrs={}) html_attrs[:class] = html_attrs[:class].blank? ? 'feature_name' : "#{html_attrs[:class]} feature_name" html_attrs[:title] ||= h(feature.name) content_tag(:span, fname_labels(feature), html_attrs) end # # # def f_link(feature, url, html_attrs={}, options={}) html_attrs[:class] = html_attrs[:class].blank? ? 'feature_name' : "#{html_attrs[:class]} feature_name" html_attrs[:title] ||= h(feature.name) # url = url_for iframe_feature_path(feature.id) if current_page?(Rails.application.routes.recognize_path iframe_feature_path(feature.id)) name = fname_labels(feature) name = name.s if !options[:s].nil? && options[:s] link_to(name, url, html_attrs) end # # This should be getting the class from the writing system, not language # def fname_labels(feature) #return feature.pid if feature.names.empty? #items = apply_name_preference feature.names.sort #items.collect do |item| # fname_label(item) #end.join(' | ') name = feature.prioritized_name(current_view) if name.nil? feature.pid else fname_label(name) end end def fname_label(feature_name) css_class=feature_name.writing_system.nil? ? nil : feature_name.writing_system.code content_tag(:span, h(feature_name.to_s), {:class=>css_class}) end def description_title(d) title = d.title.blank? ? "Essay" : d.title authors = d.authors.empty? ? "" : " <span class='by'> by </span><span class='content_by'>#{join_with_and(d.authors.collect(&:fullname))}</span><span class='by'> in </span><span class='content_by'>#{d.language.name}</span>" date = " <span class='last_updated'>(#{h(d.updated_at.to_date.to_formatted_s(:long))})</span>" "#{title}#{authors}#{date}".html_safe end def description_simple_title(d) d.title.blank? ? "Essay" : d.title end # # # def note_popup_link_for(object, options={}) unless options[:association_type].blank? if object.respond_to?(:association_notes_for) && object.association_notes_for(options[:association_type]).length > 0 notes = object.association_notes_for(options[:association_type]) link_url = polymorphic_url([object, :association_notes], :association_type => options[:association_type]) end else if object.respond_to?(:notes) && object.public_notes.length > 0 notes = object.public_notes link_url = polymorphic_url([object, :notes]) end end unless notes.nil? link_title = notes.collect{|n| (n.title.nil? ? 'Note' : n.title) + (" by #{n.authors.collect(&:fullname).join(", ").s}" if n.authors.length > 0).to_s}.join(', ') link_classes = "draggable-pop no-view-alone overflow-y-auto height-350" ("<span class='has-draggable-popups note-popup-link'>(" + link_to("", link_url, :class => "note-popup-link-icon "+link_classes, :title => h(link_title)) + link_to("See Note", link_url, :class => "note-popup-link-text "+link_classes, :title => h(link_title)) + ")</span>").html_safe else "" end end # # # def note_popup_link_list_for(object, options={}) unless options[:association_type].blank? if object.respond_to?(:association_notes_for) && object.association_notes_for(options[:association_type]).length > 0 notes = object.association_notes_for(options[:association_type]) end else if object.respond_to?(:notes) && object.public_notes.length > 0 notes = object.public_notes link_url = polymorphic_url([object, :notes]) end end if !notes.nil? && notes.length > 0 # Wrapping this in a <p /> makes its font size incorrect, so for now, we'll achieve the top margin with # a <br />. ('<br /> <strong>Notes:</strong> <ul class="note-popup-link-list">' + notes.collect{|n| "<li>#{note_popup_link(n)}</li>" }.join() + '</ul>').html_safe end end # # # def note_popup_link(note) note_title = note.title.nil? ? "Note" : note.title note_authors = " by #{note.authors.collect(&:fullname).join(", ").s}" if note.authors.length > 0 note_date = " (#{formatted_date(note.updated_at)})" link_title = "#{note_title}#{note_authors}#{note_date}" link_url = polymorphic_url([note.notable, note]) link_classes = "draggable-pop no-view-alone overflow-y-auto height-350" "<span class='has-draggable-popups'> #{link_to(link_title, link_url, :class => link_classes, :title => h(note_title))} </span>".html_safe end # # # def time_units_for(object, options={}) if object.respond_to?(:time_units) if object.time_units.size > 0 time_units_list = object.time_units_ordered_by_date.collect{|tu| "#{tu}#{note_popup_link_for(tu)}" }.reject{|str| str.blank?}.join("; ") "<span class='time-units'>(#{time_units_list})</span>".html_safe end end end # # Allows for specification of what model names should be displayed as to users (e.g. "location" instead of "shape") # def model_display_name(str) names = { 'association_note' => Note.model_name.human, 'description' => Description.model_name.human, 'feature' => Feature.model_name.human, 'feature_geo_code' => FeatureGeoCode.model_name.human, 'feature_name' => FeatureName.model_name.human, 'time_unit' => 'date' } names[str].nil? ? str : names[str] end # # # def yes_no(value) (value.nil? || value==0 || value=='false' || value == false) ? ts(:negation) : ts(:affirmation) end # # # def highlight(string) ('<span class="highlight">' + string + '</span>').html_safe end def custom_secondary_tabs(current_tab_id=:place) @tab_options ||= {} if @tab_options[:entity].blank? tabs = {} else tabs = custom_secondary_tabs_list end current_tab_id = :place unless (tabs.keys << :home).include? current_tab_id tabs = tabs.sort_by{ |t| t[1][:index] }.collect{|tab_id, tab| remove_tab = false if tab[:url].blank? && !@tab_options[:entity].blank? entity = @tab_options[:entity] url = nil count = nil case tab_id when :place url = feature_path(entity.fid) when :descriptions if entity.descriptions.empty? remove_tab = true else url = feature_description_path(entity.fid, entity.descriptions.first) count = entity.descriptions.size end when :related url = related_feature_path(entity.fid) count = entity.all_relations.size end else tab_url = tab[:url] end title = count.nil? ? tab[:title] : "#{tab[:title]} <span class=\"badge\">#{count}</span>" remove_tab ? nil : [tab_id, title, url, tab[:shanticon]] }.reject{|t| t.nil?} tabs end # TODO: Add rules here based on language of name and perspective. def apply_name_preference(names) return [] if names.empty? filtered = [] # FIXME: This should be cleaned up; most direct implementation to get something working latin_names = names.select {|n| !n.writing_system.blank? and n.writing_system.is_latin?} latin_names.each do |name| unless name.language.blank? filtered << name if name.language.is_english? if name.language.is_chinese? related_name = name.relations.select {|r| !r.phonetic_system.blank? and r.phonetic_system.is_pinyin? } filtered << related_name.first.child_node unless related_name.empty? end if name.language.is_nepali? related_name = name.relations.select {|r| !r.phonetic_system.blank? and r.phonetic_system.is_ind_transcrip? } filtered << related_name.first.child_node unless related_name.empty? filtered << name if name.is_original? and related_name.empty? end if name.language.is_tibetan? related_name = name.relations.select {|r| !r.phonetic_system.blank? and r.phonetic_system.is_thl_simple_transcrip? } filtered << related_name.first.child_node unless related_name.empty? end end end # TODO: improve fallback. For now names transcript in latin script are better than nothing. if filtered.empty? latin_names else filtered.uniq # in case any dupes get added end end def join_with_and(list) size = list.size case size when 0 then nil when 1 then list.first when 2 then list.join(' and ') when 3 then [list[0..size-2].join(', '), list[size-1]].join(', and ') end.s end # Custom HTML truncate for PD descriptions, which don't always validate def truncate_html(input, len = 30, extension = "...") #output = input #output.gsub!(/<\/p>\s*<p>/iu, "<br /><br />") #output = sanitize(input, :tags => %w(br h1 h2 h3 h4 h5 h6 ul ol li)) #output.gsub!(/<br.*?>/, "\v") # We need to be able to call .s on the input, but not on the extension, so we # have to use a modified version of truncate() instead of truncate() itself. # output = truncate(input, :length => len, :omission => extension) l = len - extension.size # Temporarily removing .s, as it takes a while to run on long strings #output = (chars.length > len ? chars[0...l].s + extension : input).to_s #output = input.size > len ? input[0...l] + extension : input output = strip_tags(input) output.strip! #output.gsub!(/\v/, "<br />") return (output.size < len ? output : (output[0...l] + extension)).html_safe end # HTML truncate for valid HTML, requires REXML::Parsers::PullParser def truncate_well_formed_html(input, len = 30, extension = "...") def attrs_to_s(attrs) return '' if attrs.empty? attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ') end p = REXML::Parsers::PullParser.new(input) tags = [] new_len = len results = '' while p.has_next? && new_len > 0 p_e = p.pull case p_e.event_type when :start_element tags.push p_e[0] results << "<#{tags.last} #{attrs_to_s(p_e[1])}>" when :end_element results << "</#{tags.pop}>" when :text results << p_e[0].first(new_len) new_len -= p_e[0].length end end tags.reverse.each do |tag| results << "</#{tag}>" end (results.to_s + (input.length > len ? extension : '')).html_safe end # Override the default page_entries_info from will_paginate def page_entries_info(collection, options = {}) entry_name = options[:entry_name] || (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) (if collection.total_pages < 2 case collection.size when 0; "No #{entry_name.pluralize} found" when 1; "Displaying <b>1</b> #{entry_name}" else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}" end else %{Showing #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b>} % [ collection.offset + 1, collection.offset + collection.length, collection.total_entries ] end).html_safe end def pictures_url(feature) pictures_associated_medium_path(feature.fid) end def videos_url(feature) videos_associated_medium_path(feature.fid) end def documents_url(feature) documents_associated_medium_path(feature.fid) end def object_authorized?(o) current_user.object_authorized?(o) end end
class Vcpkg < Formula desc "C++ Library Manager" homepage "https://github.com/microsoft/vcpkg" url "https://github.com/microsoft/vcpkg/archive/2020.11-1.tar.gz" version "2020.11-1" sha256 "dcae747fddfc1540b57d576afd2ad5191611013cce0bf30f184a1535c3d90fbe" license "MIT" head "https://github.com/microsoft/vcpkg.git" bottle do cellar :any sha256 "e181bbe56ef0d1db7c1cae4a5c6fda76b876ae5a737dbf2748bd84e0b91d1dde" => :catalina sha256 "f055bfcd2264536b1b1b53d6c86d895d10da02a1984fba1350ee24693473dfe6" => :mojave sha256 "64cb1e7805e0908c553974dfe70e19533abd6f3b2ef3c6253276e417e91fc16b" => :high_sierra end depends_on "cmake" => :build depends_on "ninja" => :build if MacOS.version <= :mojave depends_on "gcc" fails_with :clang do cause "'file_status' is unavailable: introduced in macOS 10.15" end end def install # fix for conflicting declaration of 'char* ctermid(char*)' on Mojave # https://github.com/microsoft/vcpkg/issues/9029 ENV.prepend "CXXFLAGS", "-D_CTERMID_H_" if MacOS.version == :mojave args = %w[-useSystemBinaries -disableMetrics] args << "-allowAppleClang" if MacOS.version > :mojave system "./bootstrap-vcpkg.sh", *args bin.install "vcpkg" bin.env_script_all_files(libexec/"bin", VCPKG_ROOT: libexec) libexec.install Dir["*.txt", ".vcpkg-root", "{ports,scripts,triplets}"] end def post_install (var/"vcpkg/installed").mkpath (var/"vcpkg/packages").mkpath ln_s var/"vcpkg/installed", libexec/"installed" ln_s var/"vcpkg/packages", libexec/"packages" end test do assert_match "sqlite3", shell_output("#{bin}/vcpkg search sqlite") end end vcpkg: update 2020.11-1 bottle. class Vcpkg < Formula desc "C++ Library Manager" homepage "https://github.com/microsoft/vcpkg" url "https://github.com/microsoft/vcpkg/archive/2020.11-1.tar.gz" version "2020.11-1" sha256 "dcae747fddfc1540b57d576afd2ad5191611013cce0bf30f184a1535c3d90fbe" license "MIT" head "https://github.com/microsoft/vcpkg.git" bottle do cellar :any sha256 "585cc3fd22497deca02ec61dd63b14653fcb59258f14f3313110d323f240102d" => :catalina sha256 "0e5f3a484461879e358301f2b3e26d26fbd726d5d0495e57c934ecab99e189a7" => :mojave sha256 "79a09d5626c2dc3230e03d412b27762531ae7d7a223653a29666a93d30acdd43" => :high_sierra end depends_on "cmake" => :build depends_on "ninja" => :build if MacOS.version <= :mojave depends_on "gcc" fails_with :clang do cause "'file_status' is unavailable: introduced in macOS 10.15" end end def install # fix for conflicting declaration of 'char* ctermid(char*)' on Mojave # https://github.com/microsoft/vcpkg/issues/9029 ENV.prepend "CXXFLAGS", "-D_CTERMID_H_" if MacOS.version == :mojave args = %w[-useSystemBinaries -disableMetrics] args << "-allowAppleClang" if MacOS.version > :mojave system "./bootstrap-vcpkg.sh", *args bin.install "vcpkg" bin.env_script_all_files(libexec/"bin", VCPKG_ROOT: libexec) libexec.install Dir["*.txt", ".vcpkg-root", "{ports,scripts,triplets}"] end def post_install (var/"vcpkg/installed").mkpath (var/"vcpkg/packages").mkpath ln_s var/"vcpkg/installed", libexec/"installed" ln_s var/"vcpkg/packages", libexec/"packages" end test do assert_match "sqlite3", shell_output("#{bin}/vcpkg search sqlite") end end
module ApplicationHelper include_concern 'ViewsShared' include_concern 'Flash' include_concern 'Listnav' include_concern 'Navbar' include_concern 'PageLayouts' include_concern 'Tasks' include Sandbox include JsHelper include StiRoutingHelper include ToolbarHelper include TextualSummaryHelper include NumberHelper include Title include ReactjsHelper include Webpack VALID_PERF_PARENTS = { "EmsCluster" => :ems_cluster, "Host" => :host }.freeze # Need to generate paths w/o hostname by default to make proxying work. # def url_for_only_path(args) url_for(:only_path => true, **args) end def api_collection_path(klass, *options) identifier = api_identifier_by_class(klass) send("api_#{identifier}_path", *options) end def api_resource_path(record, *options) identifier = api_identifier_by_class(record.class).to_s.singularize send("api_#{identifier}_path", nil, record.id, *options) end def api_identifier_by_class(klass) raise "API plugin not loaded" unless defined?(Api::ApiConfig) @api_cc ||= Api::CollectionConfig.new @api_cc.name_for_klass(klass) || @api_cc.name_for_subclass(klass) end def settings(*path) @settings ||= {} @settings.fetch_path(*path) end def settings_default(default, *path) settings(*path) || default end def websocket_origin proto = request.ssl? ? 'wss' : 'ws' # Retrieve the host that needs to be explicitly allowed for websocket connections host = if request.env['HTTP_X_FORWARDED_HOST'] # Use the first proxy (production) request.env['HTTP_X_FORWARDED_HOST'].split(/,\s*/).first else # Use the HOST header (development) request.env['HTTP_HOST'] end "#{proto}://#{host}" end # Create a hidden div area based on a condition (using for hiding nav panes) def hidden_div_if(condition, options = {}, &block) hidden_tag_if(:div, condition, options, &block) end # Create a hidden span tag based on a condition (using for hiding nav panes) def hidden_span_if(condition, options = {}, &block) hidden_tag_if(:span, condition, options, &block) end def hidden_tag_if(tag, condition, options = {}, &block) options[:style] = "display: none" if condition if block_given? content_tag(tag, options, &block) else # TODO: Remove this old open-tag-only way in favor of block style tag(tag, options, true) end end def hover_class(item) if item.fetch_path(:link) || item.fetch_path(:value).kind_of?(Array) && item[:value].any? { |val| val[:link] } '' else 'no-hover' end end # Check role based authorization for a UI task def role_allows?(**options) features = Array(options[:feature]) if features.blank? $log.debug("Auth failed - no feature was specified (required)") return false end # Detect if queried features are missing from the database and possibly invalid if !Rails.env.production? && MiqProductFeature.where(:identifier => features).count != features.length message = "#{__method__} no feature was found with identifier: #{features.inspect}. Correct the identifier or add it to miq_product_features.yml." identifiers = MiqProductFeature.all.pluck(:identifier) if Rails.env.development? raise message elsif Rails.env.test? && identifiers.length >= 5 raise("#{message} Note: detected features: #{identifiers.inspect}") end end Rbac.role_allows?(:user => User.current_user, **options) rescue false end module_function :role_allows? public :role_allows? # NB: This differs from controller_for_model; until they're unified, # make sure you have the right one. def model_to_controller(record) record.class.base_model.name.underscore end CONTROLLER_TO_MODEL = { "ManageIQ::Providers::CloudManager::Template" => VmOrTemplate, "ManageIQ::Providers::CloudManager::Vm" => VmOrTemplate, "ManageIQ::Providers::InfraManager::Template" => VmOrTemplate, "ManageIQ::Providers::InfraManager::Vm" => VmOrTemplate, "ManageIQ::Providers::AutomationManager" => ConfigurationScript }.freeze def controller_to_model model = self.class.model CONTROLLER_TO_MODEL[model.to_s] || model end MODEL_STRING = { "all_vms" => VmOrTemplate, "all_miq_templates" => MiqTemplate, "based_volumes" => CloudVolume, "instances" => Vm, "images" => MiqTemplate, "groups" => Account, "users" => Account, "host_services" => SystemService, "chargebacks" => ChargebackRate, "playbooks" => ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook, "physical_servers_with_host" => PhysicalServer, "manageiq/providers/automation_managers" => ConfigurationScript, "vms" => VmOrTemplate, "ServiceCatalog" => ServiceTemplate }.freeze HAS_ASSOCATION = { "groups" => "groups", "users" => "users", "event_logs" => "event_logs", "OsProcess" => "processes", "scan_histories" => "scan_histories", "based_volumes" => "based_volumes", "PersistentVolume" => "persistent_volumes", "PhysicalSwitch" => "physical_switches" }.freeze def model_to_report_data # @report_data_additional_options[:model] is most important, others can be removed return @report_data_additional_options[:model] if @report_data_additional_options && @report_data_additional_options[:model] return @display.classify if @display && @display != "main" return params[:db].classify if params[:db] return params[:display].classify if params[:display] controller.class.model.to_s if defined? controller.class.model end def model_string_to_constant(model_string) MODEL_STRING[model_string] || model_string.singularize.classify.constantize end def restful_routed?(record_or_model) model = if record_or_model.kind_of?(Class) record_or_model else record_or_model.class end model = ui_base_model(model) respond_to?("#{model.model_name.route_key}_path") end # Returns whether records support feature or not. # # Params: # records - an array of record instances or a single instance of a record # feature - symbol # Returns: # boolean - true if all records support the feature # - false in case the record (or one of many records) does not # support the feature def records_support_feature?(records, feature) Array.wrap(records).all? do |record| if record.respond_to?("supports_#{feature}?") record.supports?(feature) else # TODO: remove with deleting AvailabilityMixin module record.is_available?(feature) end end end # Create a url for a record that links to the proper controller def url_for_db(db, action = "show", item = nil) if item && restful_routed?(item) return polymorphic_path(item) end if @vm && %w[Account User Group Patch GuestApplication].include?(db) return url_for_only_path(:controller => "vm_or_template", :action => @lastaction, :id => @vm, :show => @id) elsif @host && %w[Patch GuestApplication].include?(db) return url_for_only_path(:controller => "host", :action => @lastaction, :id => @host, :show => @id) else controller, action = db_to_controller(db, action) return url_for_only_path(:controller => controller, :action => action, :id => @id) end end TREE_WITH_TAB = { "diagnostics_server_list" => "svr", "db_details" => "tb", "report_info" => "msc" }.freeze # Create a url to show a record from the passed in view def view_to_url(view, parent = nil) association = view_to_association(view, parent) if association.nil? controller, action = db_to_controller(view.db) if controller == "ems_cloud" && action == "show" return ems_clouds_path end if controller == "ems_infra" && action == "show" return ems_infras_path end if controller == "ems_physical_infra" && action == "show" return ems_physical_infras_path end if controller == "ems_container" && action == "show" return ems_containers_path end if controller == "ems_network" && action == "show" return ems_networks_path end if controller == "ems_storage" && action == "show" return ems_storages_path end if request[:controller] == 'service' && view.db == 'GenericObject' action = 'show' return url_for_only_path(:action => action, :id => params[:id]) + "?display=generic_objects&generic_object_id=" end if @explorer # showing a list view of another CI inside vmx if %w[SecurityGroup SecurityPolicy SecurityPolicyRule FloatingIp NetworkRouter NetwokrService NetworkPort CloudNetwork CloudSubnet LoadBalancer CloudVolume].include?(view.db) return url_for_only_path(:controller => controller, :action => "show") + "/" elsif ["Vm"].include?(view.db) && parent && request.parameters[:controller] != "vm" # this is to handle link to a vm in vm explorer from service explorer return url_for_only_path(:controller => "vm_or_template", :action => "show") + "/" elsif %w[MiqWidget ConfigurationScript MiqReportResult].include?(view.db) && %w[report].include?(request.parameters[:controller]) suffix = '' if params[:tab_id] == "saved_reports" || params[:pressed] == "miq_report_run" || params[:action] == "reload" suffix = x_node end return "/" + request.parameters[:controller] + "/tree_select?id=" + suffix elsif %w[User MiqGroup MiqUserRole Tenant].include?(view.db) && %w[ops].include?(request.parameters[:controller]) if @tagging return false # when tagging Users, Groups, Roles and Tenants, the table is non-clickable else return "/" + request.parameters[:controller] + "/tree_select/?id=" + x_node.split("-")[1] end elsif view.db == "MiqServer" && %w[ops report].include?(request.parameters[:controller]) return "/" + request.parameters[:controller] + "/tree_select/?id=" + TREE_WITH_TAB[active_tab] elsif %w[ScanItemSet MiqSchedule PxeServer PxeImageType IsoDatastore CustomizationTemplate].include?(view.db) && %w[ops pxe report].include?(params[:controller]) return "/#{params[:controller]}/tree_select/?id=#{TreeBuilder.get_prefix_for_model(view.db)}" else return url_for_only_path(:action => action) + "/" # In explorer, don't jump to other controllers end else controller = case controller when 'template_cloud' 'vm_cloud' when 'template_infra' 'vm_infra' when 'miq_ae_domain' 'miq_ae_class' else controller end return url_for_only_path(:controller => 'restful_redirect', :model => 'ExtManagementSystem') if controller == 'ext_management_system' return url_for_only_path(:controller => controller, :action => action, :id => nil) + "/" end else # need to add a check for @explorer while setting controller incase building a link for details screen to show items # i.e users list view screen inside explorer needs to point to vm_or_template controller return url_for_only_path(:controller => parent.kind_of?(VmOrTemplate) && !@explorer ? parent.class.base_model.to_s.underscore : request.parameters["controller"], :action => association, :id => parent.id) + "?#{@explorer ? "x_show" : "show"}=" end end def view_to_association(view, parent) case view.db when "OrchestrationStackOutput" then "outputs" when "OrchestrationStackParameter" then "parameters" when "OrchestrationStackResource" then "resources" when 'AdvancedSetting', 'Filesystem', 'FirewallRule', 'GuestApplication', 'Patch', 'RegistryItem', 'ScanHistory', 'OpenscapRuleResult' then view.db.tableize when "SystemService" case parent.class.base_class.to_s.downcase when "host" then "host_services" when "vm" then @lastaction end when "CloudService" then "host_cloud_services" else view.scoped_association end end # Convert a db name to a controller name and an action def db_to_controller(db, action = "show") action = "x_show" if @explorer case db when "ActionSet" controller = "miq_action" action = "show_set" when "AutomationRequest" controller = "miq_request" action = "show" when "ConditionSet" controller = "condition" when "ManageIQ::Providers::EmbeddedAutomationManager::ConfigurationScriptSource" controller = "ansible_repository" when "ScanItemSet" controller = "ops" action = "ap_show" when "User", "Group", "Patch", "GuestApplication" controller = "vm" action = @lastaction when "Host" && action == 'x_show' controller = "infra_networking" action = @lastaction when "MiqReportResult" if params[:controller] == "chargeback_report" controller = "chargeback_report" action = "show" else controller = "report" action = "show_saved" end when "MiqSchedule" if request.parameters["controller"] == "report" controller = "report" action = "show_schedule" else controller = "ops" action = "schedule_show" end when "MiqAeClass" controller = "miq_ae_class" action = "show_instances" when "MiqAeInstance" controller = "miq_ae_class" action = "show_details" when "SecurityGroup" controller = "security_group" action = "show" when "ServiceResource", "ServiceTemplate" controller = "catalog" when "ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook" controller = "ansible_playbook" when "ManageIQ::Providers::EmbeddedAutomationManager::Authentication" controller = "ansible_credential" when "MiqWorker" controller = request.parameters[:controller] when "ManageIQ::Providers::AnsibleTower::AutomationManager", "OrchestrationStackOutput", "OrchestrationStackParameter", "OrchestrationStackResource", "ManageIQ::Providers::CloudManager::OrchestrationStack", "ManageIQ::Providers::CloudManager::CloudDatabase", "ManageIQ::Providers::ConfigurationManager", "ManageIQ::Providers::AnsibleTower::AutomationManager::ConfiguredSystem", "ManageIQ::Providers::AnsibleTower::AutomationManager::Job", "ConfigurationScript" controller = request.parameters[:controller] when "ContainerVolume" controller = "persistent_volume" when /^ManageIQ::Providers::(\w+)Manager$/ controller = "ems_#{$1.underscore}" when /^ManageIQ::Providers::(\w+)Manager::(\w+)$/ controller = "#{$2.underscore}_#{$1.underscore}" when "EmsAutomation" controller = "ems_automation" when "GenericObject" && request.parameters[:controller] == 'service' controller = request.parameters[:controller] action = 'generic_object' else controller = db.underscore end return controller, action end # Method to create the center toolbar XML def build_toolbar(tb_name) _toolbar_builder.build_toolbar(tb_name) end def _toolbar_builder ToolbarBuilder.new( self, binding, :active => @active, :changed => @changed, :condition => @condition, :condition_policy => @condition_policy, :dashboard => @dashboard, :display => @display, :edit => @edit, :explorer => @explorer, :ght_type => @ght_type, :html => @html, :lastaction => @lastaction, :layout => @layout, :miq_request => @miq_request, :msg_title => @msg_title, :perf_options => @perf_options, :policy => @policy, :record => @record, :report => @report, :report_result_id => @report_result_id, :request_tab => @request_tab, :resolve => @resolve, :sb => @sb, :selected_zone => @selected_zone, :settings => @settings, :showtype => @showtype, :tabform => @tabform, :widget_running => @widget_running, :widgetsets => @widgetsets, :render_chart => @render_chart, ) end # Convert a field (Vm.hardware.disks-size) to a col (disks.size) def field_to_col(field) dbs, fld = field.split("-") (dbs.include?(".") ? "#{dbs.split(".").last}.#{fld}" : fld) end def controller_model_name(controller) ui_lookup(:model => (controller.camelize + "Controller").constantize.model.name) end def is_browser?(name) browser_name = browser_info(:name) name.kind_of?(Array) ? name.include?(browser_name) : (browser_name == name) end def is_browser_os?(os) browser_os = browser_info(:os) os.kind_of?(Array) ? os.include?(browser_os) : (browser_os == os) end def browser_info(typ) session.fetch_path(:browser, typ).to_s end ############# Following methods generate JS lines for render page blocks def javascript_for_timer_type(timer_type) case timer_type when "Monthly" [ javascript_hide("weekly_span"), javascript_hide("daily_span"), javascript_hide("hourly_span"), javascript_show("monthly_span") ] when "Weekly" [ javascript_hide("daily_span"), javascript_hide("hourly_span"), javascript_hide("monthly_span"), javascript_show("weekly_span") ] when "Daily" [ javascript_hide("hourly_span"), javascript_hide("monthly_span"), javascript_hide("weekly_span"), javascript_show("daily_span") ] when "Hourly" [ javascript_hide("daily_span"), javascript_hide("monthly_span"), javascript_hide("weekly_span"), javascript_show("hourly_span") ] when nil [] else [ javascript_hide("daily_span"), javascript_hide("hourly_span"), javascript_hide("monthly_span"), javascript_hide("weekly_span") ] end end # Show/hide the Save and Reset buttons based on whether changes have been made def javascript_for_miq_button_visibility(display, prefix = nil) if prefix "miqButtons('#{display ? 'show' : 'hide'}', '#{prefix}');".html_safe else "miqButtons('#{display ? 'show' : 'hide'}');".html_safe end end def javascript_for_miq_button_visibility_changed(changed) return "" if changed == session[:changed] session[:changed] = changed javascript_for_miq_button_visibility(changed) end # reload all toolbars def javascript_reload_toolbars "sendDataWithRx({redrawToolbar: #{toolbar_from_hash.to_json}});" end def set_edit_timer_from_schedule(schedule) @edit[:new][:timer] ||= ReportHelper::Timer.new if schedule.run_at.nil? t = Time.now.in_time_zone(@edit[:tz]) + 1.day # Default date/time to tomorrow in selected time zone @edit[:new][:timer].typ = 'Once' @edit[:new][:timer].start_date = "#{t.month}/#{t.day}/#{t.year}" else @edit[:new][:timer].update_from_miq_schedule(schedule.run_at, @edit[:tz]) end end # Check if a parent chart has been selected and applies def perf_parent? @perf_options[:model] == "VmOrTemplate" && @perf_options[:typ] != "realtime" && VALID_PERF_PARENTS.keys.include?(@perf_options[:parent]) end # Determine the type of report (performance/trend/chargeback) based on the model def model_report_type(model) if model if model.ends_with?("Performance", "MetricsRollup") return :performance elsif model == ApplicationController::TREND_MODEL return :trend elsif model.starts_with?("Chargeback") return model.downcase.to_sym end end nil end def show_taskbar_in_header? return false if @explorer return false if controller.action_name.end_with?("tagging_edit") hide_actions = %w[ auth_error change_tab show ] return false if @layout == "" && hide_actions.include?(controller.action_name) hide_layouts = %w[ about chargeback container_dashboard ems_infra_dashboard exception miq_ae_automate_button miq_ae_class miq_ae_export miq_ae_tools miq_policy_export miq_policy_rsop monitor_alerts_list monitor_alerts_most_recent monitor_alerts_overview ops pxe report server_build ] return false if hide_layouts.include?(@layout) return false if @layout == "configuration" && @tabform != "ui_4" true end def taskbar_in_header? # this is just @show_taskbar ||= show_taskbar_in_header? .. but nil if @show_taskbar.nil? @show_taskbar = show_taskbar_in_header? else @show_taskbar end end # checking if any of the toolbar is visible def toolbars_visible? (@toolbars['history_tb'] || @toolbars['center_tb'] || @toolbars['view_tb']) && (@toolbars['history_tb'] != 'blank_view_tb' && @toolbars['history_tb'] != 'blank_view_tb' && @toolbars['view_tb'] != 'blank_view_tb') end def check_if_button_is_implemented if !@flash_array && !@refresh_partial # if no button handler ran, show not implemented msg add_flash(_("Button not yet implemented"), :error) @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" elsif @flash_array && @lastaction == "show" @ems = @record = identify_record(params[:id]) @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" end end # Return a blank tb if a placeholder is needed for AJAX explorer screens, return nil if no center toolbar to be shown delegate :center_toolbar_filename, :to => :_toolbar_chooser delegate :x_view_toolbar_filename, :to => :_toolbar_chooser delegate :view_toolbar_filename, :to => :_toolbar_chooser def _toolbar_chooser ToolbarChooser.new( self, binding, :alert_profiles => @alert_profiles, :conditions => @conditions, :dialog => @dialog, :display => @display, :explorer => @explorer, :in_a_form => @in_a_form, :lastaction => @lastaction, :layout => @layout, :nodetype => @nodetype, :policies => @policies, :record => @record, :report => @report, :sb => @sb, :showtype => @showtype, :tabform => @tabform, :view => @view, :center_toolbar => @center_toolbar ) end # Calculate hash of toolbars to render # # keys are toolbar <div> names and values are toobar identifiers (now YAML files) # def calculate_toolbars toolbars = {} if display_back_button? # taskbar branch toolbars['summary_center_tb'] = controller.restful? ? "summary_center_restful_tb" : "summary_center_tb" end # FIXME: singular vs plural for controller.class.toolbar_singular toolbars['center_tb'] = if controller.class.toolbar_plural.present? && params[:action] == 'show_list' "#{controller.class.toolbar_plural}_center_tb" elsif controller.class.toolbar_singular.present? "#{controller.class.toolbar_singular}_center_tb" elsif controller.try(:toolbar) controller.toolbar.to_s else center_toolbar_filename end toolbars['custom_tb'] = controller.custom_toolbar toolbars['view_tb'] = inner_layout_present? ? x_view_toolbar_filename : view_toolbar_filename toolbars end # check if back to summary button needs to be show def display_back_button? # don't need to back button if @record is not there or @record doesnt have name or # evm_display_name column, i.e MiqProvisionRequest return false if @display == "dashboard" if (@lastaction != "show" || (@lastaction == "show" && @display != "main")) && @record && (@record.respond_to?('name') && !@record.name.nil?) return true else return false end end def display_adv_search? %w[auth_key_pair_cloud storage_resource host_initiator physical_storage automation_manager_configured_system availability_zone ems_automation cloud_database cloud_network cloud_object_store_container cloud_object_store_object cloud_subnet cloud_tenant cloud_volume cloud_volume_backup cloud_volume_snapshot cloud_volume_type configuration_job configuration_profile configuration_script configured_system container container_build container_group container_image container_image_registry container_node container_project container_replicator container_route container_service container_template ems_cloud ems_cluster ems_configuration ems_container ems_infra ems_network ems_physical_infra ems_storage flavor floating_ip generic_object_definition host host_aggregate load_balancer miq_template network_port network_router network_service network_service_entry offline orchestration_stack persistent_volume physical_server provider_foreman resource_pool retired security_group security_policy security_policy_rule service services storage templates vm].include?(@layout) end def default_search?(search_name) @default_search.present? && @default_search.name == search_name end def no_default_search?(search_id) @default_search.blank? && search_id.to_i.zero? end def expression_selected_id_or_name(id_or_name, search) @edit[:expression][:selected] && @edit[:expression][:selected][id_or_name] == search && !@edit[:custom_search] end def expression_selected_nil_or_id(search_id) @edit[:expression][:selected].nil? && @edit[:selected].nil? || expression_selected_id_or_name(:id, search_id.to_i) end # Returns description of a filter, for default filter also with "(Default)" def search_description(search) if default_search?(search.name) || @edit && no_default_search?(search.id) && settings_default('0', :default_search, @edit&.dig(@expkey, :exp_model).to_s.to_sym).to_s == '0' _("%{description} (Default)") % {:description => search.description} else _("%{description}") % {:description => search.description} end end # Returns class for a filter from Global filters to highlight it def def_searches_active_filter?(search) if @edit && @edit[:expression] && ((default_search?(search.name) || no_default_search?(search.id)) && expression_selected_nil_or_id(search.id) || (@edit[:expression][:selected] && @edit[:expression][:selected][:id].zero? && search.id.to_i.zero? || expression_selected_id_or_name(:name, search.name))) 'active' else '' end end # Returns class for a filter from My filters to highlight it def my_searches_active_filter?(search) if @edit && @edit[:expression] && (default_search?(search.name) && expression_selected_nil_or_id(search.id) || (@edit[:expression][:selected].nil? && search.id.to_i.zero? || expression_selected_id_or_name(:name, search.name))) 'active' else '' end end # Do we show or hide the clear_search link in the list view title def clear_search_status !!(@edit&.fetch_path(:adv_search_applied, :text)) end # Should we allow the user input checkbox be shown for an atom in the expression editor QS_VALID_USER_INPUT_OPERATORS = ["=", "!=", ">", ">=", "<", "<=", "INCLUDES", "STARTS WITH", "ENDS WITH", "CONTAINS"].freeze QS_VALID_FIELD_TYPES = %i[string boolean integer float percent bytes megabytes].freeze def qs_show_user_input_checkbox? return true if @edit[:expression_method] return false unless @edit[:adv_search_open] # Only allow user input for advanced searches return false unless QS_VALID_USER_INPUT_OPERATORS.include?(@edit[@expkey][:exp_key]) val = (@edit[@expkey][:exp_typ] == "field" && # Field atoms with certain field types return true QS_VALID_FIELD_TYPES.include?(@edit[@expkey][:val1][:type])) || (@edit[@expkey][:exp_typ] == "tag" && # Tag atoms with a tag category chosen return true @edit[@expkey][:exp_tag]) || (@edit[@expkey][:exp_typ] == "count" && # Count atoms with a count col chosen return true @edit[@expkey][:exp_count]) val end # Should we allow the field alias checkbox to be shown for an atom in the expression editor def adv_search_show_alias_checkbox? @edit[:adv_search_open] # Only allow field aliases for advanced searches end def pressed2model_action(pressed) pressed =~ /^(ems_cluster|miq_template|infra_networking|ems_automation)_(.*)$/ ? [$1, $2] : pressed.split('_', 2) end def model_for_vm(record) raise _("Record is not VmOrTemplate class") unless record.kind_of?(VmOrTemplate) if record.kind_of?(ManageIQ::Providers::CloudManager::Vm) ManageIQ::Providers::CloudManager::Vm elsif record.kind_of?(ManageIQ::Providers::InfraManager::Vm) ManageIQ::Providers::InfraManager::Vm elsif record.kind_of?(ManageIQ::Providers::CloudManager::Template) ManageIQ::Providers::CloudManager::Template elsif record.kind_of?(ManageIQ::Providers::InfraManager::Template) ManageIQ::Providers::InfraManager::Template end end def controller_for_vm(model) case model.to_s when "ManageIQ::Providers::CloudManager::Template", "ManageIQ::Providers::CloudManager::Vm" "vm_cloud" when "ManageIQ::Providers::InfraManager::Template", "ManageIQ::Providers::InfraManager::Vm" "vm_infra" else "vm_or_template" end end def model_from_active_tree(tree) case tree when :instances_filter_tree "ManageIQ::Providers::CloudManager::Vm" when :images_filter_tree "ManageIQ::Providers::CloudManager::Template" when :svcs_tree "Service" when :vms_filter_tree "ManageIQ::Providers::InfraManager::Vm" when :templates_filter_tree "ManageIQ::Providers::InfraManager::Template" when :templates_images_filter_tree "MiqTemplate" when :vms_instances_filter_tree "Vm" end end def object_types_for_flash_message(klass, record_ids) if klass == VmOrTemplate object_ary = klass.where(:id => record_ids).collect { |rec| ui_lookup(:model => model_for_vm(rec).to_s) } obj_hash = object_ary.each.with_object(Hash.new(0)) { |obj, h| h[obj] += 1 } obj_hash.collect { |k, v| v == 1 ? k : k.pluralize }.sort.to_sentence else object = ui_lookup(:model => klass.to_s) record_ids.length == 1 ? object : object.pluralize end end def pagination_or_gtl_request? %i[ppsetting searchtag entry sortby sort_choice page].find { |k| params[k] } end def update_gtl_div(action_url = 'explorer', button_div = 'center_tb') render :update do |page| page << javascript_prologue page.replace("gtl_div", :partial => "layouts/x_gtl", :locals => {:action_url => action_url, :button_div => button_div}) page << "miqSparkle(false)" end end def perfmenu_click? return false unless params[:menu_click] perf_menu_click true end def javascript_process_redirect_args(args) # there's no model for ResourceController - defaulting to traditional routing begin model = self.class.model rescue StandardError => _err model = nil end if model && args.class == Hash && args[:action] == 'show' && restful_routed?(model) args.delete(:action) polymorphic_path_redirect(model, args) else args end end def javascript_redirect(args) render :update do |page| page << javascript_prologue page.redirect_to(args) end end def polymorphic_path_redirect(model, args) record = args[:record] ? args[:record] : model.find(args[:id] || params[:id]) args.delete(:record) args.delete(:id) polymorphic_path(record, args) end def javascript_open_window(url) ex = ExplorerPresenter.open_window(url) ex.spinner_off render :json => ex.for_render end # this keeps the main_div wrapping tag, replaces only the inside def replace_main_div(args, options = {}) ex = ExplorerPresenter.main_div.update('main_div', render_to_string(args)) ex.replace("flash_msg_div", render_to_string(:partial => "layouts/flash_msg")) if options[:flash] ex.scroll_top if @flash_array.present? ex.spinner_off if options[:spinner_off] render :json => ex.for_render end def javascript_miq_button_visibility(changed) render :json => ExplorerPresenter.buttons(changed).for_render end def record_no_longer_exists?(what, model = nil) return false unless what.nil? if !@bang || @flash_array.empty? # We already added a better flash message in 'identify_record' # in that case we keep that flash message # otherwise we make a new one. # FIXME: a refactoring of identify_record and related is needed add_flash( if model.present? _("%{model} no longer exists") % {:model => ui_lookup(:model => model)} else _("Error: Record no longer exists in the database") end, :error, true ) session[:flash_msgs] = @flash_array end # Error message is displayed in 'show_list' action if such action exists # otherwise we assume that the 'explorer' action must exist that will display it. redirect_to(:action => respond_to?(:show_list) ? 'show_list' : 'explorer') end def pdf_page_size_style "#{@options[:page_size].sub(/^US-/i, '') || "legal"} #{@options[:page_layout]}" end DOWNLOAD_VIEW_LAYOUTS = %w[action auth_key_pair_cloud automation_manager_configured_system availability_zone alerts_overview alerts_list alerts_most_recent cloud_database cloud_network cloud_object_store_container cloud_object_store_object cloud_subnet cloud_tenant cloud_volume cloud_volume_backup cloud_volume_snapshot cloud_volume_type configuration_job configuration_profile configuration_script_source configured_system container container_build container_dashboard container_group container_image container_image_registry container_node container_project container_replicator container_route container_service container_template storage_resource host_initiator ems_storage ems_cloud ems_cluster ems_configuration ems_container ems_infra ems_infra_dashboard ems_network ems_physical_infra event flavor floating_ip generic_object generic_object_definition guest_device host host_aggregate load_balancer manageiq/providers/embedded_ansible/automation_manager/playbook manageiq/providers/embedded_automation_manager/authentication manageiq/providers/embedded_automation_manager/configuration_script_source miq_schedule miq_template monitor_alerts_overview monitor_alerts_list monitor_alerts_most_recent network_port network_router network_service network_service_entry offline orchestration_stack physical_rack physical_chassis physical_switch physical_storage physical_server persistent_volume policy policy_group security_policy security_policy_rule policy_profile resource_pool retired scan_profile security_group services storage templates].freeze def render_download_view_tb? DOWNLOAD_VIEW_LAYOUTS.include?(@layout) && !@record && !@tagitems && !@ownershipitems && !@retireitems && !@politems && !@in_a_form && %w[show show_list].include?(params[:action]) && @display != "custom_button_events" end def placeholder_if_present(password) password.present? ? "\u25cf" * 8 : '' end def miq_tab_header(id, active = nil, options = {}, &_block) tag_options = {:class => "#{options[:class]} #{active == id ? 'active' : ''}", 'role' => 'tab', 'aria-selected' => "#{active == id ? 'true' : 'false'}", 'aria-controls' => "#{id}", :id => "#{id}_tab"}.merge!(options) content_tag(:li, tag_options) do content_tag(:a, :href => "##{id}", 'data-toggle' => 'tab') do yield end end end def miq_tab_content(id, active = nil, options = {}, &_block) lazy = options[:lazy] && active != id classname = %w[tab-pane] classname << options[:class] if options[:class] classname << 'active' if active == id classname << 'lazy' if lazy options.delete(:lazy) options.delete(:class) content_tag(:div, :id => id, 'role' => 'tabpanel', 'aria-labelledby' => "#{id}_tab", :class => classname.join(' '), **options) do yield unless lazy end end def tree_with_advanced_search? %i[ images_tree images_filter_tree instances_tree instances_filter_tree providers_tree storage_tree svcs_tree templates_filter_tree templates_images_filter_tree vandt_tree vms_filter_tree vms_instances_filter_tree ].include?(x_tree[:tree]) end CONTENT_TYPE_ID = { "report" => "r", "menu" => "m", "chart" => "c" }.freeze def process_show_list_options(options, curr_model = nil) @report_data_additional_options = ApplicationController::ReportDataAdditionalOptions.from_options(options) @report_data_additional_options.with_quadicon_options( :embedded => @embedded, :showlinks => @showlinks, :policy_sim => @policy_sim, :lastaction => @lastaction, :in_a_form => @in_a_form, :display => @display ) @report_data_additional_options.with_row_button(@row_button) if @row_button @report_data_additional_options.with_menu_click(params[:menu_click]) if params[:menu_click] @report_data_additional_options.with_sb_controller(params[:sb_controller]) if params[:sb_controller] @report_data_additional_options.with_model(curr_model) if curr_model @report_data_additional_options.with_no_checkboxes(@no_checkboxes || options[:no_checkboxes]) @report_data_additional_options.with_checkboxes_clicked(params[:miq_grid_checks]) if params[:miq_grid_checks] @report_data_additional_options.freeze end def from_additional_options(additional_options) if additional_options[:match_via_descendants].present? additional_options[:match_via_descendants] = additional_options[:match_via_descendants].constantize end if additional_options[:parent_id].present? && additional_options[:parent_class_name].present? parent_id = additional_options[:parent_id] parent_class = additional_options[:parent_class_name].constantize additional_options[:parent] = parent_class.find(parent_id) if parent_class < ActiveRecord::Base end @row_button = additional_options[:row_button] @no_checkboxes = additional_options[:no_checkboxes] additional_options end # Restore instance variables necessary for proper rendering of quadicons. # This is a temporary solution that is ot be replaced by proper # parametrization of an ancessor class of QuadiconHelper. def restore_quadicon_options(quadicon_options) @embedded = quadicon_options[:embedded] @showlinks = quadicon_options[:showlinks] @policy_sim = quadicon_options[:policy_sim] # @explorer # @view.db # @parent @lastaction = quadicon_options[:lastaction] # we also need to pass the @display because @display passed throught the # session does not persist the null value @display = quadicon_options[:display] # need to pass @in_a_form so get_view does not set advanced search options # in the forms that render gtl that mess up @edit @in_a_form = quadicon_options[:in_a_form] end # Wrapper around jquery-rjs' remote_function which adds an extra .html_safe() # Remove if merged: https://github.com/amatsuda/jquery-rjs/pull/3 def remote_function(options) super(options).to_str end def appliance_name MiqServer.my_server.name end def rbac_common_feature_for_buttons(pressed) # return feature that should be checked for the button that came in case pressed when "rbac_project_add", "rbac_tenant_add" "rbac_tenant_add" else pressed end end def route_exists?(hash) begin url_for_only_path(hash) rescue return false end true end def translate_header_text(text) if text == "Region" Vmdb::Appliance.PRODUCT_NAME + " " + _(text) else _(text) end end def parse_nodetype_and_id(x_node) x_node.split('_').last.split('-') end def r @r ||= proc { |opts| render_to_string(opts) } end # Test if just succesfully deleted an entity that was being displayed def single_delete_test(any_button = false) @flash_array.present? && @single_delete && (any_button || params[:pressed] == "#{table_name}_delete") end # redirect to show_list (after succesfully deleted the entity being displayed) def single_delete_redirect javascript_redirect(:action => 'show_list', :flash_msg => @flash_array[0][:message], :flash_error => @flash_array[0][:level] == :error) end def accessible_select_event_types ApplicationController::Timelines::SELECT_EVENT_TYPE.map { |key, value| [_(key), value] } end def unique_html_id(prefix = 'unknown') "#{prefix}-#{rand(36**8).to_s(36)}" end def self.miq_favicon_path Settings.server.custom_favicon ? '/upload/custom_favicon.ico' : ActionController::Base.helpers.image_path('favicon.ico') end def miq_favicon_link_tag favicon_link_tag(ApplicationHelper.miq_favicon_path) end def provider_paused?(record) provider = if record.kind_of?(ExtManagementSystem) record elsif record.respond_to?(:ext_management_system) record.ext_management_system elsif record.respond_to?(:manager) record.manager end provider.try(:enabled?) == false end # Return a proper column for an appropriate target klass def columns_for_klass(klass) if klass == 'Tenant' [:name, :use_config_for_attributes] elsif klass.safe_constantize.column_names.include?('name') [:name] else [:description] end end def safe_right_cell_text return '' if @right_cell_text.nil? ActiveSupport::SafeBuffer === @right_cell_text ? raw(@right_cell_text) : @right_cell_text end def camelize_quadicon(quad) quad.keys.each_with_object({}) { |k, h| h[k.to_s.camelcase(:lower)] = quad[k] } end def miq_toolbar(toolbars) limit = ::Settings.ui.custom_button_count || 3 react('MiqToolbar', :kebabLimit => limit, :toolbars => toolbars) end def miq_structured_list(data) react('MiqStructuredList', {:title => data[:title], :headers => data[:headers], :rows => data[:rows], :message => data[:message], :mode => ["miq_summary", data[:mode]].join(' ')}) end end fix pdf print to display all records instead of 10 module ApplicationHelper include_concern 'ViewsShared' include_concern 'Flash' include_concern 'Listnav' include_concern 'Navbar' include_concern 'PageLayouts' include_concern 'Tasks' include Sandbox include JsHelper include StiRoutingHelper include ToolbarHelper include TextualSummaryHelper include NumberHelper include Title include ReactjsHelper include Webpack VALID_PERF_PARENTS = { "EmsCluster" => :ems_cluster, "Host" => :host }.freeze # Need to generate paths w/o hostname by default to make proxying work. # def url_for_only_path(args) url_for(:only_path => true, **args) end def api_collection_path(klass, *options) identifier = api_identifier_by_class(klass) send("api_#{identifier}_path", *options) end def api_resource_path(record, *options) identifier = api_identifier_by_class(record.class).to_s.singularize send("api_#{identifier}_path", nil, record.id, *options) end def api_identifier_by_class(klass) raise "API plugin not loaded" unless defined?(Api::ApiConfig) @api_cc ||= Api::CollectionConfig.new @api_cc.name_for_klass(klass) || @api_cc.name_for_subclass(klass) end def settings(*path) @settings ||= {} @settings.fetch_path(*path) end def settings_default(default, *path) settings(*path) || default end def websocket_origin proto = request.ssl? ? 'wss' : 'ws' # Retrieve the host that needs to be explicitly allowed for websocket connections host = if request.env['HTTP_X_FORWARDED_HOST'] # Use the first proxy (production) request.env['HTTP_X_FORWARDED_HOST'].split(/,\s*/).first else # Use the HOST header (development) request.env['HTTP_HOST'] end "#{proto}://#{host}" end # Create a hidden div area based on a condition (using for hiding nav panes) def hidden_div_if(condition, options = {}, &block) hidden_tag_if(:div, condition, options, &block) end # Create a hidden span tag based on a condition (using for hiding nav panes) def hidden_span_if(condition, options = {}, &block) hidden_tag_if(:span, condition, options, &block) end def hidden_tag_if(tag, condition, options = {}, &block) options[:style] = "display: none" if condition if block_given? content_tag(tag, options, &block) else # TODO: Remove this old open-tag-only way in favor of block style tag(tag, options, true) end end def hover_class(item) if item.fetch_path(:link) || item.fetch_path(:value).kind_of?(Array) && item[:value].any? { |val| val[:link] } '' else 'no-hover' end end # Check role based authorization for a UI task def role_allows?(**options) features = Array(options[:feature]) if features.blank? $log.debug("Auth failed - no feature was specified (required)") return false end # Detect if queried features are missing from the database and possibly invalid if !Rails.env.production? && MiqProductFeature.where(:identifier => features).count != features.length message = "#{__method__} no feature was found with identifier: #{features.inspect}. Correct the identifier or add it to miq_product_features.yml." identifiers = MiqProductFeature.all.pluck(:identifier) if Rails.env.development? raise message elsif Rails.env.test? && identifiers.length >= 5 raise("#{message} Note: detected features: #{identifiers.inspect}") end end Rbac.role_allows?(:user => User.current_user, **options) rescue false end module_function :role_allows? public :role_allows? # NB: This differs from controller_for_model; until they're unified, # make sure you have the right one. def model_to_controller(record) record.class.base_model.name.underscore end CONTROLLER_TO_MODEL = { "ManageIQ::Providers::CloudManager::Template" => VmOrTemplate, "ManageIQ::Providers::CloudManager::Vm" => VmOrTemplate, "ManageIQ::Providers::InfraManager::Template" => VmOrTemplate, "ManageIQ::Providers::InfraManager::Vm" => VmOrTemplate, "ManageIQ::Providers::AutomationManager" => ConfigurationScript }.freeze def controller_to_model model = self.class.model CONTROLLER_TO_MODEL[model.to_s] || model end MODEL_STRING = { "all_vms" => VmOrTemplate, "all_miq_templates" => MiqTemplate, "based_volumes" => CloudVolume, "instances" => Vm, "images" => MiqTemplate, "groups" => Account, "users" => Account, "host_services" => SystemService, "chargebacks" => ChargebackRate, "playbooks" => ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook, "physical_servers_with_host" => PhysicalServer, "manageiq/providers/automation_managers" => ConfigurationScript, "vms" => VmOrTemplate, "ServiceCatalog" => ServiceTemplate }.freeze HAS_ASSOCATION = { "groups" => "groups", "users" => "users", "event_logs" => "event_logs", "OsProcess" => "processes", "scan_histories" => "scan_histories", "based_volumes" => "based_volumes", "PersistentVolume" => "persistent_volumes", "PhysicalSwitch" => "physical_switches" }.freeze def model_to_report_data # @report_data_additional_options[:model] is most important, others can be removed return @report_data_additional_options[:model] if @report_data_additional_options && @report_data_additional_options[:model] return @display.classify if @display && @display != "main" return params[:db].classify if params[:db] return params[:display].classify if params[:display] controller.class.model.to_s if defined? controller.class.model end def model_string_to_constant(model_string) MODEL_STRING[model_string] || model_string.singularize.classify.constantize end def restful_routed?(record_or_model) model = if record_or_model.kind_of?(Class) record_or_model else record_or_model.class end model = ui_base_model(model) respond_to?("#{model.model_name.route_key}_path") end # Returns whether records support feature or not. # # Params: # records - an array of record instances or a single instance of a record # feature - symbol # Returns: # boolean - true if all records support the feature # - false in case the record (or one of many records) does not # support the feature def records_support_feature?(records, feature) Array.wrap(records).all? do |record| if record.respond_to?("supports_#{feature}?") record.supports?(feature) else # TODO: remove with deleting AvailabilityMixin module record.is_available?(feature) end end end # Create a url for a record that links to the proper controller def url_for_db(db, action = "show", item = nil) if item && restful_routed?(item) return polymorphic_path(item) end if @vm && %w[Account User Group Patch GuestApplication].include?(db) return url_for_only_path(:controller => "vm_or_template", :action => @lastaction, :id => @vm, :show => @id) elsif @host && %w[Patch GuestApplication].include?(db) return url_for_only_path(:controller => "host", :action => @lastaction, :id => @host, :show => @id) else controller, action = db_to_controller(db, action) return url_for_only_path(:controller => controller, :action => action, :id => @id) end end TREE_WITH_TAB = { "diagnostics_server_list" => "svr", "db_details" => "tb", "report_info" => "msc" }.freeze # Create a url to show a record from the passed in view def view_to_url(view, parent = nil) association = view_to_association(view, parent) if association.nil? controller, action = db_to_controller(view.db) if controller == "ems_cloud" && action == "show" return ems_clouds_path end if controller == "ems_infra" && action == "show" return ems_infras_path end if controller == "ems_physical_infra" && action == "show" return ems_physical_infras_path end if controller == "ems_container" && action == "show" return ems_containers_path end if controller == "ems_network" && action == "show" return ems_networks_path end if controller == "ems_storage" && action == "show" return ems_storages_path end if request[:controller] == 'service' && view.db == 'GenericObject' action = 'show' return url_for_only_path(:action => action, :id => params[:id]) + "?display=generic_objects&generic_object_id=" end if @explorer # showing a list view of another CI inside vmx if %w[SecurityGroup SecurityPolicy SecurityPolicyRule FloatingIp NetworkRouter NetwokrService NetworkPort CloudNetwork CloudSubnet LoadBalancer CloudVolume].include?(view.db) return url_for_only_path(:controller => controller, :action => "show") + "/" elsif ["Vm"].include?(view.db) && parent && request.parameters[:controller] != "vm" # this is to handle link to a vm in vm explorer from service explorer return url_for_only_path(:controller => "vm_or_template", :action => "show") + "/" elsif %w[MiqWidget ConfigurationScript MiqReportResult].include?(view.db) && %w[report].include?(request.parameters[:controller]) suffix = '' if params[:tab_id] == "saved_reports" || params[:pressed] == "miq_report_run" || params[:action] == "reload" suffix = x_node end return "/" + request.parameters[:controller] + "/tree_select?id=" + suffix elsif %w[User MiqGroup MiqUserRole Tenant].include?(view.db) && %w[ops].include?(request.parameters[:controller]) if @tagging return false # when tagging Users, Groups, Roles and Tenants, the table is non-clickable else return "/" + request.parameters[:controller] + "/tree_select/?id=" + x_node.split("-")[1] end elsif view.db == "MiqServer" && %w[ops report].include?(request.parameters[:controller]) return "/" + request.parameters[:controller] + "/tree_select/?id=" + TREE_WITH_TAB[active_tab] elsif %w[ScanItemSet MiqSchedule PxeServer PxeImageType IsoDatastore CustomizationTemplate].include?(view.db) && %w[ops pxe report].include?(params[:controller]) return "/#{params[:controller]}/tree_select/?id=#{TreeBuilder.get_prefix_for_model(view.db)}" else return url_for_only_path(:action => action) + "/" # In explorer, don't jump to other controllers end else controller = case controller when 'template_cloud' 'vm_cloud' when 'template_infra' 'vm_infra' when 'miq_ae_domain' 'miq_ae_class' else controller end return url_for_only_path(:controller => 'restful_redirect', :model => 'ExtManagementSystem') if controller == 'ext_management_system' return url_for_only_path(:controller => controller, :action => action, :id => nil) + "/" end else # need to add a check for @explorer while setting controller incase building a link for details screen to show items # i.e users list view screen inside explorer needs to point to vm_or_template controller return url_for_only_path(:controller => parent.kind_of?(VmOrTemplate) && !@explorer ? parent.class.base_model.to_s.underscore : request.parameters["controller"], :action => association, :id => parent.id) + "?#{@explorer ? "x_show" : "show"}=" end end def view_to_association(view, parent) case view.db when "OrchestrationStackOutput" then "outputs" when "OrchestrationStackParameter" then "parameters" when "OrchestrationStackResource" then "resources" when 'AdvancedSetting', 'Filesystem', 'FirewallRule', 'GuestApplication', 'Patch', 'RegistryItem', 'ScanHistory', 'OpenscapRuleResult' then view.db.tableize when "SystemService" case parent.class.base_class.to_s.downcase when "host" then "host_services" when "vm" then @lastaction end when "CloudService" then "host_cloud_services" else view.scoped_association end end # Convert a db name to a controller name and an action def db_to_controller(db, action = "show") action = "x_show" if @explorer case db when "ActionSet" controller = "miq_action" action = "show_set" when "AutomationRequest" controller = "miq_request" action = "show" when "ConditionSet" controller = "condition" when "ManageIQ::Providers::EmbeddedAutomationManager::ConfigurationScriptSource" controller = "ansible_repository" when "ScanItemSet" controller = "ops" action = "ap_show" when "User", "Group", "Patch", "GuestApplication" controller = "vm" action = @lastaction when "Host" && action == 'x_show' controller = "infra_networking" action = @lastaction when "MiqReportResult" if params[:controller] == "chargeback_report" controller = "chargeback_report" action = "show" else controller = "report" action = "show_saved" end when "MiqSchedule" if request.parameters["controller"] == "report" controller = "report" action = "show_schedule" else controller = "ops" action = "schedule_show" end when "MiqAeClass" controller = "miq_ae_class" action = "show_instances" when "MiqAeInstance" controller = "miq_ae_class" action = "show_details" when "SecurityGroup" controller = "security_group" action = "show" when "ServiceResource", "ServiceTemplate" controller = "catalog" when "ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook" controller = "ansible_playbook" when "ManageIQ::Providers::EmbeddedAutomationManager::Authentication" controller = "ansible_credential" when "MiqWorker" controller = request.parameters[:controller] when "ManageIQ::Providers::AnsibleTower::AutomationManager", "OrchestrationStackOutput", "OrchestrationStackParameter", "OrchestrationStackResource", "ManageIQ::Providers::CloudManager::OrchestrationStack", "ManageIQ::Providers::CloudManager::CloudDatabase", "ManageIQ::Providers::ConfigurationManager", "ManageIQ::Providers::AnsibleTower::AutomationManager::ConfiguredSystem", "ManageIQ::Providers::AnsibleTower::AutomationManager::Job", "ConfigurationScript" controller = request.parameters[:controller] when "ContainerVolume" controller = "persistent_volume" when /^ManageIQ::Providers::(\w+)Manager$/ controller = "ems_#{$1.underscore}" when /^ManageIQ::Providers::(\w+)Manager::(\w+)$/ controller = "#{$2.underscore}_#{$1.underscore}" when "EmsAutomation" controller = "ems_automation" when "GenericObject" && request.parameters[:controller] == 'service' controller = request.parameters[:controller] action = 'generic_object' else controller = db.underscore end return controller, action end # Method to create the center toolbar XML def build_toolbar(tb_name) _toolbar_builder.build_toolbar(tb_name) end def _toolbar_builder ToolbarBuilder.new( self, binding, :active => @active, :changed => @changed, :condition => @condition, :condition_policy => @condition_policy, :dashboard => @dashboard, :display => @display, :edit => @edit, :explorer => @explorer, :ght_type => @ght_type, :html => @html, :lastaction => @lastaction, :layout => @layout, :miq_request => @miq_request, :msg_title => @msg_title, :perf_options => @perf_options, :policy => @policy, :record => @record, :report => @report, :report_result_id => @report_result_id, :request_tab => @request_tab, :resolve => @resolve, :sb => @sb, :selected_zone => @selected_zone, :settings => @settings, :showtype => @showtype, :tabform => @tabform, :widget_running => @widget_running, :widgetsets => @widgetsets, :render_chart => @render_chart, ) end # Convert a field (Vm.hardware.disks-size) to a col (disks.size) def field_to_col(field) dbs, fld = field.split("-") (dbs.include?(".") ? "#{dbs.split(".").last}.#{fld}" : fld) end def controller_model_name(controller) ui_lookup(:model => (controller.camelize + "Controller").constantize.model.name) end def is_browser?(name) browser_name = browser_info(:name) name.kind_of?(Array) ? name.include?(browser_name) : (browser_name == name) end def is_browser_os?(os) browser_os = browser_info(:os) os.kind_of?(Array) ? os.include?(browser_os) : (browser_os == os) end def browser_info(typ) session.fetch_path(:browser, typ).to_s end ############# Following methods generate JS lines for render page blocks def javascript_for_timer_type(timer_type) case timer_type when "Monthly" [ javascript_hide("weekly_span"), javascript_hide("daily_span"), javascript_hide("hourly_span"), javascript_show("monthly_span") ] when "Weekly" [ javascript_hide("daily_span"), javascript_hide("hourly_span"), javascript_hide("monthly_span"), javascript_show("weekly_span") ] when "Daily" [ javascript_hide("hourly_span"), javascript_hide("monthly_span"), javascript_hide("weekly_span"), javascript_show("daily_span") ] when "Hourly" [ javascript_hide("daily_span"), javascript_hide("monthly_span"), javascript_hide("weekly_span"), javascript_show("hourly_span") ] when nil [] else [ javascript_hide("daily_span"), javascript_hide("hourly_span"), javascript_hide("monthly_span"), javascript_hide("weekly_span") ] end end # Show/hide the Save and Reset buttons based on whether changes have been made def javascript_for_miq_button_visibility(display, prefix = nil) if prefix "miqButtons('#{display ? 'show' : 'hide'}', '#{prefix}');".html_safe else "miqButtons('#{display ? 'show' : 'hide'}');".html_safe end end def javascript_for_miq_button_visibility_changed(changed) return "" if changed == session[:changed] session[:changed] = changed javascript_for_miq_button_visibility(changed) end # reload all toolbars def javascript_reload_toolbars "sendDataWithRx({redrawToolbar: #{toolbar_from_hash.to_json}});" end def set_edit_timer_from_schedule(schedule) @edit[:new][:timer] ||= ReportHelper::Timer.new if schedule.run_at.nil? t = Time.now.in_time_zone(@edit[:tz]) + 1.day # Default date/time to tomorrow in selected time zone @edit[:new][:timer].typ = 'Once' @edit[:new][:timer].start_date = "#{t.month}/#{t.day}/#{t.year}" else @edit[:new][:timer].update_from_miq_schedule(schedule.run_at, @edit[:tz]) end end # Check if a parent chart has been selected and applies def perf_parent? @perf_options[:model] == "VmOrTemplate" && @perf_options[:typ] != "realtime" && VALID_PERF_PARENTS.keys.include?(@perf_options[:parent]) end # Determine the type of report (performance/trend/chargeback) based on the model def model_report_type(model) if model if model.ends_with?("Performance", "MetricsRollup") return :performance elsif model == ApplicationController::TREND_MODEL return :trend elsif model.starts_with?("Chargeback") return model.downcase.to_sym end end nil end def show_taskbar_in_header? return false if @explorer return false if controller.action_name.end_with?("tagging_edit") hide_actions = %w[ auth_error change_tab show ] return false if @layout == "" && hide_actions.include?(controller.action_name) hide_layouts = %w[ about chargeback container_dashboard ems_infra_dashboard exception miq_ae_automate_button miq_ae_class miq_ae_export miq_ae_tools miq_policy_export miq_policy_rsop monitor_alerts_list monitor_alerts_most_recent monitor_alerts_overview ops pxe report server_build ] return false if hide_layouts.include?(@layout) return false if @layout == "configuration" && @tabform != "ui_4" true end def taskbar_in_header? # this is just @show_taskbar ||= show_taskbar_in_header? .. but nil if @show_taskbar.nil? @show_taskbar = show_taskbar_in_header? else @show_taskbar end end # checking if any of the toolbar is visible def toolbars_visible? (@toolbars['history_tb'] || @toolbars['center_tb'] || @toolbars['view_tb']) && (@toolbars['history_tb'] != 'blank_view_tb' && @toolbars['history_tb'] != 'blank_view_tb' && @toolbars['view_tb'] != 'blank_view_tb') end def check_if_button_is_implemented if !@flash_array && !@refresh_partial # if no button handler ran, show not implemented msg add_flash(_("Button not yet implemented"), :error) @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" elsif @flash_array && @lastaction == "show" @ems = @record = identify_record(params[:id]) @refresh_partial = "layouts/flash_msg" @refresh_div = "flash_msg_div" end end # Return a blank tb if a placeholder is needed for AJAX explorer screens, return nil if no center toolbar to be shown delegate :center_toolbar_filename, :to => :_toolbar_chooser delegate :x_view_toolbar_filename, :to => :_toolbar_chooser delegate :view_toolbar_filename, :to => :_toolbar_chooser def _toolbar_chooser ToolbarChooser.new( self, binding, :alert_profiles => @alert_profiles, :conditions => @conditions, :dialog => @dialog, :display => @display, :explorer => @explorer, :in_a_form => @in_a_form, :lastaction => @lastaction, :layout => @layout, :nodetype => @nodetype, :policies => @policies, :record => @record, :report => @report, :sb => @sb, :showtype => @showtype, :tabform => @tabform, :view => @view, :center_toolbar => @center_toolbar ) end # Calculate hash of toolbars to render # # keys are toolbar <div> names and values are toobar identifiers (now YAML files) # def calculate_toolbars toolbars = {} if display_back_button? # taskbar branch toolbars['summary_center_tb'] = controller.restful? ? "summary_center_restful_tb" : "summary_center_tb" end # FIXME: singular vs plural for controller.class.toolbar_singular toolbars['center_tb'] = if controller.class.toolbar_plural.present? && params[:action] == 'show_list' "#{controller.class.toolbar_plural}_center_tb" elsif controller.class.toolbar_singular.present? "#{controller.class.toolbar_singular}_center_tb" elsif controller.try(:toolbar) controller.toolbar.to_s else center_toolbar_filename end toolbars['custom_tb'] = controller.custom_toolbar toolbars['view_tb'] = inner_layout_present? ? x_view_toolbar_filename : view_toolbar_filename toolbars end # check if back to summary button needs to be show def display_back_button? # don't need to back button if @record is not there or @record doesnt have name or # evm_display_name column, i.e MiqProvisionRequest return false if @display == "dashboard" if (@lastaction != "show" || (@lastaction == "show" && @display != "main")) && @record && (@record.respond_to?('name') && !@record.name.nil?) return true else return false end end def display_adv_search? %w[auth_key_pair_cloud storage_resource host_initiator physical_storage automation_manager_configured_system availability_zone ems_automation cloud_database cloud_network cloud_object_store_container cloud_object_store_object cloud_subnet cloud_tenant cloud_volume cloud_volume_backup cloud_volume_snapshot cloud_volume_type configuration_job configuration_profile configuration_script configured_system container container_build container_group container_image container_image_registry container_node container_project container_replicator container_route container_service container_template ems_cloud ems_cluster ems_configuration ems_container ems_infra ems_network ems_physical_infra ems_storage flavor floating_ip generic_object_definition host host_aggregate load_balancer miq_template network_port network_router network_service network_service_entry offline orchestration_stack persistent_volume physical_server provider_foreman resource_pool retired security_group security_policy security_policy_rule service services storage templates vm].include?(@layout) end def default_search?(search_name) @default_search.present? && @default_search.name == search_name end def no_default_search?(search_id) @default_search.blank? && search_id.to_i.zero? end def expression_selected_id_or_name(id_or_name, search) @edit[:expression][:selected] && @edit[:expression][:selected][id_or_name] == search && !@edit[:custom_search] end def expression_selected_nil_or_id(search_id) @edit[:expression][:selected].nil? && @edit[:selected].nil? || expression_selected_id_or_name(:id, search_id.to_i) end # Returns description of a filter, for default filter also with "(Default)" def search_description(search) if default_search?(search.name) || @edit && no_default_search?(search.id) && settings_default('0', :default_search, @edit&.dig(@expkey, :exp_model).to_s.to_sym).to_s == '0' _("%{description} (Default)") % {:description => search.description} else _("%{description}") % {:description => search.description} end end # Returns class for a filter from Global filters to highlight it def def_searches_active_filter?(search) if @edit && @edit[:expression] && ((default_search?(search.name) || no_default_search?(search.id)) && expression_selected_nil_or_id(search.id) || (@edit[:expression][:selected] && @edit[:expression][:selected][:id].zero? && search.id.to_i.zero? || expression_selected_id_or_name(:name, search.name))) 'active' else '' end end # Returns class for a filter from My filters to highlight it def my_searches_active_filter?(search) if @edit && @edit[:expression] && (default_search?(search.name) && expression_selected_nil_or_id(search.id) || (@edit[:expression][:selected].nil? && search.id.to_i.zero? || expression_selected_id_or_name(:name, search.name))) 'active' else '' end end # Do we show or hide the clear_search link in the list view title def clear_search_status !!(@edit&.fetch_path(:adv_search_applied, :text)) end # Should we allow the user input checkbox be shown for an atom in the expression editor QS_VALID_USER_INPUT_OPERATORS = ["=", "!=", ">", ">=", "<", "<=", "INCLUDES", "STARTS WITH", "ENDS WITH", "CONTAINS"].freeze QS_VALID_FIELD_TYPES = %i[string boolean integer float percent bytes megabytes].freeze def qs_show_user_input_checkbox? return true if @edit[:expression_method] return false unless @edit[:adv_search_open] # Only allow user input for advanced searches return false unless QS_VALID_USER_INPUT_OPERATORS.include?(@edit[@expkey][:exp_key]) val = (@edit[@expkey][:exp_typ] == "field" && # Field atoms with certain field types return true QS_VALID_FIELD_TYPES.include?(@edit[@expkey][:val1][:type])) || (@edit[@expkey][:exp_typ] == "tag" && # Tag atoms with a tag category chosen return true @edit[@expkey][:exp_tag]) || (@edit[@expkey][:exp_typ] == "count" && # Count atoms with a count col chosen return true @edit[@expkey][:exp_count]) val end # Should we allow the field alias checkbox to be shown for an atom in the expression editor def adv_search_show_alias_checkbox? @edit[:adv_search_open] # Only allow field aliases for advanced searches end def pressed2model_action(pressed) pressed =~ /^(ems_cluster|miq_template|infra_networking|ems_automation)_(.*)$/ ? [$1, $2] : pressed.split('_', 2) end def model_for_vm(record) raise _("Record is not VmOrTemplate class") unless record.kind_of?(VmOrTemplate) if record.kind_of?(ManageIQ::Providers::CloudManager::Vm) ManageIQ::Providers::CloudManager::Vm elsif record.kind_of?(ManageIQ::Providers::InfraManager::Vm) ManageIQ::Providers::InfraManager::Vm elsif record.kind_of?(ManageIQ::Providers::CloudManager::Template) ManageIQ::Providers::CloudManager::Template elsif record.kind_of?(ManageIQ::Providers::InfraManager::Template) ManageIQ::Providers::InfraManager::Template end end def controller_for_vm(model) case model.to_s when "ManageIQ::Providers::CloudManager::Template", "ManageIQ::Providers::CloudManager::Vm" "vm_cloud" when "ManageIQ::Providers::InfraManager::Template", "ManageIQ::Providers::InfraManager::Vm" "vm_infra" else "vm_or_template" end end def model_from_active_tree(tree) case tree when :instances_filter_tree "ManageIQ::Providers::CloudManager::Vm" when :images_filter_tree "ManageIQ::Providers::CloudManager::Template" when :svcs_tree "Service" when :vms_filter_tree "ManageIQ::Providers::InfraManager::Vm" when :templates_filter_tree "ManageIQ::Providers::InfraManager::Template" when :templates_images_filter_tree "MiqTemplate" when :vms_instances_filter_tree "Vm" end end def object_types_for_flash_message(klass, record_ids) if klass == VmOrTemplate object_ary = klass.where(:id => record_ids).collect { |rec| ui_lookup(:model => model_for_vm(rec).to_s) } obj_hash = object_ary.each.with_object(Hash.new(0)) { |obj, h| h[obj] += 1 } obj_hash.collect { |k, v| v == 1 ? k : k.pluralize }.sort.to_sentence else object = ui_lookup(:model => klass.to_s) record_ids.length == 1 ? object : object.pluralize end end def pagination_or_gtl_request? %i[ppsetting searchtag entry sortby sort_choice page].find { |k| params[k] } end def update_gtl_div(action_url = 'explorer', button_div = 'center_tb') render :update do |page| page << javascript_prologue page.replace("gtl_div", :partial => "layouts/x_gtl", :locals => {:action_url => action_url, :button_div => button_div}) page << "miqSparkle(false)" end end def perfmenu_click? return false unless params[:menu_click] perf_menu_click true end def javascript_process_redirect_args(args) # there's no model for ResourceController - defaulting to traditional routing begin model = self.class.model rescue StandardError => _err model = nil end if model && args.class == Hash && args[:action] == 'show' && restful_routed?(model) args.delete(:action) polymorphic_path_redirect(model, args) else args end end def javascript_redirect(args) render :update do |page| page << javascript_prologue page.redirect_to(args) end end def polymorphic_path_redirect(model, args) record = args[:record] ? args[:record] : model.find(args[:id] || params[:id]) args.delete(:record) args.delete(:id) polymorphic_path(record, args) end def javascript_open_window(url) ex = ExplorerPresenter.open_window(url) ex.spinner_off render :json => ex.for_render end # this keeps the main_div wrapping tag, replaces only the inside def replace_main_div(args, options = {}) ex = ExplorerPresenter.main_div.update('main_div', render_to_string(args)) ex.replace("flash_msg_div", render_to_string(:partial => "layouts/flash_msg")) if options[:flash] ex.scroll_top if @flash_array.present? ex.spinner_off if options[:spinner_off] render :json => ex.for_render end def javascript_miq_button_visibility(changed) render :json => ExplorerPresenter.buttons(changed).for_render end def record_no_longer_exists?(what, model = nil) return false unless what.nil? if !@bang || @flash_array.empty? # We already added a better flash message in 'identify_record' # in that case we keep that flash message # otherwise we make a new one. # FIXME: a refactoring of identify_record and related is needed add_flash( if model.present? _("%{model} no longer exists") % {:model => ui_lookup(:model => model)} else _("Error: Record no longer exists in the database") end, :error, true ) session[:flash_msgs] = @flash_array end # Error message is displayed in 'show_list' action if such action exists # otherwise we assume that the 'explorer' action must exist that will display it. redirect_to(:action => respond_to?(:show_list) ? 'show_list' : 'explorer') end def pdf_page_size_style "#{@options[:page_layout]}" end DOWNLOAD_VIEW_LAYOUTS = %w[action auth_key_pair_cloud automation_manager_configured_system availability_zone alerts_overview alerts_list alerts_most_recent cloud_database cloud_network cloud_object_store_container cloud_object_store_object cloud_subnet cloud_tenant cloud_volume cloud_volume_backup cloud_volume_snapshot cloud_volume_type configuration_job configuration_profile configuration_script_source configured_system container container_build container_dashboard container_group container_image container_image_registry container_node container_project container_replicator container_route container_service container_template storage_resource host_initiator ems_storage ems_cloud ems_cluster ems_configuration ems_container ems_infra ems_infra_dashboard ems_network ems_physical_infra event flavor floating_ip generic_object generic_object_definition guest_device host host_aggregate load_balancer manageiq/providers/embedded_ansible/automation_manager/playbook manageiq/providers/embedded_automation_manager/authentication manageiq/providers/embedded_automation_manager/configuration_script_source miq_schedule miq_template monitor_alerts_overview monitor_alerts_list monitor_alerts_most_recent network_port network_router network_service network_service_entry offline orchestration_stack physical_rack physical_chassis physical_switch physical_storage physical_server persistent_volume policy policy_group security_policy security_policy_rule policy_profile resource_pool retired scan_profile security_group services storage templates].freeze def render_download_view_tb? DOWNLOAD_VIEW_LAYOUTS.include?(@layout) && !@record && !@tagitems && !@ownershipitems && !@retireitems && !@politems && !@in_a_form && %w[show show_list].include?(params[:action]) && @display != "custom_button_events" end def placeholder_if_present(password) password.present? ? "\u25cf" * 8 : '' end def miq_tab_header(id, active = nil, options = {}, &_block) tag_options = {:class => "#{options[:class]} #{active == id ? 'active' : ''}", 'role' => 'tab', 'aria-selected' => "#{active == id ? 'true' : 'false'}", 'aria-controls' => "#{id}", :id => "#{id}_tab"}.merge!(options) content_tag(:li, tag_options) do content_tag(:a, :href => "##{id}", 'data-toggle' => 'tab') do yield end end end def miq_tab_content(id, active = nil, options = {}, &_block) lazy = options[:lazy] && active != id classname = %w[tab-pane] classname << options[:class] if options[:class] classname << 'active' if active == id classname << 'lazy' if lazy options.delete(:lazy) options.delete(:class) content_tag(:div, :id => id, 'role' => 'tabpanel', 'aria-labelledby' => "#{id}_tab", :class => classname.join(' '), **options) do yield unless lazy end end def tree_with_advanced_search? %i[ images_tree images_filter_tree instances_tree instances_filter_tree providers_tree storage_tree svcs_tree templates_filter_tree templates_images_filter_tree vandt_tree vms_filter_tree vms_instances_filter_tree ].include?(x_tree[:tree]) end CONTENT_TYPE_ID = { "report" => "r", "menu" => "m", "chart" => "c" }.freeze def process_show_list_options(options, curr_model = nil) @report_data_additional_options = ApplicationController::ReportDataAdditionalOptions.from_options(options) @report_data_additional_options.with_quadicon_options( :embedded => @embedded, :showlinks => @showlinks, :policy_sim => @policy_sim, :lastaction => @lastaction, :in_a_form => @in_a_form, :display => @display ) @report_data_additional_options.with_row_button(@row_button) if @row_button @report_data_additional_options.with_menu_click(params[:menu_click]) if params[:menu_click] @report_data_additional_options.with_sb_controller(params[:sb_controller]) if params[:sb_controller] @report_data_additional_options.with_model(curr_model) if curr_model @report_data_additional_options.with_no_checkboxes(@no_checkboxes || options[:no_checkboxes]) @report_data_additional_options.with_checkboxes_clicked(params[:miq_grid_checks]) if params[:miq_grid_checks] @report_data_additional_options.freeze end def from_additional_options(additional_options) if additional_options[:match_via_descendants].present? additional_options[:match_via_descendants] = additional_options[:match_via_descendants].constantize end if additional_options[:parent_id].present? && additional_options[:parent_class_name].present? parent_id = additional_options[:parent_id] parent_class = additional_options[:parent_class_name].constantize additional_options[:parent] = parent_class.find(parent_id) if parent_class < ActiveRecord::Base end @row_button = additional_options[:row_button] @no_checkboxes = additional_options[:no_checkboxes] additional_options end # Restore instance variables necessary for proper rendering of quadicons. # This is a temporary solution that is ot be replaced by proper # parametrization of an ancessor class of QuadiconHelper. def restore_quadicon_options(quadicon_options) @embedded = quadicon_options[:embedded] @showlinks = quadicon_options[:showlinks] @policy_sim = quadicon_options[:policy_sim] # @explorer # @view.db # @parent @lastaction = quadicon_options[:lastaction] # we also need to pass the @display because @display passed throught the # session does not persist the null value @display = quadicon_options[:display] # need to pass @in_a_form so get_view does not set advanced search options # in the forms that render gtl that mess up @edit @in_a_form = quadicon_options[:in_a_form] end # Wrapper around jquery-rjs' remote_function which adds an extra .html_safe() # Remove if merged: https://github.com/amatsuda/jquery-rjs/pull/3 def remote_function(options) super(options).to_str end def appliance_name MiqServer.my_server.name end def rbac_common_feature_for_buttons(pressed) # return feature that should be checked for the button that came in case pressed when "rbac_project_add", "rbac_tenant_add" "rbac_tenant_add" else pressed end end def route_exists?(hash) begin url_for_only_path(hash) rescue return false end true end def translate_header_text(text) if text == "Region" Vmdb::Appliance.PRODUCT_NAME + " " + _(text) else _(text) end end def parse_nodetype_and_id(x_node) x_node.split('_').last.split('-') end def r @r ||= proc { |opts| render_to_string(opts) } end # Test if just succesfully deleted an entity that was being displayed def single_delete_test(any_button = false) @flash_array.present? && @single_delete && (any_button || params[:pressed] == "#{table_name}_delete") end # redirect to show_list (after succesfully deleted the entity being displayed) def single_delete_redirect javascript_redirect(:action => 'show_list', :flash_msg => @flash_array[0][:message], :flash_error => @flash_array[0][:level] == :error) end def accessible_select_event_types ApplicationController::Timelines::SELECT_EVENT_TYPE.map { |key, value| [_(key), value] } end def unique_html_id(prefix = 'unknown') "#{prefix}-#{rand(36**8).to_s(36)}" end def self.miq_favicon_path Settings.server.custom_favicon ? '/upload/custom_favicon.ico' : ActionController::Base.helpers.image_path('favicon.ico') end def miq_favicon_link_tag favicon_link_tag(ApplicationHelper.miq_favicon_path) end def provider_paused?(record) provider = if record.kind_of?(ExtManagementSystem) record elsif record.respond_to?(:ext_management_system) record.ext_management_system elsif record.respond_to?(:manager) record.manager end provider.try(:enabled?) == false end # Return a proper column for an appropriate target klass def columns_for_klass(klass) if klass == 'Tenant' [:name, :use_config_for_attributes] elsif klass.safe_constantize.column_names.include?('name') [:name] else [:description] end end def safe_right_cell_text return '' if @right_cell_text.nil? ActiveSupport::SafeBuffer === @right_cell_text ? raw(@right_cell_text) : @right_cell_text end def camelize_quadicon(quad) quad.keys.each_with_object({}) { |k, h| h[k.to_s.camelcase(:lower)] = quad[k] } end def miq_toolbar(toolbars) limit = ::Settings.ui.custom_button_count || 3 react('MiqToolbar', :kebabLimit => limit, :toolbars => toolbars) end def miq_structured_list(data) react('MiqStructuredList', {:title => data[:title], :headers => data[:headers], :rows => data[:rows], :message => data[:message], :mode => ["miq_summary", data[:mode]].join(' ')}) end end
#!/usr/bin/env ../test_wrapper.sh app/controllers require_relative 'controller_test_base' class SetupControllerTest < ControllerTestBase test 'setup uses cached exercises when present' do set_disk_class_name('HostDisk') set_exercises_root(Dir.mktmpdir + '/') exercises.dir.write('cache.json', { 'fake-Print-Diamond' => 'fake-Print-Diamond instructions', 'fake-Roman-Numerals' => 'fake-Roman-Numerals instructions' }) get 'setup/show' FileUtils.remove_entry get_exercises_root assert_response :success assert /data-exercise\=\"fake-Print-Diamond/.match(html), "fake-Print-Diamond" assert /data-exercise\=\"fake-Roman-Numerals/.match(html), "fake-Roman-Numerals" end # - - - - - - - - - - - - - - - - - - - - - - test 'setup uses cached languages when present' do set_disk_class_name('HostDisk') set_languages_root(Dir.mktmpdir + '/') languages.dir.write('cache.json', [ 'C++, catch', 'Java, JMock' ]) get 'setup/show' FileUtils.remove_entry get_languages_root assert_response :success assert /data-language\=\"C++/.match(html), "C++" assert /data-language\=\"Java/.match(html), "Java" assert /data-test\=\"catch/.match(html), "catch" assert /data-test\=\"JMock/.match(html), "JMock" end # - - - - - - - - - - - - - - - - - - - - - - test 'setup/show chooses language and exercise of kata ' + 'whose 10-char id is passed in URL ' + '(to encourage repetition)' do setup_show(10) end # - - - - - - - - - - - - - - - - - - - - - - test 'setup/show chooses language and exercise of kata ' + 'whose 6-char id is passed in URL ' + '(to encourage repetition) by using completion' do setup_show(6) end # - - - - - - - - - - - - - - - - - - - - - - def setup_show(n) # exercises/cache.json was out of date and this test failed. # Some code uses cache.json and some code does not. # There is a disconnect between the cache.json files in the # exercises/ and languages/ folders and the caches used # in Exercises.rb and Languages.rb whose caches do *not* # use the disk cache but iterate through their respective # folders on disk. set_runner_class_name('RunnerStub') runner.stub_runnable(true) languages_names = languages.each.map{|language| language.display_name}.sort exercises_names = exercises.each.map{|exercise| exercise.name}.sort language_name = languages_names.shuffle[0] exercise_name = exercises_names.shuffle[0] id = create_kata(language_name,exercise_name) get 'setup/show', :id => id[0...n] assert_response :success md = /var selectedExercise = \$\('#exercise_' \+ (\d+)/.match(html) selected_exercise = exercises_names[md[1].to_i] assert_equal exercise_name, selected_exercise, 'exercise' # next bit is trickier than it should be because language.display_name # contains the name of the test framework too. md = /var selectedLanguage = \$\('#language_' \+ (\d+)/.match(html) just_languages_names = languages_names.each.map {|name| name.split(',')[0].strip }.uniq.sort selected_language = just_languages_names[md[1].to_i] assert_equal language_name.split(',')[0].strip, selected_language, 'language' end end more notes on cache relationship to different Runners #!/usr/bin/env ../test_wrapper.sh app/controllers require_relative 'controller_test_base' class SetupControllerTest < ControllerTestBase test 'setup uses cached exercises when present' do set_disk_class_name('HostDisk') set_exercises_root(Dir.mktmpdir + '/') exercises.dir.write('cache.json', { 'fake-Print-Diamond' => 'fake-Print-Diamond instructions', 'fake-Roman-Numerals' => 'fake-Roman-Numerals instructions' }) get 'setup/show' FileUtils.remove_entry get_exercises_root assert_response :success assert /data-exercise\=\"fake-Print-Diamond/.match(html), "fake-Print-Diamond" assert /data-exercise\=\"fake-Roman-Numerals/.match(html), "fake-Roman-Numerals" end # - - - - - - - - - - - - - - - - - - - - - - test 'setup uses cached languages when present' do set_disk_class_name('HostDisk') set_languages_root(Dir.mktmpdir + '/') languages.dir.write('cache.json', [ 'C++, catch', 'Java, JMock' ]) get 'setup/show' FileUtils.remove_entry get_languages_root assert_response :success assert /data-language\=\"C++/.match(html), "C++" assert /data-language\=\"Java/.match(html), "Java" assert /data-test\=\"catch/.match(html), "catch" assert /data-test\=\"JMock/.match(html), "JMock" end # - - - - - - - - - - - - - - - - - - - - - - test 'setup/show chooses language and exercise of kata ' + 'whose 10-char id is passed in URL ' + '(to encourage repetition)' do setup_show(10) end # - - - - - - - - - - - - - - - - - - - - - - test 'setup/show chooses language and exercise of kata ' + 'whose 6-char id is passed in URL ' + '(to encourage repetition) by using completion' do setup_show(6) end # - - - - - - - - - - - - - - - - - - - - - - def setup_show(n) # exercises/cache.json was out of date and this test failed. # Some code uses cache.json and some code does not. # There is a disconnect between the cache.json files in the # exercises/ and languages/ folders and the caches used # in Exercises.rb and Languages.rb whose caches do *not* # use the disk cache but iterate through their respective # folders on disk. # # Note further that different Runners may have a different # opinion on what languages exist (are supported). Should # there be a languages/ cache file per Runner class? set_runner_class_name('RunnerStub') runner.stub_runnable(true) languages_names = languages.each.map{|language| language.display_name}.sort exercises_names = exercises.each.map{|exercise| exercise.name}.sort language_name = languages_names.shuffle[0] exercise_name = exercises_names.shuffle[0] id = create_kata(language_name,exercise_name) get 'setup/show', :id => id[0...n] assert_response :success md = /var selectedExercise = \$\('#exercise_' \+ (\d+)/.match(html) selected_exercise = exercises_names[md[1].to_i] assert_equal exercise_name, selected_exercise, 'exercise' # next bit is trickier than it should be because language.display_name # contains the name of the test framework too. md = /var selectedLanguage = \$\('#language_' \+ (\d+)/.match(html) just_languages_names = languages_names.each.map {|name| name.split(',')[0].strip }.uniq.sort selected_language = just_languages_names[md[1].to_i] assert_equal language_name.split(',')[0].strip, selected_language, 'language' end end
class Vcpkg < Formula desc "C++ Library Manager" homepage "https://github.com/microsoft/vcpkg" url "https://github.com/microsoft/vcpkg-tool/archive/2022-02-01.tar.gz" version "2022.02.01" sha256 "cbbefd729f5ba60f3ab0c9db64f271ac931a432781baae333939f4bd57db949c" license "MIT" head "https://github.com/microsoft/vcpkg-tool.git", branch: "main" # The source repository has pre-release tags with the same # format as the stable tags. livecheck do url :stable strategy :github_latest regex(%r{href=.*?/tag/v?(\d{4}(?:[._-]\d{2}){2})["' >]}i) end bottle do sha256 cellar: :any, arm64_monterey: "e56d14451c5fff08954f5e80b28fbdd526b8a3b67613b67e950fcea904c3a670" sha256 cellar: :any, arm64_big_sur: "63e30448648cd0fd0a4c3061eb7ae9daae1ef12b5e427ab6116311a061c2001c" sha256 cellar: :any, monterey: "ec36c7272114fabb727c9022676c84f5bc3122fcf0b15f46bbcd123ec4c33aea" sha256 cellar: :any, big_sur: "a9167340b8bfec76065321945e99403ae94667d0601341aea657cf723af10cef" sha256 cellar: :any, catalina: "ad3ee6bbc1bfeaf59455fc8f9fd853b7b65a7d626875159207fc10e054593edd" sha256 cellar: :any_skip_relocation, x86_64_linux: "b6274ab6a2f28983a1125f45eea28ed1cb5d04009988b2092602091734f1724d" end depends_on "cmake" => :build depends_on "fmt" depends_on "ninja" # This will install its own copy at runtime if one isn't found. on_linux do depends_on "gcc" # for C++17 end fails_with gcc: "5" def install # Improve error message when user fails to set `VCPKG_ROOT`. inreplace ["src/vcpkg/vcpkgpaths.cpp", "locales/messages.json"], "If you are trying to use a copy of vcpkg that you've built, y", "Y" system "cmake", "-S", ".", "-B", "build", "-DVCPKG_DEVELOPMENT_WARNINGS=OFF", "-DVCPKG_BASE_VERSION=#{version.to_s.tr(".", "-")}", "-DVCPKG_VERSION=#{version}", "-DVCPKG_DEPENDENCY_EXTERNAL_FMT=ON", *std_cmake_args system "cmake", "--build", "build" system "cmake", "--install", "build" end # This is specific to the way we install only the `vcpkg` tool. def caveats <<~EOS This formula provieds only the `vcpkg` executable. To use vcpkg: git clone https://github.com/microsoft/vcpkg "$HOME/vcpkg" export VCPKG_ROOT="$HOME/vcpkg" EOS end test do message = "Error: Could not detect vcpkg-root. You must define the VCPKG_ROOT environment variable" assert_match message, shell_output("#{bin}/vcpkg search sqlite", 1) end end vcpkg 2022.03.09 Closes #97919. Signed-off-by: Carlo Cabrera <3ffc397d0e4bded29cb84b56167de54c01e3a55b@users.noreply.github.com> Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com> class Vcpkg < Formula desc "C++ Library Manager" homepage "https://github.com/microsoft/vcpkg" url "https://github.com/microsoft/vcpkg-tool/archive/2022-03-09.tar.gz" version "2022.03.09" sha256 "174a9081059efc29f8c617e6d673d342388816872a3c57c7042051d029b77841" license "MIT" head "https://github.com/microsoft/vcpkg-tool.git", branch: "main" # The source repository has pre-release tags with the same # format as the stable tags. livecheck do url :stable strategy :github_latest regex(%r{href=.*?/tag/v?(\d{4}(?:[._-]\d{2}){2})["' >]}i) end bottle do sha256 cellar: :any, arm64_monterey: "e56d14451c5fff08954f5e80b28fbdd526b8a3b67613b67e950fcea904c3a670" sha256 cellar: :any, arm64_big_sur: "63e30448648cd0fd0a4c3061eb7ae9daae1ef12b5e427ab6116311a061c2001c" sha256 cellar: :any, monterey: "ec36c7272114fabb727c9022676c84f5bc3122fcf0b15f46bbcd123ec4c33aea" sha256 cellar: :any, big_sur: "a9167340b8bfec76065321945e99403ae94667d0601341aea657cf723af10cef" sha256 cellar: :any, catalina: "ad3ee6bbc1bfeaf59455fc8f9fd853b7b65a7d626875159207fc10e054593edd" sha256 cellar: :any_skip_relocation, x86_64_linux: "b6274ab6a2f28983a1125f45eea28ed1cb5d04009988b2092602091734f1724d" end depends_on "cmake" => :build depends_on "fmt" depends_on "ninja" # This will install its own copy at runtime if one isn't found. on_linux do depends_on "gcc" # for C++17 end fails_with gcc: "5" def install # Improve error message when user fails to set `VCPKG_ROOT`. inreplace ["src/vcpkg/vcpkgpaths.cpp", "locales/messages.json"], "If you are trying to use a copy of vcpkg that you've built, y", "Y" system "cmake", "-S", ".", "-B", "build", "-DVCPKG_DEVELOPMENT_WARNINGS=OFF", "-DVCPKG_BASE_VERSION=#{version.to_s.tr(".", "-")}", "-DVCPKG_VERSION=#{version}", "-DVCPKG_DEPENDENCY_EXTERNAL_FMT=ON", *std_cmake_args system "cmake", "--build", "build" system "cmake", "--install", "build" end # This is specific to the way we install only the `vcpkg` tool. def caveats <<~EOS This formula provieds only the `vcpkg` executable. To use vcpkg: git clone https://github.com/microsoft/vcpkg "$HOME/vcpkg" export VCPKG_ROOT="$HOME/vcpkg" EOS end test do message = "Error: Could not detect vcpkg-root. You must define the VCPKG_ROOT environment variable" assert_match message, shell_output("#{bin}/vcpkg search sqlite", 1) end end
require 'syntax/convertors/html' # Methods added to this helper will be available to all templates in the application. module ApplicationHelper include Zena::Acts::SecureScope include Zena::Acts::SecureController::InstanceMethods # helpers to include clean javascript def javascript( string ) javascript_start + string + javascript_end end def javascript_start "<script type=\"text/javascript\" language=\"javascript\" charset=\"utf-8\">\n// <![CDATA[\n" end def javascript_end "\n// ]]>\n</script>" end # Calendar seizure setup def uses_calendar if ZENA_ENV[:calendar_langs].include?(lang) l = lang else l = ZENA_ENV[:default_lang] end <<-EOL <script src="/calendar/calendar.js" type="text/javascript"></script> <script src="/calendar/calendar-setup.js" type="text/javascript"></script> <script src="/calendar/lang/calendar-#{lang}-utf8.js" type="text/javascript"></script> <link href="/calendar/calendar-brown.css" media="screen" rel="Stylesheet" type="text/css" /> #{javascript_start} Calendar._TT["DEF_DATE_FORMAT"] = "#{transb('datetime')}"; Calendar._TT["FIRST_DAY"] = #{transb('week_start_day')}; #{javascript_end} EOL end # Date selection tool def date_box(obj, var, opts = {}) rnd_id = Time.now.to_i defaults = { :id=>"datef#{rnd_id}", :button=>"dateb#{rnd_id}", :display=>"dated#{rnd_id}", :class=>var.to_s } opts = defaults.merge(opts) date = eval("@#{obj} ? @#{obj}.#{var} : nil") || Time.now.utc value = format_date(date,'datetime') if opts[:size] == 0 fld = hidden_field obj, var, :id=>opts[:id] , :value=>value, :class=>opts[:class] else fld = text_field obj, var, :id=>opts[:id] , :value=>value, :class=>opts[:class], :size=>opts[:size] end <<-EOL <div class="date_box"><img src="/calendar/iconCalendar.gif" id="#{opts[:button]}"/> #{fld} <script type="text/javascript"> Calendar.setup({ inputField : "#{opts[:id]}", // id of the input field button : "#{opts[:button]}", // trigger for the calendar (button ID) singleClick : true, showsTime : true }); </script></div> EOL end # Translate submit_tag def tsubmit_tag(*args) args[0] = trans(args[0],:edit=>false) submit_tag(*args) end # Translate link_to_remote def tlink_to_remote(*args) args[0] = trans(args[0],:edit=>false) link_to_remote(*args) end # Translate link_to_remote def tlink_to(*args) args[0] = trans(args[0],:edit=>false) link_to(*args) end # Add class='on' if the link points to the current page def tlink_to_with_state(*args) title, url, options = *args options ||= {} same = true url.each do |k,v| same &&= (params[k.to_s] == v.to_s) end if same options[:class] = 'on' end tlink_to(title, url, options) end # Translate link_to_remote def tlink_to_function(*args) args[0] = trans(args[0],:edit=>false) link_to_function(*args) end # Translate links/button (not editable) def transb(key) trans(key, :edit=>false) end # creates a pseudo random string to avoid browser side ajax caching def rnd Time.now.to_i end # "Translate" static text into the current lang def trans(keyword, opt={}) opt = {:edit=>true}.merge(opt) if opt[:translate] || (session[:translate] && opt[:edit]) key = TransPhrase.translate(keyword) "<div id='phrase#{key[:id]}' class='trans'>" + link_to_remote(key.into(lang), :update=>"phrase#{key[:id]}", :url=>{:controller=>'trans', :action=>'edit', :id=>key[:id]}, :complete=>'$("trans_value").focus();$("trans_value").select()') + "</div>" else TransPhrase[keyword][lang] end end # Shows 'login' or 'logout' button. def login_link if session[:user] "<div id='logout'><a href='/logout'>#{transb('logout')}</a></div>" else "<div id='logout'><a href='/login'>#{transb('login')}</a></div>" end end # display the time with the format provided by the translation of 'long_time' def long_time(atime) format_date(atime, "long_time") end # display the time with the format provided by the translation of 'short_time' def short_time(atime) format_date(atime, "short_time") end # display the time with the format provided by the translation of 'full_date' def full_date(adate) format_date(adate, "full_date") end # display the time with the format provided by the translation of 'long_date' def long_date(adate) format_date(adate, "long_date") end # display the time with the format provided by the translation of 'short_date' def short_date(adate) format_date(adate, "short_date") end # format a date with the given format. Translate month and day names. def format_date(thedate, fmt) if thedate adate = visitor.tz.adjust(thedate) format = trans(fmt) if format != fmt # month name format.gsub!("%b", trans(adate.strftime("%b")) ) format.gsub!("%B", trans(adate.strftime("%B")) ) # weekday name format.gsub!("%a", trans(adate.strftime("%a")) ) format.gsub!("%A", trans(adate.strftime("%A")) ) adate.strftime(format) else trans fmt end end end # Show visitor name if logged in def visitor_link if session[:user] "<div id='visitor'>" + link_to( visitor.fullname, user_home_url ) + "</div>" else "" end end # Display flash[:notice] or flash[:error] if any. <%= flash <i>[:notice, :error, :both]</i> %>" def flash_messages(type=:both) "<div id='messages'>" + if (type == :notice || type == :both) && @flash[:notice] "<div id='notice' class='flash' onClick='new Effect.Fade(\"notice\")'>#{@flash[:notice]}</div>" else '' end + if (type == :error || type == :both) && @flash[:error ] "<div id='error' class='flash' onClick='new Effect.Fade(\"error\")'>#{@flash[:error]}</div>" else '' end + "</div>" end # Display logo with message (can be a date or a string) def logo(message='') if message.kind_of?(Time) message = format_date(message, 'logo_date') end "<div id='logo'>" + link_to( image_tag('/img/logo.png', :size=>'220x100'), :prefix => prefix, :controller => 'main', :action=>'index') + "<div id='logo_msg'>#{message}</div></div>" end # This method renders the Textile text contained in an object as html. It also renders the zena additions : # === Zena additions # all these additions are replaced by the traduction of 'unknown link' or 'unknown image' if the user does # not have read access to the linked node. # * ["":34] creates a link to node 34 with node's title. # * ["title":34] creates a link to node 34 with the given title. # * ["":034] if the node id starts with '0', creates a popup link. # * [!14!] inline image 14 or link to document 14 with icon. (default format for images is 'std' defined in #ImageBuilder). Options are : # ** [!014!] if the id starts with '0', the image becomes a link to the full image. # ** [!<.14!] or [!<14!] inline image surrounded with <p class='img_left'></p> # ** [!>.14!] or [!>14!] inline image surrounded with <p class='img_right'></p> # ** [!=.14!] or [!=14!] inline image with <p class='img_center'></p> # ** [!14.pv!] inline image transformed to format 'pv' (class is also set to 'pv'). Formats are defined in #ImageBuilder. # ** all the options above can be used together as in [!>.14.med!] : inline image on the right, size 'med'. # ** [![2,3,5]!] gallery : inline preview with javascript inline viewer # ** [![]!] gallery with all images contained in the current node # * [!{7,9}!] documents listing for documents 7 and 9 # * [!{}!] list all documents (with images) for the current node # * [!{d}!] list all documents (without images) for the current node # * [!{i}!] list all images for the current node # * [!14!:37] you can use an image as the source for a link # * [!14!:www.example.com] use an image for an outgoing link def zazen(text, opt={}) opt = {:images=>true}.merge(opt) img = opt[:images] if opt[:limit] opt[:limit] -= 1 unless opt[:limit] <= 0 paragraphs = text.split(/\n\n/) if paragraphs.size > (opt[:limit]+1) && opt[:limit] != -1 text = paragraphs[0..opt[:limit]].join("\n\n") + " &#8230;<span class='more'>" + trans("(click to read more)") + "</span>" end end r = RedCloth.new(text) #, [:hard_breaks]) r.gsub!( /(\A|[^\w])@(.*?)@(\Z|[^\w])/ ) { "#{$1}\\AT_START\\#{zazen_escape($2)}\\AT_END\\#{$3}" } r.gsub!( /<code>(.*?)<\/code>/m ) { "\\CODE_START\\#{zazen_escape($1)}\\CODE_END\\" } r.gsub!( /\!\[([^\]]*)\]\!/ ) { img ? make_gallery($1) : trans('[gallery]') } r.gsub!( /\!([^0-9]{0,2})\{([^\}]*)\}\!/ ) { img ? list_nodes(:style=>$1, :ids=>$2) : trans('[documents]')} r.gsub!( /\!([^0-9]{0,2})([0-9]+)(\.([^\/\!]+)|)(\/([^\!]*)|)\!(:([^\s]+)|)/ ) { img ? make_image(:style=>$1, :id=>$2, :size=>$4, :title=>$6, :link=>$8) : "[#{trans('image')}#{$6 ? (": " + zazen($6,:images=>false)) : ''}]"} r.gsub!( /"([^"]*)":([0-9]+)/ ) { make_link(:title=>$1,:id=>$2)} r = r.to_html r.gsub!( /(\\CODE_START\\)(.*?)(\\CODE_END\\)/m ) { "<div class='box'>#{zazen_unescape($2)}</div>" } r.gsub!( /(\\AT_START\\)(.*?)(\\AT_END\\)/ ) { "#{zazen_unescape($2)}" } r.gsub!( /\?(\w[^\?]+?\w)\?/ ) { make_wiki_link($1) } r end # Creates a link to the node referenced by id def make_link(opts) node = secure(Node) { Node.find(opts[:id]) } title = (opts[:title] && opts[:title] != '') ? opts[:title] : node.v_title if opts[:id][0..0] == '0' link_to title, {:prefix => prefix, :controller => 'main', :action=>'show', :path=>node.fullpath}, :popup=>true else link_to title, :prefix => prefix, :controller => 'main', :action=>'show', :path=>node.fullpath end rescue ActiveRecord::RecordNotFound "<span class='unknownLink'>#{trans('unknown link')}</span>" end # TODO: test def make_wiki_link(keyword) "<a href='http://#{lang}.wikipedia.org/wiki/Special:Search?search=#{CGI::escape(keyword)}' class='wiki'>#{keyword}</a>" end # Create an img tag for the given image. See ApplicationHelper#zazen for details. def make_image(opts) id, style, link, size, title = opts[:id], opts[:style], opts[:link], opts[:size], opts[:title] img = secure(Document) { Document.find(id) } title = img.v_summary if title == "" size = IMAGEBUILDER_FORMAT[size] ? size : nil if !size && img.kind_of?(Image) size = 'std' end image = img.img_tag(size) unless link if id[0..0] == "0" || !img.kind_of?(Image) # if the id starts with '0' or it is not an Image, link to data link = url_for(data_url(img)) end end style ||= '' case style.sub('.', '') when ">" prefix = "<div class='img_right'>" suffix = "</div>" when "<" prefix = "<div class='img_left'>" suffix = "</div>" when "=" prefix = "<div class='img_center'>" suffix = "</div>" else prefix = suffix = "" end if title prefix = "#{prefix}<div class='img_with_title'>" suffix = "<div class='img_title'>#{zazen(title, :images=>false)}</div></div>#{suffix}" end if link.nil? prefix + image + suffix elsif link =~ /^\d+$/ prefix + make_link(:id=>link,:title=>image) + suffix else link = "http://#{link}" unless link =~ %r{(^/|.+://.+)} prefix + "<a href='#{link}'>" + image + "</a>" + suffix end rescue ActiveRecord::RecordNotFound "<span class='unknownLink'>#{trans('unknown document')}</span>" end # Create a gallery from a list of images. See ApplicationHelper#zazen for details. def make_gallery(ids="") if ids == "" images = @node.images else ids = ids.split(',').map{|i| i.to_i}.join(',') # sql injection security images = secure(Document) { Document.find(:all, :conditions=>"id IN (#{ids})") } end render_to_string( :partial=>'main/gallery', :locals=>{:gallery=>images} ) end def list_nodes(opt={}) ids = opt[:ids] style = opt[:style] || '' case style.sub('.', '') when ">" prefix = "<div class='img_right'>" suffix = "</div>" when "<" prefix = "<div class='img_left'>" suffix = "</div>" when "=" prefix = "<div class='img_center'>" suffix = "</div>" else prefix = suffix = "" end if ids == "" docs = @node.documents elsif ids == "d" docs = @node.documents_only elsif ids == "i" docs = @node.images else ids = ids.split(',').map{|i| i.to_i}.join(',') # sql injection security docs = secure(Document) { Document.find(:all, :order=>'name ASC', :conditions=>"id IN (#{ids})") } end prefix + render_to_string( :partial=>'main/list_nodes', :locals=>{:docs=>docs}) + suffix end def data_url(obj) if obj.kind_of?(Document) {:controller=>'document', :action=>'data', :version_id=>obj.v_id, :filename=>obj.c_filename, :ext=>obj.c_ext} else raise StandardError, "Cannot create 'data_url' for #{obj.class}." end end # return a readable text version of a file size def fsize(size) size = size.to_f if size >= 1024 * 1024 * 1024 sprintf("%.2f Gb", size/(1024*1024*1024)) elsif size >= 1024 * 1024 sprintf("%.1f Mb", size/(1024*1024)) elsif size >= 1024 sprintf("%i Kb", (size/(1024)).ceil) else sprintf("%i octets", size) end end # Hierachical menu. (same on all pages) def show_menu Cache.with(visitor.id, visitor.group_ids, Page.kpath, 'show_menu') do if ZENA_ENV[:menu_tag_id] !=nil menu = secure(Tag) { Tag.find(ZENA_ENV[:menu_tag_id]) } menus = menu.pages elsif ZENA_ENV[:root_id] != nil menus = secure(Node) { Node.find(ZENA_ENV[:root_id]) }.pages else menus = secure(Page) { Page.find(:all, :conditions=>"parent_id IS NULL") } end res = ["<div id='menu'>"] res << "<ul>" res << render_to_string(:partial=>'main/menu', :collection=>menus) res << "</ul>" res << "</div>" res.join("\n") end end def calendar(options={}) source = options[:from ] || (@project ||= (@node ? @node.project : nil)) date = options[:date ] || Date.today method = options[:find ] || :notes size = options[:size ] || :tiny using = options[:using ] || :event_at day_names, on_day = calendar_get_options(size, source, method) return "" unless on_day && source Cache.with(visitor.id, visitor.group_ids, 'NN', size, method, source.id, date.ajd, lang) do # find start and end date week_start_day = trans('week_start_day').to_i start_date = Date.civil(date.year, date.mon, 1) start_date -= (start_date.wday + 7 - week_start_day) % 7 end_date = Date.civil(date.year, date.mon, -1) end_date += (6 + week_start_day - end_date.wday) % 7 # get list of notes in this scope # TODO: use time_zone here ? notes = source.send(method,:conditions=>["#{using} >= ? AND #{using} <= ?", start_date, end_date], :order=>"#{using} ASC") # build event hash calendar = {} notes.each do |n| calendar[n.send(using.to_sym).strftime("%Y-%m-%d")] ||= [] calendar[n.send(using.to_sym).strftime("%Y-%m-%d")] << n end title = "#{trans(Date::MONTHNAMES[date.mon])} #{date.year}" head_day_names = [] 0.upto(6) do |i| head_day_names << "<td>#{trans(day_names[(i+week_start_day) % 7])}</td>" end content = [] start_date.step(end_date,7) do |week| # each week content << "<tr class='body'>" week.step(week+6,1) do |day| # each day content << "<td#{ calendar_class(day,date)}#{day == Date.today ? " id='#{size}_today'" : "" }><p>#{on_day.call(calendar[day.strftime("%Y-%m-%d")], day)}</p></td>" end content << '</tr>' end render_to_string(:partial=>"calendar/#{size}", :locals=>{ :content=>content.join("\n"), :day_names=>head_day_names.join(""), :title=>title, :date=>date, :source=>source, :method=>method, :size=>size }) end end def unless_empty(obj) if obj.nil? || obj.empty? return '' else yield(obj) end end # Show a little [xx] next to the title if the desired language could not be found. def check_lang(obj) obj.v_lang != lang ? " <span class='wrong_lang'>[#{obj.v_lang}]</span> " : "" end # TODO: test # display the title with necessary id and checks for 'lang'. Options : # * :link if true, the title is a link to the object's page # default = true if obj is not the current node '@node' # * :project if true , the project name is added before the object title as 'project / .....' # default = obj project is different from current node project # if no options are provided show the current object title def show_title(obj=@node, opt={}) unless opt.include?(:link) opt[:link] = (obj[:id] != @node[:id]) end unless opt.include?(:project) opt[:project] = (obj[:project_id] != @node[:project_id] && obj[:id] != @node[:id]) end if opt[:project] title = "#{obj.project.name} / #{obj.v_title}" else title = obj.v_title end if opt[:link] title = link_to(title, node_url(obj)) end "<span id='v_title#{obj.v_id}'>#{title}#{check_lang(obj)}</span>" end # TODO: test def show(obj, sym, opt={}) return show_title(obj, opt) if sym == :v_title if opt[:as] key = "#{opt[:as]}#{obj.v_id}" preview_for = opt[:as] opt.delete(:as) else key = "#{sym}#{obj.v_id}" end if opt[:text] text = opt[:text] opt.delete(:text) else text = obj.send(sym) if (text.nil? || text == '') && sym == :v_summary text = obj.v_text opt[:images] = false else opt.delete(:limit) end end if [:v_text, :v_summary].include?(sym) text = zazen(text, opt) klass = " class='text'" else klass = "" end if preview_for render_to_string :partial=>'node/show_attr', :locals=>{:id=>obj[:id], :text=>text, :preview_for=>preview_for, :key=>key, :klass=>klass, :key_on=>"#{key}#{Time.now.to_i}_on", :key_off=>"#{key}#{Time.now.to_i}_off"} else "<div id='#{key}'#{klass}>#{text}</div>" end end # TODO: test def link_box(obj, sym, opt={}) # FIXME: SECURITY is there a better way to do this ? node = eval("@#{obj}") method = "#{sym}_for_form".to_sym role = node.class.role[sym.to_s] setter = sym.to_s.singularize if role[:unique] # unique res = [select_id(obj,"#{setter}_id", :class=>role[:klass], :include_blank=>true)] else # many if opt[:in] ids = opt[:in].map{|i| i.to_i} list = node.send(method, :conditions=>["nodes.id IN (#{ids.join(',')})"]) else list = node.send(method) end res = list.inject([]) do |list, l| list << "<input type='checkbox' name='node[#{setter}_ids][]' value='#{l.id}' class='box' #{ l[:link_id] ? "checked='1' " : ""}/>#{l.name}" list end end if opt.include?(:title) if opt[:title].nil? title = '' else title = "<li><b>#{opt[:title]}</b></li>" end else title = "<li><b>#{trans(sym.to_s)}</b></li>" end "<ul class='link_box'>#{title}<li>#{res.join('</li><li>')}</li></ul>" end #TODO: test # Return the list of groups from the visitor for forms def form_groups @form_groups ||= Group.find(:all, :select=>'id, name', :conditions=>"id IN (#{visitor.group_ids.join(',')})", :order=>"name ASC").collect {|p| [p.name, p.id]} end #TODO: test # Return the list of possible templates def form_templates return @form_templates if @form_templates @form_templates = [] Dir.foreach(File.join(RAILS_ROOT, 'app', 'views', 'templates')) do |file| next unless file =~ /^([a-zA-Z0-9]+)\.rhtml$/ next if ['index', 'not_found'].include?($1) @form_templates << $1 end @form_templates end #TODO: test def site_tree(obj=nil) skip = obj ? obj[:id] : nil base = secure(Node) { Node.find(ZENA_ENV[:root_id]) } level = 0 if obj.nil? klass = Node elsif obj.kind_of?(Document) klass = Node elsif obj.kind_of?(Note) klass = Project else klass = Page end tree = get_site_tree(skip,base,level) tree.reject! { |node| !(node[1][:kpath] =~ /^#{klass.kpath}/) } return [] unless tree tree.map {|p| ["Β Β "*p[0] + p[1][:name], p[1][:id] ]} end #TODO: test def readers_for(obj=@node) readers = if obj.private? trans('img_private') elsif [obj.rgroup_id,obj.pgroup_id,obj.user_id].include?(1) trans('img_public') else names = [] names |= [obj.rgroup.name.limit(4)] if obj.rgroup names |= [obj.pgroup.name.limit(4)] if obj.pgroup names << obj.user.initials names.join(', ') end custom = obj.inherit != 1 ? "<span class='custom'>#{trans('img_custom_inherit')}</span>" : '' "#{custom} #{readers}" end # Used by edit_buttons def form_action(action, version_id=nil, link_text=nil) version_id ||= @node.v_id if action == 'edit' "<a href='#' title='#{transb('btn_title_edit')}' onClick=\"editor=window.open('" + url_for(:controller=>'version', :id=>version_id, :action=>'edit', :rnd=>rnd) + "', 'edit', 'location=0,width=300,height=400,resizable=1');return false;\">" + (link_text || transb('btn_edit')) + "</a>" elsif action == 'view' tlink_to_function((link_text || 'btn_view'), "opener.Zena.version_preview(#{version_id}); return false;") elsif action == 'drive' "<a href='#' title='#{transb('btn_title_drive')}' onClick=\"editor=window.open('" + url_for(:controller=>'node', :version_id=>version_id, :action=>'drive', :rnd=>rnd) + "', 'drive', 'location=0,width=300,height=400,resizable=1');return false;\">" + (link_text || transb('btn_drive')) + "</a>" else tlink_to( (link_text || "btn_#{action}"), {:controller=>'version', :action => action , :id => version_id}, :title=>transb("btn_title_#{action}"), :post=>true ) + "\n" end end # Buttons are :edit, :add, :propose, :publish, :refuse, or :drive. :all = (:edit, :propose, :publish, :refuse, :drive) def edit_button(action, opt={}) res = [] if opt[:node] version_id = opt[:node].v_id node = opt[:node] else version_id = nil node = @node end if (action == :edit or action == :all) && node.can_edit? res << form_action('edit',version_id, opt[:text]) end if (action == :propose or action == :all) && node.can_propose? res << form_action('propose',version_id, opt[:text]) end if (action == :publish or action == :all) && node.can_publish? res << form_action('publish',version_id, opt[:text]) end if (action == :refuse or action == :all) && node.can_refuse? res << form_action('refuse',version_id, opt[:text]) end if (action == :drive or action == :all) && node.can_drive? res << form_action('drive',version_id, opt[:text]) end "<li>#{res.join("</li>\n<li>")}</li>" end # TODO: test def version_form_action(action,version_id) tlink_to_remote( "btn_#{action}", :url=>{:controller=>'version', :action => action , :id => version_id, :drive=>true}, :title=>transb("btn_title_#{action}"), :post=>true ) + "\n" end # TODO: test # show actions on versions def version_actions(version, opt={}) opt = {:action=>:all}.merge(opt) return "" unless version.kind_of?(Version) actions = [] if opt[:action] == :view if (version.status != Zena::Status[:del]) || (version[:user_id] == visitor.id ) actions << version_form_action('view', version[:id]) end elsif opt[:action] == :all case version.status when Zena::Status[:pub] actions << version_form_action('unpublish',version[:id]) if @node.can_unpublish? when Zena::Status[:prop] actions << version_form_action('publish',version[:id]) actions << version_form_action('refuse',version[:id]) when Zena::Status[:prop_with] actions << version_form_action('publish',version[:id]) actions << version_form_action('refuse',version[:id]) when Zena::Status[:red] actions << version_form_action('publish',version[:id]) actions << version_form_action('propose',version[:id]) actions << version_form_action('remove',version[:id]) if version.user[:id] == visitor.id when Zena::Status[:rep] actions << version_form_action('edit',version[:id]) if @node.can_edit_lang?(version.lang) actions << version_form_action('publish',version[:id]) actions << version_form_action('propose',version[:id]) when Zena::Status[:rem] actions << version_form_action('edit',version[:id]) if @node.can_edit_lang?(version.lang) actions << version_form_action('publish',version[:id]) actions << version_form_action('propose',version[:id]) when Zena::Status[:del] if (version[:user_id] == session[:user][:id]) actions << version_form_action('edit',version[:id]) if @node.can_edit_lang?(version.lang) end end end actions.join(" ") end # TODO: test def discussion_actions(discussion, opt={}) opt = {:action=>:all}.merge(opt) return '' unless @node.can_drive? if opt[:action] == :view tlink_to_function('btn_view', "opener.Zena.discussion_show(#{discussion[:id]}); return false;") elsif opt[:action] == :all if discussion.open? link_to_remote( transb("img_open"),:with=>'discussions', :url=>{:controller=>'discussion', :action => 'close' , :id => discussion[:id]}, :title=>transb("btn_title_close")) + "\n" else link_to_remote( transb("img_closed"), :with=>'discussions', :url=>{:controller=>'discussion', :action => 'open', :id => discussion[:id]}, :title=>transb("btn_title_open")) + "\n" end + if discussion.can_destroy? link_to_remote( transb("btn_remove"), :with=>'discussions', :url=>{:controller=>'discussion', :action => 'remove', :id => discussion[:id]}, :title=>transb("btn_title_destroy")) + "\n" else '' end end end # TODO: test def css_edit(css_file = 'zen.css') return '' if RAILS_ENV == 'production' str = <<ENDTXT <div id='css_edit'> <div id='css' onClick='cssUpdate()'></div> <script type="text/javascript"> var c=0 var t function timedCount() { var file = $('css_file').value if (c == '#'){ c = '_' } else { c = '#' } document.getElementById('css_counter').innerHTML=c new Ajax.Request('/z/version/css_preview', {asynchronous:true, evalScripts:true, parameters:'css='+file}); t=setTimeout("timedCount()",2000) } function stopCount() { clearTimeout(t) } </script> <form> <input type="button" value="Start CSS" onClick="timedCount()"> <input type="button" value="Stop CSS" onClick="stopCount()"> <span id='css_counter'></span> <input type='text' id='css_file' name='css_file' value='#{css_file}'/> </form> </div> ENDTXT end # Create the traduction list for the current node def traductions(obj=@node) trad_list = [] lang_found = false obj.traductions.map do |ed| if ed == obj.v_lang lang_found = (ed == lang) # current node is in the requested lang trad_list << "<span class='on'>" + link_to( ed, change_lang(ed)) + "</span>" else trad_list << "<span>" + link_to( ed, change_lang(ed)) + "</span>" end end trad_list << "<span class='off'>#{lang}</span>" unless lang_found trad_list end def change_lang(new_lang) if session[:user] {:overwrite_params => { :lang => new_lang }} else {:overwrite_params => { :prefix => new_lang }} end end # find the title partial for the current object or parameter def title_partial(obj=@node) klass = obj.class path = nil partial = nil while (partial == nil) && (klass != ActiveRecord::Base) do path = File.join(RAILS_ROOT,'app', 'views', klass.to_s.downcase, '_title.rhtml') if File.exist?(path) partial = "#{klass.to_s.downcase}/title" break end klass = klass.superclass end partial end # show author information # size can be either :small or :large, options are # :node=>object def author(size, opt={}) obj = opt[:node] || @node if size == :large res = [] res << "<div class='info'>" if obj.author.id == obj.v_author.id res << trans("posted by") + " <b>" + obj.author.fullname + "</b>" else res << trans("original by") + " <b>" + obj.author.fullname + "</b>" res << trans("new post by") + " <b>" + obj.v_author.fullname + "</b>" end res << trans("on") + " " + short_date(obj.v_updated_at) + "." res << trans("Traductions") + " : <span id='trad'>" + traductions.join(", ") + "</span>" res << "</div>" res.join("\n") else "<div class='info'><b>#{obj.v_author.initials}</b> - #{short_date(obj.v_updated_at)}</div>" end end # show current path with links to ancestors def path_links(node=@node) nav = [] node.ancestors.each do |obj| nav << link_to(obj.name, node_url(obj)) end nav << "<a href='#{url_for(node_url(node))}' class='current'>#{node.name}</a>" if node[:id] == @node[:id] res = "<ul id='path' class='path'>" else res = "<ul class='path'>" end "#{res}<li>#{nav.join(" / </li><li>")}</li></ul>" end # shows links for site features def show_link(link, opt={}) case link when :admin_links [show_link(:home), show_link(:preferences), show_link(:comments), show_link(:users), show_link(:groups), show_link(:translation)].reject {|l| l==''} when :home return '' unless session[:user] tlink_to_with_state('my home', :controller=>'user', :action=>'home') when :preferences return '' unless session[:user] tlink_to_with_state('preferences', :controller=>'preferences', :action=>'list') when :translation return '' unless visitor.group_ids.include?(ZENA_ENV[:translate_group]) tlink_to_with_state('translate interface', :controller=>'trans', :action=>'list') when :comments return '' unless visitor.is_admin? tlink_to_with_state('manage comments', :controller=>'comment', :action=>'list') when :users return '' unless visitor.is_admin? tlink_to_with_state('manage users', :controller=>'user', :action=>'list') when :groups return '' unless visitor.is_admin? tlink_to_with_state('manage groups', :controller=>'group', :action=>'list') when :site_tree tlink_to_with_state('site tree', :controller=>'main', :action=>'site_tree', :id=>@node) when :print if @node tlink_to('print', :controller=>'main', :action=>'print', :id=>@node) else '' end else '' end end # show language selector def lang_links if ZENA_ENV[:monolingual] "<div id='lang' class='empty'></div>" else res = [] ZENA_ENV[:languages].sort.each do |l| if l == lang res << "<b>#{l}</b>" else if session[:user] res << link_to(l, request.parameters.merge(:lang=>l)) else res << link_to(l, request.parameters.merge(:prefix=>l)) end end end "<div id='lang'><span>#{res.join(' | ')}</span></div>" end end def lang_ajax_link if ZENA_ENV[:monolingual] "<div id='lang' class='empty'></div>" else res = "<div id='lang'><span>" + link_to_remote( lang, :update=>'lang', :url=>{:controller => 'trans', :action=>'lang_menu'}) if session[:translate] res << show_link(:translation, :menu=>true) end res << '</span></div>' res end end # TODO: test def search_box "<div id='search_anchor'>" + render_to_string(:partial=>'search/form') + "</div>" end private # list of escaped sequences used by zazen_escape and zazen_unescape def escaped_sequences [['"','\\QUOTE\\'], [':', '\\DDOT\\'], ['!', '\\EXCLAM\\'], ['<', '\\LESSTHEN\\'], ['>', '\\GREATERTHEN\\']] end # escape sequences for 'code' blocks. This avoids 'zazen' to run on the code. def zazen_escape(str) escaped_sequences.each do |from, to| str.gsub!(from, to) end str end # unescape for 'code' blocks after 'zazen' is run. def zazen_unescape(str) escaped_sequences.each do |from, to| str.gsub!(to, from) end if str =~ /^([a-z]+)\|/ code_lang = $1 str = str[(code_lang.length + 1)..-1] if ['ruby'].include?(code_lang) convertor = Syntax::Convertors::HTML.for_syntax(code_lang) res = convertor.convert( str ) "<div class='ruby'>#{res}</div>" else str end else str end end def calendar_get_options(size, source, method) case size when :tiny day_names = Date::ABBR_DAYNAMES on_day = Proc.new { |e,d| e ? "<b class='has_note'>#{d.day}</b>" : d.day } when :large day_names = Date::DAYNAMES on_day = Proc.new do |notes,d| if notes res = ["#{d.day}"] notes.each do |e| #largecal_preview res << "<div>" + link_to_remote(e.name.limit(14), :update=>'largecal_preview', :url=>{:controller=>'note', :action=>'day_list', :id=>source[:id], :find=>method, :date=>d, :selected=>e[:id] }) + "</div>" end res.join("\n") else d.day end end end [day_names, on_day] end def calendar_class(day, ref) case day.wday when 6 s = "sat" when 0 s = "sun" else s = "" end s+= day.mon == ref.mon ? '' : 'other' s != "" ? " class='#{s}'" : "" end # This lets helpers render partials def render_to_string(*args) @controller.send(:render_to_string, *args) end # TODO: test # clever id selector def select_id(obj, sym, opt={}) if ['Project', 'Tag', 'Contact'].include?(opt[:class].to_s) klass = opt[:class].kind_of?(Class) ? opt[:class] : eval(opt[:class]) return select(obj,sym, secure(klass) { klass.find(:all, :select=>'id,name', :order=>'name ASC') }.map{|r| [r[:name], r[:id]]}, { :include_blank => opt[:include_blank] }) end # FIXME: SECURITY is there a better way to do this ? node = eval("@#{obj}") if node id = node.send(sym.to_sym) current_obj = secure(Node) { Node.find_by_id(id) } if id else id = '' current_obj = nil end name_ref = "#{obj}_#{sym}_name" attribute = opt[:show] || 'name' if current_obj current = current_obj.send(attribute.to_sym) if current.kind_of?(Array) current = current.join('/') end else current = '' end # we use both 'onChange' and 'onKeyup' for old javascript compatibility update = "new Ajax.Updater('#{name_ref}', '/z/node/attribute/' + this.value + '?attr=#{attribute}', {asynchronous:true, evalScripts:true});" "<div class='select_id'><input type='text' size='8' id='#{obj}_#{sym}' name='#{obj}[#{sym}]' value='#{id}' onChange=\"#{update}\" onKeyup=\"#{update}\"/>"+ "<span class='select_id_name' id='#{name_ref}'>#{current}</span></div>" end end =begin # Methods added to this helper will be available to all templates in the application. module ApplicationHelper include Zena::Acts::SecureScope include Zena::Acts::SecureController::InstanceMethods include ZenaGlobals uses_strips :base, :admin, :calendar # Overwrite error_messages_for to include translation def error_messages_for(object_name, options = {}) options = options.symbolize_keys object = instance_variable_get("@#{object_name}") if object && !object.errors.empty? content_tag("div", content_tag("ul", object.errors.full_messages.collect { |msg| content_tag("li", t(msg)) }), "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation" ) else "" end end end =end fixed problem rendering ' (twice escaped) git-svn-id: e099d366fb13ea49c9e8e170ced890dab3ea84f7@230 aaa19a3b-e121-0410-9d45-962fd44e537e require 'syntax/convertors/html' # Methods added to this helper will be available to all templates in the application. module ApplicationHelper include Zena::Acts::SecureScope include Zena::Acts::SecureController::InstanceMethods # helpers to include clean javascript def javascript( string ) javascript_start + string + javascript_end end def javascript_start "<script type=\"text/javascript\" language=\"javascript\" charset=\"utf-8\">\n// <![CDATA[\n" end def javascript_end "\n// ]]>\n</script>" end # Calendar seizure setup def uses_calendar if ZENA_ENV[:calendar_langs].include?(lang) l = lang else l = ZENA_ENV[:default_lang] end <<-EOL <script src="/calendar/calendar.js" type="text/javascript"></script> <script src="/calendar/calendar-setup.js" type="text/javascript"></script> <script src="/calendar/lang/calendar-#{lang}-utf8.js" type="text/javascript"></script> <link href="/calendar/calendar-brown.css" media="screen" rel="Stylesheet" type="text/css" /> #{javascript_start} Calendar._TT["DEF_DATE_FORMAT"] = "#{transb('datetime')}"; Calendar._TT["FIRST_DAY"] = #{transb('week_start_day')}; #{javascript_end} EOL end # Date selection tool def date_box(obj, var, opts = {}) rnd_id = Time.now.to_i defaults = { :id=>"datef#{rnd_id}", :button=>"dateb#{rnd_id}", :display=>"dated#{rnd_id}", :class=>var.to_s } opts = defaults.merge(opts) date = eval("@#{obj} ? @#{obj}.#{var} : nil") || Time.now.utc value = format_date(date,'datetime') if opts[:size] == 0 fld = hidden_field obj, var, :id=>opts[:id] , :value=>value, :class=>opts[:class] else fld = text_field obj, var, :id=>opts[:id] , :value=>value, :class=>opts[:class], :size=>opts[:size] end <<-EOL <div class="date_box"><img src="/calendar/iconCalendar.gif" id="#{opts[:button]}"/> #{fld} <script type="text/javascript"> Calendar.setup({ inputField : "#{opts[:id]}", // id of the input field button : "#{opts[:button]}", // trigger for the calendar (button ID) singleClick : true, showsTime : true }); </script></div> EOL end # Translate submit_tag def tsubmit_tag(*args) args[0] = trans(args[0],:edit=>false) submit_tag(*args) end # Translate link_to_remote def tlink_to_remote(*args) args[0] = trans(args[0],:edit=>false) link_to_remote(*args) end # Translate link_to_remote def tlink_to(*args) args[0] = trans(args[0],:edit=>false) link_to(*args) end # Add class='on' if the link points to the current page def tlink_to_with_state(*args) title, url, options = *args options ||= {} same = true url.each do |k,v| same &&= (params[k.to_s] == v.to_s) end if same options[:class] = 'on' end tlink_to(title, url, options) end # Translate link_to_remote def tlink_to_function(*args) args[0] = trans(args[0],:edit=>false) link_to_function(*args) end # Translate links/button (not editable) def transb(key) trans(key, :edit=>false) end # creates a pseudo random string to avoid browser side ajax caching def rnd Time.now.to_i end # "Translate" static text into the current lang def trans(keyword, opt={}) opt = {:edit=>true}.merge(opt) if opt[:translate] || (session[:translate] && opt[:edit]) key = TransPhrase.translate(keyword) "<div id='phrase#{key[:id]}' class='trans'>" + link_to_remote(key.into(lang), :update=>"phrase#{key[:id]}", :url=>{:controller=>'trans', :action=>'edit', :id=>key[:id]}, :complete=>'$("trans_value").focus();$("trans_value").select()') + "</div>" else TransPhrase[keyword][lang] end end # Shows 'login' or 'logout' button. def login_link if session[:user] "<div id='logout'><a href='/logout'>#{transb('logout')}</a></div>" else "<div id='logout'><a href='/login'>#{transb('login')}</a></div>" end end # display the time with the format provided by the translation of 'long_time' def long_time(atime) format_date(atime, "long_time") end # display the time with the format provided by the translation of 'short_time' def short_time(atime) format_date(atime, "short_time") end # display the time with the format provided by the translation of 'full_date' def full_date(adate) format_date(adate, "full_date") end # display the time with the format provided by the translation of 'long_date' def long_date(adate) format_date(adate, "long_date") end # display the time with the format provided by the translation of 'short_date' def short_date(adate) format_date(adate, "short_date") end # format a date with the given format. Translate month and day names. def format_date(thedate, fmt) if thedate adate = visitor.tz.adjust(thedate) format = trans(fmt) if format != fmt # month name format.gsub!("%b", trans(adate.strftime("%b")) ) format.gsub!("%B", trans(adate.strftime("%B")) ) # weekday name format.gsub!("%a", trans(adate.strftime("%a")) ) format.gsub!("%A", trans(adate.strftime("%A")) ) adate.strftime(format) else trans fmt end end end # Show visitor name if logged in def visitor_link if session[:user] "<div id='visitor'>" + link_to( visitor.fullname, user_home_url ) + "</div>" else "" end end # Display flash[:notice] or flash[:error] if any. <%= flash <i>[:notice, :error, :both]</i> %>" def flash_messages(type=:both) "<div id='messages'>" + if (type == :notice || type == :both) && @flash[:notice] "<div id='notice' class='flash' onClick='new Effect.Fade(\"notice\")'>#{@flash[:notice]}</div>" else '' end + if (type == :error || type == :both) && @flash[:error ] "<div id='error' class='flash' onClick='new Effect.Fade(\"error\")'>#{@flash[:error]}</div>" else '' end + "</div>" end # Display logo with message (can be a date or a string) def logo(message='') if message.kind_of?(Time) message = format_date(message, 'logo_date') end "<div id='logo'>" + link_to( image_tag('/img/logo.png', :size=>'220x100'), :prefix => prefix, :controller => 'main', :action=>'index') + "<div id='logo_msg'>#{message}</div></div>" end # This method renders the Textile text contained in an object as html. It also renders the zena additions : # === Zena additions # all these additions are replaced by the traduction of 'unknown link' or 'unknown image' if the user does # not have read access to the linked node. # * ["":34] creates a link to node 34 with node's title. # * ["title":34] creates a link to node 34 with the given title. # * ["":034] if the node id starts with '0', creates a popup link. # * [!14!] inline image 14 or link to document 14 with icon. (default format for images is 'std' defined in #ImageBuilder). Options are : # ** [!014!] if the id starts with '0', the image becomes a link to the full image. # ** [!<.14!] or [!<14!] inline image surrounded with <p class='img_left'></p> # ** [!>.14!] or [!>14!] inline image surrounded with <p class='img_right'></p> # ** [!=.14!] or [!=14!] inline image with <p class='img_center'></p> # ** [!14.pv!] inline image transformed to format 'pv' (class is also set to 'pv'). Formats are defined in #ImageBuilder. # ** all the options above can be used together as in [!>.14.med!] : inline image on the right, size 'med'. # ** [![2,3,5]!] gallery : inline preview with javascript inline viewer # ** [![]!] gallery with all images contained in the current node # * [!{7,9}!] documents listing for documents 7 and 9 # * [!{}!] list all documents (with images) for the current node # * [!{d}!] list all documents (without images) for the current node # * [!{i}!] list all images for the current node # * [!14!:37] you can use an image as the source for a link # * [!14!:www.example.com] use an image for an outgoing link def zazen(text, opt={}) opt = {:images=>true}.merge(opt) img = opt[:images] if opt[:limit] opt[:limit] -= 1 unless opt[:limit] <= 0 paragraphs = text.split(/\n\n/) if paragraphs.size > (opt[:limit]+1) && opt[:limit] != -1 text = paragraphs[0..opt[:limit]].join("\n\n") + " &#8230;<span class='more'>" + trans("(click to read more)") + "</span>" end end r = RedCloth.new(text) #, [:hard_breaks]) r.gsub!( /(\A|[^\w])@(.*?)@(\Z|[^\w])/ ) { "#{$1}\\AT_START\\#{zazen_escape($2)}\\AT_END\\#{$3}" } r.gsub!( /<code>(.*?)<\/code>/m ) { "\\CODE_START\\#{zazen_escape($1)}\\CODE_END\\" } r.gsub!( /\!\[([^\]]*)\]\!/ ) { img ? make_gallery($1) : trans('[gallery]') } r.gsub!( /\!([^0-9]{0,2})\{([^\}]*)\}\!/ ) { img ? list_nodes(:style=>$1, :ids=>$2) : trans('[documents]')} r.gsub!( /\!([^0-9]{0,2})([0-9]+)(\.([^\/\!]+)|)(\/([^\!]*)|)\!(:([^\s]+)|)/ ) { img ? make_image(:style=>$1, :id=>$2, :size=>$4, :title=>$6, :link=>$8) : "[#{trans('image')}#{$6 ? (": " + zazen($6,:images=>false)) : ''}]"} r.gsub!( /"([^"]*)":([0-9]+)/ ) { make_link(:title=>$1,:id=>$2)} r = r.to_html r.gsub!( /(\\CODE_START\\)(.*?)(\\CODE_END\\)/m ) { "<div class='box'>#{zazen_unescape($2)}</div>" } r.gsub!( /(\\AT_START\\)(.*?)(\\AT_END\\)/ ) { "#{zazen_unescape($2)}" } r.gsub!( /\?(\w[^\?]+?\w)\?/ ) { make_wiki_link($1) } r end # Creates a link to the node referenced by id def make_link(opts) node = secure(Node) { Node.find(opts[:id]) } title = (opts[:title] && opts[:title] != '') ? opts[:title] : node.v_title if opts[:id][0..0] == '0' link_to title, {:prefix => prefix, :controller => 'main', :action=>'show', :path=>node.fullpath}, :popup=>true else link_to title, :prefix => prefix, :controller => 'main', :action=>'show', :path=>node.fullpath end rescue ActiveRecord::RecordNotFound "<span class='unknownLink'>#{trans('unknown link')}</span>" end # TODO: test def make_wiki_link(keyword) "<a href='http://#{lang}.wikipedia.org/wiki/Special:Search?search=#{CGI::escape(keyword)}' class='wiki'>#{keyword}</a>" end # Create an img tag for the given image. See ApplicationHelper#zazen for details. def make_image(opts) id, style, link, size, title = opts[:id], opts[:style], opts[:link], opts[:size], opts[:title] img = secure(Document) { Document.find(id) } title = img.v_summary if title == "" size = IMAGEBUILDER_FORMAT[size] ? size : nil if !size && img.kind_of?(Image) size = 'std' end image = img.img_tag(size) unless link if id[0..0] == "0" || !img.kind_of?(Image) # if the id starts with '0' or it is not an Image, link to data link = url_for(data_url(img)) end end style ||= '' case style.sub('.', '') when ">" prefix = "<div class='img_right'>" suffix = "</div>" when "<" prefix = "<div class='img_left'>" suffix = "</div>" when "=" prefix = "<div class='img_center'>" suffix = "</div>" else prefix = suffix = "" end if title prefix = "#{prefix}<div class='img_with_title'>" suffix = "<div class='img_title'>#{zazen(title, :images=>false)}</div></div>#{suffix}" end if link.nil? prefix + image + suffix elsif link =~ /^\d+$/ prefix + make_link(:id=>link,:title=>image) + suffix else link = "http://#{link}" unless link =~ %r{(^/|.+://.+)} prefix + "<a href='#{link}'>" + image + "</a>" + suffix end rescue ActiveRecord::RecordNotFound "<span class='unknownLink'>#{trans('unknown document')}</span>" end # Create a gallery from a list of images. See ApplicationHelper#zazen for details. def make_gallery(ids="") if ids == "" images = @node.images else ids = ids.split(',').map{|i| i.to_i}.join(',') # sql injection security images = secure(Document) { Document.find(:all, :conditions=>"id IN (#{ids})") } end render_to_string( :partial=>'main/gallery', :locals=>{:gallery=>images} ) end def list_nodes(opt={}) ids = opt[:ids] style = opt[:style] || '' case style.sub('.', '') when ">" prefix = "<div class='img_right'>" suffix = "</div>" when "<" prefix = "<div class='img_left'>" suffix = "</div>" when "=" prefix = "<div class='img_center'>" suffix = "</div>" else prefix = suffix = "" end if ids == "" docs = @node.documents elsif ids == "d" docs = @node.documents_only elsif ids == "i" docs = @node.images else ids = ids.split(',').map{|i| i.to_i}.join(',') # sql injection security docs = secure(Document) { Document.find(:all, :order=>'name ASC', :conditions=>"id IN (#{ids})") } end prefix + render_to_string( :partial=>'main/list_nodes', :locals=>{:docs=>docs}) + suffix end def data_url(obj) if obj.kind_of?(Document) {:controller=>'document', :action=>'data', :version_id=>obj.v_id, :filename=>obj.c_filename, :ext=>obj.c_ext} else raise StandardError, "Cannot create 'data_url' for #{obj.class}." end end # return a readable text version of a file size def fsize(size) size = size.to_f if size >= 1024 * 1024 * 1024 sprintf("%.2f Gb", size/(1024*1024*1024)) elsif size >= 1024 * 1024 sprintf("%.1f Mb", size/(1024*1024)) elsif size >= 1024 sprintf("%i Kb", (size/(1024)).ceil) else sprintf("%i octets", size) end end # Hierachical menu. (same on all pages) def show_menu Cache.with(visitor.id, visitor.group_ids, Page.kpath, 'show_menu') do if ZENA_ENV[:menu_tag_id] !=nil menu = secure(Tag) { Tag.find(ZENA_ENV[:menu_tag_id]) } menus = menu.pages elsif ZENA_ENV[:root_id] != nil menus = secure(Node) { Node.find(ZENA_ENV[:root_id]) }.pages else menus = secure(Page) { Page.find(:all, :conditions=>"parent_id IS NULL") } end res = ["<div id='menu'>"] res << "<ul>" res << render_to_string(:partial=>'main/menu', :collection=>menus) res << "</ul>" res << "</div>" res.join("\n") end end def calendar(options={}) source = options[:from ] || (@project ||= (@node ? @node.project : nil)) date = options[:date ] || Date.today method = options[:find ] || :notes size = options[:size ] || :tiny using = options[:using ] || :event_at day_names, on_day = calendar_get_options(size, source, method) return "" unless on_day && source Cache.with(visitor.id, visitor.group_ids, 'NN', size, method, source.id, date.ajd, lang) do # find start and end date week_start_day = trans('week_start_day').to_i start_date = Date.civil(date.year, date.mon, 1) start_date -= (start_date.wday + 7 - week_start_day) % 7 end_date = Date.civil(date.year, date.mon, -1) end_date += (6 + week_start_day - end_date.wday) % 7 # get list of notes in this scope # TODO: use time_zone here ? notes = source.send(method,:conditions=>["#{using} >= ? AND #{using} <= ?", start_date, end_date], :order=>"#{using} ASC") # build event hash calendar = {} notes.each do |n| calendar[n.send(using.to_sym).strftime("%Y-%m-%d")] ||= [] calendar[n.send(using.to_sym).strftime("%Y-%m-%d")] << n end title = "#{trans(Date::MONTHNAMES[date.mon])} #{date.year}" head_day_names = [] 0.upto(6) do |i| head_day_names << "<td>#{trans(day_names[(i+week_start_day) % 7])}</td>" end content = [] start_date.step(end_date,7) do |week| # each week content << "<tr class='body'>" week.step(week+6,1) do |day| # each day content << "<td#{ calendar_class(day,date)}#{day == Date.today ? " id='#{size}_today'" : "" }><p>#{on_day.call(calendar[day.strftime("%Y-%m-%d")], day)}</p></td>" end content << '</tr>' end render_to_string(:partial=>"calendar/#{size}", :locals=>{ :content=>content.join("\n"), :day_names=>head_day_names.join(""), :title=>title, :date=>date, :source=>source, :method=>method, :size=>size }) end end def unless_empty(obj) if obj.nil? || obj.empty? return '' else yield(obj) end end # Show a little [xx] next to the title if the desired language could not be found. def check_lang(obj) obj.v_lang != lang ? " <span class='wrong_lang'>[#{obj.v_lang}]</span> " : "" end # TODO: test # display the title with necessary id and checks for 'lang'. Options : # * :link if true, the title is a link to the object's page # default = true if obj is not the current node '@node' # * :project if true , the project name is added before the object title as 'project / .....' # default = obj project is different from current node project # if no options are provided show the current object title def show_title(obj=@node, opt={}) unless opt.include?(:link) opt[:link] = (obj[:id] != @node[:id]) end unless opt.include?(:project) opt[:project] = (obj[:project_id] != @node[:project_id] && obj[:id] != @node[:id]) end if opt[:project] title = "#{obj.project.name} / #{obj.v_title}" else title = obj.v_title end if opt[:link] title = link_to(title, node_url(obj)) end "<span id='v_title#{obj.v_id}'>#{title}#{check_lang(obj)}</span>" end # TODO: test def show(obj, sym, opt={}) return show_title(obj, opt) if sym == :v_title if opt[:as] key = "#{opt[:as]}#{obj.v_id}" preview_for = opt[:as] opt.delete(:as) else key = "#{sym}#{obj.v_id}" end if opt[:text] text = opt[:text] opt.delete(:text) else text = obj.send(sym) if (text.nil? || text == '') && sym == :v_summary text = obj.v_text opt[:images] = false else opt.delete(:limit) end end if [:v_text, :v_summary].include?(sym) text = zazen(text, opt) klass = " class='text'" else klass = "" end if preview_for render_to_string :partial=>'node/show_attr', :locals=>{:id=>obj[:id], :text=>text, :preview_for=>preview_for, :key=>key, :klass=>klass, :key_on=>"#{key}#{Time.now.to_i}_on", :key_off=>"#{key}#{Time.now.to_i}_off"} else "<div id='#{key}'#{klass}>#{text}</div>" end end # TODO: test def link_box(obj, sym, opt={}) # FIXME: SECURITY is there a better way to do this ? node = eval("@#{obj}") method = "#{sym}_for_form".to_sym role = node.class.role[sym.to_s] setter = sym.to_s.singularize if role[:unique] # unique res = [select_id(obj,"#{setter}_id", :class=>role[:klass], :include_blank=>true)] else # many if opt[:in] ids = opt[:in].map{|i| i.to_i} list = node.send(method, :conditions=>["nodes.id IN (#{ids.join(',')})"]) else list = node.send(method) end res = list.inject([]) do |list, l| list << "<input type='checkbox' name='node[#{setter}_ids][]' value='#{l.id}' class='box' #{ l[:link_id] ? "checked='1' " : ""}/>#{l.name}" list end end if opt.include?(:title) if opt[:title].nil? title = '' else title = "<li><b>#{opt[:title]}</b></li>" end else title = "<li><b>#{trans(sym.to_s)}</b></li>" end "<ul class='link_box'>#{title}<li>#{res.join('</li><li>')}</li></ul>" end #TODO: test # Return the list of groups from the visitor for forms def form_groups @form_groups ||= Group.find(:all, :select=>'id, name', :conditions=>"id IN (#{visitor.group_ids.join(',')})", :order=>"name ASC").collect {|p| [p.name, p.id]} end #TODO: test # Return the list of possible templates def form_templates return @form_templates if @form_templates @form_templates = [] Dir.foreach(File.join(RAILS_ROOT, 'app', 'views', 'templates')) do |file| next unless file =~ /^([a-zA-Z0-9]+)\.rhtml$/ next if ['index', 'not_found'].include?($1) @form_templates << $1 end @form_templates end #TODO: test def site_tree(obj=nil) skip = obj ? obj[:id] : nil base = secure(Node) { Node.find(ZENA_ENV[:root_id]) } level = 0 if obj.nil? klass = Node elsif obj.kind_of?(Document) klass = Node elsif obj.kind_of?(Note) klass = Project else klass = Page end tree = get_site_tree(skip,base,level) tree.reject! { |node| !(node[1][:kpath] =~ /^#{klass.kpath}/) } return [] unless tree tree.map {|p| ["Β Β "*p[0] + p[1][:name], p[1][:id] ]} end #TODO: test def readers_for(obj=@node) readers = if obj.private? trans('img_private') elsif [obj.rgroup_id,obj.pgroup_id,obj.user_id].include?(1) trans('img_public') else names = [] names |= [obj.rgroup.name.limit(4)] if obj.rgroup names |= [obj.pgroup.name.limit(4)] if obj.pgroup names << obj.user.initials names.join(', ') end custom = obj.inherit != 1 ? "<span class='custom'>#{trans('img_custom_inherit')}</span>" : '' "#{custom} #{readers}" end # Used by edit_buttons def form_action(action, version_id=nil, link_text=nil) version_id ||= @node.v_id if action == 'edit' "<a href='#' title='#{transb('btn_title_edit')}' onClick=\"editor=window.open('" + url_for(:controller=>'version', :id=>version_id, :action=>'edit', :rnd=>rnd) + "', 'edit', 'location=0,width=300,height=400,resizable=1');return false;\">" + (link_text || transb('btn_edit')) + "</a>" elsif action == 'view' tlink_to_function((link_text || 'btn_view'), "opener.Zena.version_preview(#{version_id}); return false;") elsif action == 'drive' "<a href='#' title='#{transb('btn_title_drive')}' onClick=\"editor=window.open('" + url_for(:controller=>'node', :version_id=>version_id, :action=>'drive', :rnd=>rnd) + "', 'drive', 'location=0,width=300,height=400,resizable=1');return false;\">" + (link_text || transb('btn_drive')) + "</a>" else tlink_to( (link_text || "btn_#{action}"), {:controller=>'version', :action => action , :id => version_id}, :title=>transb("btn_title_#{action}"), :post=>true ) + "\n" end end # Buttons are :edit, :add, :propose, :publish, :refuse, or :drive. :all = (:edit, :propose, :publish, :refuse, :drive) def edit_button(action, opt={}) res = [] if opt[:node] version_id = opt[:node].v_id node = opt[:node] else version_id = nil node = @node end if (action == :edit or action == :all) && node.can_edit? res << form_action('edit',version_id, opt[:text]) end if (action == :propose or action == :all) && node.can_propose? res << form_action('propose',version_id, opt[:text]) end if (action == :publish or action == :all) && node.can_publish? res << form_action('publish',version_id, opt[:text]) end if (action == :refuse or action == :all) && node.can_refuse? res << form_action('refuse',version_id, opt[:text]) end if (action == :drive or action == :all) && node.can_drive? res << form_action('drive',version_id, opt[:text]) end "<li>#{res.join("</li>\n<li>")}</li>" end # TODO: test def version_form_action(action,version_id) tlink_to_remote( "btn_#{action}", :url=>{:controller=>'version', :action => action , :id => version_id, :drive=>true}, :title=>transb("btn_title_#{action}"), :post=>true ) + "\n" end # TODO: test # show actions on versions def version_actions(version, opt={}) opt = {:action=>:all}.merge(opt) return "" unless version.kind_of?(Version) actions = [] if opt[:action] == :view if (version.status != Zena::Status[:del]) || (version[:user_id] == visitor.id ) actions << version_form_action('view', version[:id]) end elsif opt[:action] == :all case version.status when Zena::Status[:pub] actions << version_form_action('unpublish',version[:id]) if @node.can_unpublish? when Zena::Status[:prop] actions << version_form_action('publish',version[:id]) actions << version_form_action('refuse',version[:id]) when Zena::Status[:prop_with] actions << version_form_action('publish',version[:id]) actions << version_form_action('refuse',version[:id]) when Zena::Status[:red] actions << version_form_action('publish',version[:id]) actions << version_form_action('propose',version[:id]) actions << version_form_action('remove',version[:id]) if version.user[:id] == visitor.id when Zena::Status[:rep] actions << version_form_action('edit',version[:id]) if @node.can_edit_lang?(version.lang) actions << version_form_action('publish',version[:id]) actions << version_form_action('propose',version[:id]) when Zena::Status[:rem] actions << version_form_action('edit',version[:id]) if @node.can_edit_lang?(version.lang) actions << version_form_action('publish',version[:id]) actions << version_form_action('propose',version[:id]) when Zena::Status[:del] if (version[:user_id] == session[:user][:id]) actions << version_form_action('edit',version[:id]) if @node.can_edit_lang?(version.lang) end end end actions.join(" ") end # TODO: test def discussion_actions(discussion, opt={}) opt = {:action=>:all}.merge(opt) return '' unless @node.can_drive? if opt[:action] == :view tlink_to_function('btn_view', "opener.Zena.discussion_show(#{discussion[:id]}); return false;") elsif opt[:action] == :all if discussion.open? link_to_remote( transb("img_open"),:with=>'discussions', :url=>{:controller=>'discussion', :action => 'close' , :id => discussion[:id]}, :title=>transb("btn_title_close")) + "\n" else link_to_remote( transb("img_closed"), :with=>'discussions', :url=>{:controller=>'discussion', :action => 'open', :id => discussion[:id]}, :title=>transb("btn_title_open")) + "\n" end + if discussion.can_destroy? link_to_remote( transb("btn_remove"), :with=>'discussions', :url=>{:controller=>'discussion', :action => 'remove', :id => discussion[:id]}, :title=>transb("btn_title_destroy")) + "\n" else '' end end end # TODO: test def css_edit(css_file = 'zen.css') return '' if RAILS_ENV == 'production' str = <<ENDTXT <div id='css_edit'> <div id='css' onClick='cssUpdate()'></div> <script type="text/javascript"> var c=0 var t function timedCount() { var file = $('css_file').value if (c == '#'){ c = '_' } else { c = '#' } document.getElementById('css_counter').innerHTML=c new Ajax.Request('/z/version/css_preview', {asynchronous:true, evalScripts:true, parameters:'css='+file}); t=setTimeout("timedCount()",2000) } function stopCount() { clearTimeout(t) } </script> <form> <input type="button" value="Start CSS" onClick="timedCount()"> <input type="button" value="Stop CSS" onClick="stopCount()"> <span id='css_counter'></span> <input type='text' id='css_file' name='css_file' value='#{css_file}'/> </form> </div> ENDTXT end # Create the traduction list for the current node def traductions(obj=@node) trad_list = [] lang_found = false obj.traductions.map do |ed| if ed == obj.v_lang lang_found = (ed == lang) # current node is in the requested lang trad_list << "<span class='on'>" + link_to( ed, change_lang(ed)) + "</span>" else trad_list << "<span>" + link_to( ed, change_lang(ed)) + "</span>" end end trad_list << "<span class='off'>#{lang}</span>" unless lang_found trad_list end def change_lang(new_lang) if session[:user] {:overwrite_params => { :lang => new_lang }} else {:overwrite_params => { :prefix => new_lang }} end end # find the title partial for the current object or parameter def title_partial(obj=@node) klass = obj.class path = nil partial = nil while (partial == nil) && (klass != ActiveRecord::Base) do path = File.join(RAILS_ROOT,'app', 'views', klass.to_s.downcase, '_title.rhtml') if File.exist?(path) partial = "#{klass.to_s.downcase}/title" break end klass = klass.superclass end partial end # show author information # size can be either :small or :large, options are # :node=>object def author(size, opt={}) obj = opt[:node] || @node if size == :large res = [] res << "<div class='info'>" if obj.author.id == obj.v_author.id res << trans("posted by") + " <b>" + obj.author.fullname + "</b>" else res << trans("original by") + " <b>" + obj.author.fullname + "</b>" res << trans("new post by") + " <b>" + obj.v_author.fullname + "</b>" end res << trans("on") + " " + short_date(obj.v_updated_at) + "." res << trans("Traductions") + " : <span id='trad'>" + traductions.join(", ") + "</span>" res << "</div>" res.join("\n") else "<div class='info'><b>#{obj.v_author.initials}</b> - #{short_date(obj.v_updated_at)}</div>" end end # show current path with links to ancestors def path_links(node=@node) nav = [] node.ancestors.each do |obj| nav << link_to(obj.name, node_url(obj)) end nav << "<a href='#{url_for(node_url(node))}' class='current'>#{node.name}</a>" if node[:id] == @node[:id] res = "<ul id='path' class='path'>" else res = "<ul class='path'>" end "#{res}<li>#{nav.join(" / </li><li>")}</li></ul>" end # shows links for site features def show_link(link, opt={}) case link when :admin_links [show_link(:home), show_link(:preferences), show_link(:comments), show_link(:users), show_link(:groups), show_link(:translation)].reject {|l| l==''} when :home return '' unless session[:user] tlink_to_with_state('my home', :controller=>'user', :action=>'home') when :preferences return '' unless session[:user] tlink_to_with_state('preferences', :controller=>'preferences', :action=>'list') when :translation return '' unless visitor.group_ids.include?(ZENA_ENV[:translate_group]) tlink_to_with_state('translate interface', :controller=>'trans', :action=>'list') when :comments return '' unless visitor.is_admin? tlink_to_with_state('manage comments', :controller=>'comment', :action=>'list') when :users return '' unless visitor.is_admin? tlink_to_with_state('manage users', :controller=>'user', :action=>'list') when :groups return '' unless visitor.is_admin? tlink_to_with_state('manage groups', :controller=>'group', :action=>'list') when :site_tree tlink_to_with_state('site tree', :controller=>'main', :action=>'site_tree', :id=>@node) when :print if @node tlink_to('print', :controller=>'main', :action=>'print', :id=>@node) else '' end else '' end end # show language selector def lang_links if ZENA_ENV[:monolingual] "<div id='lang' class='empty'></div>" else res = [] ZENA_ENV[:languages].sort.each do |l| if l == lang res << "<b>#{l}</b>" else if session[:user] res << link_to(l, request.parameters.merge(:lang=>l)) else res << link_to(l, request.parameters.merge(:prefix=>l)) end end end "<div id='lang'><span>#{res.join(' | ')}</span></div>" end end def lang_ajax_link if ZENA_ENV[:monolingual] "<div id='lang' class='empty'></div>" else res = "<div id='lang'><span>" + link_to_remote( lang, :update=>'lang', :url=>{:controller => 'trans', :action=>'lang_menu'}) if session[:translate] res << show_link(:translation, :menu=>true) end res << '</span></div>' res end end # TODO: test def search_box "<div id='search_anchor'>" + render_to_string(:partial=>'search/form') + "</div>" end private # list of escaped sequences used by zazen_escape and zazen_unescape def escaped_sequences [['"','\\QUOTE\\'], ["'",'\\SQUOTE\\'], [':', '\\DDOT\\'], ['!', '\\EXCLAM\\'], ['<', '\\LESSTHEN\\'], ['>', '\\GREATERTHEN\\']] end # escape sequences for 'code' blocks. This avoids 'zazen' to run on the code. def zazen_escape(str) escaped_sequences.each do |from, to| str.gsub!(from, to) end str end # unescape for 'code' blocks after 'zazen' is run. def zazen_unescape(str) escaped_sequences.each do |from, to| str.gsub!(to, from) end if str =~ /^([a-z]+)\|/ code_lang = $1 str = str[(code_lang.length + 1)..-1] if ['ruby'].include?(code_lang) convertor = Syntax::Convertors::HTML.for_syntax(code_lang) res = convertor.convert( str ) "<div class='ruby'>#{res}</div>" else RedCloth.new("<code>#{str}</code>").to_html end else RedCloth.new("<code>#{str}</code>").to_html end end def calendar_get_options(size, source, method) case size when :tiny day_names = Date::ABBR_DAYNAMES on_day = Proc.new { |e,d| e ? "<b class='has_note'>#{d.day}</b>" : d.day } when :large day_names = Date::DAYNAMES on_day = Proc.new do |notes,d| if notes res = ["#{d.day}"] notes.each do |e| #largecal_preview res << "<div>" + link_to_remote(e.name.limit(14), :update=>'largecal_preview', :url=>{:controller=>'note', :action=>'day_list', :id=>source[:id], :find=>method, :date=>d, :selected=>e[:id] }) + "</div>" end res.join("\n") else d.day end end end [day_names, on_day] end def calendar_class(day, ref) case day.wday when 6 s = "sat" when 0 s = "sun" else s = "" end s+= day.mon == ref.mon ? '' : 'other' s != "" ? " class='#{s}'" : "" end # This lets helpers render partials def render_to_string(*args) @controller.send(:render_to_string, *args) end # TODO: test # clever id selector def select_id(obj, sym, opt={}) if ['Project', 'Tag', 'Contact'].include?(opt[:class].to_s) klass = opt[:class].kind_of?(Class) ? opt[:class] : eval(opt[:class]) return select(obj,sym, secure(klass) { klass.find(:all, :select=>'id,name', :order=>'name ASC') }.map{|r| [r[:name], r[:id]]}, { :include_blank => opt[:include_blank] }) end # FIXME: SECURITY is there a better way to do this ? node = eval("@#{obj}") if node id = node.send(sym.to_sym) current_obj = secure(Node) { Node.find_by_id(id) } if id else id = '' current_obj = nil end name_ref = "#{obj}_#{sym}_name" attribute = opt[:show] || 'name' if current_obj current = current_obj.send(attribute.to_sym) if current.kind_of?(Array) current = current.join('/') end else current = '' end # we use both 'onChange' and 'onKeyup' for old javascript compatibility update = "new Ajax.Updater('#{name_ref}', '/z/node/attribute/' + this.value + '?attr=#{attribute}', {asynchronous:true, evalScripts:true});" "<div class='select_id'><input type='text' size='8' id='#{obj}_#{sym}' name='#{obj}[#{sym}]' value='#{id}' onChange=\"#{update}\" onKeyup=\"#{update}\"/>"+ "<span class='select_id_name' id='#{name_ref}'>#{current}</span></div>" end end =begin # Methods added to this helper will be available to all templates in the application. module ApplicationHelper include Zena::Acts::SecureScope include Zena::Acts::SecureController::InstanceMethods include ZenaGlobals uses_strips :base, :admin, :calendar # Overwrite error_messages_for to include translation def error_messages_for(object_name, options = {}) options = options.symbolize_keys object = instance_variable_get("@#{object_name}") if object && !object.errors.empty? content_tag("div", content_tag("ul", object.errors.full_messages.collect { |msg| content_tag("li", t(msg)) }), "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation" ) else "" end end end =end
class Volta < Formula desc "JavaScript toolchain manager for reproducible environments" homepage "https://volta.sh" url "https://github.com/volta-cli/volta.git", tag: "v1.0.4", revision: "e4ab3604097bd48b5d32fa8adf69daa336d66c21" license "BSD-2-Clause" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "b48dd9fcdeaf5bd99d19670b90435ecef8b40b0f6e8b406a302f1e7f0d9d804e" sha256 cellar: :any_skip_relocation, big_sur: "b05113b680e109746163c3bf082ca7a2b2a00da1dcebb899416d7822e68d3a67" sha256 cellar: :any_skip_relocation, catalina: "dc76e1f95915f42a5289f7f368cdd970771f002992200e19160d7ae89651ebd2" sha256 cellar: :any_skip_relocation, mojave: "4f7ad7853a922751e34e48ac78656beea5fcb51b1c0c65f1d30010f2acbc85dc" end depends_on "rust" => :build uses_from_macos "openssl@1.1" on_linux do depends_on "pkg-config" => :build end def install system "cargo", "install", *std_cargo_args bash_output = Utils.safe_popen_read("#{bin}/volta", "completions", "bash") (bash_completion/"volta").write bash_output zsh_output = Utils.safe_popen_read("#{bin}/volta", "completions", "zsh") (zsh_completion/"_volta").write zsh_output fish_output = Utils.safe_popen_read("#{bin}/volta", "completions", "fish") (fish_completion/"volta.fish").write fish_output end test do system "#{bin}/volta", "install", "node@12.16.1" node = shell_output("#{bin}/volta which node").chomp assert_match "12.16.1", shell_output("#{node} --version") end end volta: add sha256 back after merge class Volta < Formula desc "JavaScript toolchain manager for reproducible environments" homepage "https://volta.sh" url "https://github.com/volta-cli/volta.git", tag: "v1.0.4", revision: "e4ab3604097bd48b5d32fa8adf69daa336d66c21" license "BSD-2-Clause" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "b48dd9fcdeaf5bd99d19670b90435ecef8b40b0f6e8b406a302f1e7f0d9d804e" sha256 cellar: :any_skip_relocation, big_sur: "b05113b680e109746163c3bf082ca7a2b2a00da1dcebb899416d7822e68d3a67" sha256 cellar: :any_skip_relocation, catalina: "dc76e1f95915f42a5289f7f368cdd970771f002992200e19160d7ae89651ebd2" sha256 cellar: :any_skip_relocation, mojave: "4f7ad7853a922751e34e48ac78656beea5fcb51b1c0c65f1d30010f2acbc85dc" sha256 cellar: :any_skip_relocation, x86_64_linux: "ab596bf783b9335ff4fc202fe97b9f3fa4c76a306b1740af8fa1436fd81343a9" end depends_on "rust" => :build uses_from_macos "openssl@1.1" on_linux do depends_on "pkg-config" => :build end def install system "cargo", "install", *std_cargo_args bash_output = Utils.safe_popen_read("#{bin}/volta", "completions", "bash") (bash_completion/"volta").write bash_output zsh_output = Utils.safe_popen_read("#{bin}/volta", "completions", "zsh") (zsh_completion/"_volta").write zsh_output fish_output = Utils.safe_popen_read("#{bin}/volta", "completions", "fish") (fish_completion/"volta.fish").write fish_output end test do system "#{bin}/volta", "install", "node@12.16.1" node = shell_output("#{bin}/volta which node").chomp assert_match "12.16.1", shell_output("#{node} --version") end end
module ApplicationHelper def admin? controller.class.parent == Admin end def partner? controller.class.parent == Partner end def get_namespace controller.class.parent.name.downcase end def breadcrumb(items) html = '<p id="breadcrumb">' items.each do |item| if item.is_a?(Hash) html += link_to( item[:label], item[:href]) else html += item end html += " &raquo " end html.html_safe end def user_is_admin? if session[:userinfo] && session[:userinfo]['extra'] && session[:userinfo]['extra']['raw_info'] return session[:userinfo]['extra']['raw_info']['role'] == 'admin' && session[:userinfo]['extra']['raw_info']['email_verified'] end return false end def user_is_coordinator? if session[:userinfo] && session[:userinfo]['extra'] && session[:userinfo]['extra']['raw_info'] if session[:userinfo]['extra']['raw_info']['email_verified'] return Organization.joins(:partners).where('partners.email = ? and partners.active = ? and partners.is_coordinator = ?', session[:userinfo]['info']['email'], true, true).count() > 0 end end return false end def is_coordinator?(organization) organization.partners.any?{|p| p.active && p.email == session[:userinfo]['info']['email'] && p.is_coordinator } end def live_campaigns? Campaign.where("deadline > ? and ready_for_donations = ?", 1.day.from_now.at_midnight, true).count > 0 end def get_scrivito_menu_items Obj.all.select{|obj|obj.permalink}.select{|obj| obj.show_in_menu == 'true' }.sort_by(&:get_menu_order) end end Using postgres in travis module ApplicationHelper def admin? controller.class.parent == Admin end def partner? controller.class.parent == Partner end def get_namespace controller.class.parent.name.downcase end def breadcrumb(items) html = '<p id="breadcrumb">' items.each do |item| if item.is_a?(Hash) html += link_to( item[:label], item[:href]) else html += item end html += " &raquo " end html.html_safe end def user_is_admin? if session[:userinfo] && session[:userinfo]['extra'] && session[:userinfo]['extra']['raw_info'] return session[:userinfo]['extra']['raw_info']['role'] == 'admin' && session[:userinfo]['extra']['raw_info']['email_verified'] end return false end def user_is_coordinator? if session[:userinfo] && session[:userinfo]['extra'] && session[:userinfo]['extra']['raw_info'] if session[:userinfo]['extra']['raw_info']['email_verified'] return Organization.joins(:partners).where('partners.email = ? and partners.active = ? and partners.is_coordinator = ?', session[:userinfo]['info']['email'], true, true).count() > 0 end end return false end def is_coordinator?(organization) organization.partners.any?{|p| p.active && p.email == session[:userinfo]['info']['email'] && p.is_coordinator } end def live_campaigns? Campaign.where("deadline > ? and ready_for_donations = ?", 1.day.from_now.at_midnight, true).count > 0 end def get_scrivito_menu_items Obj.all.select{|obj|obj.permalink}.select{|obj| obj.show_in_menu == 'true' }.sort_by(&:get_menu_order) unless Rails.env.test? end end
class Wdiff < Formula desc "Display word differences between text files" homepage "https://www.gnu.org/software/wdiff/" url "https://ftp.gnu.org/gnu/wdiff/wdiff-1.2.2.tar.gz" mirror "https://ftpmirror.gnu.org/wdiff/wdiff-1.2.2.tar.gz" sha256 "34ff698c870c87e6e47a838eeaaae729fa73349139fc8db12211d2a22b78af6b" revision 2 bottle do sha256 "89e0de3859b91c4dcdc4a9ac2ae4569f72cd472658e6d3dfa82e6acc919c68a1" => :mojave sha256 "579a8972310d39ac2e660f3114fc6d1536df7ad9f7659a9b00619cc7c50a2191" => :high_sierra sha256 "fcfe6296c4b9879895a4977274f56474faa84ca74c792866ea3149a2f02df553" => :sierra end depends_on "gettext" unless OS.mac? depends_on "texinfo" => :build depends_on "ncurses" end conflicts_with "montage", :because => "Both install an mdiff executable" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-experimental" system "make", "install" end test do a = testpath/"a.txt" a.write "The missing package manager for OS X" b = testpath/"b.txt" b.write "The package manager for OS X" output = shell_output("#{bin}/wdiff #{a} #{b}", 1) assert_equal "The [-missing-] package manager for OS X", output end end wdiff: update 1.2.2_2 bottle. Closes #13774. Signed-off-by: Michka Popoff <7b0496f66f66ee22a38826c310c38b415671b832@gmail.com> class Wdiff < Formula desc "Display word differences between text files" homepage "https://www.gnu.org/software/wdiff/" url "https://ftp.gnu.org/gnu/wdiff/wdiff-1.2.2.tar.gz" mirror "https://ftpmirror.gnu.org/wdiff/wdiff-1.2.2.tar.gz" sha256 "34ff698c870c87e6e47a838eeaaae729fa73349139fc8db12211d2a22b78af6b" revision 2 bottle do sha256 "89e0de3859b91c4dcdc4a9ac2ae4569f72cd472658e6d3dfa82e6acc919c68a1" => :mojave sha256 "579a8972310d39ac2e660f3114fc6d1536df7ad9f7659a9b00619cc7c50a2191" => :high_sierra sha256 "fcfe6296c4b9879895a4977274f56474faa84ca74c792866ea3149a2f02df553" => :sierra sha256 "915a7d9113b2cfd41dbe57344425599165b6891f4f5f0fdaf134009abf7aba73" => :x86_64_linux end depends_on "gettext" unless OS.mac? depends_on "texinfo" => :build depends_on "ncurses" end conflicts_with "montage", :because => "Both install an mdiff executable" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-experimental" system "make", "install" end test do a = testpath/"a.txt" a.write "The missing package manager for OS X" b = testpath/"b.txt" b.write "The package manager for OS X" output = shell_output("#{bin}/wdiff #{a} #{b}", 1) assert_equal "The [-missing-] package manager for OS X", output end end
module ApplicationHelper ## # ====Returns # * +String+ -> number of registrations / max allowed registrations def registered_text(event) return "Registered: #{event.registrations.count}/#{event.max_attendees}" if event.max_attendees "Registered: #{event.registrations.count}" end # Set resource_name for devise so that we can call the devise help links (views/devise/shared/_links) from anywhere (eg sign_up form in proposal#new) def resource_name :user end # Set devise_mapping for devise so that we can call the devise help links (views/devise/shared/_links) from anywhere (eg sign_up form in proposal#new) def devise_mapping @devise_mapping ||= Devise.mappings[:user] end def pluralize_without_count(count, noun, text = nil) if count != 0 count == 1 ? "#{noun}#{text}" : "#{noun.pluralize}#{text}" end end def event_status_icon(event) case event.state when 'new' 'fa-eye' when 'unconfirmed' 'fa-check text-muted' when 'confirmed' 'fa-check text-success' when 'rejected', 'withdrawn', 'canceled' 'fa-ban' end end def event_progress_color(progress) progress = progress.to_i if progress == 100 'progress-bar-success' elsif progress >= 85 'progress-bar-info' elsif progress >= 71 'progress-bar-warning' else 'progress-bar-danger' end end def format_role(role) role.parameterize.underscore end def target_progress_color(progress) progress = progress.to_i result = case when progress >= 90 then 'green' when progress < 90 && progress >= 80 then 'orange' else 'red' end result end def days_left_color(days_left) days_left = days_left.to_i if days_left > 30 result = 'green' elsif days_left < 30 && days_left > 10 result = 'orange' else result = 'red' end result end def bootstrap_class_for(flash_type) case flash_type when 'success' 'alert-success' when 'error' 'alert-danger' when 'alert' 'alert-warning' when 'notice' 'alert-info' else 'alert-warning' end end def label_for(event_state) result = '' case event_state when 'new' result = 'label label-primary' when 'withdrawn' result = 'label label-danger' when 'unconfirmed' result = 'label label-success' when 'confirmed' result = 'label label-success' when 'rejected' result = 'label label-warning' when 'canceled' result = 'label label-danger' end result end def icon_for_todo(bool) if bool return 'fa fa-check' else return 'fa fa-times' end end def class_for_todo(bool) if bool return 'todolist-ok' else return 'todolist-missing' end end def normalize_array_length(hashmap, length) hashmap.each do |_, value| if value.length < length value.fill(value[-1], value.length...length) end end end def active_nav_li(link) if current_page?(link) return 'active' else return '' end end def getdatetime(registration, field) if registration.send(field.to_sym).kind_of?(String) DateTime.parse(registration.send(field.to_sym)).strftime('%d %b %H:%M') if registration.send(field.to_sym) else registration.send(field.to_sym).strftime('%d %b %H:%M') if registration.send(field.to_sym) end end def getdate(var) if var.kind_of?(String) DateTime.parse(var).strftime('%a, %d %b') else var.strftime('%a, %d %b') end end def show_time(length) h = length / 60 min = length - h * 60 if h != 0 if min != 0 "#{h} h #{min} min" else "#{h} h" end else "#{min} min" end end def pre_registered(event) @conference.program.events.joins(:registrations).where('events.id = ?', event.id) end def add_association_link(association_name, form_builder, div_class, html_options = {}) link_to_add_association 'Add ' + association_name.to_s.singularize, form_builder, div_class, html_options.merge(class: 'assoc btn btn-success') end def remove_association_link(association_name, form_builder) link_to_remove_association('Remove ' + association_name.to_s.singularize, form_builder, class: 'assoc btn btn-danger') + tag(:hr) end def dynamic_association(association_name, title, form_builder, options = {}) render 'shared/dynamic_association', association_name: association_name, title: title, f: form_builder, hint: options[:hint] end # Same as redirect_to(:back) if there is a valid HTTP referer, otherwise redirect_to() def redirect_back_or_to(options = {}, response_status = {}) if request.env['HTTP_REFERER'] redirect_to :back else redirect_to options, response_status end end def event_types(conference) all = conference.program.event_types.map { |et | et.title.pluralize } first = all[0...-1] last = all[-1] ets = '' if all.length > 1 ets << first.join(', ') ets << " and #{last}" else ets = all.join end return ets end def tracks(conference) all = conference.program.tracks.map {|t| t.name} first = all[0...-1] last = all[-1] ts = '' if all.length > 1 ts << first.join(', ') ts << " and #{last}" else ts = all.join end return ts end def difficulty_levels(conference) all = conference.program.difficulty_levels.map {|t| t.title} first = all[0...-1] last = all[-1] ts = '' if all.length > 1 ts << first.join(', ') ts << " and #{last}" else ts = all.join end return ts end # rubocop:disable Lint/EndAlignment def word_pluralize(count, singular, plural = nil) word = if (count == 1 || count =~ /^1(\.0+)?$/) singular else plural || singular.pluralize end "#{word}" end def markdown(text) options = { autolink: true, space_after_headers: true, no_intra_emphasis: true } markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, options) markdown.render(text).html_safe end def markdown_hint(text='') markdown("#{text} Please look at #{link_to '**Markdown Syntax**', 'https://daringfireball.net/projects/markdown/syntax', target: '_blank'} to format your text") end def omniauth_configured providers = [] Devise.omniauth_providers.each do |provider| provider_key = "#{provider}_key" provider_secret = "#{provider}_secret" unless Rails.application.secrets.send(provider_key).blank? || Rails.application.secrets.send(provider_secret).blank? providers << provider end providers << provider if !ENV["OSEM_#{provider.upcase}_KEY"].blank? && !ENV["OSEM_#{provider.upcase}_SECRET"].blank? end return providers.uniq end # Receives a hash, generated from User model, function get_roles # Outputs the roles of a user, including the conferences for which the user has the roles # Eg. organizer(oSC13, oSC14), cfp(oSC12, oSC13) def show_roles(roles) roles.map{ |x| x[0].titleize + ' (' + x[1].join(', ') + ')' }.join ', ' end def can_manage_volunteers(conference) if (current_user.has_role? :organizer, conference) || (current_user.has_role? :volunteers_coordinator, conference) true else false end end def sign_in_path if ENV['OSEM_ICHAIN_ENABLED'] == 'true' new_user_ichain_session_path else new_user_session_path end end def sign_up_path if ENV['OSEM_ICHAIN_ENABLED'] == 'true' new_user_ichain_registration_path else new_user_registration_path end end def unread_notifications(user) Comment.accessible_by(current_ability).find_since_last_login(user) end end Remove unused helper methods module ApplicationHelper ## # ====Returns # * +String+ -> number of registrations / max allowed registrations def registered_text(event) return "Registered: #{event.registrations.count}/#{event.max_attendees}" if event.max_attendees "Registered: #{event.registrations.count}" end # Set resource_name for devise so that we can call the devise help links (views/devise/shared/_links) from anywhere (eg sign_up form in proposal#new) def resource_name :user end # Set devise_mapping for devise so that we can call the devise help links (views/devise/shared/_links) from anywhere (eg sign_up form in proposal#new) def devise_mapping @devise_mapping ||= Devise.mappings[:user] end def event_status_icon(event) case event.state when 'new' 'fa-eye' when 'unconfirmed' 'fa-check text-muted' when 'confirmed' 'fa-check text-success' when 'rejected', 'withdrawn', 'canceled' 'fa-ban' end end def event_progress_color(progress) progress = progress.to_i if progress == 100 'progress-bar-success' elsif progress >= 85 'progress-bar-info' elsif progress >= 71 'progress-bar-warning' else 'progress-bar-danger' end end def target_progress_color(progress) progress = progress.to_i result = case when progress >= 90 then 'green' when progress < 90 && progress >= 80 then 'orange' else 'red' end result end def days_left_color(days_left) days_left = days_left.to_i if days_left > 30 result = 'green' elsif days_left < 30 && days_left > 10 result = 'orange' else result = 'red' end result end def bootstrap_class_for(flash_type) case flash_type when 'success' 'alert-success' when 'error' 'alert-danger' when 'alert' 'alert-warning' when 'notice' 'alert-info' else 'alert-warning' end end def label_for(event_state) result = '' case event_state when 'new' result = 'label label-primary' when 'withdrawn' result = 'label label-danger' when 'unconfirmed' result = 'label label-success' when 'confirmed' result = 'label label-success' when 'rejected' result = 'label label-warning' when 'canceled' result = 'label label-danger' end result end def icon_for_todo(bool) if bool return 'fa fa-check' else return 'fa fa-times' end end def class_for_todo(bool) if bool return 'todolist-ok' else return 'todolist-missing' end end def normalize_array_length(hashmap, length) hashmap.each do |_, value| if value.length < length value.fill(value[-1], value.length...length) end end end def active_nav_li(link) if current_page?(link) return 'active' else return '' end end def show_time(length) h = length / 60 min = length - h * 60 if h != 0 if min != 0 "#{h} h #{min} min" else "#{h} h" end else "#{min} min" end end def add_association_link(association_name, form_builder, div_class, html_options = {}) link_to_add_association 'Add ' + association_name.to_s.singularize, form_builder, div_class, html_options.merge(class: 'assoc btn btn-success') end def remove_association_link(association_name, form_builder) link_to_remove_association('Remove ' + association_name.to_s.singularize, form_builder, class: 'assoc btn btn-danger') + tag(:hr) end def dynamic_association(association_name, title, form_builder, options = {}) render 'shared/dynamic_association', association_name: association_name, title: title, f: form_builder, hint: options[:hint] end # Same as redirect_to(:back) if there is a valid HTTP referer, otherwise redirect_to() def redirect_back_or_to(options = {}, response_status = {}) if request.env['HTTP_REFERER'] redirect_to :back else redirect_to options, response_status end end def event_types(conference) all = conference.program.event_types.map { |et | et.title.pluralize } first = all[0...-1] last = all[-1] ets = '' if all.length > 1 ets << first.join(', ') ets << " and #{last}" else ets = all.join end return ets end def tracks(conference) all = conference.program.tracks.map {|t| t.name} first = all[0...-1] last = all[-1] ts = '' if all.length > 1 ts << first.join(', ') ts << " and #{last}" else ts = all.join end return ts end def difficulty_levels(conference) all = conference.program.difficulty_levels.map {|t| t.title} first = all[0...-1] last = all[-1] ts = '' if all.length > 1 ts << first.join(', ') ts << " and #{last}" else ts = all.join end return ts end # rubocop:disable Lint/EndAlignment def word_pluralize(count, singular, plural = nil) word = if (count == 1 || count =~ /^1(\.0+)?$/) singular else plural || singular.pluralize end "#{word}" end def markdown(text) options = { autolink: true, space_after_headers: true, no_intra_emphasis: true } markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, options) markdown.render(text).html_safe end def markdown_hint(text='') markdown("#{text} Please look at #{link_to '**Markdown Syntax**', 'https://daringfireball.net/projects/markdown/syntax', target: '_blank'} to format your text") end def omniauth_configured providers = [] Devise.omniauth_providers.each do |provider| provider_key = "#{provider}_key" provider_secret = "#{provider}_secret" unless Rails.application.secrets.send(provider_key).blank? || Rails.application.secrets.send(provider_secret).blank? providers << provider end providers << provider if !ENV["OSEM_#{provider.upcase}_KEY"].blank? && !ENV["OSEM_#{provider.upcase}_SECRET"].blank? end return providers.uniq end # Receives a hash, generated from User model, function get_roles # Outputs the roles of a user, including the conferences for which the user has the roles # Eg. organizer(oSC13, oSC14), cfp(oSC12, oSC13) def show_roles(roles) roles.map{ |x| x[0].titleize + ' (' + x[1].join(', ') + ')' }.join ', ' end def can_manage_volunteers(conference) if (current_user.has_role? :organizer, conference) || (current_user.has_role? :volunteers_coordinator, conference) true else false end end def sign_in_path if ENV['OSEM_ICHAIN_ENABLED'] == 'true' new_user_ichain_session_path else new_user_session_path end end def unread_notifications(user) Comment.accessible_by(current_ability).find_since_last_login(user) end end
class Whois < Formula desc "Lookup tool for domain names and other internet resources" homepage "https://packages.debian.org/sid/whois" url "https://mirrors.ocf.berkeley.edu/debian/pool/main/w/whois/whois_5.2.19.tar.xz" mirror "https://mirrorservice.org/sites/ftp.debian.org/debian/pool/main/w/whois/whois_5.2.19.tar.xz" sha256 "6c39a274fd73b87c0ce1e34dfbd1842a0b2ca7a00c97d4202d639ec010e1262c" head "https://github.com/rfc1036/whois.git" bottle do cellar :any_skip_relocation sha256 "860edeb178e893ecda346e0b6fe1d0b56a736b68c78f84ef645be38a97d410c2" => :high_sierra sha256 "7713cd5ecd196c30ef3d08ae99eba161a438b4caf8856229dbb836a4b26dc33e" => :sierra sha256 "77fa515bde70cca3c6d5c891f1dd740fed33e59d177d0d04ea37548bb32b97cf" => :el_capitan end option "with-libidn2", "Compile with IDN support" depends_on "pkg-config" => :build if build.with? "libidn2" depends_on "libidn2" => :optional def install ENV.append "LDFLAGS", "-L/usr/lib -liconv" system "make", "whois", *("HAVE_ICONV=1" if OS.mac?) bin.install "whois" man1.install "whois.1" man5.install "whois.conf.5" end def caveats; <<~EOS Debian whois has been installed as `whois` and may shadow the system binary of the same name. EOS end test do system "#{bin}/whois", "brew.sh" end end whois: Fix build for Linuxbrew Closes Linuxbrew/homebrew-core#5197. Signed-off-by: Michka Popoff <7b0496f66f66ee22a38826c310c38b415671b832@gmail.com> class Whois < Formula desc "Lookup tool for domain names and other internet resources" homepage "https://packages.debian.org/sid/whois" url "https://mirrors.ocf.berkeley.edu/debian/pool/main/w/whois/whois_5.2.19.tar.xz" mirror "https://mirrorservice.org/sites/ftp.debian.org/debian/pool/main/w/whois/whois_5.2.19.tar.xz" sha256 "6c39a274fd73b87c0ce1e34dfbd1842a0b2ca7a00c97d4202d639ec010e1262c" head "https://github.com/rfc1036/whois.git" bottle do cellar :any_skip_relocation sha256 "860edeb178e893ecda346e0b6fe1d0b56a736b68c78f84ef645be38a97d410c2" => :high_sierra sha256 "7713cd5ecd196c30ef3d08ae99eba161a438b4caf8856229dbb836a4b26dc33e" => :sierra sha256 "77fa515bde70cca3c6d5c891f1dd740fed33e59d177d0d04ea37548bb32b97cf" => :el_capitan end option "with-libidn2", "Compile with IDN support" depends_on "pkg-config" => :build if build.with?("libidn2") || !OS.mac? depends_on "libidn2" => :optional def install ENV.append "LDFLAGS", "-L/usr/lib -liconv" if OS.mac? system "make", "whois", *(OS.mac? ? "HAVE_ICONV=1" : "HAVE_ICONV=0") bin.install "whois" man1.install "whois.1" man5.install "whois.conf.5" end def caveats; <<~EOS Debian whois has been installed as `whois` and may shadow the system binary of the same name. EOS end test do system "#{bin}/whois", "brew.sh" end end
module ApplicationHelper # nicely_joined_with_commata(['1', '2', '3', '4']) # = '1, 2, 3 und 4' # def nicely_joined_with_commata(array_of_things) if array_of_things.count == 1 array_of_things.first.to_s else if array_of_things.count > 1 output = array_of_things[0, array_of_things.count - 1].map{|item| item.to_s}.join(', ') if I18n.locale == :de output += ' und ' else output += ' and ' end output += array_of_things.last.to_s end end end end sortable helper method added module ApplicationHelper # nicely_joined_with_commata(['1', '2', '3', '4']) # = '1, 2, 3 und 4' # def nicely_joined_with_commata(array_of_things) if array_of_things.count == 1 array_of_things.first.to_s else if array_of_things.count > 1 output = array_of_things[0, array_of_things.count - 1].map{|item| item.to_s}.join(', ') if I18n.locale == :de output += ' und ' else output += ' and ' end output += array_of_things.last.to_s end end end def sortable(column, title) link_class = (column.to_s == sort_column.to_s) ? "sort_descending #{sort_descending}" : nil link_to title, {:sort => column, :desc => !!(!sort_descending && column), :type => @type}, {:class => link_class} end end
class X3270 < Formula desc "IBM 3270 terminal emulator for the X Window System and Windows" homepage "http://x3270.bgp.nu/" url "http://x3270.bgp.nu/download/04.00/suite3270-4.0ga14-src.tgz" sha256 "9796f2b47ed222776d4fe2756a0db3617f84dbbf02d0a9374c36a13b1b416375" license "BSD-3-Clause" livecheck do url "http://x3270.bgp.nu/download.html" regex(/href=.*?suite3270[._-]v?(\d+(?:\.\d+)+(?:ga\d+)?)(?:-src)?\.t/i) end bottle do sha256 arm64_big_sur: "bf8dcba7b17bb1ebc1fdf8987badc037236e2f83c20a5621c914295355e0f545" sha256 big_sur: "0fb9e40a2f6d56e3f166d7cee9ef8eae4166e3e038c19b114ff840e33a3aad3e" sha256 catalina: "1e8f59bedd3fbda46cab9db08944ab21b3549f9ca9002423590015da3cf75ce6" sha256 mojave: "50108883c53cb6ef78dd63372952451db9d182d4409e340a31146397fbacaf93" end depends_on "readline" def install args = %W[ --prefix=#{prefix} --enable-c3270 --enable-pr3287 --enable-s3270 --enable-tcl3270 ] system "./configure", *args system "make", "install" system "make", "install.man" end test do system bin/"c3270", "--version" end end x3270: fix for Linux (#72953) class X3270 < Formula desc "IBM 3270 terminal emulator for the X Window System and Windows" homepage "http://x3270.bgp.nu/" url "http://x3270.bgp.nu/download/04.00/suite3270-4.0ga14-src.tgz" sha256 "9796f2b47ed222776d4fe2756a0db3617f84dbbf02d0a9374c36a13b1b416375" license "BSD-3-Clause" livecheck do url "http://x3270.bgp.nu/download.html" regex(/href=.*?suite3270[._-]v?(\d+(?:\.\d+)+(?:ga\d+)?)(?:-src)?\.t/i) end bottle do sha256 arm64_big_sur: "bf8dcba7b17bb1ebc1fdf8987badc037236e2f83c20a5621c914295355e0f545" sha256 big_sur: "0fb9e40a2f6d56e3f166d7cee9ef8eae4166e3e038c19b114ff840e33a3aad3e" sha256 catalina: "1e8f59bedd3fbda46cab9db08944ab21b3549f9ca9002423590015da3cf75ce6" sha256 mojave: "50108883c53cb6ef78dd63372952451db9d182d4409e340a31146397fbacaf93" end depends_on "readline" uses_from_macos "tcl-tk" def install args = %W[ --prefix=#{prefix} --enable-c3270 --enable-pr3287 --enable-s3270 --enable-tcl3270 ] system "./configure", *args system "make", "install" system "make", "install.man" end test do system bin/"c3270", "--version" end end
module ApplicationHelper def requirejs_base_url folder_name(requirejs_main_path) end def requirejs_main_path if Rails.application.assets.find_asset("production.js").present? asset_path("production.js") else asset_path("main.js") end end def requirejs_module_path(asset) trim_leading_slash(trim_extension(remove_requirejs_base_url(asset_path(asset)))) end def service_name if Limelight::Application.config.available_services.key? params[:slug] params[:slug] else nil end end private def folder_name(path) path.gsub(%r{/[^./]+.js}, '') end def trim_leading_slash(remove_requirejs_base_url) remove_requirejs_base_url.gsub(%r{^/}, '') end def trim_extension(path) path.gsub(%r{.[^./]+$}, '') end def remove_requirejs_base_url(asset_path) asset_path.gsub(requirejs_base_url, '') end def main_navigation_link_to(name, path, html_options = {}, &block) classes = (html_options[:class] || "").split if current_main_navigation_path(params) == path classes << "active" end link_to(name, path, html_options.merge(class: classes.join(" ")), &block) end def current_main_navigation_path(parameters) # Currently, everything in Limelight lives under the "Services" main nav # item. As we add datainsight-frontend in, this method will need to get # smarter. services_path end end Don't underline Services when on the homepage module ApplicationHelper def requirejs_base_url folder_name(requirejs_main_path) end def requirejs_main_path if Rails.application.assets.find_asset("production.js").present? asset_path("production.js") else asset_path("main.js") end end def requirejs_module_path(asset) trim_leading_slash(trim_extension(remove_requirejs_base_url(asset_path(asset)))) end def service_name if Limelight::Application.config.available_services.key? params[:slug] params[:slug] else nil end end private def folder_name(path) path.gsub(%r{/[^./]+.js}, '') end def trim_leading_slash(remove_requirejs_base_url) remove_requirejs_base_url.gsub(%r{^/}, '') end def trim_extension(path) path.gsub(%r{.[^./]+$}, '') end def remove_requirejs_base_url(asset_path) asset_path.gsub(requirejs_base_url, '') end def main_navigation_link_to(name, path, html_options = {}, &block) classes = (html_options[:class] || "").split if current_main_navigation_path(params) == path classes << "active" end link_to(name, path, html_options.merge(class: classes.join(" ")), &block) end def current_main_navigation_path(parameters) # Decide which main navigation item to underline if parameters['controller'] == 'root' root_path else services_path end end end
xclip 0.12 Closes Homebrew/homebrew#11597. Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com> require 'formula' class Xclip < Formula homepage 'http://xclip.sourceforge.net/' url 'http://downloads.sourceforge.net/project/xclip/xclip/0.12/xclip-0.12.tar.gz' md5 'f7e19d3e976fecdc1ea36cd39e39900d' def install ENV.x11 system "./configure", "--prefix=#{prefix}" system "make install" end def test system "#{bin}/xclip -version" end end
module ApplicationHelper end adds helper methods needs fix for syntax module ApplicationHelper helpers do def current_user @user ||= User.find_by_id(session[:user_id]) if session[:user_id] end def login(user) session[:user_id] = user.id end def logout! session[:user_id] = nil end def find_user @user ||= User.find_by(username: params[:username]) end def bounce redirect '/login' unless current_user end end end
class Xsane < Formula desc "Graphical scanning frontend" homepage "http://www.xsane.org" url "https://ftp.osuosl.org/pub/blfs/conglomeration/xsane/xsane-0.999.tar.gz" mirror "https://fossies.org/linux/misc/xsane-0.999.tar.gz" sha256 "5782d23e67dc961c81eef13a87b17eb0144cae3d1ffc5cf7e0322da751482b4b" revision 4 bottle do sha256 "028fa4b1496e6e0a0d6f0443bff7157b5bb70e56b1a9fd1e1b83072aa076f6a1" => :mojave sha256 "197b36716d2df9e81581650549571ce379ce74290fb45c703e6173c190024dad" => :high_sierra sha256 "cb6cd9fabadf727b9414d4a252fa648f579bfe168eb44dd25fb2cb18a84395ed" => :sierra sha256 "4346e2b40f260128b2ac562cff15be61c96bcc31b04457f44e41d28aeb7d6be2" => :el_capitan end depends_on "pkg-config" => :build depends_on "gtk+" depends_on "sane-backends" # Needed to compile against libpng 1.5, Project appears to be dead. patch :p0 do url "https://raw.githubusercontent.com/Homebrew/formula-patches/e1a592d/xsane/patch-src__xsane-save.c-libpng15-compat.diff" sha256 "404b963b30081bfc64020179be7b1a85668f6f16e608c741369e39114af46e27" end def install system "./configure", "--prefix=#{prefix}" system "make", "install" end test do system "#{bin}/xsane", "--version" end end xsane: update 0.999_4 bottle. class Xsane < Formula desc "Graphical scanning frontend" homepage "http://www.xsane.org" url "https://ftp.osuosl.org/pub/blfs/conglomeration/xsane/xsane-0.999.tar.gz" mirror "https://fossies.org/linux/misc/xsane-0.999.tar.gz" sha256 "5782d23e67dc961c81eef13a87b17eb0144cae3d1ffc5cf7e0322da751482b4b" revision 4 bottle do sha256 "93064b6ec70657f6815a0aba5d52c8b7e54e9ef6f223c608351b790887c62b92" => :mojave sha256 "4242d28d56f5ed634f7f8632d41e441e1cbeaf60a362628796a436ba2f8eac11" => :high_sierra sha256 "f247067d49d44f8c0662cd64c99524f13c4b3a18ef7e49a19dd377bb449c859d" => :sierra end depends_on "pkg-config" => :build depends_on "gtk+" depends_on "sane-backends" # Needed to compile against libpng 1.5, Project appears to be dead. patch :p0 do url "https://raw.githubusercontent.com/Homebrew/formula-patches/e1a592d/xsane/patch-src__xsane-save.c-libpng15-compat.diff" sha256 "404b963b30081bfc64020179be7b1a85668f6f16e608c741369e39114af46e27" end def install system "./configure", "--prefix=#{prefix}" system "make", "install" end test do system "#{bin}/xsane", "--version" end end
class Xspin < Formula desc "Software verification tool (developed at Bell Labs)" homepage "https://spinroot.com/spin/Src/index.html" url "https://spinroot.com/spin/Src/xspin525.tcl" version "5.2.5" sha256 "e23d8d562e39db6fe73570e52ee895cd806d15c3e52e638299cbc1eb61289eb6" bottle do cellar :any_skip_relocation sha256 "2128720e4a7cda7778a5f6e0f16ecadb1b37eb125d37db2958ba1c84d97c379c" => :catalina sha256 "e268eebef598b8df39bcd1bb2daaf5ea7b13975532f4dcba6426659fecf47482" => :mojave sha256 "f35ea74745fac858274f01c76d879c3713a9ca35e8282ced5c080276f2934580" => :high_sierra sha256 "493d8bfac9052ece7d96eaed9b70792d7fe41b7566de2a523dd86664e3a3debb" => :sierra sha256 "896d3acc7e60648410ff86b1f8e744059bb71015900360fc18b3a75537e2c13e" => :el_capitan sha256 "2ff10f844a1c09cc99bf8e630bde4e191a450697ab6ea286c85bfb66670db405" => :yosemite sha256 "a1b19b1227fc19b6ea00cfea5a49955a82d180521e8df29d68842b465e5b4b89" => :mavericks end depends_on "spin" patch :DATA def install inreplace "xspin525.tcl", "CELLAR", prefix bin.install "xspin525.tcl" => "xspin" end end # manual patching is required by the spin install process __END__ diff --git a/xspin525.tcl b/xspin525.tcl old mode 100644 new mode 100755 index 73fc6bf..444b0ad --- a/xspin525.tcl +++ b/xspin525.tcl @@ -1,8 +1,9 @@ -#!/bin/sh +#!/usr/bin/wish -f # the next line restarts using wish \ -exec wish c:/cygwin/bin/xspin -- $* +exec wish CELLAR/bin/xspin -- $* + + cd ;# enable to cd to home directory by default -# cd ;# enable to cd to home directory by default # on PCs: # adjust the first argument to wish above with the name and xspin: delete
module Forem module PostsHelper def avatar(user, options = {}) if (email = user.try(:email)).present? avatar_url(email, options).html_safe end end def avatar_url(email, options = {}) options = {:size => 60} require 'digest/md5' size = ("?s=#{options[:size]}" if options[:size]) "http://gravatar.com/avatar/#{Digest::MD5.hexdigest(email.to_s.strip.downcase)}#{size}.jpg" end end end PostsHelper#avatar now actually returns an image tag module Forem module PostsHelper def avatar(user, options = {}) if (email = user.try(:email)).present? image_tag(avatar_url(email, options), :alt => "Gravatar") end end def avatar_url(email, options = {}) options = {:size => 60} require 'digest/md5' size = ("?s=#{options[:size]}" if options[:size]) "http://gravatar.com/avatar/#{Digest::MD5.hexdigest(email.to_s.strip.downcase)}#{size}.jpg" end end end
class Ydiff < Formula desc "View colored diff with side by side and auto pager support" homepage "https://github.com/ymattw/ydiff" url "https://github.com/ymattw/ydiff/archive/1.2.tar.gz" sha256 "0a0acf326b1471b257f51d63136f3534a41c0f9a405a1bbbd410457cebfdd6a1" license "BSD-3-Clause" revision 1 bottle :unneeded depends_on "python@3.9" def install xy = Language::Python.major_minor_version "python3" ENV["PYTHONPATH"] = libexec/"lib/python#{xy}/site-packages" system "python3", *Language::Python.setup_install_args(libexec) bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec/"bin", PYTHONPATH: ENV["PYTHONPATH"]) end test do diff_fixture = test_fixtures("test.diff").read assert_equal diff_fixture, pipe_output("#{bin}/ydiff -cnever", diff_fixture) end end ydiff: remove bottle :unneeded. https://github.com/Homebrew/homebrew-core/issues/75943 class Ydiff < Formula desc "View colored diff with side by side and auto pager support" homepage "https://github.com/ymattw/ydiff" url "https://github.com/ymattw/ydiff/archive/1.2.tar.gz" sha256 "0a0acf326b1471b257f51d63136f3534a41c0f9a405a1bbbd410457cebfdd6a1" license "BSD-3-Clause" revision 1 depends_on "python@3.9" def install xy = Language::Python.major_minor_version "python3" ENV["PYTHONPATH"] = libexec/"lib/python#{xy}/site-packages" system "python3", *Language::Python.setup_install_args(libexec) bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec/"bin", PYTHONPATH: ENV["PYTHONPATH"]) end test do diff_fixture = test_fixtures("test.diff").read assert_equal diff_fixture, pipe_output("#{bin}/ydiff -cnever", diff_fixture) end end
module PageLayoutHelper def page_title(*titles) @page_title ||= [] @page_title.push(*titles.compact) if titles.any? @page_title.join(" | ") end def header_title(title = nil, title_url = nil) if title @header_title = title @header_title_url = title_url else @header_title_url ? link_to(@header_title, @header_title_url) : @header_title end end def sidebar(name = nil) if name @sidebar = name else @sidebar end end def fluid_layout(enabled = false) if @fluid_layout.nil? @fluid_layout = (current_user && current_user.layout == "fluid") || enabled else @fluid_layout end end def blank_container(enabled = false) if @blank_container.nil? @blank_container = enabled else @blank_container end end def container_class css_class = "container-fluid" unless fluid_layout css_class += " container-limited" end if blank_container css_class += " container-blank" end css_class end end Separate page title segments by middot rather than pipe module PageLayoutHelper def page_title(*titles) @page_title ||= [] @page_title.push(*titles.compact) if titles.any? # Segments are seperated by middot @page_title.join(" \u00b7 ") end def header_title(title = nil, title_url = nil) if title @header_title = title @header_title_url = title_url else @header_title_url ? link_to(@header_title, @header_title_url) : @header_title end end def sidebar(name = nil) if name @sidebar = name else @sidebar end end def fluid_layout(enabled = false) if @fluid_layout.nil? @fluid_layout = (current_user && current_user.layout == "fluid") || enabled else @fluid_layout end end def blank_container(enabled = false) if @blank_container.nil? @blank_container = enabled else @blank_container end end def container_class css_class = "container-fluid" unless fluid_layout css_class += " container-limited" end if blank_container css_class += " container-blank" end css_class end end
class Ykman < Formula include Language::Python::Virtualenv desc "Tool for managing your YubiKey configuration" homepage "https://developers.yubico.com/yubikey-manager/" url "https://developers.yubico.com/yubikey-manager/Releases/yubikey-manager-3.1.0.tar.gz" sha256 "0137acd30cffa60421dde8277b3bb0c5d5e2179d36df0d190de6faf7eec76359" revision 2 head "https://github.com/Yubico/yubikey-manager.git" bottle do cellar :any sha256 "bbcdddf68a76536a6579fc903a32595bdc51ac369a6bdf9562d768bb5aa5f354" => :mojave sha256 "e415bd795d6b7f43c673ea14f5c61beb6309ad18e0d9de30b84fd03f65afaa2a" => :high_sierra sha256 "7e943215909e0c4f0d98aba219be77ce4c1e921fd42b12781a3ddeaefba16e07" => :sierra end depends_on "swig" => :build depends_on "libusb" depends_on "openssl@1.1" depends_on "python" depends_on "ykpers" resource "asn1crypto" do url "https://files.pythonhosted.org/packages/c1/a9/86bfedaf41ca590747b4c9075bc470d0b2ec44fb5db5d378bc61447b3b6b/asn1crypto-1.2.0.tar.gz" sha256 "87620880a477123e01177a1f73d0f327210b43a3cdbd714efcd2fa49a8d7b384" end resource "cffi" do url "https://files.pythonhosted.org/packages/93/1a/ab8c62b5838722f29f3daffcc8d4bd61844aa9b5f437341cc890ceee483b/cffi-1.12.3.tar.gz" sha256 "041c81822e9f84b1d9c401182e174996f0bae9991f33725d059b771744290774" end resource "click" do url "https://files.pythonhosted.org/packages/f8/5c/f60e9d8a1e77005f664b76ff8aeaee5bc05d0a91798afd7f53fc998dbc47/Click-7.0.tar.gz" sha256 "5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" end resource "cryptography" do url "https://files.pythonhosted.org/packages/c2/95/f43d02315f4ec074219c6e3124a87eba1d2d12196c2767fadfdc07a83884/cryptography-2.7.tar.gz" sha256 "e6347742ac8f35ded4a46ff835c60e68c22a536a8ae5c4422966d06946b6d4c6" end resource "fido2" do url "https://files.pythonhosted.org/packages/53/35/cc293d0157ff7a9836ba36e45bd99a4a98883fd3f2dc451e463510764f6c/fido2-0.7.0.tar.gz" sha256 "47b02852780849bb4bb698b9727d61970ee77a83eb25715fe7c6235ebd648d87" end resource "idna" do url "https://files.pythonhosted.org/packages/ad/13/eb56951b6f7950cadb579ca166e448ba77f9d24efc03edd7e55fa57d04b7/idna-2.8.tar.gz" sha256 "c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407" end resource "ipaddress" do url "https://files.pythonhosted.org/packages/97/8d/77b8cedcfbf93676148518036c6b1ce7f8e14bf07e95d7fd4ddcb8cc052f/ipaddress-1.0.22.tar.gz" sha256 "b146c751ea45cad6188dd6cf2d9b757f6f4f8d6ffb96a023e6f2e26eea02a72c" end resource "pycparser" do url "https://files.pythonhosted.org/packages/68/9e/49196946aee219aead1290e00d1e7fdeab8567783e83e1b9ab5585e6206a/pycparser-2.19.tar.gz" sha256 "a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3" end resource "pyOpenSSL" do url "https://files.pythonhosted.org/packages/40/d0/8efd61531f338a89b4efa48fcf1972d870d2b67a7aea9dcf70783c8464dc/pyOpenSSL-19.0.0.tar.gz" sha256 "aeca66338f6de19d1aa46ed634c3b9ae519a64b458f8468aec688e7e3c20f200" end resource "pyscard" do url "https://files.pythonhosted.org/packages/ed/dd/c575bb75122c250cbed3f70440cb8e25582bf991855bb4eb27371fb8d962/pyscard-1.9.9.tar.gz" sha256 "e6bde541990183858740793806b1c7f4e798670519ae4c96145f35d5d7944c20" end resource "pyusb" do url "https://files.pythonhosted.org/packages/5f/34/2095e821c01225377dda4ebdbd53d8316d6abb243c9bee43d3888fa91dd6/pyusb-1.0.2.tar.gz" sha256 "4e9b72cc4a4205ca64fbf1f3fff39a335512166c151ad103e55c8223ac147362" end resource "six" do url "https://files.pythonhosted.org/packages/dd/bf/4138e7bfb757de47d1f4b6994648ec67a51efe58fa907c1e11e350cddfca/six-1.12.0.tar.gz" sha256 "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" end def install virtualenv_install_with_resources end test do assert_match version.to_s, shell_output("#{bin}/ykman --version") end end ykman: update 3.1.0_2 bottle. class Ykman < Formula include Language::Python::Virtualenv desc "Tool for managing your YubiKey configuration" homepage "https://developers.yubico.com/yubikey-manager/" url "https://developers.yubico.com/yubikey-manager/Releases/yubikey-manager-3.1.0.tar.gz" sha256 "0137acd30cffa60421dde8277b3bb0c5d5e2179d36df0d190de6faf7eec76359" revision 2 head "https://github.com/Yubico/yubikey-manager.git" bottle do cellar :any sha256 "6167b5271e16ec0578c19e057d3640ef915078ea49283c33527e5eb1f8fb761c" => :catalina sha256 "c61168ce749d7c6642028a64d5be0e6a27de9f9e5ad7cc7e7d63e3e7f9f022de" => :mojave sha256 "b290e4341fd449971cb3b9d6459b28120b603cc96a2e2895473d6d3d5f12317b" => :high_sierra end depends_on "swig" => :build depends_on "libusb" depends_on "openssl@1.1" depends_on "python" depends_on "ykpers" resource "asn1crypto" do url "https://files.pythonhosted.org/packages/c1/a9/86bfedaf41ca590747b4c9075bc470d0b2ec44fb5db5d378bc61447b3b6b/asn1crypto-1.2.0.tar.gz" sha256 "87620880a477123e01177a1f73d0f327210b43a3cdbd714efcd2fa49a8d7b384" end resource "cffi" do url "https://files.pythonhosted.org/packages/93/1a/ab8c62b5838722f29f3daffcc8d4bd61844aa9b5f437341cc890ceee483b/cffi-1.12.3.tar.gz" sha256 "041c81822e9f84b1d9c401182e174996f0bae9991f33725d059b771744290774" end resource "click" do url "https://files.pythonhosted.org/packages/f8/5c/f60e9d8a1e77005f664b76ff8aeaee5bc05d0a91798afd7f53fc998dbc47/Click-7.0.tar.gz" sha256 "5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" end resource "cryptography" do url "https://files.pythonhosted.org/packages/c2/95/f43d02315f4ec074219c6e3124a87eba1d2d12196c2767fadfdc07a83884/cryptography-2.7.tar.gz" sha256 "e6347742ac8f35ded4a46ff835c60e68c22a536a8ae5c4422966d06946b6d4c6" end resource "fido2" do url "https://files.pythonhosted.org/packages/53/35/cc293d0157ff7a9836ba36e45bd99a4a98883fd3f2dc451e463510764f6c/fido2-0.7.0.tar.gz" sha256 "47b02852780849bb4bb698b9727d61970ee77a83eb25715fe7c6235ebd648d87" end resource "idna" do url "https://files.pythonhosted.org/packages/ad/13/eb56951b6f7950cadb579ca166e448ba77f9d24efc03edd7e55fa57d04b7/idna-2.8.tar.gz" sha256 "c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407" end resource "ipaddress" do url "https://files.pythonhosted.org/packages/97/8d/77b8cedcfbf93676148518036c6b1ce7f8e14bf07e95d7fd4ddcb8cc052f/ipaddress-1.0.22.tar.gz" sha256 "b146c751ea45cad6188dd6cf2d9b757f6f4f8d6ffb96a023e6f2e26eea02a72c" end resource "pycparser" do url "https://files.pythonhosted.org/packages/68/9e/49196946aee219aead1290e00d1e7fdeab8567783e83e1b9ab5585e6206a/pycparser-2.19.tar.gz" sha256 "a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3" end resource "pyOpenSSL" do url "https://files.pythonhosted.org/packages/40/d0/8efd61531f338a89b4efa48fcf1972d870d2b67a7aea9dcf70783c8464dc/pyOpenSSL-19.0.0.tar.gz" sha256 "aeca66338f6de19d1aa46ed634c3b9ae519a64b458f8468aec688e7e3c20f200" end resource "pyscard" do url "https://files.pythonhosted.org/packages/ed/dd/c575bb75122c250cbed3f70440cb8e25582bf991855bb4eb27371fb8d962/pyscard-1.9.9.tar.gz" sha256 "e6bde541990183858740793806b1c7f4e798670519ae4c96145f35d5d7944c20" end resource "pyusb" do url "https://files.pythonhosted.org/packages/5f/34/2095e821c01225377dda4ebdbd53d8316d6abb243c9bee43d3888fa91dd6/pyusb-1.0.2.tar.gz" sha256 "4e9b72cc4a4205ca64fbf1f3fff39a335512166c151ad103e55c8223ac147362" end resource "six" do url "https://files.pythonhosted.org/packages/dd/bf/4138e7bfb757de47d1f4b6994648ec67a51efe58fa907c1e11e350cddfca/six-1.12.0.tar.gz" sha256 "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" end def install virtualenv_install_with_resources end test do assert_match version.to_s, shell_output("#{bin}/ykman --version") end end
module SubmissionsHelper def find_appropriate_grouping(assignment_id, params) if current_user.admin? || current_user.ta? Grouping.find(params[:grouping_id]) else current_user.accepted_grouping_for(assignment_id) end end # Release or unrelease the submissions of a set of groupings. # TODO: Note that this terminates the first time an error is encountered, # and displays an error message to the user, even though some groupings # *will* have their results released. We should change this to behave # similar to other bulk actions, in which all errors are collected # and reported, but the page does refresh and successes displayed. def set_release_on_results(groupings, release) changed = 0 groupings.each do |grouping| name = grouping.group.group_name unless grouping.has_submission? raise t('marking_state.no_submission', group_name: name) end unless grouping.marking_completed? if release raise t('marking_state.not_complete', group_name: name) else raise t('marking_state.not_complete_unrelease', group_name: name) end end result = grouping.current_submission_used.get_latest_result result.released_to_students = release unless result.save raise t('marking_state.result_not_saved', group_name: name) end changed += 1 end changed end def get_submissions_table_info(assignment, groupings) parts = groupings.select &:has_submission? results = Result.where(submission_id: parts.map(&:current_submission_used)) .order(:id) groupings.map do |grouping| g = Hash.new begin # if anything raises an error, catch it and log in the object. submission = grouping.current_submission_used if submission.nil? result = nil elsif !submission.remark_submitted? result = (results.select do |r| r.submission_id == submission.id end).first else result = (results.select do |r| r.id == submission.remark_result_id end).first end final_due_date = assignment.submission_rule.get_collection_time g[:name] = grouping.get_group_name g[:id] = grouping.id g[:section] = grouping.section g[:tags] = grouping.tags g[:commit_date] = grouping.last_commit_date g[:has_files] = grouping.has_files_in_submission? g[:late_commit] = grouping.past_due_date? g[:name_url] = get_grouping_name_url(grouping, final_due_date, result) g[:class_name] = get_tr_class(grouping) g[:grace_credits_used] = grouping.grace_period_deduction_single g[:repo_name] = grouping.group.repository_name g[:repo_url] = repo_browser_assignment_submission_path(assignment, grouping) g[:final_grade] = grouping.final_grade(result) g[:state] = grouping.marking_state(result) g[:error] = '' rescue => e m_logger = MarkusLogger.instance m_logger.log( "Unexpected exception #{e.message}: could not display submission " + "on assignment id #{grouping.group_id}. Backtrace follows:" + "\n" + e.backtrace.join("\n"), MarkusLogger::ERROR) g[:error] = e.message end g end end # If the grouping is collected or has an error, # style the table row green or red respectively. # Classname will be applied to the table row # and actually styled in CSS. def get_tr_class(grouping) if grouping.is_collected? 'submission_collected' elsif grouping.error_collecting 'submission_error' else nil end end def get_grouping_name_url(grouping, final_due_date, result) assignment = grouping.assignment if grouping.is_collected? url_for(edit_assignment_submission_result_path( assignment, grouping, result)) elsif grouping.has_submission? || (grouping.inviter.section.nil? && Time.zone.now > final_due_date) || assignment.submission_rule.can_collect_grouping_now?(grouping) url_for(collect_and_begin_grading_assignment_submission_path( assignment, grouping)) else '' end end # Collects submissions for all the groupings of the given section and assignment # Return the number of actually collected submissions def collect_submissions_for_section(section_id, assignment, errors) collected = 0 begin raise I18n.t('collect_submissions.could_not_find_section') if !Section.exists?(section_id) section = Section.find(section_id) # Check collection date if Time.zone.now < SectionDueDate.due_date_for(section, assignment) raise I18n.t('collect_submissions.could_not_collect_section', assignment_identifier: assignment.short_identifier, section_name: section.name) end # Collect and count submissions for all groupings of this section groupings = Grouping.where(assignment_id: assignment.id) submission_collector = SubmissionCollector.instance groupings.each do |grouping| if grouping.section == section.name submission_collector.push_grouping_to_priority_queue(grouping) collected += 1 end end if collected == 0 raise I18n.t('collect_submissions.no_submission_for_section', section_name: section.name) end rescue Exception => e errors.push(e.message) end collected end def get_repo_browser_table_info(assignment, revision, revision_number, path, previous_path, grouping_id) exit_directory = get_exit_directory(previous_path, grouping_id, revision_number, revision, assignment.repository_folder) full_path = File.join(assignment.repository_folder, path) if revision.path_exists?(full_path) files = revision.files_at_path(full_path) files_info = get_files_info(files, assignment.id, revision_number, path, grouping_id) directories = revision.directories_at_path(full_path) directories_info = get_directories_info(directories, revision_number, path, grouping_id) return exit_directory + files_info + directories_info else return exit_directory end end def get_exit_directory(previous_path, grouping_id, revision_number, revision, folder) full_previous_path = File.join('/', folder, previous_path) parent_path_of_prev_dir, prev_dir = File.split(full_previous_path) directories = revision.directories_at_path(parent_path_of_prev_dir) e = {} e[:id] = nil e[:filename] = view_context.link_to '../', action: 'repo_browser', id: grouping_id, path: previous_path, revision_number: revision_number e[:last_revised_date] = directories[prev_dir].last_modified_date e[:revision_by] = directories[prev_dir].user_id [e] end def get_files_info(files, assignment_id, revision_number, path, grouping_id) files.map do |file_name, file| f = {} f[:id] = file.object_id f[:filename] = view_context.image_tag('icons/page_white_text.png') + view_context.link_to(" #{file_name}", action: 'download', id: assignment_id, revision_number: revision_number, file_name: file_name, path: path, grouping_id: grouping_id) f[:raw_name] = file_name f[:last_revised_date] = I18n.l(file.last_modified_date, format: :long_date) f[:last_modified_revision] = file.last_modified_revision f[:revision_by] = file.user_id f end end def get_directories_info(directories, revision_number, path, grouping_id) directories.map do |directory_name, directory| d = {} d[:id] = directory.object_id d[:filename] = view_context.image_tag('icons/folder.png') + # TODO: should the call below use # id: assignment_id and grouping_id: grouping_id # like the files info? view_context.link_to(" #{directory_name}/", action: 'repo_browser', id: grouping_id, revision_number: revision_number, path: File.join(path, directory_name)) d[:last_revised_date] = I18n.l(directory.last_modified_date, format: :long_date) d[:last_modified_revision] = directory.last_modified_revision d[:revision_by] = directory.user_id d end end def sanitize_file_name(file_name) # If file_name is blank, return the empty string return '' if file_name.nil? File.basename(file_name).gsub( SubmissionFile::FILENAME_SANITIZATION_REGEXP, SubmissionFile::SUBSTITUTION_CHAR) end # Helper methods to determine remark request status on a submission def remark_in_progress(submission) submission.remark_result && submission.remark_result.marking_state == Result::MARKING_STATES[:partial] end def remark_complete_but_unreleased(submission) submission.remark_result && (submission.remark_result.marking_state == Result::MARKING_STATES[:complete]) && !submission.remark_result.released_to_students end # Checks if all the assignments for the current submission are marked. def all_assignments_marked? Assignment.includes(groupings: [:current_submission_used]) .find(params[:assignment_id]) .groupings.all?(&:marking_completed?) end end Localize date for exit directory module SubmissionsHelper def find_appropriate_grouping(assignment_id, params) if current_user.admin? || current_user.ta? Grouping.find(params[:grouping_id]) else current_user.accepted_grouping_for(assignment_id) end end # Release or unrelease the submissions of a set of groupings. # TODO: Note that this terminates the first time an error is encountered, # and displays an error message to the user, even though some groupings # *will* have their results released. We should change this to behave # similar to other bulk actions, in which all errors are collected # and reported, but the page does refresh and successes displayed. def set_release_on_results(groupings, release) changed = 0 groupings.each do |grouping| name = grouping.group.group_name unless grouping.has_submission? raise t('marking_state.no_submission', group_name: name) end unless grouping.marking_completed? if release raise t('marking_state.not_complete', group_name: name) else raise t('marking_state.not_complete_unrelease', group_name: name) end end result = grouping.current_submission_used.get_latest_result result.released_to_students = release unless result.save raise t('marking_state.result_not_saved', group_name: name) end changed += 1 end changed end def get_submissions_table_info(assignment, groupings) parts = groupings.select &:has_submission? results = Result.where(submission_id: parts.map(&:current_submission_used)) .order(:id) groupings.map do |grouping| g = Hash.new begin # if anything raises an error, catch it and log in the object. submission = grouping.current_submission_used if submission.nil? result = nil elsif !submission.remark_submitted? result = (results.select do |r| r.submission_id == submission.id end).first else result = (results.select do |r| r.id == submission.remark_result_id end).first end final_due_date = assignment.submission_rule.get_collection_time g[:name] = grouping.get_group_name g[:id] = grouping.id g[:section] = grouping.section g[:tags] = grouping.tags g[:commit_date] = grouping.last_commit_date g[:has_files] = grouping.has_files_in_submission? g[:late_commit] = grouping.past_due_date? g[:name_url] = get_grouping_name_url(grouping, final_due_date, result) g[:class_name] = get_tr_class(grouping) g[:grace_credits_used] = grouping.grace_period_deduction_single g[:repo_name] = grouping.group.repository_name g[:repo_url] = repo_browser_assignment_submission_path(assignment, grouping) g[:final_grade] = grouping.final_grade(result) g[:state] = grouping.marking_state(result) g[:error] = '' rescue => e m_logger = MarkusLogger.instance m_logger.log( "Unexpected exception #{e.message}: could not display submission " + "on assignment id #{grouping.group_id}. Backtrace follows:" + "\n" + e.backtrace.join("\n"), MarkusLogger::ERROR) g[:error] = e.message end g end end # If the grouping is collected or has an error, # style the table row green or red respectively. # Classname will be applied to the table row # and actually styled in CSS. def get_tr_class(grouping) if grouping.is_collected? 'submission_collected' elsif grouping.error_collecting 'submission_error' else nil end end def get_grouping_name_url(grouping, final_due_date, result) assignment = grouping.assignment if grouping.is_collected? url_for(edit_assignment_submission_result_path( assignment, grouping, result)) elsif grouping.has_submission? || (grouping.inviter.section.nil? && Time.zone.now > final_due_date) || assignment.submission_rule.can_collect_grouping_now?(grouping) url_for(collect_and_begin_grading_assignment_submission_path( assignment, grouping)) else '' end end # Collects submissions for all the groupings of the given section and assignment # Return the number of actually collected submissions def collect_submissions_for_section(section_id, assignment, errors) collected = 0 begin raise I18n.t('collect_submissions.could_not_find_section') if !Section.exists?(section_id) section = Section.find(section_id) # Check collection date if Time.zone.now < SectionDueDate.due_date_for(section, assignment) raise I18n.t('collect_submissions.could_not_collect_section', assignment_identifier: assignment.short_identifier, section_name: section.name) end # Collect and count submissions for all groupings of this section groupings = Grouping.where(assignment_id: assignment.id) submission_collector = SubmissionCollector.instance groupings.each do |grouping| if grouping.section == section.name submission_collector.push_grouping_to_priority_queue(grouping) collected += 1 end end if collected == 0 raise I18n.t('collect_submissions.no_submission_for_section', section_name: section.name) end rescue Exception => e errors.push(e.message) end collected end def get_repo_browser_table_info(assignment, revision, revision_number, path, previous_path, grouping_id) exit_directory = get_exit_directory(previous_path, grouping_id, revision_number, revision, assignment.repository_folder) full_path = File.join(assignment.repository_folder, path) if revision.path_exists?(full_path) files = revision.files_at_path(full_path) files_info = get_files_info(files, assignment.id, revision_number, path, grouping_id) directories = revision.directories_at_path(full_path) directories_info = get_directories_info(directories, revision_number, path, grouping_id) return exit_directory + files_info + directories_info else return exit_directory end end def get_exit_directory(previous_path, grouping_id, revision_number, revision, folder) full_previous_path = File.join('/', folder, previous_path) parent_path_of_prev_dir, prev_dir = File.split(full_previous_path) directories = revision.directories_at_path(parent_path_of_prev_dir) e = {} e[:id] = nil e[:filename] = view_context.link_to '../', action: 'repo_browser', id: grouping_id, path: previous_path, revision_number: revision_number e[:last_revised_date] = I18n.l(directories[prev_dir].last_modified_date, format: :long_date) e[:revision_by] = directories[prev_dir].user_id [e] end def get_files_info(files, assignment_id, revision_number, path, grouping_id) files.map do |file_name, file| f = {} f[:id] = file.object_id f[:filename] = view_context.image_tag('icons/page_white_text.png') + view_context.link_to(" #{file_name}", action: 'download', id: assignment_id, revision_number: revision_number, file_name: file_name, path: path, grouping_id: grouping_id) f[:raw_name] = file_name f[:last_revised_date] = I18n.l(file.last_modified_date, format: :long_date) f[:last_modified_revision] = file.last_modified_revision f[:revision_by] = file.user_id f end end def get_directories_info(directories, revision_number, path, grouping_id) directories.map do |directory_name, directory| d = {} d[:id] = directory.object_id d[:filename] = view_context.image_tag('icons/folder.png') + # TODO: should the call below use # id: assignment_id and grouping_id: grouping_id # like the files info? view_context.link_to(" #{directory_name}/", action: 'repo_browser', id: grouping_id, revision_number: revision_number, path: File.join(path, directory_name)) d[:last_revised_date] = I18n.l(directory.last_modified_date, format: :long_date) d[:last_modified_revision] = directory.last_modified_revision d[:revision_by] = directory.user_id d end end def sanitize_file_name(file_name) # If file_name is blank, return the empty string return '' if file_name.nil? File.basename(file_name).gsub( SubmissionFile::FILENAME_SANITIZATION_REGEXP, SubmissionFile::SUBSTITUTION_CHAR) end # Helper methods to determine remark request status on a submission def remark_in_progress(submission) submission.remark_result && submission.remark_result.marking_state == Result::MARKING_STATES[:partial] end def remark_complete_but_unreleased(submission) submission.remark_result && (submission.remark_result.marking_state == Result::MARKING_STATES[:complete]) && !submission.remark_result.released_to_students end # Checks if all the assignments for the current submission are marked. def all_assignments_marked? Assignment.includes(groupings: [:current_submission_used]) .find(params[:assignment_id]) .groupings.all?(&:marking_completed?) end end
class Zebra < Formula desc "Information management system" homepage "http://www.indexdata.com/zebra" url "http://ftp.indexdata.dk/pub/zebra/idzebra-2.0.61.tar.gz" sha256 "e3e5d3c50500847c4d065c93108ab9fd0222a8dbddc12565090cfdd8a885cf6f" revision 1 bottle do sha256 "bcfbe5b360d8cc65c0851123bd8be65563128dfc3ca840f5c0a9b9b18e8f1a4d" => :el_capitan sha256 "4723c0bc882ea66416ba7f3af54d227c055c9c940419da44a9c95b1567be4292" => :yosemite sha256 "c83e5ca5feeb378ae0220842428fd99731d1b8005f78497b09b5d0342da7bb72" => :mavericks end depends_on "icu4c" => :recommended depends_on "yaz" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-mod-text", "--enable-mod-grs-regx", "--enable-mod-grs-marc", "--enable-mod-grs-xml", "--enable-mod-dom", "--enable-mod-alvis", "--enable-mod-safari" system "make", "install" end test do cd share/"idzebra-2.0-examples/oai-pmh/" do system "zebraidx-2.0", "-c", "conf/zebra.cfg", "init" system "zebraidx-2.0", "-c", "conf/zebra.cfg", "commit" end end end zebra: use secure homepage (redirect to http) class Zebra < Formula desc "Information management system" homepage "https://www.indexdata.com/zebra" url "http://ftp.indexdata.dk/pub/zebra/idzebra-2.0.61.tar.gz" sha256 "e3e5d3c50500847c4d065c93108ab9fd0222a8dbddc12565090cfdd8a885cf6f" revision 1 bottle do sha256 "bcfbe5b360d8cc65c0851123bd8be65563128dfc3ca840f5c0a9b9b18e8f1a4d" => :el_capitan sha256 "4723c0bc882ea66416ba7f3af54d227c055c9c940419da44a9c95b1567be4292" => :yosemite sha256 "c83e5ca5feeb378ae0220842428fd99731d1b8005f78497b09b5d0342da7bb72" => :mavericks end depends_on "icu4c" => :recommended depends_on "yaz" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-mod-text", "--enable-mod-grs-regx", "--enable-mod-grs-marc", "--enable-mod-grs-xml", "--enable-mod-dom", "--enable-mod-alvis", "--enable-mod-safari" system "make", "install" end test do cd share/"idzebra-2.0-examples/oai-pmh/" do system "zebraidx-2.0", "-c", "conf/zebra.cfg", "init" system "zebraidx-2.0", "-c", "conf/zebra.cfg", "commit" end end end
module TransamTagHelper def loader_panel_tag(options={}) html = "<div class='loader'><i class='fa fa-spinner fa-spin fa-2x'></div>" return html.html_safe end def image_thumbnail_tag(options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='shadow thumbnail action-thumbnail " html << options[:class] unless options[:class].blank? html << "'>" html << "<div data-action-path='" html << options[:path] html << "'>" html << content html << "</div>" html << "</li>" return html.html_safe end def action_thumbnail_tag(options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='thumbnail shadow action-thumbnail " html << options[:class] unless options[:class].blank? html << "'>" html << "<div data-action-path='" html << options[:path] html << "'>" html << "<div class='well well-small' style='margin-bottom:0px;height:125px;'>" html << "<div class='row-fluid'>" html << "<div class='span4'>" html << "<i class='" html << options[:icon] html << " fa-4x' style='margin-top:5px;'></i>" html << "</div>" html << "<div class='span8'>" html << "<h4'>" html << options[:title] html << "</div>" html << "</div>" html << "<div class='row-fluid'>" html << "<div class='span12'>" html << content html << "</div>" html << "</div>" html << "</div>" html << "</div>" html << "</li>" return html.html_safe end # # # Sub Navigation Tag Helpers # # def sub_nav_elem_tag(&block) content = capture(&block) html = "<li>" html << content html << "</li>" return html.html_safe end def sub_nav_tag(options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<div class='row-fluid " html << options[:class] unless options[:class].blank? html << "'>" html << "<div class='span12'>" html << "<div class='navbar'>" html << "<div class='navbar-inner'>" html << "<ul class='nav'>" html << content html << "</ul>" html << "</div>" html << "</div>" html << "</div>" html << "</div>" return html.html_safe end def panel_tag(panel_name, options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='thumbnail shadow " html << options[:class] unless options[:class].blank? html << "'>" html << "<div class='panel-header navbar-inner'>" html << "<h4 class='panel-title'>" if options[:icon] html << "<i class='" html << options[:icon] html << "'></i> " end html << panel_name html << "</h4>" html << "</div>" html << "<div class='panel-content'>" html << content html << "</div>" html << "</li>" return html.html_safe end def dialog_tag(dialog_name, icon=nil, link_text=nil, link_path=nil, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='span12 thumbnail first-in-row shadow'>" html << "<div class='dialog-header navbar-inner'>" if link_path.nil? html << "<h4 class='dialog-title'>" if icon html << "<i class='" html << icon html << "'></i> " end html << dialog_name html << "</h4>" else html << "<h4 class='span6 dialog-title'>" if icon html << "<i class='" html << icon html << "'></i> " end html << dialog_name html << "</h4>" html << "<div class='span6 dialog-controls'>" html << link_to(link_text, link_path, :class => "btn btn-small pull-right") html << "</div>" end html << "</div>" html << "<div class='dialog-content'>" html << content html << "</div>" html << "</li>" return html.html_safe end end Fix tag flow module TransamTagHelper def loader_panel_tag(options={}) html = "<div class='loader'><i class='fa fa-spinner fa-spin fa-2x'></div>" return html.html_safe end def image_thumbnail_tag(options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='shadow thumbnail action-thumbnail " html << options[:class] unless options[:class].blank? html << "'>" html << "<div data-action-path='" html << options[:path] html << "'>" html << content html << "</div>" html << "</li>" return html.html_safe end def action_thumbnail_tag(options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='thumbnail shadow action-thumbnail " html << options[:class] unless options[:class].blank? html << "'>" html << "<div data-action-path='" html << options[:path] html << "' style='overflow:hidden;'>" html << "<div class='well well-small' style='margin-bottom:0px;height:125px;'>" html << "<div class='row-fluid'>" html << "<div class='span4'>" html << "<i class='" html << options[:icon] html << " fa-4x' style='margin-top:5px;'></i>" html << "</div>" html << "<div class='span8'>" html << "<h4'>" html << options[:title] html << "</div>" html << "</div>" html << "<div class='row-fluid'>" html << "<div class='span12'>" html << content html << "</div>" html << "</div>" html << "</div>" html << "</div>" html << "</li>" return html.html_safe end # # # Sub Navigation Tag Helpers # # def sub_nav_elem_tag(&block) content = capture(&block) html = "<li>" html << content html << "</li>" return html.html_safe end def sub_nav_tag(options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<div class='row-fluid " html << options[:class] unless options[:class].blank? html << "'>" html << "<div class='span12'>" html << "<div class='navbar'>" html << "<div class='navbar-inner'>" html << "<ul class='nav'>" html << content html << "</ul>" html << "</div>" html << "</div>" html << "</div>" html << "</div>" return html.html_safe end def panel_tag(panel_name, options={}, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='thumbnail shadow " html << options[:class] unless options[:class].blank? html << "'>" html << "<div class='panel-header navbar-inner'>" html << "<h4 class='panel-title'>" if options[:icon] html << "<i class='" html << options[:icon] html << "'></i> " end html << panel_name html << "</h4>" html << "</div>" html << "<div class='panel-content'>" html << content html << "</div>" html << "</li>" return html.html_safe end def dialog_tag(dialog_name, icon=nil, link_text=nil, link_path=nil, &block) # Check to see if there is any content in the block content = capture(&block) if content.nil? content = "<p>&nbsp;</p>" end html = "<li class='span12 thumbnail first-in-row shadow'>" html << "<div class='dialog-header navbar-inner'>" if link_path.nil? html << "<h4 class='dialog-title'>" if icon html << "<i class='" html << icon html << "'></i> " end html << dialog_name html << "</h4>" else html << "<h4 class='span6 dialog-title'>" if icon html << "<i class='" html << icon html << "'></i> " end html << dialog_name html << "</h4>" html << "<div class='span6 dialog-controls'>" html << link_to(link_text, link_path, :class => "btn btn-small pull-right") html << "</div>" end html << "</div>" html << "<div class='dialog-content'>" html << content html << "</div>" html << "</li>" return html.html_safe end end
class Zebra < Formula desc "Information management system" homepage "https://www.indexdata.com/resources/software/zebra/" url "https://ftp.indexdata.com/pub/zebra/idzebra-2.2.5.tar.gz" sha256 "747714b33b653cbe5697193703b9955489fa2f51597433f9b072ab2bf9cf92bb" license "GPL-2.0-or-later" livecheck do url "https://ftp.indexdata.com/pub/zebra/" regex(/href=.*?idzebra[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 arm64_monterey: "3151e5dcd9a07585d8f6d4f81235394e665a2443c35a45a89f673801c6150971" sha256 arm64_big_sur: "eb74e46a14ff57b506bd931116576cd0254274ea64538ee694cd2a1f87f0f09c" sha256 monterey: "b09a16015fa21a43563b01a182c6fa7ccfe277cba465f07f01c770ee36b8de11" sha256 big_sur: "f03be76a850297ab5ca3b56f989f8cc2ca05034e83be744cf46ea38d903ecacb" sha256 catalina: "56d4d4d9606a9f1da02ec47aa53d06d87e6d216b66dbe90510dff70a9f3313b5" sha256 x86_64_linux: "1c46c43a552fc8e9572efa1b294e22b2635c089417d7d0e33c79de3c0e6868b8" end depends_on "icu4c" depends_on "yaz" uses_from_macos "bzip2" uses_from_macos "expat" uses_from_macos "libxcrypt" uses_from_macos "libxml2" uses_from_macos "libxslt" uses_from_macos "zlib" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-mod-text", "--enable-mod-grs-regx", "--enable-mod-grs-marc", "--enable-mod-grs-xml", "--enable-mod-dom", "--enable-mod-alvis", "--enable-mod-safari" system "make", "install" end test do cd share/"idzebra-2.0-examples/oai-pmh/" do system bin/"zebraidx-2.0", "-c", "conf/zebra.cfg", "init" system bin/"zebraidx-2.0", "-c", "conf/zebra.cfg", "commit" end end end zebra: update 2.2.5 bottle. class Zebra < Formula desc "Information management system" homepage "https://www.indexdata.com/resources/software/zebra/" url "https://ftp.indexdata.com/pub/zebra/idzebra-2.2.5.tar.gz" sha256 "747714b33b653cbe5697193703b9955489fa2f51597433f9b072ab2bf9cf92bb" license "GPL-2.0-or-later" livecheck do url "https://ftp.indexdata.com/pub/zebra/" regex(/href=.*?idzebra[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 arm64_monterey: "d2d4d08210da41a8cee406e186797b38f8b3e04c9529c3abb27b9bcd79e0e380" sha256 arm64_big_sur: "08bdad0b345de815886ba491efc05c64301de4f58db1d18b2ac1467da2f1473c" sha256 monterey: "9327880be4912d03219f7a691b59560bf33a33dfe1f994275bc7ec9ede54a10d" sha256 big_sur: "9f4f272f7a6d0de6184755bd8304c3c00c9c8ed10d5143f8048f2ff528398854" sha256 catalina: "23adf3398ce56fbcb527f772362b2d3b551684470563ea4911d06dde14e43b29" sha256 x86_64_linux: "384a18ddb1e2ab16a1fc679cef45fea988b6df9f93759aaaeeebdec71ba509d5" end depends_on "icu4c" depends_on "yaz" uses_from_macos "bzip2" uses_from_macos "expat" uses_from_macos "libxcrypt" uses_from_macos "libxml2" uses_from_macos "libxslt" uses_from_macos "zlib" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--enable-mod-text", "--enable-mod-grs-regx", "--enable-mod-grs-marc", "--enable-mod-grs-xml", "--enable-mod-dom", "--enable-mod-alvis", "--enable-mod-safari" system "make", "install" end test do cd share/"idzebra-2.0-examples/oai-pmh/" do system bin/"zebraidx-2.0", "-c", "conf/zebra.cfg", "init" system bin/"zebraidx-2.0", "-c", "conf/zebra.cfg", "commit" end end end
require 'test_helper' require 'action_controller' class DummyAppIntegrationTest < ActionController::TestCase tests DummyController test "should succesfully load the app and show index" do get :index assert_response :success end test "index should have html imports" do get :index assert_select "link[rel='import']" end test "the compiled assets should be served from the right directory" do get :index assert_match /href="\/assets\/application\.html"/, @response.body end # To test the contents of our compiled application.html, we have a custom route # and controller action. The controller action renders the compiled file as a # json response, which we can test against here. test "the test files should get concatenated" do get :assets assert_equal @response.body, <<-EOS.strip_heredoc <script>var life = "is good"; </script> <p>test4</p> <style>p { color: red; } </style> <script>(function() { var hello; hello = "world"; }).call(this); </script> <p>compiled scss and CoffeeScript</p> <style>p { color: pink; } </style> <p>test3</p> <p>test2</p> <p>test1</p> EOS end end Integration test comment require 'test_helper' require 'action_controller' class DummyAppIntegrationTest < ActionController::TestCase tests DummyController test "should succesfully load the app and show index" do get :index assert_response :success end test "index should have html imports" do get :index assert_select "link[rel='import']" end test "the compiled assets should be served from the right directory" do get :index assert_match /href="\/assets\/application\.html"/, @response.body end # The dummy app has a custom route and controller action that renders the # compiled html import as a json response. We test against that here. test "the test files should get concatenated" do get :assets assert_equal @response.body, <<-EOS.strip_heredoc <script>var life = "is good"; </script> <p>test4</p> <style>p { color: red; } </style> <script>(function() { var hello; hello = "world"; }).call(this); </script> <p>compiled scss and CoffeeScript</p> <style>p { color: pink; } </style> <p>test3</p> <p>test2</p> <p>test1</p> EOS end end
# frozen_string_literal: true class MonographIndexer < Hyrax::WorkIndexer include Hyrax::IndexesBasicMetadata def generate_solr_document super.tap do |solr_doc| press = Press.find_by(subdomain: object.press) press_name = press.name unless press.nil? solr_doc[Solrizer.solr_name('press_name', :symbol)] = press_name solr_doc[Solrizer.solr_name('title', :sortable)] = normalize_for_sort(object&.title&.first) roleless_creators = multiline_names_minus_role('creator') roleless_contributors = multiline_names_minus_role('contributor') # fix for imported Monographs that only have contributors for whatever reason, i.e. the metadata was created... # outside Fulcrum and only had supposed "non-author roles" which were put in as contributors so we'll promote... # the first contributor to a creator for use in citations roleless_creators = [roleless_contributors&.shift] if roleless_creators.blank? solr_doc[Solrizer.solr_name('creator', :stored_searchable)] = roleless_creators solr_doc[Solrizer.solr_name('creator', :facetable)] = roleless_creators solr_doc[Solrizer.solr_name('creator_full_name', :stored_searchable)] = roleless_creators&.first solr_doc[Solrizer.solr_name('creator_full_name', :sortable)] = normalize_for_sort(roleless_creators&.first) solr_doc[Solrizer.solr_name('contributor', :stored_searchable)] = roleless_contributors # probably we'll need more substantial cleanup here, for now discard anything that isn't a number as... # HEB often has stuff like 'c1999' in the Publication Year (`date_created`) solr_doc[Solrizer.solr_name('date_created', :sortable)] = object.date_created&.first&.gsub(/[^0-9]/, '') # grab previous file set order here from Solr (before they are reindexed) existing_fileset_order = existing_filesets solr_doc[Solrizer.solr_name('ordered_member_ids', :symbol)] = object.ordered_member_ids solr_doc[Solrizer.solr_name('representative_id', :symbol)] = object.representative_id trigger_fileset_reindexing(existing_fileset_order, object.ordered_member_ids) end end def existing_filesets existing_monograph_doc = ActiveFedora::SolrService.query("{!terms f=id}#{object.id}", rows: 1) order = existing_monograph_doc.blank? ? [] : existing_monograph_doc[0][Solrizer.solr_name('ordered_member_ids', :symbol)] order || [] end def trigger_fileset_reindexing(existing_fileset_order, new_fileset_order) new_fileset_order.each_with_index do |id, new_index| former_position = existing_fileset_order.index(id) next unless former_position && former_position != new_index # ReindexFileSetJob.perform_later(FileSet.find(id)) FileSet.find(id).update_index end end def multiline_names_minus_role(field) value = object.public_send(field).first value.present? ? value.split(/\r?\n/).reject(&:blank?).map { |val| val.sub(/\s*\(.+\)$/, '').strip } : value end def normalize_for_sort(value) # transliterate() can't handle nil value ||= '' # Removing punctuation so that, e.g., a value starting with quotes doesn't always come first # transliterate will take care of mapping accented chars to an ASCII equivalent value = ActiveSupport::Inflector.transliterate(value).downcase.gsub(/[^\w\s\d-]/, '') # return nil to ensure removal of Solr doc value if appropriate value.presence end end queue jobs to index file_sets' positions # frozen_string_literal: true class MonographIndexer < Hyrax::WorkIndexer include Hyrax::IndexesBasicMetadata def generate_solr_document super.tap do |solr_doc| press = Press.find_by(subdomain: object.press) press_name = press.name unless press.nil? solr_doc[Solrizer.solr_name('press_name', :symbol)] = press_name solr_doc[Solrizer.solr_name('title', :sortable)] = normalize_for_sort(object&.title&.first) roleless_creators = multiline_names_minus_role('creator') roleless_contributors = multiline_names_minus_role('contributor') # fix for imported Monographs that only have contributors for whatever reason, i.e. the metadata was created... # outside Fulcrum and only had supposed "non-author roles" which were put in as contributors so we'll promote... # the first contributor to a creator for use in citations roleless_creators = [roleless_contributors&.shift] if roleless_creators.blank? solr_doc[Solrizer.solr_name('creator', :stored_searchable)] = roleless_creators solr_doc[Solrizer.solr_name('creator', :facetable)] = roleless_creators solr_doc[Solrizer.solr_name('creator_full_name', :stored_searchable)] = roleless_creators&.first solr_doc[Solrizer.solr_name('creator_full_name', :sortable)] = normalize_for_sort(roleless_creators&.first) solr_doc[Solrizer.solr_name('contributor', :stored_searchable)] = roleless_contributors # probably we'll need more substantial cleanup here, for now discard anything that isn't a number as... # HEB often has stuff like 'c1999' in the Publication Year (`date_created`) solr_doc[Solrizer.solr_name('date_created', :sortable)] = object.date_created&.first&.gsub(/[^0-9]/, '') # grab previous file set order here from Solr (before they are reindexed) existing_fileset_order = existing_filesets solr_doc[Solrizer.solr_name('ordered_member_ids', :symbol)] = object.ordered_member_ids solr_doc[Solrizer.solr_name('representative_id', :symbol)] = object.representative_id trigger_fileset_reindexing(existing_fileset_order, object.ordered_member_ids) end end def existing_filesets existing_monograph_doc = ActiveFedora::SolrService.query("{!terms f=id}#{object.id}", rows: 1) order = existing_monograph_doc.blank? ? [] : existing_monograph_doc[0][Solrizer.solr_name('ordered_member_ids', :symbol)] order || [] end def trigger_fileset_reindexing(existing_fileset_order, new_fileset_order) new_fileset_order.each_with_index do |id, new_index| former_position = existing_fileset_order.index(id) next unless former_position && former_position != new_index CurationConcernUpdateIndexJob.perform_later(FileSet.find(id)) end end def multiline_names_minus_role(field) value = object.public_send(field).first value.present? ? value.split(/\r?\n/).reject(&:blank?).map { |val| val.sub(/\s*\(.+\)$/, '').strip } : value end def normalize_for_sort(value) # transliterate() can't handle nil value ||= '' # Removing punctuation so that, e.g., a value starting with quotes doesn't always come first # transliterate will take care of mapping accented chars to an ASCII equivalent value = ActiveSupport::Inflector.transliterate(value).downcase.gsub(/[^\w\s\d-]/, '') # return nil to ensure removal of Solr doc value if appropriate value.presence end end
# frozen_string_literal: true # # Copyright (C) 2014 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # NOTE: Indented gems are meant to indicate transient dependencies of parent gems if CANVAS_RAILS6_0 gem 'rails', '6.0.4.1' gem 'tzinfo', '1.2.7' gem 'switchman', '2.2.1' gem 'guardrail', '2.0.1' gem 'switchman-inst-jobs', '3.2.4' else gem 'rails', '6.1.4.1' gem 'tzinfo', '2.0.4' gem 'switchman', '3.0.5' gem 'guardrail', '3.0.0' gem 'switchman-inst-jobs', '4.0.0' end gem 'irb', '1.3.5' gem 'open4', '1.3.4', require: false gem 'academic_benchmarks', '1.1.1', require: false gem 'active_model-better_errors', '1.6.7', require: 'active_model/better_errors' gem 'active_model_serializers', '0.9.0alpha1', github: 'rails-api/active_model_serializers', ref: '61882e1e4127facfe92e49057aec71edbe981829' gem 'activerecord-pg-extensions', '0.4.2' gem 'addressable', '2.7.0', require: false gem 'after_transaction_commit', '2.2.2' gem 'authlogic', '6.4.1' gem 'scrypt', '3.0.7' gem 'aws-sdk-core', '3.109.2', require: false gem 'aws-partitions', '1.393.0', require: false gem 'aws-sdk-dynamodb', '1.57.0' gem 'aws-sdk-kinesis', '1.30.0', require: false gem 'aws-sdk-s3', '1.84.1', require: false gem 'aws-sdk-sns', '1.36.0', require: false gem 'aws-sdk-sqs', '1.34.0', require: false gem 'aws-sdk-kms', '1.39.0', require: false gem 'aws-sigv4', '1.2.2', require: false gem 'barby', '0.6.8', require: false gem 'rqrcode', '1.2.0', require: false gem 'chunky_png', '1.3.14', require: false gem 'bcrypt', '3.1.16' gem 'browser', '5.1.0', require: false gem 'builder', '3.2.4' gem 'business_time', '0.10.0' gem 'canvas_connect', '0.3.13' gem 'adobe_connect', '1.0.9', require: false gem 'canvas_webex', '0.17' gem 'crocodoc-ruby', '0.0.1', require: false gem 'ddtrace', '0.42.0', require: false gem 'encrypted_cookie_store-instructure', '1.2.11', require: 'encrypted_cookie_store' gem 'folio-pagination', '0.0.12', require: 'folio/rails' gem 'ffi', '1.13.1', require: false gem 'gepub', '1.0.13' gem 'apollo-federation', '1.1.5' gem 'graphql', '1.12.14' gem 'graphql-batch', '0.4.3' gem 'hashery', '2.1.2', require: false gem 'highline', '2.0.3', require: false gem 'httparty', '0.18.1' gem 'i18n', '1.8.5' gem 'i18nliner', '0.1.2' gem 'ruby2ruby', '2.4.4', require: false gem 'ruby_parser', '3.15.0', require: false gem 'icalendar', '2.7.0', require: false gem 'diplomat', '2.5.1', require: false gem 'ims-lti', '2.3.0', require: 'ims' gem 'inst_statsd', '2.2.0' gem 'statsd-ruby', '1.4.0', require: false gem 'aroi', '0.0.7', require: false gem 'dogstatsd-ruby', '4.8.2' gem 'inst-jobs', '3.0.0' gem 'fugit', '1.4.0', require: false gem 'et-orbi', '1.2.4', require: false gem 'inst-jobs-autoscaling', '2.1.1' gem 'aws-sdk-autoscaling', '1.49.0', require: false gem 'inst-jobs-statsd', '2.1.2' # if updating json gem it will need to be hotfixed because if a newer version of # the json gem is installed, it will always use that one even before bundler # gets activated. Updating the gem in it's own commit will make this easier. gem 'json', '2.5.1' gem 'json_schemer', '0.2.16', github: 'robotdana/json_schemer', ref: '0d2ac359a87964f74c07a14cafeb98cfcae4e29f' gem 'ecma-re-validator', '0.2.1' gem 'json-jwt', '1.13.0', require: false gem 'link_header', '0.0.8' gem 'mail', '2.7.1', require: false gem 'mini_mime', '1.0.2', require: false gem 'marginalia', '1.9.0', require: false gem 'mime-types', '3.3.1' gem 'mini_magick', '4.11.0' gem 'multi_json', '1.15.0' gem 'net-ldap', '0.16.3', require: false gem 'nokogiri', '1.11.5', require: false gem 'nokogumbo', '2.0.4' gem 'oauth', '0.5.4', require: false gem 'oauth2', '1.4.4', require: false gem 'oj', '3.10.16' gem 'outrigger', '3.0.0' gem 'prawn-rails', '1.3.0' gem 'rack', '2.2.3' gem 'rack-brotli', '1.0.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.3' gem 'rails-observers', '0.1.5' gem 'ratom-nokogiri', '0.10.10', require: false gem 'redcarpet', '3.5.0', require: false gem 'retriable', '1.4.1' gem 'ritex', '1.0.1', require: false gem 'rotp', '6.2.0', require: false gem 'ruby-duration', '3.2.3', require: false gem 'ruby2_keywords', '0.0.3' gem 'rubycas-client', '2.3.9', require: false gem 'rubyzip', '2.3.0', require: 'zip' gem 'saml2', '3.1.0' gem 'nokogiri-xmlsec-instructure', '0.10.1', require: false gem 'sanitize', '5.2.3', require: false gem 'sentry-raven', '2.13.0', require: false gem 'simple_oauth', '0.3.1', require: false gem 'twilio-ruby', '5.36.0', require: false gem 'vault', '0.15.0', require: false gem 'vericite_api', '1.5.3' gem 'week_of_month', '1.2.5', github: 'instructure/week-of-month', ref: 'b3013639e9474f302b5a6f27e4e45313e8d24902' gem 'will_paginate', '3.3.0', require: false # required for folio-pagination # needs pin to satisfy varying requirements of google_drive and another gem gem 'faraday', '0.17.4' gem 'faraday_middleware', '0.14.0' path 'engines' do gem 'audits' end path 'gems' do gem 'activesupport-suspend_callbacks' gem 'acts_as_list' gem 'adheres_to_policy' gem 'attachment_fu' gem 'autoextend' gem 'bookmarked_collection' gem 'broadcast_policy' gem 'canvas_breach_mitigation' gem 'canvas_cache' gem 'canvas_color' gem 'canvas_crummy' gem 'canvas_dynamodb' gem 'canvas_errors' gem 'canvas_ext' gem 'canvas_http' gem 'canvas_kaltura' gem 'canvas_panda_pub' gem 'canvas_partman' gem 'canvas_mimetype_fu' gem 'canvas_quiz_statistics' gem 'canvas_sanitize' gem 'canvas_security' gem 'canvas_slug' gem 'canvas_sort' gem 'canvas_stringex' gem 'canvas_text_helper' gem 'canvas_time' gem 'canvas_unzip' gem 'config_file' gem 'diigo' gem 'dynamic_settings' gem 'event_stream' gem 'google_drive' gem 'html_text_helper' gem 'incoming_mail_processor' gem 'json_token' gem 'linked_in' gem 'live_events' gem 'lti-advantage' gem 'lti_outbound' gem 'multipart' gem 'paginated_collection' gem 'request_context' gem 'stringify_ids' gem 'twitter' gem 'utf8_cleaner' gem 'workflow' end gem 'csv_diff', path: 'gems' gem 'sqlite3', '1.4.2' use latest canvas_connect 0.3.14 refs FOO-2433 flag=none TEST PLAN: 1) specs pass Change-Id: I5df36fa90cc274289ebbd596cedddb3dfbd37430 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/275960 Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> QA-Review: Ethan Vizitei <73eeb0b2f65d05a906adf3b21ee1f9f5a2aa3c1c@instructure.com> Product-Review: Ethan Vizitei <73eeb0b2f65d05a906adf3b21ee1f9f5a2aa3c1c@instructure.com> Reviewed-by: Jacob Burroughs <8ecea6e385af5cf9f53123f5ca17fb5fd6a6d4b2@instructure.com> # frozen_string_literal: true # # Copyright (C) 2014 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # NOTE: Indented gems are meant to indicate transient dependencies of parent gems if CANVAS_RAILS6_0 gem 'rails', '6.0.4.1' gem 'tzinfo', '1.2.7' gem 'switchman', '2.2.1' gem 'guardrail', '2.0.1' gem 'switchman-inst-jobs', '3.2.4' else gem 'rails', '6.1.4.1' gem 'tzinfo', '2.0.4' gem 'switchman', '3.0.5' gem 'guardrail', '3.0.0' gem 'switchman-inst-jobs', '4.0.0' end gem 'irb', '1.3.5' gem 'open4', '1.3.4', require: false gem 'academic_benchmarks', '1.1.1', require: false gem 'active_model-better_errors', '1.6.7', require: 'active_model/better_errors' gem 'active_model_serializers', '0.9.0alpha1', github: 'rails-api/active_model_serializers', ref: '61882e1e4127facfe92e49057aec71edbe981829' gem 'activerecord-pg-extensions', '0.4.2' gem 'addressable', '2.7.0', require: false gem 'after_transaction_commit', '2.2.2' gem 'authlogic', '6.4.1' gem 'scrypt', '3.0.7' gem 'aws-sdk-core', '3.109.2', require: false gem 'aws-partitions', '1.393.0', require: false gem 'aws-sdk-dynamodb', '1.57.0' gem 'aws-sdk-kinesis', '1.30.0', require: false gem 'aws-sdk-s3', '1.84.1', require: false gem 'aws-sdk-sns', '1.36.0', require: false gem 'aws-sdk-sqs', '1.34.0', require: false gem 'aws-sdk-kms', '1.39.0', require: false gem 'aws-sigv4', '1.2.2', require: false gem 'barby', '0.6.8', require: false gem 'rqrcode', '1.2.0', require: false gem 'chunky_png', '1.3.14', require: false gem 'bcrypt', '3.1.16' gem 'browser', '5.1.0', require: false gem 'builder', '3.2.4' gem 'business_time', '0.10.0' gem 'canvas_connect', '0.3.14' gem 'adobe_connect', '1.0.9', require: false gem 'canvas_webex', '0.17' gem 'crocodoc-ruby', '0.0.1', require: false gem 'ddtrace', '0.42.0', require: false gem 'encrypted_cookie_store-instructure', '1.2.11', require: 'encrypted_cookie_store' gem 'folio-pagination', '0.0.12', require: 'folio/rails' gem 'ffi', '1.13.1', require: false gem 'gepub', '1.0.13' gem 'apollo-federation', '1.1.5' gem 'graphql', '1.12.14' gem 'graphql-batch', '0.4.3' gem 'hashery', '2.1.2', require: false gem 'highline', '2.0.3', require: false gem 'httparty', '0.18.1' gem 'i18n', '1.8.5' gem 'i18nliner', '0.1.2' gem 'ruby2ruby', '2.4.4', require: false gem 'ruby_parser', '3.15.0', require: false gem 'icalendar', '2.7.0', require: false gem 'diplomat', '2.5.1', require: false gem 'ims-lti', '2.3.0', require: 'ims' gem 'inst_statsd', '2.2.0' gem 'statsd-ruby', '1.4.0', require: false gem 'aroi', '0.0.7', require: false gem 'dogstatsd-ruby', '4.8.2' gem 'inst-jobs', '3.0.0' gem 'fugit', '1.4.0', require: false gem 'et-orbi', '1.2.4', require: false gem 'inst-jobs-autoscaling', '2.1.1' gem 'aws-sdk-autoscaling', '1.49.0', require: false gem 'inst-jobs-statsd', '2.1.2' # if updating json gem it will need to be hotfixed because if a newer version of # the json gem is installed, it will always use that one even before bundler # gets activated. Updating the gem in it's own commit will make this easier. gem 'json', '2.5.1' gem 'json_schemer', '0.2.16', github: 'robotdana/json_schemer', ref: '0d2ac359a87964f74c07a14cafeb98cfcae4e29f' gem 'ecma-re-validator', '0.2.1' gem 'json-jwt', '1.13.0', require: false gem 'link_header', '0.0.8' gem 'mail', '2.7.1', require: false gem 'mini_mime', '1.0.2', require: false gem 'marginalia', '1.9.0', require: false gem 'mime-types', '3.3.1' gem 'mini_magick', '4.11.0' gem 'multi_json', '1.15.0' gem 'net-ldap', '0.16.3', require: false gem 'nokogiri', '1.11.5', require: false gem 'nokogumbo', '2.0.4' gem 'oauth', '0.5.4', require: false gem 'oauth2', '1.4.4', require: false gem 'oj', '3.10.16' gem 'outrigger', '3.0.0' gem 'prawn-rails', '1.3.0' gem 'rack', '2.2.3' gem 'rack-brotli', '1.0.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.3' gem 'rails-observers', '0.1.5' gem 'ratom-nokogiri', '0.10.10', require: false gem 'redcarpet', '3.5.0', require: false gem 'retriable', '1.4.1' gem 'ritex', '1.0.1', require: false gem 'rotp', '6.2.0', require: false gem 'ruby-duration', '3.2.3', require: false gem 'ruby2_keywords', '0.0.3' gem 'rubycas-client', '2.3.9', require: false gem 'rubyzip', '2.3.0', require: 'zip' gem 'saml2', '3.1.0' gem 'nokogiri-xmlsec-instructure', '0.10.1', require: false gem 'sanitize', '5.2.3', require: false gem 'sentry-raven', '2.13.0', require: false gem 'simple_oauth', '0.3.1', require: false gem 'twilio-ruby', '5.36.0', require: false gem 'vault', '0.15.0', require: false gem 'vericite_api', '1.5.3' gem 'week_of_month', '1.2.5', github: 'instructure/week-of-month', ref: 'b3013639e9474f302b5a6f27e4e45313e8d24902' gem 'will_paginate', '3.3.0', require: false # required for folio-pagination # needs pin to satisfy varying requirements of google_drive and another gem gem 'faraday', '0.17.4' gem 'faraday_middleware', '0.14.0' path 'engines' do gem 'audits' end path 'gems' do gem 'activesupport-suspend_callbacks' gem 'acts_as_list' gem 'adheres_to_policy' gem 'attachment_fu' gem 'autoextend' gem 'bookmarked_collection' gem 'broadcast_policy' gem 'canvas_breach_mitigation' gem 'canvas_cache' gem 'canvas_color' gem 'canvas_crummy' gem 'canvas_dynamodb' gem 'canvas_errors' gem 'canvas_ext' gem 'canvas_http' gem 'canvas_kaltura' gem 'canvas_panda_pub' gem 'canvas_partman' gem 'canvas_mimetype_fu' gem 'canvas_quiz_statistics' gem 'canvas_sanitize' gem 'canvas_security' gem 'canvas_slug' gem 'canvas_sort' gem 'canvas_stringex' gem 'canvas_text_helper' gem 'canvas_time' gem 'canvas_unzip' gem 'config_file' gem 'diigo' gem 'dynamic_settings' gem 'event_stream' gem 'google_drive' gem 'html_text_helper' gem 'incoming_mail_processor' gem 'json_token' gem 'linked_in' gem 'live_events' gem 'lti-advantage' gem 'lti_outbound' gem 'multipart' gem 'paginated_collection' gem 'request_context' gem 'stringify_ids' gem 'twitter' gem 'utf8_cleaner' gem 'workflow' end gem 'csv_diff', path: 'gems' gem 'sqlite3', '1.4.2'
# # Copyright (C) 2014 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # Note: Indented gems are meant to indicate transient dependencies of parent gems if CANVAS_RAILS5_2 gem 'rails', '5.2.4.4' gem 'loofah', '2.3.0' gem 'sprockets', '4.0.2' else gem 'rails', '6.0.3.4' end gem 'academic_benchmarks', '0.0.11', require: false gem 'active_model-better_errors', '1.6.7', require: 'active_model/better_errors' gem 'active_model_serializers', '0.9.0alpha1', github: 'rails-api/active_model_serializers', ref: '61882e1e4127facfe92e49057aec71edbe981829' gem 'addressable', '2.7.0', require: false gem 'after_transaction_commit', '2.2.1' gem 'authlogic', '6.2.0' gem 'scrypt', '3.0.7' gem 'aws-sdk-core', '3.109.2', require: false gem 'aws-partitions', '1.393.0', require: false gem 'aws-sdk-dynamodb', '1.57.0' gem 'aws-sdk-kinesis', '1.30.0', require: false gem 'aws-sdk-s3', '1.84.1', require: false gem 'aws-sdk-sns', '1.36.0', require: false gem 'aws-sdk-sqs', '1.34.0', require: false gem 'aws-sdk-kms', '1.39.0', require: false gem 'aws-sigv4', '1.2.2', require: false gem 'barby', '0.6.8', require: false gem 'rqrcode', '1.1.2', require: false gem 'chunky_png', '1.3.14', require: false gem 'bcrypt', '3.1.16' gem 'brotli', '0.2.3', require: false gem 'browser', '5.1.0', require: false gem 'builder', '3.2.4' gem 'canvas_connect', '0.3.11' gem 'adobe_connect', '1.0.8', require: false gem 'canvas_webex', '0.17' gem 'crocodoc-ruby', '0.0.1', require: false gem 'ddtrace', '0.42.0', require: false gem 'encrypted_cookie_store-instructure', '1.2.10', require: 'encrypted_cookie_store' gem 'folio-pagination', '0.0.12', require: 'folio/rails' gem 'ffi', '1.13.1', require: false gem 'gepub', '1.0.11', github: 'skoji/gepub', ref: '04c8c2542f9fa3f8d99652f9058d77c8a23c1fd9' gem 'graphql', '1.9.17' gem 'graphql-batch', '0.4.3' gem 'hashery', '2.1.2', require: false gem 'highline', '2.0.3', require: false gem 'httparty', '0.18.1' gem 'i18n', '1.8.5' gem 'i18nliner', '0.1.2' gem 'ruby2ruby', '2.4.4', require: false gem 'ruby_parser', '3.15.0', require: false gem 'icalendar', '2.7.0', require: false gem 'imperium', '0.5.2', require: false gem 'ims-lti', '2.3.0', require: 'ims' gem 'inst_statsd', '2.1.6' gem 'statsd-ruby', '1.4.0', require: false gem 'aroi', '0.0.7', require: false gem 'dogstatsd-ruby', '4.8.2' gem 'inst-jobs', '2.1.2' gem 'fugit', '1.4.0', require: false gem 'et-orbi', '1.2.4', require: false gem 'inst-jobs-autoscaling', '2.1.0' gem 'aws-sdk-autoscaling', '1.49.0', require: false gem 'inst-jobs-statsd', '2.1.0' gem 'json', '2.3.1' gem 'json_schemer', '0.2.16', github: 'robotdana/json_schemer', ref: '0d2ac359a87964f74c07a14cafeb98cfcae4e29f' gem 'json-jwt', '1.13.0', require: false gem 'link_header', '0.0.8' gem 'mail', '2.7.1', require: false gem 'mini_mime', '1.0.2', require: false gem 'marginalia', '1.9.0', require: false gem 'mime-types', '3.3.1' gem 'mini_magick', '4.11.0' gem 'multi_json', '1.15.0' gem 'net-ldap', '0.16.3', require: false gem 'nokogiri', '1.10.10', require: false gem 'oauth', '0.5.4', require: false gem 'oauth2', '1.4.4', require: false gem 'oj', '3.10.16' gem 'parallel', '1.20.0', require: false gem 'ruby-progressbar', '1.10.1', require: false # used to show progress of S3Uploader gem 'prawn-rails', '1.3.0' gem 'rack', '2.2.3' gem 'rack-brotli', '1.0.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.1' gem 'rails-observers', '0.1.5' gem 'ratom-nokogiri', '0.10.8', require: false gem 'redcarpet', '3.5.0', require: false gem 'retriable', '1.4.1' gem 'ritex', '1.0.1', require: false gem 'rotp', '6.2.0', require: false gem 'ruby-duration', '3.2.3', require: false gem 'rubycas-client', '2.3.9', require: false gem 'rubyzip', '2.3.0', require: 'zip' gem 'safe_yaml', '1.0.5', require: false gem 'saml2', '3.0.9' gem 'nokogiri-xmlsec-instructure', '0.9.7', require: false gem 'sanitize', '2.1.1', require: false gem 'sentry-raven', '2.13.0', require: false gem 'guardrail', '2.0.1' gem 'simple_oauth', '0.3.1', require: false gem 'switchman', '2.0.2' gem 'open4', '1.3.4', require: false gem 'switchman-inst-jobs', '3.1.0' gem 'twilio-ruby', '5.36.0', require: false gem 'tzinfo', '1.2.7' gem 'vault', '0.15.0', require: false gem 'vericite_api', '1.5.3' gem 'will_paginate', '3.3.0', require: false # required for folio-pagination path 'gems' do gem 'activesupport-suspend_callbacks' gem 'acts_as_list' gem 'adheres_to_policy' gem 'attachment_fu' gem 'autoextend' gem 'bookmarked_collection' gem 'broadcast_policy' gem 'canvas_breach_mitigation' gem 'canvas_color' gem 'canvas_crummy' gem 'canvas_dynamodb' gem 'canvas_ext' gem 'canvas_http' gem 'canvas_kaltura' gem 'canvas_panda_pub' gem 'canvas_partman' gem 'canvas_mimetype_fu' gem 'canvas_quiz_statistics' gem 'canvas_sanitize' gem 'canvas_slug' gem 'canvas_sort' gem 'canvas_stringex' gem 'canvas_text_helper' gem 'canvas_time' gem 'canvas_unzip' gem 'diigo' gem 'event_stream' gem 'google_drive' gem 'html_text_helper' gem 'incoming_mail_processor' gem 'json_token' gem 'linked_in' gem 'live_events' gem 'lti-advantage' gem 'lti_outbound' gem 'multipart' gem 'paginated_collection' gem 'stringify_ids' gem 'twitter' gem 'utf8_cleaner' gem 'workflow' end gem 'csv_diff', path: 'gems' gem 'sqlite3', '1.4.2' bump inst-jobs for clean abandoned jobs closes FOO-1391 flag=none TEST PLAN: 1) have abandoned job cleanup 2) it inserts successfully when you schedule it as a periodic job Change-Id: I996a508246eca0cae3d8b3a68ad3d29cad139327 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/255762 Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> QA-Review: Ethan Vizitei <73eeb0b2f65d05a906adf3b21ee1f9f5a2aa3c1c@instructure.com> Product-Review: Ethan Vizitei <73eeb0b2f65d05a906adf3b21ee1f9f5a2aa3c1c@instructure.com> Reviewed-by: Jacob Burroughs <8ecea6e385af5cf9f53123f5ca17fb5fd6a6d4b2@instructure.com> Reviewed-by: Rob Orton <7e09c9d3e96378bf549fc283fd6e1e5b7014cc33@instructure.com> # # Copyright (C) 2014 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # Note: Indented gems are meant to indicate transient dependencies of parent gems if CANVAS_RAILS5_2 gem 'rails', '5.2.4.4' gem 'loofah', '2.3.0' gem 'sprockets', '4.0.2' else gem 'rails', '6.0.3.4' end gem 'academic_benchmarks', '0.0.11', require: false gem 'active_model-better_errors', '1.6.7', require: 'active_model/better_errors' gem 'active_model_serializers', '0.9.0alpha1', github: 'rails-api/active_model_serializers', ref: '61882e1e4127facfe92e49057aec71edbe981829' gem 'addressable', '2.7.0', require: false gem 'after_transaction_commit', '2.2.1' gem 'authlogic', '6.2.0' gem 'scrypt', '3.0.7' gem 'aws-sdk-core', '3.109.2', require: false gem 'aws-partitions', '1.393.0', require: false gem 'aws-sdk-dynamodb', '1.57.0' gem 'aws-sdk-kinesis', '1.30.0', require: false gem 'aws-sdk-s3', '1.84.1', require: false gem 'aws-sdk-sns', '1.36.0', require: false gem 'aws-sdk-sqs', '1.34.0', require: false gem 'aws-sdk-kms', '1.39.0', require: false gem 'aws-sigv4', '1.2.2', require: false gem 'barby', '0.6.8', require: false gem 'rqrcode', '1.1.2', require: false gem 'chunky_png', '1.3.14', require: false gem 'bcrypt', '3.1.16' gem 'brotli', '0.2.3', require: false gem 'browser', '5.1.0', require: false gem 'builder', '3.2.4' gem 'canvas_connect', '0.3.11' gem 'adobe_connect', '1.0.8', require: false gem 'canvas_webex', '0.17' gem 'crocodoc-ruby', '0.0.1', require: false gem 'ddtrace', '0.42.0', require: false gem 'encrypted_cookie_store-instructure', '1.2.10', require: 'encrypted_cookie_store' gem 'folio-pagination', '0.0.12', require: 'folio/rails' gem 'ffi', '1.13.1', require: false gem 'gepub', '1.0.11', github: 'skoji/gepub', ref: '04c8c2542f9fa3f8d99652f9058d77c8a23c1fd9' gem 'graphql', '1.9.17' gem 'graphql-batch', '0.4.3' gem 'hashery', '2.1.2', require: false gem 'highline', '2.0.3', require: false gem 'httparty', '0.18.1' gem 'i18n', '1.8.5' gem 'i18nliner', '0.1.2' gem 'ruby2ruby', '2.4.4', require: false gem 'ruby_parser', '3.15.0', require: false gem 'icalendar', '2.7.0', require: false gem 'imperium', '0.5.2', require: false gem 'ims-lti', '2.3.0', require: 'ims' gem 'inst_statsd', '2.1.6' gem 'statsd-ruby', '1.4.0', require: false gem 'aroi', '0.0.7', require: false gem 'dogstatsd-ruby', '4.8.2' gem 'inst-jobs', '2.1.3' gem 'fugit', '1.4.0', require: false gem 'et-orbi', '1.2.4', require: false gem 'inst-jobs-autoscaling', '2.1.0' gem 'aws-sdk-autoscaling', '1.49.0', require: false gem 'inst-jobs-statsd', '2.1.0' gem 'json', '2.3.1' gem 'json_schemer', '0.2.16', github: 'robotdana/json_schemer', ref: '0d2ac359a87964f74c07a14cafeb98cfcae4e29f' gem 'json-jwt', '1.13.0', require: false gem 'link_header', '0.0.8' gem 'mail', '2.7.1', require: false gem 'mini_mime', '1.0.2', require: false gem 'marginalia', '1.9.0', require: false gem 'mime-types', '3.3.1' gem 'mini_magick', '4.11.0' gem 'multi_json', '1.15.0' gem 'net-ldap', '0.16.3', require: false gem 'nokogiri', '1.10.10', require: false gem 'oauth', '0.5.4', require: false gem 'oauth2', '1.4.4', require: false gem 'oj', '3.10.16' gem 'parallel', '1.20.0', require: false gem 'ruby-progressbar', '1.10.1', require: false # used to show progress of S3Uploader gem 'prawn-rails', '1.3.0' gem 'rack', '2.2.3' gem 'rack-brotli', '1.0.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.1' gem 'rails-observers', '0.1.5' gem 'ratom-nokogiri', '0.10.8', require: false gem 'redcarpet', '3.5.0', require: false gem 'retriable', '1.4.1' gem 'ritex', '1.0.1', require: false gem 'rotp', '6.2.0', require: false gem 'ruby-duration', '3.2.3', require: false gem 'rubycas-client', '2.3.9', require: false gem 'rubyzip', '2.3.0', require: 'zip' gem 'safe_yaml', '1.0.5', require: false gem 'saml2', '3.0.9' gem 'nokogiri-xmlsec-instructure', '0.9.7', require: false gem 'sanitize', '2.1.1', require: false gem 'sentry-raven', '2.13.0', require: false gem 'guardrail', '2.0.1' gem 'simple_oauth', '0.3.1', require: false gem 'switchman', '2.0.2' gem 'open4', '1.3.4', require: false gem 'switchman-inst-jobs', '3.1.0' gem 'twilio-ruby', '5.36.0', require: false gem 'tzinfo', '1.2.7' gem 'vault', '0.15.0', require: false gem 'vericite_api', '1.5.3' gem 'will_paginate', '3.3.0', require: false # required for folio-pagination path 'gems' do gem 'activesupport-suspend_callbacks' gem 'acts_as_list' gem 'adheres_to_policy' gem 'attachment_fu' gem 'autoextend' gem 'bookmarked_collection' gem 'broadcast_policy' gem 'canvas_breach_mitigation' gem 'canvas_color' gem 'canvas_crummy' gem 'canvas_dynamodb' gem 'canvas_ext' gem 'canvas_http' gem 'canvas_kaltura' gem 'canvas_panda_pub' gem 'canvas_partman' gem 'canvas_mimetype_fu' gem 'canvas_quiz_statistics' gem 'canvas_sanitize' gem 'canvas_slug' gem 'canvas_sort' gem 'canvas_stringex' gem 'canvas_text_helper' gem 'canvas_time' gem 'canvas_unzip' gem 'diigo' gem 'event_stream' gem 'google_drive' gem 'html_text_helper' gem 'incoming_mail_processor' gem 'json_token' gem 'linked_in' gem 'live_events' gem 'lti-advantage' gem 'lti_outbound' gem 'multipart' gem 'paginated_collection' gem 'stringify_ids' gem 'twitter' gem 'utf8_cleaner' gem 'workflow' end gem 'csv_diff', path: 'gems' gem 'sqlite3', '1.4.2'
# frozen_string_literal: true # # Copyright (C) 2014 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # Note: Indented gems are meant to indicate transient dependencies of parent gems if CANVAS_RAILS6_0 gem 'rails', '6.0.4' gem 'tzinfo', '1.2.7' gem 'switchman', '2.1.1' gem 'guardrail', '2.0.1' gem 'switchman-inst-jobs', '3.1.2' else gem 'rails', '6.1.4' gem 'tzinfo', '2.0.4' gem 'switchman', '3.0.5' gem 'guardrail', '3.0.0' gem 'switchman-inst-jobs', '4.0.0' end gem 'irb', '1.3.5' gem 'open4', '1.3.4', require: false gem 'academic_benchmarks', '1.1.1', require: false gem 'active_model-better_errors', '1.6.7', require: 'active_model/better_errors' gem 'active_model_serializers', '0.9.0alpha1', github: 'rails-api/active_model_serializers', ref: '61882e1e4127facfe92e49057aec71edbe981829' gem 'activerecord-pg-extensions', '0.2.3' gem 'addressable', '2.7.0', require: false gem 'after_transaction_commit', '2.2.2' gem 'authlogic', '6.4.1' gem 'scrypt', '3.0.7' gem 'aws-sdk-core', '3.109.2', require: false gem 'aws-partitions', '1.393.0', require: false gem 'aws-sdk-dynamodb', '1.57.0' gem 'aws-sdk-kinesis', '1.30.0', require: false gem 'aws-sdk-s3', '1.84.1', require: false gem 'aws-sdk-sns', '1.36.0', require: false gem 'aws-sdk-sqs', '1.34.0', require: false gem 'aws-sdk-kms', '1.39.0', require: false gem 'aws-sigv4', '1.2.2', require: false gem 'barby', '0.6.8', require: false gem 'rqrcode', '1.2.0', require: false gem 'chunky_png', '1.3.14', require: false gem 'bcrypt', '3.1.16' gem 'brotli', '0.2.3', require: false gem 'browser', '5.1.0', require: false gem 'builder', '3.2.4' gem 'canvas_connect', '0.3.11' gem 'adobe_connect', '1.0.9', require: false gem 'canvas_webex', '0.17' gem 'crocodoc-ruby', '0.0.1', require: false gem 'ddtrace', '0.42.0', require: false gem 'encrypted_cookie_store-instructure', '1.2.11', require: 'encrypted_cookie_store' gem 'folio-pagination', '0.0.12', require: 'folio/rails' gem 'ffi', '1.13.1', require: false gem 'gepub', '1.0.13' gem 'apollo-federation', '1.1.5' gem 'graphql', '1.9.17' gem 'graphql-batch', '0.4.3' gem 'hashery', '2.1.2', require: false gem 'highline', '2.0.3', require: false gem 'httparty', '0.18.1' gem 'i18n', '1.8.5' gem 'i18nliner', '0.1.2' gem 'ruby2ruby', '2.4.4', require: false gem 'ruby_parser', '3.15.0', require: false gem 'icalendar', '2.7.0', require: false gem 'diplomat', '2.5.1', require: false gem 'ims-lti', '2.3.0', require: 'ims' gem 'inst_statsd', '2.1.6' gem 'statsd-ruby', '1.4.0', require: false gem 'aroi', '0.0.7', require: false gem 'dogstatsd-ruby', '4.8.2' gem 'inst-jobs', '2.3.1' gem 'fugit', '1.4.0', require: false gem 'et-orbi', '1.2.4', require: false gem 'inst-jobs-autoscaling', '2.1.0' gem 'aws-sdk-autoscaling', '1.49.0', require: false gem 'inst-jobs-statsd', '2.1.0' # if updating json gem it will need to be hotfixed because if a newer version of # the json gem is installed, it will always use that one even before bundler # gets activated. Updating the gem in it's own commit will make this easier. gem 'json', '2.5.1' gem 'json_schemer', '0.2.16', github: 'robotdana/json_schemer', ref: '0d2ac359a87964f74c07a14cafeb98cfcae4e29f' gem 'ecma-re-validator', '0.2.1' gem 'json-jwt', '1.13.0', require: false gem 'link_header', '0.0.8' gem 'mail', '2.7.1', require: false gem 'mini_mime', '1.0.2', require: false gem 'marginalia', '1.9.0', require: false gem 'mime-types', '3.3.1' gem 'mini_magick', '4.11.0' gem 'multi_json', '1.15.0' gem 'net-ldap', '0.16.3', require: false gem 'nokogiri', '1.11.5', require: false gem 'nokogumbo', '2.0.4' gem 'oauth', '0.5.4', require: false gem 'oauth2', '1.4.4', require: false gem 'oj', '3.10.16' gem 'outrigger', '2.1.1' gem 'parallel', '1.20.0', require: false gem 'ruby-progressbar', '1.10.1', require: false # used to show progress of S3Uploader gem 'prawn-rails', '1.3.0' gem 'rack', '2.2.3' gem 'rack-brotli', '1.0.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.3' gem 'rails-observers', '0.1.5' gem 'ratom-nokogiri', '0.10.10', require: false gem 'redcarpet', '3.5.0', require: false gem 'retriable', '1.4.1' gem 'ritex', '1.0.1', require: false gem 'rotp', '6.2.0', require: false gem 'ruby-duration', '3.2.3', require: false gem 'ruby2_keywords', '0.0.3' gem 'rubycas-client', '2.3.9', require: false gem 'rubyzip', '2.3.0', require: 'zip' gem 'safe_yaml', '1.0.5', require: false gem 'saml2', '3.0.11' gem 'nokogiri-xmlsec-instructure', '0.10.1', require: false gem 'sanitize', '5.2.3', require: false gem 'sentry-raven', '2.13.0', require: false gem 'simple_oauth', '0.3.1', require: false gem 'twilio-ruby', '5.36.0', require: false gem 'vault', '0.15.0', require: false gem 'vericite_api', '1.5.3' gem 'week_of_month', '1.2.5', github: 'instructure/week-of-month', ref: 'b3013639e9474f302b5a6f27e4e45313e8d24902' gem 'will_paginate', '3.3.0', require: false # required for folio-pagination # needs pin to satisfy varying requirements of google_drive and another gem gem 'faraday', '0.17.4' gem 'faraday_middleware', '0.14.0' path 'engines' do gem 'audits' end path 'gems' do gem 'activesupport-suspend_callbacks' gem 'acts_as_list' gem 'adheres_to_policy' gem 'attachment_fu' gem 'autoextend' gem 'bookmarked_collection' gem 'broadcast_policy' gem 'canvas_breach_mitigation' gem 'canvas_cache' gem 'canvas_color' gem 'canvas_crummy' gem 'canvas_dynamodb' gem 'canvas_errors' gem 'canvas_ext' gem 'canvas_http' gem 'canvas_kaltura' gem 'canvas_panda_pub' gem 'canvas_partman' gem 'canvas_mimetype_fu' gem 'canvas_quiz_statistics' gem 'canvas_sanitize' gem 'canvas_security' gem 'canvas_slug' gem 'canvas_sort' gem 'canvas_stringex' gem 'canvas_text_helper' gem 'canvas_time' gem 'canvas_unzip' gem 'config_file' gem 'diigo' gem 'dynamic_settings' gem 'event_stream' gem 'google_drive' gem 'html_text_helper' gem 'incoming_mail_processor' gem 'json_token' gem 'linked_in' gem 'live_events' gem 'lti-advantage' gem 'lti_outbound' gem 'multipart' gem 'paginated_collection' gem 'request_context' gem 'stringify_ids' gem 'twitter' gem 'utf8_cleaner' gem 'workflow' end gem 'csv_diff', path: 'gems' gem 'sqlite3', '1.4.2' bump inst-jobs for resource leak fix Change-Id: I9154905f577f723e811689c7f68e00d2dc91068e Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/269397 Reviewed-by: Simon Williams <088e16a1019277b15d58faf0541e11910eb756f6@instructure.com> Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> QA-Review: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com> Product-Review: Cody Cutrer <c4fe2b1d90ef8f2548c8aeabfa633434316f0305@instructure.com> # frozen_string_literal: true # # Copyright (C) 2014 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas 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, version 3 of the License. # # Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. # Note: Indented gems are meant to indicate transient dependencies of parent gems if CANVAS_RAILS6_0 gem 'rails', '6.0.4' gem 'tzinfo', '1.2.7' gem 'switchman', '2.1.1' gem 'guardrail', '2.0.1' gem 'switchman-inst-jobs', '3.1.2' else gem 'rails', '6.1.4' gem 'tzinfo', '2.0.4' gem 'switchman', '3.0.5' gem 'guardrail', '3.0.0' gem 'switchman-inst-jobs', '4.0.0' end gem 'irb', '1.3.5' gem 'open4', '1.3.4', require: false gem 'academic_benchmarks', '1.1.1', require: false gem 'active_model-better_errors', '1.6.7', require: 'active_model/better_errors' gem 'active_model_serializers', '0.9.0alpha1', github: 'rails-api/active_model_serializers', ref: '61882e1e4127facfe92e49057aec71edbe981829' gem 'activerecord-pg-extensions', '0.2.3' gem 'addressable', '2.7.0', require: false gem 'after_transaction_commit', '2.2.2' gem 'authlogic', '6.4.1' gem 'scrypt', '3.0.7' gem 'aws-sdk-core', '3.109.2', require: false gem 'aws-partitions', '1.393.0', require: false gem 'aws-sdk-dynamodb', '1.57.0' gem 'aws-sdk-kinesis', '1.30.0', require: false gem 'aws-sdk-s3', '1.84.1', require: false gem 'aws-sdk-sns', '1.36.0', require: false gem 'aws-sdk-sqs', '1.34.0', require: false gem 'aws-sdk-kms', '1.39.0', require: false gem 'aws-sigv4', '1.2.2', require: false gem 'barby', '0.6.8', require: false gem 'rqrcode', '1.2.0', require: false gem 'chunky_png', '1.3.14', require: false gem 'bcrypt', '3.1.16' gem 'brotli', '0.2.3', require: false gem 'browser', '5.1.0', require: false gem 'builder', '3.2.4' gem 'canvas_connect', '0.3.11' gem 'adobe_connect', '1.0.9', require: false gem 'canvas_webex', '0.17' gem 'crocodoc-ruby', '0.0.1', require: false gem 'ddtrace', '0.42.0', require: false gem 'encrypted_cookie_store-instructure', '1.2.11', require: 'encrypted_cookie_store' gem 'folio-pagination', '0.0.12', require: 'folio/rails' gem 'ffi', '1.13.1', require: false gem 'gepub', '1.0.13' gem 'apollo-federation', '1.1.5' gem 'graphql', '1.9.17' gem 'graphql-batch', '0.4.3' gem 'hashery', '2.1.2', require: false gem 'highline', '2.0.3', require: false gem 'httparty', '0.18.1' gem 'i18n', '1.8.5' gem 'i18nliner', '0.1.2' gem 'ruby2ruby', '2.4.4', require: false gem 'ruby_parser', '3.15.0', require: false gem 'icalendar', '2.7.0', require: false gem 'diplomat', '2.5.1', require: false gem 'ims-lti', '2.3.0', require: 'ims' gem 'inst_statsd', '2.1.6' gem 'statsd-ruby', '1.4.0', require: false gem 'aroi', '0.0.7', require: false gem 'dogstatsd-ruby', '4.8.2' gem 'inst-jobs', '2.3.2' gem 'fugit', '1.4.0', require: false gem 'et-orbi', '1.2.4', require: false gem 'inst-jobs-autoscaling', '2.1.0' gem 'aws-sdk-autoscaling', '1.49.0', require: false gem 'inst-jobs-statsd', '2.1.0' # if updating json gem it will need to be hotfixed because if a newer version of # the json gem is installed, it will always use that one even before bundler # gets activated. Updating the gem in it's own commit will make this easier. gem 'json', '2.5.1' gem 'json_schemer', '0.2.16', github: 'robotdana/json_schemer', ref: '0d2ac359a87964f74c07a14cafeb98cfcae4e29f' gem 'ecma-re-validator', '0.2.1' gem 'json-jwt', '1.13.0', require: false gem 'link_header', '0.0.8' gem 'mail', '2.7.1', require: false gem 'mini_mime', '1.0.2', require: false gem 'marginalia', '1.9.0', require: false gem 'mime-types', '3.3.1' gem 'mini_magick', '4.11.0' gem 'multi_json', '1.15.0' gem 'net-ldap', '0.16.3', require: false gem 'nokogiri', '1.11.5', require: false gem 'nokogumbo', '2.0.4' gem 'oauth', '0.5.4', require: false gem 'oauth2', '1.4.4', require: false gem 'oj', '3.10.16' gem 'outrigger', '2.1.1' gem 'parallel', '1.20.0', require: false gem 'ruby-progressbar', '1.10.1', require: false # used to show progress of S3Uploader gem 'prawn-rails', '1.3.0' gem 'rack', '2.2.3' gem 'rack-brotli', '1.0.0' gem 'rack-test', '1.1.0' gem 'rake', '13.0.3' gem 'rails-observers', '0.1.5' gem 'ratom-nokogiri', '0.10.10', require: false gem 'redcarpet', '3.5.0', require: false gem 'retriable', '1.4.1' gem 'ritex', '1.0.1', require: false gem 'rotp', '6.2.0', require: false gem 'ruby-duration', '3.2.3', require: false gem 'ruby2_keywords', '0.0.3' gem 'rubycas-client', '2.3.9', require: false gem 'rubyzip', '2.3.0', require: 'zip' gem 'safe_yaml', '1.0.5', require: false gem 'saml2', '3.0.11' gem 'nokogiri-xmlsec-instructure', '0.10.1', require: false gem 'sanitize', '5.2.3', require: false gem 'sentry-raven', '2.13.0', require: false gem 'simple_oauth', '0.3.1', require: false gem 'twilio-ruby', '5.36.0', require: false gem 'vault', '0.15.0', require: false gem 'vericite_api', '1.5.3' gem 'week_of_month', '1.2.5', github: 'instructure/week-of-month', ref: 'b3013639e9474f302b5a6f27e4e45313e8d24902' gem 'will_paginate', '3.3.0', require: false # required for folio-pagination # needs pin to satisfy varying requirements of google_drive and another gem gem 'faraday', '0.17.4' gem 'faraday_middleware', '0.14.0' path 'engines' do gem 'audits' end path 'gems' do gem 'activesupport-suspend_callbacks' gem 'acts_as_list' gem 'adheres_to_policy' gem 'attachment_fu' gem 'autoextend' gem 'bookmarked_collection' gem 'broadcast_policy' gem 'canvas_breach_mitigation' gem 'canvas_cache' gem 'canvas_color' gem 'canvas_crummy' gem 'canvas_dynamodb' gem 'canvas_errors' gem 'canvas_ext' gem 'canvas_http' gem 'canvas_kaltura' gem 'canvas_panda_pub' gem 'canvas_partman' gem 'canvas_mimetype_fu' gem 'canvas_quiz_statistics' gem 'canvas_sanitize' gem 'canvas_security' gem 'canvas_slug' gem 'canvas_sort' gem 'canvas_stringex' gem 'canvas_text_helper' gem 'canvas_time' gem 'canvas_unzip' gem 'config_file' gem 'diigo' gem 'dynamic_settings' gem 'event_stream' gem 'google_drive' gem 'html_text_helper' gem 'incoming_mail_processor' gem 'json_token' gem 'linked_in' gem 'live_events' gem 'lti-advantage' gem 'lti_outbound' gem 'multipart' gem 'paginated_collection' gem 'request_context' gem 'stringify_ids' gem 'twitter' gem 'utf8_cleaner' gem 'workflow' end gem 'csv_diff', path: 'gems' gem 'sqlite3', '1.4.2'
Pod::Spec.new do |s| s.name = 'Geometry' s.version = '3.0.0' s.license = 'MIT' s.summary = 'Geometry is a UIView and CGRect extension that lets you work with view and rect geometry easier.' s.homepage = 'https://github.com/artman/Geometry' s.social_media_url = 'http://twitter.com/artman' s.authors = { 'Tuomas Artman' => 'tuomas@artman.fi' } s.source = { :git => 'https://github.com/artman/Geometry.git', :tag => s.version } s.ios.deployment_target = '8.0' s.source_files = 'Geometry/*.swift' s.requires_arc = true end Adds tvOS support to podspec Pod::Spec.new do |s| s.name = 'Geometry' s.version = '3.0.0' s.license = 'MIT' s.summary = 'Geometry is a UIView and CGRect extension that lets you work with view and rect geometry easier.' s.homepage = 'https://github.com/artman/Geometry' s.social_media_url = 'http://twitter.com/artman' s.authors = { 'Tuomas Artman' => 'tuomas@artman.fi' } s.source = { :git => 'https://github.com/artman/Geometry.git', :tag => s.version } s.ios.deployment_target = '8.0' s.tvos.deployment_target = '9.0' s.source_files = 'Geometry/*.swift' s.requires_arc = true end
FactoryGirl.define do factory :billing_expense do volunteer user amount 50 end end fix billing expenses factory FactoryGirl.define do factory :billing_expense do volunteer hours do |hour| hour.association(:hour) end user end end
class ApplicationMailer < ActionMailer::Base default from: ENV['MAILGUN_FROM_EMAIL'] layout 'mailer' end Add roadie to inline CSS for emails class ApplicationMailer < ActionMailer::Base include Roadie::Rails::Automatic default from: ENV['MAILGUN_FROM_EMAIL'] layout 'mailer' end
# = CacheLookupsMixin # # A mixin that provides simple caching for ActiveRecord models. It's best used # for models that have relatively few records (less than a thousand) and are # updated infrequently (less than once per second). # # == Example of usage # # Setup lookups for Thing: # # class Thing < ActiveRecord::Base # cache_lookups_for :id, :order => :created_at # ... # end # # Return array of things in the order they were created: # things = Thing.lookup # # Return a particular Thing matching ID 66: # thing = Thing.lookup(66) module CacheLookupsMixin def self.included(mixee) mixee.send(:extend, ClassMethods) mixee.class_eval do # ActiveRecord model's attribute to use when asked to lookup a specific # item. Defaults to :id. cattr_accessor :lookup_key self.lookup_key = :id # Hash of options passed to ActiveRecord::Base.find when populating the # cache. This makes it possible to add :order and filter by :condition. cattr_accessor :lookup_opts self.lookup_opts = {} end end module ClassMethods # Setup the lookup caching system. # # Arguments: # * key: The attribute you'll use as a key for doing lookups. # * opts: Options to pass to ActiveRecord::Base.find. def cache_lookups_for(key, opts={}) self.lookup_key = key self.lookup_opts = opts end def lookup_silo_name return "#{self.name.tableize}_dict" end # Return instance from cache matching +key+. If +key+ is undefined, returns # array of all instances. def lookup(key=nil) silo = self.lookup_silo_name dict = nil ActiveRecord::Base.benchmark("Lookup: #{silo}#{key.ergo{'#'+to_s}}") do dict = self.fetch_object(silo){ # FIXME Exceptions within this block are silently swallowed by something. This is bad. self.find(:all, self.lookup_opts).inject(Dictionary.new){|s,v| s[v.send(self.lookup_key)] = v; s} } end return key ? dict[key.with{kind_of?(Symbol) ? to_s : self}] : (dict.values || []) end def expire_cache Rails.logger.info("Lookup, expiring: #{self.name}") Observist.expire(/#{lookup_silo_name}_.+/) end def fetch_object(silo, &block) self.revive_associations_for(self) method = Rails.cache.respond_to?(:fetch_object) ? :fetch_object : :fetch return Rails.cache.send(method, silo, &block) end def revive_associations_for(object) if object.kind_of?(ActiveRecord::Base) || object.ancestors.include?(ActiveRecord::Base) object.reflect_on_all_associations.each do |association| name = association.class_name unless object.constants.include?(name) name.constantize # This line forces Rails to load this class end end end end end end Improved CacheLookupsMixin::lookup_silo_name, eliminated expensive tableize calls. # = CacheLookupsMixin # # A mixin that provides simple caching for ActiveRecord models. It's best used # for models that have relatively few records (less than a thousand) and are # updated infrequently (less than once per second). # # == Example of usage # # Setup lookups for Thing: # # class Thing < ActiveRecord::Base # cache_lookups_for :id, :order => :created_at # ... # end # # Return array of things in the order they were created: # things = Thing.lookup # # Return a particular Thing matching ID 66: # thing = Thing.lookup(66) module CacheLookupsMixin def self.included(mixee) mixee.send(:extend, ClassMethods) mixee.class_eval do # ActiveRecord model's attribute to use when asked to lookup a specific # item. Defaults to :id. cattr_accessor :lookup_key self.lookup_key = :id # Hash of options passed to ActiveRecord::Base.find when populating the # cache. This makes it possible to add :order and filter by :condition. cattr_accessor :lookup_opts self.lookup_opts = {} end end module ClassMethods # Setup the lookup caching system. # # Arguments: # * key: The attribute you'll use as a key for doing lookups. # * opts: Options to pass to ActiveRecord::Base.find. def cache_lookups_for(key, opts={}) self.lookup_key = key self.lookup_opts = opts end # Return silo that this class's values will be stored in. def lookup_silo_name return "#{self.name.gsub('::', '__')}_dict" end # Return instance from cache matching +key+. If +key+ is undefined, returns # array of all instances. def lookup(key=nil) silo = self.lookup_silo_name dict = nil ActiveRecord::Base.benchmark("Lookup: #{silo}#{key.ergo{'#'+to_s}}") do dict = self.fetch_object(silo){ # FIXME Exceptions within this block are silently swallowed by something. This is bad. self.find(:all, self.lookup_opts).inject(Dictionary.new){|s,v| s[v.send(self.lookup_key)] = v; s} } end return key ? dict[key.with{kind_of?(Symbol) ? to_s : self}] : (dict.values || []) end def expire_cache Rails.logger.info("Lookup, expiring: #{self.name}") Observist.expire(/#{lookup_silo_name}_.+/) end def fetch_object(silo, &block) self.revive_associations_for(self) method = Rails.cache.respond_to?(:fetch_object) ? :fetch_object : :fetch return Rails.cache.send(method, silo, &block) end def revive_associations_for(object) if object.kind_of?(ActiveRecord::Base) || object.ancestors.include?(ActiveRecord::Base) object.reflect_on_all_associations.each do |association| name = association.class_name unless object.constants.include?(name) name.constantize # This line forces Rails to load this class end end end end end end
# = Informations # # == License # # Ekylibre - Simple agricultural ERP # Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon # Copyright (C) 2010-2012 Brice Texier # Copyright (C) 2012-2016 Brice Texier, David Joulin # # This program 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 # any later version. # # This program 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 this program. If not, see http://www.gnu.org/licenses. # # == Table: activity_productions # # activity_id :integer not null # campaign_id :integer # created_at :datetime not null # creator_id :integer # cultivable_zone_id :integer # custom_fields :jsonb # id :integer not null, primary key # irrigated :boolean default(FALSE), not null # lock_version :integer default(0), not null # nitrate_fixing :boolean default(FALSE), not null # rank_number :integer not null # size_indicator_name :string not null # size_unit_name :string # size_value :decimal(19, 4) not null # started_on :date # state :string # stopped_on :date # support_id :integer not null # support_nature :string # support_shape :geometry({:srid=>4326, :type=>"multi_polygon"}) # updated_at :datetime not null # updater_id :integer # usage :string not null # class ActivityProduction < Ekylibre::Record::Base include Customizable enumerize :support_nature, in: [:cultivation, :fallow_land, :buffer, :border, :none], default: :cultivation refers_to :usage, class_name: 'ProductionUsage' refers_to :size_indicator, class_name: 'Indicator' refers_to :size_unit, class_name: 'Unit' belongs_to :activity, inverse_of: :productions belongs_to :campaign belongs_to :cultivable_zone belongs_to :support, class_name: 'Product' # , inverse_of: :supports has_many :distributions, class_name: 'TargetDistribution', inverse_of: :activity_production has_many :budgets, through: :activity has_many :manure_management_plan_zones, class_name: 'ManureManagementPlanZone', inverse_of: :activity_production has_one :selected_manure_management_plan_zone, -> { selecteds }, class_name: 'ManureManagementPlanZone', inverse_of: :activity_production has_one :cap_land_parcel, class_name: 'CapLandParcel', inverse_of: :activity_production, foreign_key: :support_id has_geometry :support_shape composed_of :size, class_name: 'Measure', mapping: [%w(size_value to_d), %w(size_unit_name unit)] # [VALIDATORS[ Do not edit these lines directly. Use `rake clean:validations`. validates_date :started_on, :stopped_on, allow_blank: true, before: Date.today + 30.years validates_numericality_of :rank_number, allow_nil: true, only_integer: true validates_numericality_of :size_value, allow_nil: true validates_inclusion_of :irrigated, :nitrate_fixing, in: [true, false] validates_presence_of :activity, :rank_number, :size_indicator_name, :size_value, :support, :usage # ]VALIDATORS] validates_uniqueness_of :rank_number, scope: :activity_id validates_presence_of :started_on # validates_presence_of :cultivable_zone, :support_nature, if: :plant_farming? validates_presence_of :support_nature, if: :plant_farming? validates_presence_of :campaign, :stopped_on, if: :annual? validates_presence_of :started_on # validates_numericality_of :size_value, greater_than: 0 # validates_presence_of :size_unit, if: :size_value? delegate :name, :work_number, to: :support, prefix: true # delegate :shape, :shape_to_ewkt, :shape_svg, :net_surface_area, :shape_area, to: :support delegate :name, :size_indicator_name, :size_unit_name, to: :activity, prefix: true delegate :animal_farming?, :plant_farming?, :at_cycle_start?, :at_cycle_end?, :with_cultivation, :cultivation_variety, :with_supports, :support_variety, :color, :annual?, :perennial?, to: :activity scope :of_campaign, lambda { |campaign| where('campaign_id = ?' \ ' OR campaign_id IS NULL AND (' \ "activity_productions.id IN (SELECT ap.id FROM activity_productions AS ap JOIN activities AS a ON a.id = ap.activity_id, campaigns AS c WHERE a.production_cycle = 'perennial' AND a.production_campaign = 'at_cycle_start' AND c.id = ? AND ((ap.stopped_on is null AND c.harvest_year >= EXTRACT(YEAR FROM ap.started_on)) OR (ap.stopped_on is not null AND EXTRACT(YEAR FROM ap.started_on) <= c.harvest_year AND c.harvest_year < EXTRACT(YEAR FROM ap.stopped_on))))" \ " OR activity_productions.id IN (SELECT ap.id FROM activity_productions AS ap JOIN activities AS a ON a.id = ap.activity_id, campaigns AS c WHERE a.production_cycle = 'perennial' AND a.production_campaign = 'at_cycle_end' AND c.id = ? AND ((ap.stopped_on is null AND c.harvest_year > EXTRACT(YEAR FROM ap.started_on)) OR (ap.stopped_on is not null AND EXTRACT(YEAR FROM ap.started_on) < c.harvest_year AND c.harvest_year <= EXTRACT(YEAR FROM ap.stopped_on))))" \ ')', campaign.id, campaign.id, campaign.id) } scope :of_cultivation_variety, lambda { |variety| where(activity: Activity.of_cultivation_variety(variety)) } scope :of_current_campaigns, -> { of_campaign(Campaign.current.last) } scope :of_activity, ->(activity) { where(activity: activity) } scope :of_activities, lambda { |*activities| where(activity_id: activities.flatten.map(&:id)) } scope :of_activity_families, lambda { |*families| where(activity: Activity.of_families(*families)) } scope :current, -> { where(':now BETWEEN COALESCE(started_on, :now) AND COALESCE(stopped_on, :now)', now: Time.zone.now) } state_machine :state, initial: :opened do state :opened state :aborted state :closed event :abort do transition opened: :aborted end event :close do transition opened: :closed end event :reopen do transition closed: :opened transition aborted: :opened end end before_validation on: :create do if self.activity self.rank_number = (self.activity.productions.maximum(:rank_number) ? self.activity.productions.maximum(:rank_number) : 0) + 1 end end before_validation do self.started_on ||= Date.today self.usage = Nomen::ProductionUsage.first unless usage if self.activity self.stopped_on ||= self.started_on + 1.year - 1.day if annual? self.size_indicator_name ||= activity_size_indicator_name if activity_size_indicator_name self.size_unit_name = activity_size_unit_name self.rank_number ||= (self.activity.productions.maximum(:rank_number) ? self.activity.productions.maximum(:rank_number) : 0) + 1 if plant_farming? self.support_shape ||= cultivable_zone.shape if cultivable_zone if support_shape && !support land_parcels = LandParcel.shape_matching(support_shape) .where.not(id: ActivityProduction.select(:support_id)) .order(:id) self.support = land_parcels.any? ? land_parcels.first : LandParcel.new support.name = computed_support_name support.initial_shape = support_shape support.initial_born_at = started_on support.variant = ProductNatureVariant.import_from_nomenclature(:land_parcel) support.save! end self.size = support_shape_area.in(size_unit_name) elsif animal_farming? unless support self.support = AnimalGroup.new support.name = computed_support_name # FIXME: Need to find better category and population_counting... nature = ProductNature.find_or_create_by!(variety: :animal_group, derivative_of: :animal, name: AnimalGroup.model_name.human, category: ProductNatureCategory.import_from_nomenclature(:cattle_herd), population_counting: :unitary) variant = ProductNatureVariant.find_or_initialize_by(nature: nature, variety: :animal_group, derivative_of: :animal) variant.name ||= nature.name variant.unit_name ||= :unit.tl variant.save! if variant.new_record? support.variant = variant support.derivative_of = self.activity.cultivation_variety support.save! end if size_value.nil? errors.add(:size_value, :empty) else self.size = size_value.in(size_unit_name) end end end end before_validation(on: :create) do self.state ||= :opened end validate do if plant_farming? errors.add(:support_shape, :empty) if self.support_shape && self.support_shape.empty? end end before_update do # self.support.name = computed_support_name support.initial_born_at = started_on if old_record.support_shape != self.support_shape support.initial_shape = support_shape if self.support_shape # TODO: Update only very first shape reading support.read!(:shape, self.support_shape, at: started_on) end end support.save! end after_commit do if self.activity.productions.where(rank_number: rank_number).count > 1 update_column(:rank_number, self.activity.productions.maximum(:rank_number) + 1) end Ekylibre::Hook.publish(:activity_production_change, activity_production_id: id) end after_destroy do Ekylibre::Hook.publish(:activity_production_change, activity_production_id: id) end def computed_support_name list = [] list << cultivable_zone.name if cultivable_zone list << activity.name list << campaign.name if campaign list << :rank.t(number: rank_number) list.reverse! if 'i18n.dir'.t == 'rtl' list.join(' ') end def update_names if support new_support_name = computed_support_name if support.name != new_support_name support.update_column(:name, new_support_name) end end end def active? activity.family.to_s != 'fallow_land' end # Returns interventions of current production def interventions Intervention.of_activity_production(self) end def campaigns Campaign.of_activity_production(self) end def started_on_for(campaign) return self.started_on if annual? on = begin Date.civil(campaign.harvest_year, self.started_on.month, self.started_on.day) rescue Date.civil(campaign.harvest_year, self.started_on.month, self.started_on.day - 1) end on -= 1.year if at_cycle_end? on end def stopped_on_for(campaign) return stopped_on if annual? on = Date.civil(campaign.harvest_year, self.started_on.month, self.started_on.day) - 1 on += 1.year if at_cycle_start? on end # Used for find current campaign for given production def current_campaign Campaign.at(Time.zone.now).first end def cost(role = :input) costs = interventions.collect do |intervention| intervention.cost(role) end costs.compact.sum end # Returns the spreaded quantity of one chemicals components (N, P, K) per area unit # Get all intervention of category 'fertilizing' and sum all indicator unity spreaded # - indicator could be (:potassium_concentration, :nitrogen_concentration, :phosphorus_concentration) # - area_unit could be (:hectare, :square_meter) # - from and to used to select intervention def soil_enrichment_indicator_content_per_area(indicator_name, from = nil, to = nil, area_unit_name = :hectare) balance = [] procedure_category = :fertilizing interventions = if from && to self.interventions.real.of_category(procedure_category).between(from, to) else self.interventions.real.of_category(procedure_category) end interventions.each do |intervention| intervention.inputs.each do |input| # m = net_mass of the input at intervention time # n = indicator (in %) of the input at intervention time m = (input.actor ? input.actor.net_mass(input).to_d(:kilogram) : 0.0) # TODO: for method phosphorus_concentration(input) n = (input.actor ? input.actor.send(indicator_name).to_d(:unity) : 0.0) balance << m * n end end # if net_surface_area, make the division area = net_surface_area.to_d(area_unit_name) indicator_unity_per_hectare = balance.compact.sum / area if area != 0 indicator_unity_per_hectare end # TODO: for nitrogen balance but will be refactorize for any chemical components def nitrogen_balance # B = O - I balance = 0.0 nitrogen_mass = [] nitrogen_unity_per_hectare = nil if selected_manure_management_plan_zone # get the output O aka nitrogen_input from opened_at (in kg N / Ha ) o = selected_manure_management_plan_zone.nitrogen_input || 0.0 # get the nitrogen input I from opened_at to now (in kg N / Ha ) opened_at = selected_manure_management_plan_zone.opened_at i = soil_enrichment_indicator_content_per_area(:nitrogen_concentration, opened_at, Time.zone.now) balance = o - i if i && o else balance = soil_enrichment_indicator_content_per_area(:nitrogen_concentration) end balance end def potassium_balance soil_enrichment_indicator_content_per_area(:potassium_concentration) end def phosphorus_balance soil_enrichment_indicator_content_per_area(:phosphorus_concentration) end def provisional_nitrogen_input 0 end def tool_cost(surface_unit_name = :hectare) if net_surface_area.to_s.to_f > 0.0 return cost(:tool) / net_surface_area.to_d(surface_unit_name).to_s.to_f end 0.0 end def input_cost(surface_unit_name = :hectare) if net_surface_area.to_s.to_f > 0.0 return cost(:input) / net_surface_area.to_d(surface_unit_name).to_s.to_f end 0.0 end def time_cost(surface_unit_name = :hectare) if net_surface_area.to_s.to_f > 0.0 return cost(:doer) / net_surface_area.to_d(surface_unit_name).to_s.to_f end 0.0 end # Returns all plants concerning by this activity production # TODO: No plant here, a more generic method should be largely preferable def inside_plants inside_products(Plant) end def inside_products(products = Product) products = if campaign products.of_campaign(campaign) else products.where(born_at: started_on..(stopped_on || Time.zone.now.to_date)) end products.shape_within(support_shape) end # Returns the started_at attribute of the intervention of nature sowing if # exist and if it's a vegetal activity def implanted_at intervention = interventions.real.of_category(:planting).first return intervention.started_at if intervention nil end # Returns the started_at attribute of the intervention of nature harvesting # if exist and if it's a vegetal activity def harvested_at intervention = interventions.real.of_category(:harvesting).first return intervention.started_at if intervention nil end # Generic method to get harvest yield def harvest_yield(harvest_variety, options = {}) size_indicator_name = options[:size_indicator_name] || :net_mass ind = Nomen::Indicator.find(size_indicator_name) raise "Invalid indicator: #{size_indicator_name}" unless ind size_unit_name = options[:size_unit_name] || ind.unit unless Nomen::Unit.find(size_unit_name) raise "Invalid indicator unit: #{size_unit_name.inspect}" end surface_unit_name = options[:surface_unit_name] || :hectare procedure_category = options[:procedure_category] || :harvesting unless net_surface_area && net_surface_area.to_d > 0 Rails.logger.warn 'No surface area. Cannot compute harvest yield' return nil end harvest_yield_unit_name = "#{size_unit_name}_per_#{surface_unit_name}".to_sym unless Nomen::Unit.find(harvest_yield_unit_name) raise "Harvest yield unit doesn't exist: #{harvest_yield_unit_name.inspect}" end total_quantity = 0.0.in(size_unit_name) # harvest_interventions = interventions.real.of_category(procedure_category).with_targets(inside_plants) harvest_interventions = Intervention.real.of_category(procedure_category).with_targets(inside_plants) if harvest_interventions.any? harvest_interventions.find_each do |harvest| harvest.outputs.each do |cast| actor = cast.product next unless actor && actor.variety variety = Nomen::Variety.find(actor.variety) if variety && variety <= harvest_variety quantity = cast.quantity_population.in(actor.variant.send(size_indicator_name).unit) total_quantity += quantity.convert(size_unit_name) if quantity end end end end harvest_yield = total_quantity.to_f / net_surface_area.to_d(surface_unit_name).to_f Measure.new(harvest_yield, harvest_yield_unit_name) end # Returns the yield of grain in mass per surface unit def grains_yield(mass_unit_name = :quintal, surface_unit_name = :hectare) harvest_yield(:grain, procedure_category: :harvesting, size_indicator_name: :net_mass, size_unit_name: mass_unit_name, surface_unit_name: surface_unit_name) end # Returns the yield of grape in volume per surface unit def vine_yield(volume_unit_name = :hectoliter, surface_unit_name = :hectare) harvest_yield(:grape, procedure_category: :harvesting, size_indicator_name: :net_volume, size_unit_name: volume_unit_name, surface_unit_name: surface_unit_name) end # call method in production for instance def estimate_yield(options = {}) raise 'Not possible anymore' production.estimate_yield(options) end def current_cultivation # get the first object with variety 'plant', availables if cultivation = support.contents.where(type: Plant).of_variety(variant.variety).availables.reorder(:born_at).first return cultivation else return nil end end def unified_size_unit size_unit_name.blank? ? :unity : size_unit_name end # Compute quantity of a support as defined in production def current_size(options = {}) options[:at] ||= self.started_on ? self.started_on.to_time : Time.zone.now value = support.get(size_indicator_name, options) value = value.in(size_unit_name) unless size_unit_name.blank? value end def duplicate!(updates = {}) new_attributes = [ :activity, :campaign, :cultivable_zone, :irrigated, :nitrate_fixing, :size_indicator_name, :size_unit_name, :size_value, :started_on, :support_nature, :support_shape, :usage].each_with_object({}) do |attr, h| h[attr] = send(attr) h end.merge(updates) self.class.create!(new_attributes) end alias net_surface_area support_shape_area ## LABEL METHODS ## def work_name "#{support_work_number} - #{net_surface_area.convert(:hectare).round(2)}" end # Returns unique i18nized name for given production def name(options = {}) list = [] list << activity.name unless options[:activity].is_a?(FalseClass) list << cultivable_zone.name if cultivable_zone v = Nomen::Variety.find(cultivation_variety) list << v.human_name if v && !(activity.name.start_with?(v.human_name) || activity.name.end_with?(v.human_name)) # list << support.name if !options[:support].is_a?(FalseClass) && support list << started_on.to_date.l(format: :month) if started_on list << :rank.t(number: rank_number) list = list.reverse! if 'i18n.dir'.t == 'rtl' list.join(' ') end def get(*args) unless support.present? raise StandardError, "No support defined. Got: #{support.inspect}" end support.get(*args) end # # Returns value of an indicator if its name correspond to # def method_missing(method_name, *args) # if Nomen::Indicator.include?(method_name.to_s) # return get(method_name, *args) # end # super # end end Renames AP destruction notif name # = Informations # # == License # # Ekylibre - Simple agricultural ERP # Copyright (C) 2008-2009 Brice Texier, Thibaud Merigon # Copyright (C) 2010-2012 Brice Texier # Copyright (C) 2012-2016 Brice Texier, David Joulin # # This program 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 # any later version. # # This program 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 this program. If not, see http://www.gnu.org/licenses. # # == Table: activity_productions # # activity_id :integer not null # campaign_id :integer # created_at :datetime not null # creator_id :integer # cultivable_zone_id :integer # custom_fields :jsonb # id :integer not null, primary key # irrigated :boolean default(FALSE), not null # lock_version :integer default(0), not null # nitrate_fixing :boolean default(FALSE), not null # rank_number :integer not null # size_indicator_name :string not null # size_unit_name :string # size_value :decimal(19, 4) not null # started_on :date # state :string # stopped_on :date # support_id :integer not null # support_nature :string # support_shape :geometry({:srid=>4326, :type=>"multi_polygon"}) # updated_at :datetime not null # updater_id :integer # usage :string not null # class ActivityProduction < Ekylibre::Record::Base include Customizable enumerize :support_nature, in: [:cultivation, :fallow_land, :buffer, :border, :none], default: :cultivation refers_to :usage, class_name: 'ProductionUsage' refers_to :size_indicator, class_name: 'Indicator' refers_to :size_unit, class_name: 'Unit' belongs_to :activity, inverse_of: :productions belongs_to :campaign belongs_to :cultivable_zone belongs_to :support, class_name: 'Product' # , inverse_of: :supports has_many :distributions, class_name: 'TargetDistribution', inverse_of: :activity_production has_many :budgets, through: :activity has_many :manure_management_plan_zones, class_name: 'ManureManagementPlanZone', inverse_of: :activity_production has_one :selected_manure_management_plan_zone, -> { selecteds }, class_name: 'ManureManagementPlanZone', inverse_of: :activity_production has_one :cap_land_parcel, class_name: 'CapLandParcel', inverse_of: :activity_production, foreign_key: :support_id has_geometry :support_shape composed_of :size, class_name: 'Measure', mapping: [%w(size_value to_d), %w(size_unit_name unit)] # [VALIDATORS[ Do not edit these lines directly. Use `rake clean:validations`. validates_date :started_on, :stopped_on, allow_blank: true, before: Date.today + 30.years validates_numericality_of :rank_number, allow_nil: true, only_integer: true validates_numericality_of :size_value, allow_nil: true validates_inclusion_of :irrigated, :nitrate_fixing, in: [true, false] validates_presence_of :activity, :rank_number, :size_indicator_name, :size_value, :support, :usage # ]VALIDATORS] validates_uniqueness_of :rank_number, scope: :activity_id validates_presence_of :started_on # validates_presence_of :cultivable_zone, :support_nature, if: :plant_farming? validates_presence_of :support_nature, if: :plant_farming? validates_presence_of :campaign, :stopped_on, if: :annual? validates_presence_of :started_on # validates_numericality_of :size_value, greater_than: 0 # validates_presence_of :size_unit, if: :size_value? delegate :name, :work_number, to: :support, prefix: true # delegate :shape, :shape_to_ewkt, :shape_svg, :net_surface_area, :shape_area, to: :support delegate :name, :size_indicator_name, :size_unit_name, to: :activity, prefix: true delegate :animal_farming?, :plant_farming?, :at_cycle_start?, :at_cycle_end?, :with_cultivation, :cultivation_variety, :with_supports, :support_variety, :color, :annual?, :perennial?, to: :activity scope :of_campaign, lambda { |campaign| where('campaign_id = ?' \ ' OR campaign_id IS NULL AND (' \ "activity_productions.id IN (SELECT ap.id FROM activity_productions AS ap JOIN activities AS a ON a.id = ap.activity_id, campaigns AS c WHERE a.production_cycle = 'perennial' AND a.production_campaign = 'at_cycle_start' AND c.id = ? AND ((ap.stopped_on is null AND c.harvest_year >= EXTRACT(YEAR FROM ap.started_on)) OR (ap.stopped_on is not null AND EXTRACT(YEAR FROM ap.started_on) <= c.harvest_year AND c.harvest_year < EXTRACT(YEAR FROM ap.stopped_on))))" \ " OR activity_productions.id IN (SELECT ap.id FROM activity_productions AS ap JOIN activities AS a ON a.id = ap.activity_id, campaigns AS c WHERE a.production_cycle = 'perennial' AND a.production_campaign = 'at_cycle_end' AND c.id = ? AND ((ap.stopped_on is null AND c.harvest_year > EXTRACT(YEAR FROM ap.started_on)) OR (ap.stopped_on is not null AND EXTRACT(YEAR FROM ap.started_on) < c.harvest_year AND c.harvest_year <= EXTRACT(YEAR FROM ap.stopped_on))))" \ ')', campaign.id, campaign.id, campaign.id) } scope :of_cultivation_variety, lambda { |variety| where(activity: Activity.of_cultivation_variety(variety)) } scope :of_current_campaigns, -> { of_campaign(Campaign.current.last) } scope :of_activity, ->(activity) { where(activity: activity) } scope :of_activities, lambda { |*activities| where(activity_id: activities.flatten.map(&:id)) } scope :of_activity_families, lambda { |*families| where(activity: Activity.of_families(*families)) } scope :current, -> { where(':now BETWEEN COALESCE(started_on, :now) AND COALESCE(stopped_on, :now)', now: Time.zone.now) } state_machine :state, initial: :opened do state :opened state :aborted state :closed event :abort do transition opened: :aborted end event :close do transition opened: :closed end event :reopen do transition closed: :opened transition aborted: :opened end end before_validation on: :create do if self.activity self.rank_number = (self.activity.productions.maximum(:rank_number) ? self.activity.productions.maximum(:rank_number) : 0) + 1 end end before_validation do self.started_on ||= Date.today self.usage = Nomen::ProductionUsage.first unless usage if self.activity self.stopped_on ||= self.started_on + 1.year - 1.day if annual? self.size_indicator_name ||= activity_size_indicator_name if activity_size_indicator_name self.size_unit_name = activity_size_unit_name self.rank_number ||= (self.activity.productions.maximum(:rank_number) ? self.activity.productions.maximum(:rank_number) : 0) + 1 if plant_farming? self.support_shape ||= cultivable_zone.shape if cultivable_zone if support_shape && !support land_parcels = LandParcel.shape_matching(support_shape) .where.not(id: ActivityProduction.select(:support_id)) .order(:id) self.support = land_parcels.any? ? land_parcels.first : LandParcel.new support.name = computed_support_name support.initial_shape = support_shape support.initial_born_at = started_on support.variant = ProductNatureVariant.import_from_nomenclature(:land_parcel) support.save! end self.size = support_shape_area.in(size_unit_name) elsif animal_farming? unless support self.support = AnimalGroup.new support.name = computed_support_name # FIXME: Need to find better category and population_counting... nature = ProductNature.find_or_create_by!(variety: :animal_group, derivative_of: :animal, name: AnimalGroup.model_name.human, category: ProductNatureCategory.import_from_nomenclature(:cattle_herd), population_counting: :unitary) variant = ProductNatureVariant.find_or_initialize_by(nature: nature, variety: :animal_group, derivative_of: :animal) variant.name ||= nature.name variant.unit_name ||= :unit.tl variant.save! if variant.new_record? support.variant = variant support.derivative_of = self.activity.cultivation_variety support.save! end if size_value.nil? errors.add(:size_value, :empty) else self.size = size_value.in(size_unit_name) end end end end before_validation(on: :create) do self.state ||= :opened end validate do if plant_farming? errors.add(:support_shape, :empty) if self.support_shape && self.support_shape.empty? end end before_update do # self.support.name = computed_support_name support.initial_born_at = started_on if old_record.support_shape != self.support_shape support.initial_shape = support_shape if self.support_shape # TODO: Update only very first shape reading support.read!(:shape, self.support_shape, at: started_on) end end support.save! end after_commit do if self.activity.productions.where(rank_number: rank_number).count > 1 update_column(:rank_number, self.activity.productions.maximum(:rank_number) + 1) end Ekylibre::Hook.publish(:activity_production_change, activity_production_id: id) end after_destroy do Ekylibre::Hook.publish(:activity_production_destroy, activity_production_id: id) end def computed_support_name list = [] list << cultivable_zone.name if cultivable_zone list << activity.name list << campaign.name if campaign list << :rank.t(number: rank_number) list.reverse! if 'i18n.dir'.t == 'rtl' list.join(' ') end def update_names if support new_support_name = computed_support_name if support.name != new_support_name support.update_column(:name, new_support_name) end end end def active? activity.family.to_s != 'fallow_land' end # Returns interventions of current production def interventions Intervention.of_activity_production(self) end def campaigns Campaign.of_activity_production(self) end def started_on_for(campaign) return self.started_on if annual? on = begin Date.civil(campaign.harvest_year, self.started_on.month, self.started_on.day) rescue Date.civil(campaign.harvest_year, self.started_on.month, self.started_on.day - 1) end on -= 1.year if at_cycle_end? on end def stopped_on_for(campaign) return stopped_on if annual? on = Date.civil(campaign.harvest_year, self.started_on.month, self.started_on.day) - 1 on += 1.year if at_cycle_start? on end # Used for find current campaign for given production def current_campaign Campaign.at(Time.zone.now).first end def cost(role = :input) costs = interventions.collect do |intervention| intervention.cost(role) end costs.compact.sum end # Returns the spreaded quantity of one chemicals components (N, P, K) per area unit # Get all intervention of category 'fertilizing' and sum all indicator unity spreaded # - indicator could be (:potassium_concentration, :nitrogen_concentration, :phosphorus_concentration) # - area_unit could be (:hectare, :square_meter) # - from and to used to select intervention def soil_enrichment_indicator_content_per_area(indicator_name, from = nil, to = nil, area_unit_name = :hectare) balance = [] procedure_category = :fertilizing interventions = if from && to self.interventions.real.of_category(procedure_category).between(from, to) else self.interventions.real.of_category(procedure_category) end interventions.each do |intervention| intervention.inputs.each do |input| # m = net_mass of the input at intervention time # n = indicator (in %) of the input at intervention time m = (input.actor ? input.actor.net_mass(input).to_d(:kilogram) : 0.0) # TODO: for method phosphorus_concentration(input) n = (input.actor ? input.actor.send(indicator_name).to_d(:unity) : 0.0) balance << m * n end end # if net_surface_area, make the division area = net_surface_area.to_d(area_unit_name) indicator_unity_per_hectare = balance.compact.sum / area if area != 0 indicator_unity_per_hectare end # TODO: for nitrogen balance but will be refactorize for any chemical components def nitrogen_balance # B = O - I balance = 0.0 nitrogen_mass = [] nitrogen_unity_per_hectare = nil if selected_manure_management_plan_zone # get the output O aka nitrogen_input from opened_at (in kg N / Ha ) o = selected_manure_management_plan_zone.nitrogen_input || 0.0 # get the nitrogen input I from opened_at to now (in kg N / Ha ) opened_at = selected_manure_management_plan_zone.opened_at i = soil_enrichment_indicator_content_per_area(:nitrogen_concentration, opened_at, Time.zone.now) balance = o - i if i && o else balance = soil_enrichment_indicator_content_per_area(:nitrogen_concentration) end balance end def potassium_balance soil_enrichment_indicator_content_per_area(:potassium_concentration) end def phosphorus_balance soil_enrichment_indicator_content_per_area(:phosphorus_concentration) end def provisional_nitrogen_input 0 end def tool_cost(surface_unit_name = :hectare) if net_surface_area.to_s.to_f > 0.0 return cost(:tool) / net_surface_area.to_d(surface_unit_name).to_s.to_f end 0.0 end def input_cost(surface_unit_name = :hectare) if net_surface_area.to_s.to_f > 0.0 return cost(:input) / net_surface_area.to_d(surface_unit_name).to_s.to_f end 0.0 end def time_cost(surface_unit_name = :hectare) if net_surface_area.to_s.to_f > 0.0 return cost(:doer) / net_surface_area.to_d(surface_unit_name).to_s.to_f end 0.0 end # Returns all plants concerning by this activity production # TODO: No plant here, a more generic method should be largely preferable def inside_plants inside_products(Plant) end def inside_products(products = Product) products = if campaign products.of_campaign(campaign) else products.where(born_at: started_on..(stopped_on || Time.zone.now.to_date)) end products.shape_within(support_shape) end # Returns the started_at attribute of the intervention of nature sowing if # exist and if it's a vegetal activity def implanted_at intervention = interventions.real.of_category(:planting).first return intervention.started_at if intervention nil end # Returns the started_at attribute of the intervention of nature harvesting # if exist and if it's a vegetal activity def harvested_at intervention = interventions.real.of_category(:harvesting).first return intervention.started_at if intervention nil end # Generic method to get harvest yield def harvest_yield(harvest_variety, options = {}) size_indicator_name = options[:size_indicator_name] || :net_mass ind = Nomen::Indicator.find(size_indicator_name) raise "Invalid indicator: #{size_indicator_name}" unless ind size_unit_name = options[:size_unit_name] || ind.unit unless Nomen::Unit.find(size_unit_name) raise "Invalid indicator unit: #{size_unit_name.inspect}" end surface_unit_name = options[:surface_unit_name] || :hectare procedure_category = options[:procedure_category] || :harvesting unless net_surface_area && net_surface_area.to_d > 0 Rails.logger.warn 'No surface area. Cannot compute harvest yield' return nil end harvest_yield_unit_name = "#{size_unit_name}_per_#{surface_unit_name}".to_sym unless Nomen::Unit.find(harvest_yield_unit_name) raise "Harvest yield unit doesn't exist: #{harvest_yield_unit_name.inspect}" end total_quantity = 0.0.in(size_unit_name) # harvest_interventions = interventions.real.of_category(procedure_category).with_targets(inside_plants) harvest_interventions = Intervention.real.of_category(procedure_category).with_targets(inside_plants) if harvest_interventions.any? harvest_interventions.find_each do |harvest| harvest.outputs.each do |cast| actor = cast.product next unless actor && actor.variety variety = Nomen::Variety.find(actor.variety) if variety && variety <= harvest_variety quantity = cast.quantity_population.in(actor.variant.send(size_indicator_name).unit) total_quantity += quantity.convert(size_unit_name) if quantity end end end end harvest_yield = total_quantity.to_f / net_surface_area.to_d(surface_unit_name).to_f Measure.new(harvest_yield, harvest_yield_unit_name) end # Returns the yield of grain in mass per surface unit def grains_yield(mass_unit_name = :quintal, surface_unit_name = :hectare) harvest_yield(:grain, procedure_category: :harvesting, size_indicator_name: :net_mass, size_unit_name: mass_unit_name, surface_unit_name: surface_unit_name) end # Returns the yield of grape in volume per surface unit def vine_yield(volume_unit_name = :hectoliter, surface_unit_name = :hectare) harvest_yield(:grape, procedure_category: :harvesting, size_indicator_name: :net_volume, size_unit_name: volume_unit_name, surface_unit_name: surface_unit_name) end # call method in production for instance def estimate_yield(options = {}) raise 'Not possible anymore' production.estimate_yield(options) end def current_cultivation # get the first object with variety 'plant', availables if cultivation = support.contents.where(type: Plant).of_variety(variant.variety).availables.reorder(:born_at).first return cultivation else return nil end end def unified_size_unit size_unit_name.blank? ? :unity : size_unit_name end # Compute quantity of a support as defined in production def current_size(options = {}) options[:at] ||= self.started_on ? self.started_on.to_time : Time.zone.now value = support.get(size_indicator_name, options) value = value.in(size_unit_name) unless size_unit_name.blank? value end def duplicate!(updates = {}) new_attributes = [ :activity, :campaign, :cultivable_zone, :irrigated, :nitrate_fixing, :size_indicator_name, :size_unit_name, :size_value, :started_on, :support_nature, :support_shape, :usage].each_with_object({}) do |attr, h| h[attr] = send(attr) h end.merge(updates) self.class.create!(new_attributes) end alias net_surface_area support_shape_area ## LABEL METHODS ## def work_name "#{support_work_number} - #{net_surface_area.convert(:hectare).round(2)}" end # Returns unique i18nized name for given production def name(options = {}) list = [] list << activity.name unless options[:activity].is_a?(FalseClass) list << cultivable_zone.name if cultivable_zone v = Nomen::Variety.find(cultivation_variety) list << v.human_name if v && !(activity.name.start_with?(v.human_name) || activity.name.end_with?(v.human_name)) # list << support.name if !options[:support].is_a?(FalseClass) && support list << started_on.to_date.l(format: :month) if started_on list << :rank.t(number: rank_number) list = list.reverse! if 'i18n.dir'.t == 'rtl' list.join(' ') end def get(*args) unless support.present? raise StandardError, "No support defined. Got: #{support.inspect}" end support.get(*args) end # # Returns value of an indicator if its name correspond to # def method_missing(method_name, *args) # if Nomen::Indicator.include?(method_name.to_s) # return get(method_name, *args) # end # super # end end
require 'active_record' require_relative '../visualization/stats' require_relative '../../helpers/embed_redis_cache' require_dependency 'cartodb/redis_vizjson_cache' require_dependency 'carto/named_maps/api' require_dependency 'carto/helpers/auth_token_generator' class Carto::Visualization < ActiveRecord::Base include CacheHelper include Carto::AuthTokenGenerator AUTH_DIGEST = '1211b3e77138f6e1724721f1ab740c9c70e66ba6fec5e989bb6640c4541ed15d06dbd5fdcbd3052b'.freeze TYPE_CANONICAL = 'table'.freeze TYPE_DERIVED = 'derived'.freeze TYPE_SLIDE = 'slide'.freeze TYPE_REMOTE = 'remote'.freeze KIND_GEOM = 'geom'.freeze KIND_RASTER = 'raster'.freeze PRIVACY_PUBLIC = 'public'.freeze PRIVACY_PRIVATE = 'private'.freeze PRIVACY_LINK = 'link'.freeze PRIVACY_PROTECTED = 'password'.freeze VERSION_BUILDER = 3 V2_VISUALIZATIONS_REDIS_KEY = 'vizjson2_visualizations'.freeze # INFO: disable ActiveRecord inheritance column self.inheritance_column = :_type belongs_to :user, inverse_of: :visualizations, select: Carto::User::DEFAULT_SELECT belongs_to :full_user, class_name: Carto::User, foreign_key: :user_id, primary_key: :id, inverse_of: :visualizations, readonly: true belongs_to :user_table, class_name: Carto::UserTable, primary_key: :map_id, foreign_key: :map_id, inverse_of: :visualization belongs_to :permission has_many :likes, foreign_key: :subject has_many :shared_entities, foreign_key: :entity_id, inverse_of: :visualization # TODO: duplicated with user_table? belongs_to :table, class_name: Carto::UserTable, primary_key: :map_id, foreign_key: :map_id, inverse_of: :visualization has_one :external_source has_many :unordered_children, class_name: Carto::Visualization, foreign_key: :parent_id has_many :overlays, order: '"order"' belongs_to :parent, class_name: Carto::Visualization, primary_key: :parent_id belongs_to :active_layer, class_name: Carto::Layer belongs_to :map, class_name: Carto::Map has_many :related_templates, class_name: Carto::Template, foreign_key: :source_visualization_id has_one :synchronization, class_name: Carto::Synchronization has_many :external_sources, class_name: Carto::ExternalSource has_many :analyses, class_name: Carto::Analysis has_many :mapcaps, class_name: Carto::Mapcap, dependent: :destroy, order: 'created_at DESC' belongs_to :state, class_name: Carto::State after_save :save_state_if_needed validates :version, presence: true before_validation :set_default_version def set_default_version self.version ||= user.try(:new_visualizations_version) end def self.columns super.reject { |c| c.name == 'url_options' } end def ==(other_visualization) id == other_visualization.id end def size # Only canonical visualizations (Datasets) have a related table and then count against disk quota, # but we want to not break and even allow ordering by size multiple types if table table.size elsif type == TYPE_REMOTE && !external_source.nil? external_source.size else 0 end end def tags tags = super tags == nil ? [] : tags end def tags=(tags) tags.reject!(&:blank?) if tags super(tags) end def layers_with_data_readable_by(user) return [] unless map map.layers.select { |l| l.data_readable_by?(user) } end def related_tables @related_tables ||= get_related_tables end def related_tables_readable_by(user) layers_with_data_readable_by(user).map { |l| l.affected_tables_readable_by(user) }.flatten.uniq end def related_canonical_visualizations @related_canonical_visualizations ||= get_related_canonical_visualizations end def stats @stats ||= CartoDB::Visualization::Stats.new(self).to_poro end def transition_options @transition_options ||= (slide_transition_options.nil? ? {} : JSON.parse(slide_transition_options).symbolize_keys) end def children ordered = [] children_vis = self.unordered_children if children_vis.count > 0 ordered << children_vis.select { |vis| vis.prev_id.nil? }.first while !ordered.last.next_id.nil? target = ordered.last.next_id unless target.nil? ordered << children_vis.select { |vis| vis.id == target }.first end end end ordered end # TODO: refactor next methods, all have similar naming but some receive user and some others user_id def is_liked_by_user_id?(user_id) likes_by_user_id(user_id).count > 0 end def likes_by_user_id(user_id) likes.where(actor: user_id) end def is_viewable_by_user?(user) is_publically_accesible? || has_read_permission?(user) end def is_accesible_by_user?(user) is_viewable_by_user?(user) || password_protected? end def is_publically_accesible? (is_public? || is_link_privacy?) && published? end def writable_by?(user) (user_id == user.id && !user.viewer?) || has_write_permission?(user) end def varnish_key "#{user.database_name}:#{sorted_related_table_names},#{id}" end def surrogate_key get_surrogate_key(CartoDB::SURROGATE_NAMESPACE_VISUALIZATION, id) end def qualified_name(viewer_user = nil) if viewer_user.nil? || owner?(viewer_user) name else "#{user.sql_safe_database_schema}.#{name}" end end # Despite storing always a named map, no need to retrieve it for "public" visualizations def retrieve_named_map? password_protected? || has_private_tables? end def has_password? !password_salt.nil? && !encrypted_password.nil? end def type_slide? type == TYPE_SLIDE end def kind_raster? kind == KIND_RASTER end def canonical? type == TYPE_CANONICAL end def derived? type == TYPE_DERIVED end # TODO: Check if for type slide should return true also def dependent? derived? && single_data_layer? end # TODO: Check if for type slide should return true also def non_dependent? derived? && !single_data_layer? end def single_data_layer? data_layers.count == 1 || related_tables.count == 1 end def layers map ? map.layers : [] end def data_layers map ? map.data_layers : [] end def user_layers map ? map.user_layers : [] end def carto_and_torque_layers map ? map.carto_and_torque_layers : [] end def torque_layers map ? map.torque_layers : [] end def other_layers map ? map.other_layers : [] end def base_layers map ? map.base_layers : [] end def named_map_layers map ? map.named_map_layers : [] end def password_valid?(password) has_password? && ( password_digest(password, password_salt) == encrypted_password ) end def organization? privacy == PRIVACY_PRIVATE && !permission.acl.empty? end def password_protected? privacy == PRIVACY_PROTECTED end def private? is_privacy_private? && !organization? end def is_privacy_private? privacy == PRIVACY_PRIVATE end def is_public? privacy == PRIVACY_PUBLIC end def is_link_privacy? self.privacy == PRIVACY_LINK end def editable? !(kind_raster? || type_slide?) end def get_auth_tokens [get_auth_token] end def mapviews @mapviews ||= CartoDB::Visualization::Stats.mapviews(stats) end def total_mapviews @total_mapviews ||= CartoDB::Visualization::Stats.new(self, nil).total_mapviews end def geometry_types @geometry_types ||= user_table.geometry_types if user_table end def table_service table.nil? ? nil : table.service end def has_read_permission?(user) user && (owner?(user) || (permission && permission.user_has_read_permission?(user))) end def estimated_row_count table_service.nil? ? nil : table_service.estimated_row_count end def actual_row_count table_service.nil? ? nil : table_service.actual_row_count end def license_info if !license.nil? Carto::License.find(license.to_sym) end end def can_be_cached? !is_privacy_private? end def likes_count likes.count end def widgets # Preload widgets for all layers ActiveRecord::Associations::Preloader.new(layers, :widgets).run layers.map(&:widgets).flatten end def analysis_widgets widgets.select { |w| w.source_id.present? } end def attributions_from_derived_visualizations related_canonical_visualizations.map(&:attributions).reject(&:blank?) end def get_named_map return false if type == TYPE_REMOTE named_maps_api.show end def save_named_map return if type == TYPE_REMOTE || mapcapped? get_named_map ? named_maps_api.update : named_maps_api.create end def invalidate_cache redis_vizjson_cache.invalidate(id) embed_redis_cache.invalidate(id) CartoDB::Varnish.new.purge(varnish_vizjson_key) end def allowed_auth_tokens entities = [user] + permission.entities_with_read_permission entities.map(&:get_auth_token) end # - v2 (Editor): not private # - v3 (Builder): not derived or not private, mapcapped # This Ruby code should match the SQL code at Carto::VisualizationQueryBuilder#build section for @only_published. def published? !is_privacy_private? && (!builder? || !derived? || mapcapped?) end def builder? version == VERSION_BUILDER end MAX_MAPCAPS_PER_VISUALIZATION = 1 def create_mapcap! unless mapcaps.count < MAX_MAPCAPS_PER_VISUALIZATION mapcaps.last.destroy end auto_generate_indices_for_all_layers mapcaps.create! end def mapcapped? latest_mapcap.present? end def latest_mapcap mapcaps.first end def uses_builder_features? analyses.any? || widgets.any? || mapcapped? end def add_source_analyses return unless analyses.empty? carto_and_torque_layers.each_with_index do |layer, index| analysis = Carto::Analysis.source_analysis_for_layer(layer, index) if analysis.save layer.options[:source] = analysis.natural_id layer.options[:letter] = analysis.natural_id.first layer.save else CartoDB::Logger.warning(message: 'Couldn\'t add source analysis for layer', user: user, layer: layer) end end # This is needed because Carto::Layer does not yet triggers invalidations on save # It can be safely removed once it does map.notify_map_change end def ids_json layers_for_hash = layers.map do |layer| { layer_id: layer.id, widgets: layer.widgets.map(&:id) } end { visualization_id: id, map_id: map.id, layers: layers_for_hash } end def populate_ids(ids_json) self.id = ids_json[:visualization_id] map.id = ids_json[:map_id] map.layers.each_with_index do |layer, index| stored_layer_ids = ids_json[:layers][index] stored_layer_id = stored_layer_ids[:layer_id] layer.id = stored_layer_id layer.maps = [map] layer.widgets.each_with_index do |widget, widget_index| widget.id = stored_layer_ids[:widgets][widget_index] widget.layer_id = stored_layer_id end end end def for_presentation mapcapped? ? latest_mapcap.regenerate_visualization : self end # TODO: we should make visualization privacy/security methods aware of mapcaps and make those # deal with all the different the cases internally. # See https://github.com/CartoDB/cartodb/pull/9678 def non_mapcapped mapcapped? ? latest_mapcap.visualization : self end def state super ? super : build_state end def mark_as_vizjson2 $tables_metadata.SADD(V2_VISUALIZATIONS_REDIS_KEY, id) end def uses_vizjson2? $tables_metadata.SISMEMBER(V2_VISUALIZATIONS_REDIS_KEY, id) > 0 end def open_in_editor? !builder? && (uses_vizjson2? || layers.any?(&:gmapsbase?)) end def can_be_automatically_migrated_to_v3? overlays.builder_incompatible.none? end private def auto_generate_indices_for_all_layers user_tables = data_layers.map(&:user_tables).flatten.uniq user_tables.each do |ut| ::Resque.enqueue(::Resque::UserDBJobs::UserDBMaintenance::AutoIndexTable, ut.id) end end def build_state self.state = Carto::State.new end def save_state_if_needed if state.changed? update_attribute(:state_id, state.id) if state.save && !state_id end end def named_maps_api Carto::NamedMaps::Api.new(self) end def redis_vizjson_cache @redis_vizjson_cache ||= CartoDB::Visualization::RedisVizjsonCache.new end def embed_redis_cache @embed_redis_cache ||= EmbedRedisCache.new($tables_metadata) end def password_digest(password, salt) digest = AUTH_DIGEST 10.times do digest = secure_digest(digest, salt, password, AUTH_DIGEST) end digest end def secure_digest(*args) #noinspection RubyArgCount Digest::SHA256.hexdigest(args.flatten.join) end def has_private_tables? !related_tables.index { |table| table.private? }.nil? end def sorted_related_table_names mapped_table_names = related_tables.map { |table| "#{user.database_schema}.#{table.name}" } mapped_table_names.sort { |i, j| i <=> j }.join(',') end def get_related_tables return [] unless map map.carto_and_torque_layers.flat_map(&:affected_tables).uniq end def get_related_canonical_visualizations get_related_visualizations_by_types([TYPE_CANONICAL]) end def get_related_visualizations_by_types(types) Carto::Visualization.where(map_id: related_tables.map(&:map_id), type: types).all end def has_write_permission?(user) user && !user.viewer? && (owner?(user) || (permission && permission.user_has_write_permission?(user))) end def owner?(user) user_id == user.id end def varnish_vizjson_key ".*#{id}:vizjson" end end stop using state_id in visualization require 'active_record' require_relative '../visualization/stats' require_relative '../../helpers/embed_redis_cache' require_dependency 'cartodb/redis_vizjson_cache' require_dependency 'carto/named_maps/api' require_dependency 'carto/helpers/auth_token_generator' class Carto::Visualization < ActiveRecord::Base include CacheHelper include Carto::AuthTokenGenerator AUTH_DIGEST = '1211b3e77138f6e1724721f1ab740c9c70e66ba6fec5e989bb6640c4541ed15d06dbd5fdcbd3052b'.freeze TYPE_CANONICAL = 'table'.freeze TYPE_DERIVED = 'derived'.freeze TYPE_SLIDE = 'slide'.freeze TYPE_REMOTE = 'remote'.freeze KIND_GEOM = 'geom'.freeze KIND_RASTER = 'raster'.freeze PRIVACY_PUBLIC = 'public'.freeze PRIVACY_PRIVATE = 'private'.freeze PRIVACY_LINK = 'link'.freeze PRIVACY_PROTECTED = 'password'.freeze VERSION_BUILDER = 3 V2_VISUALIZATIONS_REDIS_KEY = 'vizjson2_visualizations'.freeze # INFO: disable ActiveRecord inheritance column self.inheritance_column = :_type belongs_to :user, inverse_of: :visualizations, select: Carto::User::DEFAULT_SELECT belongs_to :full_user, class_name: Carto::User, foreign_key: :user_id, primary_key: :id, inverse_of: :visualizations, readonly: true belongs_to :user_table, class_name: Carto::UserTable, primary_key: :map_id, foreign_key: :map_id, inverse_of: :visualization belongs_to :permission has_many :likes, foreign_key: :subject has_many :shared_entities, foreign_key: :entity_id, inverse_of: :visualization # TODO: duplicated with user_table? belongs_to :table, class_name: Carto::UserTable, primary_key: :map_id, foreign_key: :map_id, inverse_of: :visualization has_one :external_source has_many :unordered_children, class_name: Carto::Visualization, foreign_key: :parent_id has_many :overlays, order: '"order"' belongs_to :parent, class_name: Carto::Visualization, primary_key: :parent_id belongs_to :active_layer, class_name: Carto::Layer belongs_to :map, class_name: Carto::Map has_many :related_templates, class_name: Carto::Template, foreign_key: :source_visualization_id has_one :synchronization, class_name: Carto::Synchronization has_many :external_sources, class_name: Carto::ExternalSource has_many :analyses, class_name: Carto::Analysis has_many :mapcaps, class_name: Carto::Mapcap, dependent: :destroy, order: 'created_at DESC' belongs_to :state, class_name: Carto::State after_save :save_state_if_needed validates :version, presence: true before_validation :set_default_version def set_default_version self.version ||= user.try(:new_visualizations_version) end DELETED_COLUMNS = ['state', 'url_options'].freeze def self.columns super.reject { |c| DELETED_COLUMNS.include?(c.name) } end def ==(other_visualization) id == other_visualization.id end def size # Only canonical visualizations (Datasets) have a related table and then count against disk quota, # but we want to not break and even allow ordering by size multiple types if table table.size elsif type == TYPE_REMOTE && !external_source.nil? external_source.size else 0 end end def tags tags = super tags == nil ? [] : tags end def tags=(tags) tags.reject!(&:blank?) if tags super(tags) end def layers_with_data_readable_by(user) return [] unless map map.layers.select { |l| l.data_readable_by?(user) } end def related_tables @related_tables ||= get_related_tables end def related_tables_readable_by(user) layers_with_data_readable_by(user).map { |l| l.affected_tables_readable_by(user) }.flatten.uniq end def related_canonical_visualizations @related_canonical_visualizations ||= get_related_canonical_visualizations end def stats @stats ||= CartoDB::Visualization::Stats.new(self).to_poro end def transition_options @transition_options ||= (slide_transition_options.nil? ? {} : JSON.parse(slide_transition_options).symbolize_keys) end def children ordered = [] children_vis = self.unordered_children if children_vis.count > 0 ordered << children_vis.select { |vis| vis.prev_id.nil? }.first while !ordered.last.next_id.nil? target = ordered.last.next_id unless target.nil? ordered << children_vis.select { |vis| vis.id == target }.first end end end ordered end # TODO: refactor next methods, all have similar naming but some receive user and some others user_id def is_liked_by_user_id?(user_id) likes_by_user_id(user_id).count > 0 end def likes_by_user_id(user_id) likes.where(actor: user_id) end def is_viewable_by_user?(user) is_publically_accesible? || has_read_permission?(user) end def is_accesible_by_user?(user) is_viewable_by_user?(user) || password_protected? end def is_publically_accesible? (is_public? || is_link_privacy?) && published? end def writable_by?(user) (user_id == user.id && !user.viewer?) || has_write_permission?(user) end def varnish_key "#{user.database_name}:#{sorted_related_table_names},#{id}" end def surrogate_key get_surrogate_key(CartoDB::SURROGATE_NAMESPACE_VISUALIZATION, id) end def qualified_name(viewer_user = nil) if viewer_user.nil? || owner?(viewer_user) name else "#{user.sql_safe_database_schema}.#{name}" end end # Despite storing always a named map, no need to retrieve it for "public" visualizations def retrieve_named_map? password_protected? || has_private_tables? end def has_password? !password_salt.nil? && !encrypted_password.nil? end def type_slide? type == TYPE_SLIDE end def kind_raster? kind == KIND_RASTER end def canonical? type == TYPE_CANONICAL end def derived? type == TYPE_DERIVED end # TODO: Check if for type slide should return true also def dependent? derived? && single_data_layer? end # TODO: Check if for type slide should return true also def non_dependent? derived? && !single_data_layer? end def single_data_layer? data_layers.count == 1 || related_tables.count == 1 end def layers map ? map.layers : [] end def data_layers map ? map.data_layers : [] end def user_layers map ? map.user_layers : [] end def carto_and_torque_layers map ? map.carto_and_torque_layers : [] end def torque_layers map ? map.torque_layers : [] end def other_layers map ? map.other_layers : [] end def base_layers map ? map.base_layers : [] end def named_map_layers map ? map.named_map_layers : [] end def password_valid?(password) has_password? && ( password_digest(password, password_salt) == encrypted_password ) end def organization? privacy == PRIVACY_PRIVATE && !permission.acl.empty? end def password_protected? privacy == PRIVACY_PROTECTED end def private? is_privacy_private? && !organization? end def is_privacy_private? privacy == PRIVACY_PRIVATE end def is_public? privacy == PRIVACY_PUBLIC end def is_link_privacy? self.privacy == PRIVACY_LINK end def editable? !(kind_raster? || type_slide?) end def get_auth_tokens [get_auth_token] end def mapviews @mapviews ||= CartoDB::Visualization::Stats.mapviews(stats) end def total_mapviews @total_mapviews ||= CartoDB::Visualization::Stats.new(self, nil).total_mapviews end def geometry_types @geometry_types ||= user_table.geometry_types if user_table end def table_service table.nil? ? nil : table.service end def has_read_permission?(user) user && (owner?(user) || (permission && permission.user_has_read_permission?(user))) end def estimated_row_count table_service.nil? ? nil : table_service.estimated_row_count end def actual_row_count table_service.nil? ? nil : table_service.actual_row_count end def license_info if !license.nil? Carto::License.find(license.to_sym) end end def can_be_cached? !is_privacy_private? end def likes_count likes.count end def widgets # Preload widgets for all layers ActiveRecord::Associations::Preloader.new(layers, :widgets).run layers.map(&:widgets).flatten end def analysis_widgets widgets.select { |w| w.source_id.present? } end def attributions_from_derived_visualizations related_canonical_visualizations.map(&:attributions).reject(&:blank?) end def get_named_map return false if type == TYPE_REMOTE named_maps_api.show end def save_named_map return if type == TYPE_REMOTE || mapcapped? get_named_map ? named_maps_api.update : named_maps_api.create end def invalidate_cache redis_vizjson_cache.invalidate(id) embed_redis_cache.invalidate(id) CartoDB::Varnish.new.purge(varnish_vizjson_key) end def allowed_auth_tokens entities = [user] + permission.entities_with_read_permission entities.map(&:get_auth_token) end # - v2 (Editor): not private # - v3 (Builder): not derived or not private, mapcapped # This Ruby code should match the SQL code at Carto::VisualizationQueryBuilder#build section for @only_published. def published? !is_privacy_private? && (!builder? || !derived? || mapcapped?) end def builder? version == VERSION_BUILDER end MAX_MAPCAPS_PER_VISUALIZATION = 1 def create_mapcap! unless mapcaps.count < MAX_MAPCAPS_PER_VISUALIZATION mapcaps.last.destroy end auto_generate_indices_for_all_layers mapcaps.create! end def mapcapped? latest_mapcap.present? end def latest_mapcap mapcaps.first end def uses_builder_features? analyses.any? || widgets.any? || mapcapped? end def add_source_analyses return unless analyses.empty? carto_and_torque_layers.each_with_index do |layer, index| analysis = Carto::Analysis.source_analysis_for_layer(layer, index) if analysis.save layer.options[:source] = analysis.natural_id layer.options[:letter] = analysis.natural_id.first layer.save else CartoDB::Logger.warning(message: 'Couldn\'t add source analysis for layer', user: user, layer: layer) end end # This is needed because Carto::Layer does not yet triggers invalidations on save # It can be safely removed once it does map.notify_map_change end def ids_json layers_for_hash = layers.map do |layer| { layer_id: layer.id, widgets: layer.widgets.map(&:id) } end { visualization_id: id, map_id: map.id, layers: layers_for_hash } end def populate_ids(ids_json) self.id = ids_json[:visualization_id] map.id = ids_json[:map_id] map.layers.each_with_index do |layer, index| stored_layer_ids = ids_json[:layers][index] stored_layer_id = stored_layer_ids[:layer_id] layer.id = stored_layer_id layer.maps = [map] layer.widgets.each_with_index do |widget, widget_index| widget.id = stored_layer_ids[:widgets][widget_index] widget.layer_id = stored_layer_id end end end def for_presentation mapcapped? ? latest_mapcap.regenerate_visualization : self end # TODO: we should make visualization privacy/security methods aware of mapcaps and make those # deal with all the different the cases internally. # See https://github.com/CartoDB/cartodb/pull/9678 def non_mapcapped mapcapped? ? latest_mapcap.visualization : self end def state super ? super : build_state end def mark_as_vizjson2 $tables_metadata.SADD(V2_VISUALIZATIONS_REDIS_KEY, id) end def uses_vizjson2? $tables_metadata.SISMEMBER(V2_VISUALIZATIONS_REDIS_KEY, id) > 0 end def open_in_editor? !builder? && (uses_vizjson2? || layers.any?(&:gmapsbase?)) end def can_be_automatically_migrated_to_v3? overlays.builder_incompatible.none? end private def auto_generate_indices_for_all_layers user_tables = data_layers.map(&:user_tables).flatten.uniq user_tables.each do |ut| ::Resque.enqueue(::Resque::UserDBJobs::UserDBMaintenance::AutoIndexTable, ut.id) end end def build_state self.state = Carto::State.new end def save_state_if_needed if state.changed? update_attribute(:state_id, state.id) if state.save && !state_id end end def named_maps_api Carto::NamedMaps::Api.new(self) end def redis_vizjson_cache @redis_vizjson_cache ||= CartoDB::Visualization::RedisVizjsonCache.new end def embed_redis_cache @embed_redis_cache ||= EmbedRedisCache.new($tables_metadata) end def password_digest(password, salt) digest = AUTH_DIGEST 10.times do digest = secure_digest(digest, salt, password, AUTH_DIGEST) end digest end def secure_digest(*args) #noinspection RubyArgCount Digest::SHA256.hexdigest(args.flatten.join) end def has_private_tables? !related_tables.index { |table| table.private? }.nil? end def sorted_related_table_names mapped_table_names = related_tables.map { |table| "#{user.database_schema}.#{table.name}" } mapped_table_names.sort { |i, j| i <=> j }.join(',') end def get_related_tables return [] unless map map.carto_and_torque_layers.flat_map(&:affected_tables).uniq end def get_related_canonical_visualizations get_related_visualizations_by_types([TYPE_CANONICAL]) end def get_related_visualizations_by_types(types) Carto::Visualization.where(map_id: related_tables.map(&:map_id), type: types).all end def has_write_permission?(user) user && !user.viewer? && (owner?(user) || (permission && permission.user_has_write_permission?(user))) end def owner?(user) user_id == user.id end def varnish_vizjson_key ".*#{id}:vizjson" end end
require 'active_record' require_relative '../visualization/stats' require_dependency 'carto/named_maps/api' require_dependency 'carto/helpers/auth_token_generator' require_dependency 'carto/uuidhelper' require_dependency 'carto/visualization_invalidation_service' require_dependency 'carto/visualizations_export_service_2' module Carto::VisualizationDependencies def fully_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count == data_layers.count end def partially_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count.between?(1, data_layers.count - 1) end def dependent_on?(user_table) derived? && layers_dependent_on(user_table).any? end private def layers_dependent_on(user_table) data_layers.select { |l| l.depends_on?(user_table) } end end class Carto::Visualization < ActiveRecord::Base include CacheHelper include Carto::UUIDHelper include Carto::AuthTokenGenerator include Carto::VisualizationDependencies include Carto::VisualizationsExportService2Exporter AUTH_DIGEST = '1211b3e77138f6e1724721f1ab740c9c70e66ba6fec5e989bb6640c4541ed15d06dbd5fdcbd3052b'.freeze TYPE_CANONICAL = 'table'.freeze TYPE_DERIVED = 'derived'.freeze TYPE_SLIDE = 'slide'.freeze TYPE_REMOTE = 'remote'.freeze VALID_TYPES = [TYPE_CANONICAL, TYPE_DERIVED, TYPE_SLIDE, TYPE_REMOTE].freeze KIND_GEOM = 'geom'.freeze KIND_RASTER = 'raster'.freeze PRIVACY_PUBLIC = 'public'.freeze PRIVACY_PRIVATE = 'private'.freeze PRIVACY_LINK = 'link'.freeze PRIVACY_PROTECTED = 'password'.freeze PRIVACIES = [PRIVACY_LINK, PRIVACY_PROTECTED, PRIVACY_PUBLIC, PRIVACY_PRIVATE].freeze VERSION_BUILDER = 3 V2_VISUALIZATIONS_REDIS_KEY = 'vizjson2_visualizations'.freeze scope :remotes, -> { where(type: TYPE_REMOTE) } # INFO: disable ActiveRecord inheritance column self.inheritance_column = :_type belongs_to :user, -> { select(Carto::User::DEFAULT_SELECT) }, inverse_of: :visualizations belongs_to :full_user, -> { readonly(true) }, class_name: Carto::User, inverse_of: :visualizations, primary_key: :id, foreign_key: :user_id belongs_to :permission, inverse_of: :visualization, dependent: :destroy has_many :likes, foreign_key: :subject has_many :shared_entities, foreign_key: :entity_id, inverse_of: :visualization, dependent: :destroy has_one :external_source, class_name: Carto::ExternalSource, dependent: :destroy, inverse_of: :visualization has_many :unordered_children, class_name: Carto::Visualization, foreign_key: :parent_id has_many :overlays, -> { order(:order) }, dependent: :destroy, inverse_of: :visualization belongs_to :active_layer, class_name: Carto::Layer belongs_to :map, class_name: Carto::Map, inverse_of: :visualization, dependent: :destroy has_many :related_templates, class_name: Carto::Template, foreign_key: :source_visualization_id has_one :synchronization, class_name: Carto::Synchronization, dependent: :destroy has_many :external_sources, class_name: Carto::ExternalSource has_many :analyses, class_name: Carto::Analysis has_many :mapcaps, -> { order('created_at DESC') }, class_name: Carto::Mapcap, dependent: :destroy has_one :state, class_name: Carto::State, autosave: true has_many :snapshots, class_name: Carto::Snapshot, dependent: :destroy validates :name, :privacy, :type, :user_id, :version, presence: true validates :privacy, inclusion: { in: PRIVACIES } validates :type, inclusion: { in: VALID_TYPES } validate :validate_password_presence validate :validate_privacy_changes validate :validate_user_not_viewer, on: :create before_validation :set_default_version, :set_register_table_only before_create :set_random_id, :set_default_permission before_save :remove_password_if_unprotected after_save :propagate_attribution_change after_save :propagate_privacy_and_name_to, if: :table before_destroy :backup_visualization after_commit :perform_invalidations attr_accessor :register_table_only def set_register_table_only self.register_table_only = false # This is a callback, returning `true` avoids halting because of assignment `false` return value true end def set_default_version self.version ||= user.try(:new_visualizations_version) end DELETED_COLUMNS = ['state_id', 'url_options'].freeze def self.columns super.reject { |c| DELETED_COLUMNS.include?(c.name) } end def size # Only canonical visualizations (Datasets) have a related table and then count against disk quota, # but we want to not break and even allow ordering by size multiple types if user_table user_table.size elsif remote? && external_source external_source.size else 0 end end def tags tags = super tags == nil ? [] : tags end def tags=(tags) tags.reject!(&:blank?) if tags super(tags) end def user_table map.user_table if map end def table @table ||= user_table.try(:service) end def layers_with_data_readable_by(user) return [] unless map map.layers.select { |l| l.data_readable_by?(user) } end def related_tables @related_tables ||= get_related_tables end def related_tables_readable_by(user) layers_with_data_readable_by(user).map { |l| l.user_tables_readable_by(user) }.flatten.uniq end def related_canonical_visualizations @related_canonical_visualizations ||= get_related_canonical_visualizations end def stats @stats ||= CartoDB::Visualization::Stats.new(self).to_poro end def transition_options @transition_options ||= (slide_transition_options.nil? ? {} : JSON.parse(slide_transition_options).symbolize_keys) end def transition_options=(value) self.slide_transition_options = ::JSON.dump(value.nil? ? DEFAULT_OPTIONS_VALUE : value) end def children ordered = [] children_vis = self.unordered_children if children_vis.count > 0 ordered << children_vis.select { |vis| vis.prev_id.nil? }.first while !ordered.last.next_id.nil? target = ordered.last.next_id unless target.nil? ordered << children_vis.select { |vis| vis.id == target }.first end end end ordered end # TODO: refactor next methods, all have similar naming but some receive user and some others user_id def liked_by?(user) likes_by_user(user).any? end def likes_by_user(user) likes.where(actor: user.id) end def add_like_from(user) unless has_read_permission?(user) raise UnauthorizedLikeError end likes.create!(actor: user.id) self rescue ActiveRecord::RecordNotUnique raise AlreadyLikedError end def remove_like_from(user) unless has_read_permission?(user) raise UnauthorizedLikeError end item = likes.where(actor: user.id) item.first.destroy unless item.first.nil? self end def send_like_email(current_viewer, vis_preview_image) if self.type == Carto::Visualization::TYPE_CANONICAL ::Resque.enqueue(::Resque::UserJobs::Mail::TableLiked, self.id, current_viewer.id, vis_preview_image) elsif self.type == Carto::Visualization::TYPE_DERIVED ::Resque.enqueue(::Resque::UserJobs::Mail::MapLiked, self.id, current_viewer.id, vis_preview_image) end end def is_viewable_by_user?(user) is_publically_accesible? || has_read_permission?(user) end def is_accesible_by_user?(user) is_viewable_by_user?(user) || password_protected? end def is_accessible_with_password?(user, password) is_viewable_by_user?(user) || password_valid?(password) end def is_publically_accesible? (public? || public_with_link?) && published? end def writable_by?(user) (user_id == user.id && !user.viewer?) || has_write_permission?(user) end def varnish_key "#{user.database_name}:#{sorted_related_table_names},#{id}" end def surrogate_key get_surrogate_key(CartoDB::SURROGATE_NAMESPACE_VISUALIZATION, id) end def qualified_name(viewer_user = nil) if viewer_user.nil? || owner?(viewer_user) name else "#{user.sql_safe_database_schema}.#{name}" end end # Despite storing always a named map, no need to retrieve it for "public" visualizations def retrieve_named_map? password_protected? || has_private_tables? end def has_password? !password_salt.nil? && !encrypted_password.nil? end def type_slide? type == TYPE_SLIDE end def kind_raster? kind == KIND_RASTER end def canonical? type == TYPE_CANONICAL end # TODO: remove. Kept for backwards compatibility with ::Permission model def table? type == TYPE_CANONICAL end def derived? type == TYPE_DERIVED end def remote? type == TYPE_REMOTE end def layers map ? map.layers : [] end def data_layers map ? map.data_layers : [] end def carto_layers map ? map.carto_layers : [] end def user_layers map ? map.user_layers : [] end def torque_layers map ? map.torque_layers : [] end def other_layers map ? map.other_layers : [] end def base_layers map ? map.base_layers : [] end def named_map_layers map ? map.named_map_layers : [] end def password_valid?(password) password_protected? && has_password? && (password_digest(password, password_salt) == encrypted_password) end def organization? privacy == PRIVACY_PRIVATE && !permission.acl.empty? end def password_protected? privacy == PRIVACY_PROTECTED end def private? is_privacy_private? && !organization? end def is_privacy_private? privacy == PRIVACY_PRIVATE end def public? privacy == PRIVACY_PUBLIC end def public_with_link? self.privacy == PRIVACY_LINK end def editable? !(kind_raster? || type_slide?) end def get_auth_tokens [get_auth_token] end def mapviews @mapviews ||= CartoDB::Visualization::Stats.mapviews(stats) end def total_mapviews @total_mapviews ||= CartoDB::Visualization::Stats.new(self, nil).total_mapviews end def geometry_types @geometry_types ||= user_table.geometry_types if user_table end def table_service user_table.try(:service) end def has_read_permission?(user) user && (owner?(user) || (permission && permission.user_has_read_permission?(user))) end alias :can_view_private_info? :has_read_permission? def estimated_row_count user_table.try(:row_count) end def actual_row_count user_table.try(:actual_row_count) end def license_info if !license.nil? Carto::License.find(license.to_sym) end end def can_be_cached? !is_privacy_private? end def widgets # Preload widgets for all layers ActiveRecord::Associations::Preloader.new.preload(layers, :widgets) layers.map(&:widgets).flatten end def analysis_widgets widgets.select { |w| w.source_id.present? } end def attributions_from_derived_visualizations related_canonical_visualizations.map(&:attributions).reject(&:blank?) end def delete_from_table destroy if persisted? end def allowed_auth_tokens entities = [user] + permission.entities_with_read_permission entities.map(&:get_auth_token) end # - v2 (Editor): not private # - v3 (Builder): not derived or not private, mapcapped # This Ruby code should match the SQL code at Carto::VisualizationQueryBuilder#build section for @only_published. def published? !is_privacy_private? && (!builder? || !derived? || mapcapped?) end def builder? version == VERSION_BUILDER end MAX_MAPCAPS_PER_VISUALIZATION = 1 def create_mapcap! unless mapcaps.count < MAX_MAPCAPS_PER_VISUALIZATION mapcaps.last.destroy end auto_generate_indices_for_all_layers mapcaps.create! end def mapcapped? latest_mapcap.present? end def latest_mapcap mapcaps.first end def uses_builder_features? builder? || analyses.any? || widgets.any? || mapcapped? end def add_source_analyses return unless analyses.empty? data_layers.each_with_index do |layer, index| analysis = Carto::Analysis.source_analysis_for_layer(layer, index) if analysis.save layer.options[:source] = analysis.natural_id layer.options[:letter] = analysis.natural_id.first layer.save else CartoDB::Logger.warning(message: 'Couldn\'t add source analysis for layer', user: user, layer: layer) end end end def ids_json layers_for_hash = layers.map do |layer| { layer_id: layer.id, widgets: layer.widgets.map(&:id) } end { visualization_id: id, map_id: map.id, layers: layers_for_hash } end def populate_ids(ids_json) self.id = ids_json[:visualization_id] map.id = ids_json[:map_id] map.layers.each_with_index do |layer, index| stored_layer_ids = ids_json[:layers][index] stored_layer_id = stored_layer_ids[:layer_id] layer.id = stored_layer_id layer.maps = [map] layer.widgets.each_with_index do |widget, widget_index| widget.id = stored_layer_ids[:widgets][widget_index] widget.layer_id = stored_layer_id end end end def for_presentation mapcapped? ? latest_mapcap.regenerate_visualization : self end # TODO: we should make visualization privacy/security methods aware of mapcaps and make those # deal with all the different the cases internally. # See https://github.com/CartoDB/cartodb/pull/9678 def non_mapcapped persisted? ? self : Carto::Visualization.find(id) end def mark_as_vizjson2 $tables_metadata.SADD(V2_VISUALIZATIONS_REDIS_KEY, id) end def uses_vizjson2? $tables_metadata.SISMEMBER(V2_VISUALIZATIONS_REDIS_KEY, id) > 0 end def open_in_editor? !builder? && uses_vizjson2? end def can_be_automatically_migrated_to_v3? overlays.builder_incompatible.none? end def state super ? super : build_state end def can_be_private? derived? ? user.try(:private_maps_enabled) : user.try(:private_tables_enabled) end # TODO: Backward compatibility with Sequel def store_using_table(_table_privacy_changed = false) store end def store save! self end def is_owner?(user) user && user.id == user_id end def unlink_from(user_table) layers_dependent_on(user_table).each do |layer| Carto::Analysis.find_by_natural_id(id, layer.source_id).try(:destroy) if layer.source_id layer.destroy end end def invalidate_after_commit # This marks this visualization as affected by this transaction, so AR will call its `after_commit` hook, which # performs the actual invalidations. This takes this operation outside of the DB transaction to avoid long locks if self.class.connection.open_transactions.zero? raise 'invalidate_after_commit should be called within a transaction' end add_to_transaction true end # TODO: Privacy manager compatibility, can be removed after removing ::UserTable alias :invalidate_cache :invalidate_after_commit def has_permission?(user, permission_type) return false if user.viewer && permission_type == Carto::Permission::ACCESS_READWRITE return is_owner?(user) if permission_id.nil? is_owner?(user) || permission.permitted?(user, permission_type) end def ensure_valid_privacy self.privacy = default_privacy if privacy.nil? self.privacy = PRIVACY_PUBLIC unless can_be_private? end def default_privacy can_be_private? ? PRIVACY_LINK : PRIVACY_PUBLIC end def privacy=(privacy) super(privacy.try(:downcase)) end def password=(value) if value.present? self.password_salt = generate_salt if password_salt.nil? self.encrypted_password = password_digest(value, password_salt) end end def synced? synchronization.present? end def dependent_visualizations user_table.try(:dependent_visualizations) || [] end def backup_visualization(category = Carto::VisualizationBackup::CATEGORY_VISUALIZATION) return true if remote? if map && !destroyed? export_json = export_visualization_json_hash(id, user, with_mapcaps: true, with_password: true) Carto::VisualizationBackup.create!( user_id: user.id, visualization_id: id, category: category, export: export_json ) end rescue StandardError => exception # Don't break deletion flow CartoDB::Logger.error( message: 'Error backing up visualization', exception: exception, visualization_id: id ) end private def generate_salt secure_digest(Time.now, (1..10).map { rand.to_s }) end def remove_password self.password_salt = nil self.encrypted_password = nil end def perform_invalidations invalidation_service.invalidate rescue => e # This is called at an after_commit. If there's any error, we won't notice # but the after_commit chain stops. # This was discovered during #12844, because "Updates changes even if named maps communication fails" test # begun failing because Overlay#invalidate_cache invokes this method directly. # We chose to log and continue to keep coherence on calls to this outside the callback. CartoDB::Logger.error(message: "Error on visualization invalidation", exception: e, visualization_id: id) end def propagate_privacy_and_name_to raise "Empty table sent to propagate_privacy_and_name_to()" unless table propagate_privacy if privacy_changed? && canonical? propagate_name if name_was != name # name_changed? returns false positives in changes like a->A->a (sanitization) end def propagate_privacy table.reload if privacy && table.privacy_text.casecmp(privacy) != 0 # privacy is different, case insensitive CartoDB::TablePrivacyManager.new(table).set_from_visualization(self).update_cdb_tablemetadata end end def propagate_name # TODO: Move this to ::Table? return if table.changing_name? table.register_table_only = register_table_only table.name = name if table.name != name # Sanitization. For example, spaces -> _ update_column(:name, table.name) end table.update(name: name) if name_changed? support_tables.rename(name_was, name, true, name_was) end self rescue => exception if name_changed? && !(exception.to_s =~ /relation.*does not exist/) revert_name_change(name_was) end raise CartoDB::InvalidMember.new(exception.to_s) end def revert_name_change(previous_name) self.name = previous_name store rescue => exception raise CartoDB::InvalidMember.new(exception.to_s) end def propagate_attribution_change table.propagate_attribution_change(attributions) if table && attributions_changed? end def support_tables @support_tables ||= CartoDB::Visualization::SupportTables.new( user.in_database, parent_id: id, parent_kind: kind, public_user_roles: user.db_service.public_user_roles ) end def auto_generate_indices_for_all_layers user_tables = data_layers.map(&:user_tables).flatten.uniq user_tables.each do |ut| ::Resque.enqueue(::Resque::UserDBJobs::UserDBMaintenance::AutoIndexTable, ut.id) end end def set_random_id # This should be done with a DB default self.id ||= random_uuid end def set_default_permission self.permission ||= Carto::Permission.create(owner: user, owner_username: user.username) end def password_digest(password, salt) digest = AUTH_DIGEST 10.times do digest = secure_digest(digest, salt, password, AUTH_DIGEST) end digest end def secure_digest(*args) Digest::SHA256.hexdigest(args.flatten.join) end def has_private_tables? !related_tables.index { |table| table.private? }.nil? end def sorted_related_table_names mapped_table_names = related_tables.map { |table| "#{user.database_schema}.#{table.name}" } mapped_table_names.sort { |i, j| i <=> j }.join(',') end def get_related_tables return [] unless map map.data_layers.flat_map(&:user_tables).uniq end def get_related_canonical_visualizations get_related_visualizations_by_types([TYPE_CANONICAL]) end def get_related_visualizations_by_types(types) Carto::Visualization.where(map_id: related_tables.map(&:map_id), type: types).all end def has_write_permission?(user) user && !user.viewer? && (owner?(user) || (permission && permission.user_has_write_permission?(user))) end def owner?(user) user_id == user.id end def validate_password_presence errors.add(:password, 'required for protected visualization') if password_protected? && !has_password? end def remove_password_if_unprotected remove_password unless password_protected? end def validate_privacy_changes if derived? && is_privacy_private? && privacy_changed? && !user.try(:private_maps_enabled?) errors.add(:privacy, 'cannot be set to private') end end def validate_user_not_viewer if user.viewer errors.add(:user, 'cannot be viewer') end end def invalidation_service @invalidation_service ||= Carto::VisualizationInvalidationService.new(self) end class Watcher # watcher:_orgid_:_vis_id_:_user_id_ KEY_FORMAT = "watcher:%s".freeze # @params user Carto::User # @params visualization Carto::Visualization # @throws Carto::Visualization::WatcherError def initialize(user, visualization, notification_ttl = nil) raise WatcherError.new('User must belong to an organization') if user.organization.nil? @user = user @visualization = visualization default_ttl = Cartodb.config[:watcher].present? ? Cartodb.config[:watcher].try("fetch", 'ttl', 60) : 60 @notification_ttl = notification_ttl.nil? ? default_ttl : notification_ttl end # Notifies that is editing the visualization # NOTE: Expiration is handled internally by redis def notify key = KEY_FORMAT % @visualization.id $tables_metadata.multi do $tables_metadata.hset(key, @user.username, current_timestamp + @notification_ttl) $tables_metadata.expire(key, @notification_ttl) end end # Returns a list of usernames currently editing the visualization def list key = KEY_FORMAT % @visualization.id users_expiry = $tables_metadata.hgetall(key) now = current_timestamp users_expiry.select { |_, expiry| expiry.to_i > now }.keys end private def current_timestamp Time.now.getutc.to_i end end class WatcherError < CartoDB::BaseCartoDBError; end class AlreadyLikedError < StandardError; end class UnauthorizedLikeError < StandardError; end end using service in visualization require 'active_record' require_relative '../visualization/stats' require_dependency 'carto/named_maps/api' require_dependency 'carto/helpers/auth_token_generator' require_dependency 'carto/uuidhelper' require_dependency 'carto/visualization_invalidation_service' require_dependency 'carto/visualization_backup_service' module Carto::VisualizationDependencies def fully_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count == data_layers.count end def partially_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count.between?(1, data_layers.count - 1) end def dependent_on?(user_table) derived? && layers_dependent_on(user_table).any? end private def layers_dependent_on(user_table) data_layers.select { |l| l.depends_on?(user_table) } end end class Carto::Visualization < ActiveRecord::Base include CacheHelper include Carto::UUIDHelper include Carto::AuthTokenGenerator include Carto::VisualizationDependencies include Carto::VisualizationBackupService AUTH_DIGEST = '1211b3e77138f6e1724721f1ab740c9c70e66ba6fec5e989bb6640c4541ed15d06dbd5fdcbd3052b'.freeze TYPE_CANONICAL = 'table'.freeze TYPE_DERIVED = 'derived'.freeze TYPE_SLIDE = 'slide'.freeze TYPE_REMOTE = 'remote'.freeze VALID_TYPES = [TYPE_CANONICAL, TYPE_DERIVED, TYPE_SLIDE, TYPE_REMOTE].freeze KIND_GEOM = 'geom'.freeze KIND_RASTER = 'raster'.freeze PRIVACY_PUBLIC = 'public'.freeze PRIVACY_PRIVATE = 'private'.freeze PRIVACY_LINK = 'link'.freeze PRIVACY_PROTECTED = 'password'.freeze PRIVACIES = [PRIVACY_LINK, PRIVACY_PROTECTED, PRIVACY_PUBLIC, PRIVACY_PRIVATE].freeze VERSION_BUILDER = 3 V2_VISUALIZATIONS_REDIS_KEY = 'vizjson2_visualizations'.freeze scope :remotes, -> { where(type: TYPE_REMOTE) } # INFO: disable ActiveRecord inheritance column self.inheritance_column = :_type belongs_to :user, -> { select(Carto::User::DEFAULT_SELECT) }, inverse_of: :visualizations belongs_to :full_user, -> { readonly(true) }, class_name: Carto::User, inverse_of: :visualizations, primary_key: :id, foreign_key: :user_id belongs_to :permission, inverse_of: :visualization, dependent: :destroy has_many :likes, foreign_key: :subject has_many :shared_entities, foreign_key: :entity_id, inverse_of: :visualization, dependent: :destroy has_one :external_source, class_name: Carto::ExternalSource, dependent: :destroy, inverse_of: :visualization has_many :unordered_children, class_name: Carto::Visualization, foreign_key: :parent_id has_many :overlays, -> { order(:order) }, dependent: :destroy, inverse_of: :visualization belongs_to :active_layer, class_name: Carto::Layer belongs_to :map, class_name: Carto::Map, inverse_of: :visualization, dependent: :destroy has_many :related_templates, class_name: Carto::Template, foreign_key: :source_visualization_id has_one :synchronization, class_name: Carto::Synchronization, dependent: :destroy has_many :external_sources, class_name: Carto::ExternalSource has_many :analyses, class_name: Carto::Analysis has_many :mapcaps, -> { order('created_at DESC') }, class_name: Carto::Mapcap, dependent: :destroy has_one :state, class_name: Carto::State, autosave: true has_many :snapshots, class_name: Carto::Snapshot, dependent: :destroy validates :name, :privacy, :type, :user_id, :version, presence: true validates :privacy, inclusion: { in: PRIVACIES } validates :type, inclusion: { in: VALID_TYPES } validate :validate_password_presence validate :validate_privacy_changes validate :validate_user_not_viewer, on: :create before_validation :set_default_version, :set_register_table_only before_create :set_random_id, :set_default_permission before_save :remove_password_if_unprotected after_save :propagate_attribution_change after_save :propagate_privacy_and_name_to, if: :table before_destroy :backup_visualization after_commit :perform_invalidations attr_accessor :register_table_only def set_register_table_only self.register_table_only = false # This is a callback, returning `true` avoids halting because of assignment `false` return value true end def set_default_version self.version ||= user.try(:new_visualizations_version) end DELETED_COLUMNS = ['state_id', 'url_options'].freeze def self.columns super.reject { |c| DELETED_COLUMNS.include?(c.name) } end def size # Only canonical visualizations (Datasets) have a related table and then count against disk quota, # but we want to not break and even allow ordering by size multiple types if user_table user_table.size elsif remote? && external_source external_source.size else 0 end end def tags tags = super tags == nil ? [] : tags end def tags=(tags) tags.reject!(&:blank?) if tags super(tags) end def user_table map.user_table if map end def table @table ||= user_table.try(:service) end def layers_with_data_readable_by(user) return [] unless map map.layers.select { |l| l.data_readable_by?(user) } end def related_tables @related_tables ||= get_related_tables end def related_tables_readable_by(user) layers_with_data_readable_by(user).map { |l| l.user_tables_readable_by(user) }.flatten.uniq end def related_canonical_visualizations @related_canonical_visualizations ||= get_related_canonical_visualizations end def stats @stats ||= CartoDB::Visualization::Stats.new(self).to_poro end def transition_options @transition_options ||= (slide_transition_options.nil? ? {} : JSON.parse(slide_transition_options).symbolize_keys) end def transition_options=(value) self.slide_transition_options = ::JSON.dump(value.nil? ? DEFAULT_OPTIONS_VALUE : value) end def children ordered = [] children_vis = self.unordered_children if children_vis.count > 0 ordered << children_vis.select { |vis| vis.prev_id.nil? }.first while !ordered.last.next_id.nil? target = ordered.last.next_id unless target.nil? ordered << children_vis.select { |vis| vis.id == target }.first end end end ordered end # TODO: refactor next methods, all have similar naming but some receive user and some others user_id def liked_by?(user) likes_by_user(user).any? end def likes_by_user(user) likes.where(actor: user.id) end def add_like_from(user) unless has_read_permission?(user) raise UnauthorizedLikeError end likes.create!(actor: user.id) self rescue ActiveRecord::RecordNotUnique raise AlreadyLikedError end def remove_like_from(user) unless has_read_permission?(user) raise UnauthorizedLikeError end item = likes.where(actor: user.id) item.first.destroy unless item.first.nil? self end def send_like_email(current_viewer, vis_preview_image) if self.type == Carto::Visualization::TYPE_CANONICAL ::Resque.enqueue(::Resque::UserJobs::Mail::TableLiked, self.id, current_viewer.id, vis_preview_image) elsif self.type == Carto::Visualization::TYPE_DERIVED ::Resque.enqueue(::Resque::UserJobs::Mail::MapLiked, self.id, current_viewer.id, vis_preview_image) end end def is_viewable_by_user?(user) is_publically_accesible? || has_read_permission?(user) end def is_accesible_by_user?(user) is_viewable_by_user?(user) || password_protected? end def is_accessible_with_password?(user, password) is_viewable_by_user?(user) || password_valid?(password) end def is_publically_accesible? (public? || public_with_link?) && published? end def writable_by?(user) (user_id == user.id && !user.viewer?) || has_write_permission?(user) end def varnish_key "#{user.database_name}:#{sorted_related_table_names},#{id}" end def surrogate_key get_surrogate_key(CartoDB::SURROGATE_NAMESPACE_VISUALIZATION, id) end def qualified_name(viewer_user = nil) if viewer_user.nil? || owner?(viewer_user) name else "#{user.sql_safe_database_schema}.#{name}" end end # Despite storing always a named map, no need to retrieve it for "public" visualizations def retrieve_named_map? password_protected? || has_private_tables? end def has_password? !password_salt.nil? && !encrypted_password.nil? end def type_slide? type == TYPE_SLIDE end def kind_raster? kind == KIND_RASTER end def canonical? type == TYPE_CANONICAL end # TODO: remove. Kept for backwards compatibility with ::Permission model def table? type == TYPE_CANONICAL end def derived? type == TYPE_DERIVED end def remote? type == TYPE_REMOTE end def layers map ? map.layers : [] end def data_layers map ? map.data_layers : [] end def carto_layers map ? map.carto_layers : [] end def user_layers map ? map.user_layers : [] end def torque_layers map ? map.torque_layers : [] end def other_layers map ? map.other_layers : [] end def base_layers map ? map.base_layers : [] end def named_map_layers map ? map.named_map_layers : [] end def password_valid?(password) password_protected? && has_password? && (password_digest(password, password_salt) == encrypted_password) end def organization? privacy == PRIVACY_PRIVATE && !permission.acl.empty? end def password_protected? privacy == PRIVACY_PROTECTED end def private? is_privacy_private? && !organization? end def is_privacy_private? privacy == PRIVACY_PRIVATE end def public? privacy == PRIVACY_PUBLIC end def public_with_link? self.privacy == PRIVACY_LINK end def editable? !(kind_raster? || type_slide?) end def get_auth_tokens [get_auth_token] end def mapviews @mapviews ||= CartoDB::Visualization::Stats.mapviews(stats) end def total_mapviews @total_mapviews ||= CartoDB::Visualization::Stats.new(self, nil).total_mapviews end def geometry_types @geometry_types ||= user_table.geometry_types if user_table end def table_service user_table.try(:service) end def has_read_permission?(user) user && (owner?(user) || (permission && permission.user_has_read_permission?(user))) end alias :can_view_private_info? :has_read_permission? def estimated_row_count user_table.try(:row_count) end def actual_row_count user_table.try(:actual_row_count) end def license_info if !license.nil? Carto::License.find(license.to_sym) end end def can_be_cached? !is_privacy_private? end def widgets # Preload widgets for all layers ActiveRecord::Associations::Preloader.new.preload(layers, :widgets) layers.map(&:widgets).flatten end def analysis_widgets widgets.select { |w| w.source_id.present? } end def attributions_from_derived_visualizations related_canonical_visualizations.map(&:attributions).reject(&:blank?) end def delete_from_table destroy if persisted? end def allowed_auth_tokens entities = [user] + permission.entities_with_read_permission entities.map(&:get_auth_token) end # - v2 (Editor): not private # - v3 (Builder): not derived or not private, mapcapped # This Ruby code should match the SQL code at Carto::VisualizationQueryBuilder#build section for @only_published. def published? !is_privacy_private? && (!builder? || !derived? || mapcapped?) end def builder? version == VERSION_BUILDER end MAX_MAPCAPS_PER_VISUALIZATION = 1 def create_mapcap! unless mapcaps.count < MAX_MAPCAPS_PER_VISUALIZATION mapcaps.last.destroy end auto_generate_indices_for_all_layers mapcaps.create! end def mapcapped? latest_mapcap.present? end def latest_mapcap mapcaps.first end def uses_builder_features? builder? || analyses.any? || widgets.any? || mapcapped? end def add_source_analyses return unless analyses.empty? data_layers.each_with_index do |layer, index| analysis = Carto::Analysis.source_analysis_for_layer(layer, index) if analysis.save layer.options[:source] = analysis.natural_id layer.options[:letter] = analysis.natural_id.first layer.save else CartoDB::Logger.warning(message: 'Couldn\'t add source analysis for layer', user: user, layer: layer) end end end def ids_json layers_for_hash = layers.map do |layer| { layer_id: layer.id, widgets: layer.widgets.map(&:id) } end { visualization_id: id, map_id: map.id, layers: layers_for_hash } end def populate_ids(ids_json) self.id = ids_json[:visualization_id] map.id = ids_json[:map_id] map.layers.each_with_index do |layer, index| stored_layer_ids = ids_json[:layers][index] stored_layer_id = stored_layer_ids[:layer_id] layer.id = stored_layer_id layer.maps = [map] layer.widgets.each_with_index do |widget, widget_index| widget.id = stored_layer_ids[:widgets][widget_index] widget.layer_id = stored_layer_id end end end def for_presentation mapcapped? ? latest_mapcap.regenerate_visualization : self end # TODO: we should make visualization privacy/security methods aware of mapcaps and make those # deal with all the different the cases internally. # See https://github.com/CartoDB/cartodb/pull/9678 def non_mapcapped persisted? ? self : Carto::Visualization.find(id) end def mark_as_vizjson2 $tables_metadata.SADD(V2_VISUALIZATIONS_REDIS_KEY, id) end def uses_vizjson2? $tables_metadata.SISMEMBER(V2_VISUALIZATIONS_REDIS_KEY, id) > 0 end def open_in_editor? !builder? && uses_vizjson2? end def can_be_automatically_migrated_to_v3? overlays.builder_incompatible.none? end def state super ? super : build_state end def can_be_private? derived? ? user.try(:private_maps_enabled) : user.try(:private_tables_enabled) end # TODO: Backward compatibility with Sequel def store_using_table(_table_privacy_changed = false) store end def store save! self end def is_owner?(user) user && user.id == user_id end def unlink_from(user_table) layers_dependent_on(user_table).each do |layer| Carto::Analysis.find_by_natural_id(id, layer.source_id).try(:destroy) if layer.source_id layer.destroy end end def invalidate_after_commit # This marks this visualization as affected by this transaction, so AR will call its `after_commit` hook, which # performs the actual invalidations. This takes this operation outside of the DB transaction to avoid long locks if self.class.connection.open_transactions.zero? raise 'invalidate_after_commit should be called within a transaction' end add_to_transaction true end # TODO: Privacy manager compatibility, can be removed after removing ::UserTable alias :invalidate_cache :invalidate_after_commit def has_permission?(user, permission_type) return false if user.viewer && permission_type == Carto::Permission::ACCESS_READWRITE return is_owner?(user) if permission_id.nil? is_owner?(user) || permission.permitted?(user, permission_type) end def ensure_valid_privacy self.privacy = default_privacy if privacy.nil? self.privacy = PRIVACY_PUBLIC unless can_be_private? end def default_privacy can_be_private? ? PRIVACY_LINK : PRIVACY_PUBLIC end def privacy=(privacy) super(privacy.try(:downcase)) end def password=(value) if value.present? self.password_salt = generate_salt if password_salt.nil? self.encrypted_password = password_digest(value, password_salt) end end def synced? synchronization.present? end def dependent_visualizations user_table.try(:dependent_visualizations) || [] end def backup_visualization(category = Carto::VisualizationBackup::CATEGORY_VISUALIZATION) return true if remote? if map && !destroyed? create_visualization_backup(id, user, category, with_mapcaps: true, with_password: true) end end private def generate_salt secure_digest(Time.now, (1..10).map { rand.to_s }) end def remove_password self.password_salt = nil self.encrypted_password = nil end def perform_invalidations invalidation_service.invalidate rescue => e # This is called at an after_commit. If there's any error, we won't notice # but the after_commit chain stops. # This was discovered during #12844, because "Updates changes even if named maps communication fails" test # begun failing because Overlay#invalidate_cache invokes this method directly. # We chose to log and continue to keep coherence on calls to this outside the callback. CartoDB::Logger.error(message: "Error on visualization invalidation", exception: e, visualization_id: id) end def propagate_privacy_and_name_to raise "Empty table sent to propagate_privacy_and_name_to()" unless table propagate_privacy if privacy_changed? && canonical? propagate_name if name_was != name # name_changed? returns false positives in changes like a->A->a (sanitization) end def propagate_privacy table.reload if privacy && table.privacy_text.casecmp(privacy) != 0 # privacy is different, case insensitive CartoDB::TablePrivacyManager.new(table).set_from_visualization(self).update_cdb_tablemetadata end end def propagate_name # TODO: Move this to ::Table? return if table.changing_name? table.register_table_only = register_table_only table.name = name if table.name != name # Sanitization. For example, spaces -> _ update_column(:name, table.name) end table.update(name: name) if name_changed? support_tables.rename(name_was, name, true, name_was) end self rescue => exception if name_changed? && !(exception.to_s =~ /relation.*does not exist/) revert_name_change(name_was) end raise CartoDB::InvalidMember.new(exception.to_s) end def revert_name_change(previous_name) self.name = previous_name store rescue => exception raise CartoDB::InvalidMember.new(exception.to_s) end def propagate_attribution_change table.propagate_attribution_change(attributions) if table && attributions_changed? end def support_tables @support_tables ||= CartoDB::Visualization::SupportTables.new( user.in_database, parent_id: id, parent_kind: kind, public_user_roles: user.db_service.public_user_roles ) end def auto_generate_indices_for_all_layers user_tables = data_layers.map(&:user_tables).flatten.uniq user_tables.each do |ut| ::Resque.enqueue(::Resque::UserDBJobs::UserDBMaintenance::AutoIndexTable, ut.id) end end def set_random_id # This should be done with a DB default self.id ||= random_uuid end def set_default_permission self.permission ||= Carto::Permission.create(owner: user, owner_username: user.username) end def password_digest(password, salt) digest = AUTH_DIGEST 10.times do digest = secure_digest(digest, salt, password, AUTH_DIGEST) end digest end def secure_digest(*args) Digest::SHA256.hexdigest(args.flatten.join) end def has_private_tables? !related_tables.index { |table| table.private? }.nil? end def sorted_related_table_names mapped_table_names = related_tables.map { |table| "#{user.database_schema}.#{table.name}" } mapped_table_names.sort { |i, j| i <=> j }.join(',') end def get_related_tables return [] unless map map.data_layers.flat_map(&:user_tables).uniq end def get_related_canonical_visualizations get_related_visualizations_by_types([TYPE_CANONICAL]) end def get_related_visualizations_by_types(types) Carto::Visualization.where(map_id: related_tables.map(&:map_id), type: types).all end def has_write_permission?(user) user && !user.viewer? && (owner?(user) || (permission && permission.user_has_write_permission?(user))) end def owner?(user) user_id == user.id end def validate_password_presence errors.add(:password, 'required for protected visualization') if password_protected? && !has_password? end def remove_password_if_unprotected remove_password unless password_protected? end def validate_privacy_changes if derived? && is_privacy_private? && privacy_changed? && !user.try(:private_maps_enabled?) errors.add(:privacy, 'cannot be set to private') end end def validate_user_not_viewer if user.viewer errors.add(:user, 'cannot be viewer') end end def invalidation_service @invalidation_service ||= Carto::VisualizationInvalidationService.new(self) end class Watcher # watcher:_orgid_:_vis_id_:_user_id_ KEY_FORMAT = "watcher:%s".freeze # @params user Carto::User # @params visualization Carto::Visualization # @throws Carto::Visualization::WatcherError def initialize(user, visualization, notification_ttl = nil) raise WatcherError.new('User must belong to an organization') if user.organization.nil? @user = user @visualization = visualization default_ttl = Cartodb.config[:watcher].present? ? Cartodb.config[:watcher].try("fetch", 'ttl', 60) : 60 @notification_ttl = notification_ttl.nil? ? default_ttl : notification_ttl end # Notifies that is editing the visualization # NOTE: Expiration is handled internally by redis def notify key = KEY_FORMAT % @visualization.id $tables_metadata.multi do $tables_metadata.hset(key, @user.username, current_timestamp + @notification_ttl) $tables_metadata.expire(key, @notification_ttl) end end # Returns a list of usernames currently editing the visualization def list key = KEY_FORMAT % @visualization.id users_expiry = $tables_metadata.hgetall(key) now = current_timestamp users_expiry.select { |_, expiry| expiry.to_i > now }.keys end private def current_timestamp Time.now.getutc.to_i end end class WatcherError < CartoDB::BaseCartoDBError; end class AlreadyLikedError < StandardError; end class UnauthorizedLikeError < StandardError; end end
require 'active_record' require_relative '../visualization/stats' require_relative '../../helpers/embed_redis_cache' require_dependency 'cartodb/redis_vizjson_cache' require_dependency 'carto/named_maps/api' require_dependency 'carto/helpers/auth_token_generator' require_dependency 'carto/uuidhelper' module Carto::VisualizationDependencies def fully_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count == data_layers.count end def partially_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count.between?(1, data_layers.count - 1) end def dependent_on?(user_table) derived? && layers_dependent_on(user_table).any? end private def layers_dependent_on(user_table) data_layers.select { |l| l.depends_on?(user_table) } end end class Carto::Visualization < ActiveRecord::Base include CacheHelper include Carto::UUIDHelper include Carto::AuthTokenGenerator include Carto::VisualizationDependencies AUTH_DIGEST = '1211b3e77138f6e1724721f1ab740c9c70e66ba6fec5e989bb6640c4541ed15d06dbd5fdcbd3052b'.freeze TYPE_CANONICAL = 'table'.freeze TYPE_DERIVED = 'derived'.freeze TYPE_SLIDE = 'slide'.freeze TYPE_REMOTE = 'remote'.freeze KIND_GEOM = 'geom'.freeze KIND_RASTER = 'raster'.freeze PRIVACY_PUBLIC = 'public'.freeze PRIVACY_PRIVATE = 'private'.freeze PRIVACY_LINK = 'link'.freeze PRIVACY_PROTECTED = 'password'.freeze VERSION_BUILDER = 3 V2_VISUALIZATIONS_REDIS_KEY = 'vizjson2_visualizations'.freeze # INFO: disable ActiveRecord inheritance column self.inheritance_column = :_type belongs_to :user, inverse_of: :visualizations, select: Carto::User::DEFAULT_SELECT belongs_to :full_user, class_name: Carto::User, foreign_key: :user_id, primary_key: :id, inverse_of: :visualizations, readonly: true belongs_to :permission, inverse_of: :visualization has_many :likes, foreign_key: :subject has_many :shared_entities, foreign_key: :entity_id, inverse_of: :visualization has_one :external_source has_many :unordered_children, class_name: Carto::Visualization, foreign_key: :parent_id has_many :overlays, order: '"order"' belongs_to :parent, class_name: Carto::Visualization, primary_key: :parent_id belongs_to :active_layer, class_name: Carto::Layer belongs_to :map, class_name: Carto::Map, inverse_of: :visualization has_many :related_templates, class_name: Carto::Template, foreign_key: :source_visualization_id has_one :synchronization, class_name: Carto::Synchronization has_many :external_sources, class_name: Carto::ExternalSource has_many :analyses, class_name: Carto::Analysis has_many :mapcaps, class_name: Carto::Mapcap, dependent: :destroy, order: 'created_at DESC' has_one :state, class_name: Carto::State, autosave: true has_many :snapshots, class_name: Carto::Snapshot, dependent: :destroy validates :version, presence: true validate :validate_password_presence validate :validate_privacy_changes before_validation :set_default_version, :set_register_table_only before_create :set_random_id, :set_default_permission before_save :remove_password_if_unprotected, :invalidate after_save :save_named_map_or_rollback_privacy, :propagate_attribution_change after_save :propagate_privacy_and_name_to, if: :table # INFO: workaround for array saves not working. There is a bug in `activerecord-postgresql-array` which # makes inserting including array fields to save, but updates work. Wo se insert without tags and add them # with an update after creation. This is fixed in Rails 4. before_create :delay_saving_tags after_create :save_tags attr_accessor :register_table_only def set_register_table_only self.register_table_only = false # This is a callback, returning `true` avoids halting because of assignment `false` return value true end def set_default_version self.version ||= user.try(:new_visualizations_version) end DELETED_COLUMNS = ['state_id', 'url_options'].freeze def self.columns super.reject { |c| DELETED_COLUMNS.include?(c.name) } end def ==(other_visualization) id == other_visualization.id end def size # Only canonical visualizations (Datasets) have a related table and then count against disk quota, # but we want to not break and even allow ordering by size multiple types if user_table user_table.size elsif remote? && external_source external_source.size else 0 end end def tags tags = super tags == nil ? [] : tags end def tags=(tags) tags.reject!(&:blank?) if tags super(tags) end def user_table map.user_table if map end def table @table ||= user_table.try(:service) end def layers_with_data_readable_by(user) return [] unless map map.layers.select { |l| l.data_readable_by?(user) } end def related_tables @related_tables ||= get_related_tables end def related_tables_readable_by(user) layers_with_data_readable_by(user).map { |l| l.user_tables_readable_by(user) }.flatten.uniq end def related_canonical_visualizations @related_canonical_visualizations ||= get_related_canonical_visualizations end def stats @stats ||= CartoDB::Visualization::Stats.new(self).to_poro end def transition_options @transition_options ||= (slide_transition_options.nil? ? {} : JSON.parse(slide_transition_options).symbolize_keys) end def children ordered = [] children_vis = self.unordered_children if children_vis.count > 0 ordered << children_vis.select { |vis| vis.prev_id.nil? }.first while !ordered.last.next_id.nil? target = ordered.last.next_id unless target.nil? ordered << children_vis.select { |vis| vis.id == target }.first end end end ordered end # TODO: refactor next methods, all have similar naming but some receive user and some others user_id def liked_by?(user_id) likes_by_user_id(user_id).any? end def likes_by_user_id(user_id) likes.where(actor: user_id) end def is_viewable_by_user?(user) is_publically_accesible? || has_read_permission?(user) end def is_accesible_by_user?(user) is_viewable_by_user?(user) || password_protected? end def is_publically_accesible? (public? || public_with_link?) && published? end def writable_by?(user) (user_id == user.id && !user.viewer?) || has_write_permission?(user) end def varnish_key "#{user.database_name}:#{sorted_related_table_names},#{id}" end def surrogate_key get_surrogate_key(CartoDB::SURROGATE_NAMESPACE_VISUALIZATION, id) end def qualified_name(viewer_user = nil) if viewer_user.nil? || owner?(viewer_user) name else "#{user.sql_safe_database_schema}.#{name}" end end # Despite storing always a named map, no need to retrieve it for "public" visualizations def retrieve_named_map? password_protected? || has_private_tables? end def has_password? !password_salt.nil? && !encrypted_password.nil? end def type_slide? type == TYPE_SLIDE end def kind_raster? kind == KIND_RASTER end def canonical? type == TYPE_CANONICAL end def derived? type == TYPE_DERIVED end def remote? type == TYPE_REMOTE end def layers map ? map.layers : [] end def data_layers map ? map.data_layers : [] end def carto_layers map ? map.carto_layers : [] end def user_layers map ? map.user_layers : [] end def torque_layers map ? map.torque_layers : [] end def other_layers map ? map.other_layers : [] end def base_layers map ? map.base_layers : [] end def named_map_layers map ? map.named_map_layers : [] end def password_valid?(password) has_password? && ( password_digest(password, password_salt) == encrypted_password ) end def organization? privacy == PRIVACY_PRIVATE && !permission.acl.empty? end def password_protected? privacy == PRIVACY_PROTECTED end def private? is_privacy_private? && !organization? end def is_privacy_private? privacy == PRIVACY_PRIVATE end def public? privacy == PRIVACY_PUBLIC end def public_with_link? self.privacy == PRIVACY_LINK end def editable? !(kind_raster? || type_slide?) end def get_auth_tokens [get_auth_token] end def mapviews @mapviews ||= CartoDB::Visualization::Stats.mapviews(stats) end def total_mapviews @total_mapviews ||= CartoDB::Visualization::Stats.new(self, nil).total_mapviews end def geometry_types @geometry_types ||= user_table.geometry_types if user_table end def table_service user_table.try(:service) end def has_read_permission?(user) user && (owner?(user) || (permission && permission.user_has_read_permission?(user))) end def estimated_row_count table_service.nil? ? nil : table_service.estimated_row_count end def actual_row_count table_service.nil? ? nil : table_service.actual_row_count end def license_info if !license.nil? Carto::License.find(license.to_sym) end end def can_be_cached? !is_privacy_private? end def likes_count likes.size end def widgets # Preload widgets for all layers ActiveRecord::Associations::Preloader.new(layers, :widgets).run layers.map(&:widgets).flatten end def analysis_widgets widgets.select { |w| w.source_id.present? } end def attributions_from_derived_visualizations related_canonical_visualizations.map(&:attributions).reject(&:blank?) end def get_named_map return false if remote? named_maps_api.show end def save_named_map return if remote? || mapcapped? get_named_map ? named_maps_api.update : named_maps_api.create end def invalidate_cache redis_vizjson_cache.invalidate(id) embed_redis_cache.invalidate(id) CartoDB::Varnish.new.purge(varnish_vizjson_key) end def allowed_auth_tokens entities = [user] + permission.entities_with_read_permission entities.map(&:get_auth_token) end # - v2 (Editor): not private # - v3 (Builder): not derived or not private, mapcapped # This Ruby code should match the SQL code at Carto::VisualizationQueryBuilder#build section for @only_published. def published? !is_privacy_private? && (!builder? || !derived? || mapcapped?) end def builder? version == VERSION_BUILDER end MAX_MAPCAPS_PER_VISUALIZATION = 1 def create_mapcap! unless mapcaps.count < MAX_MAPCAPS_PER_VISUALIZATION mapcaps.last.destroy end auto_generate_indices_for_all_layers mapcaps.create! end def mapcapped? latest_mapcap.present? end def latest_mapcap mapcaps.first end def uses_builder_features? builder? || analyses.any? || widgets.any? || mapcapped? end def add_source_analyses return unless analyses.empty? data_layers.each_with_index do |layer, index| analysis = Carto::Analysis.source_analysis_for_layer(layer, index) if analysis.save layer.options[:source] = analysis.natural_id layer.options[:letter] = analysis.natural_id.first layer.save else CartoDB::Logger.warning(message: 'Couldn\'t add source analysis for layer', user: user, layer: layer) end end # This is needed because Carto::Layer does not yet triggers invalidations on save # It can be safely removed once it does map.notify_map_change end def ids_json layers_for_hash = layers.map do |layer| { layer_id: layer.id, widgets: layer.widgets.map(&:id) } end { visualization_id: id, map_id: map.id, layers: layers_for_hash } end def populate_ids(ids_json) self.id = ids_json[:visualization_id] map.id = ids_json[:map_id] map.layers.each_with_index do |layer, index| stored_layer_ids = ids_json[:layers][index] stored_layer_id = stored_layer_ids[:layer_id] layer.id = stored_layer_id layer.maps = [map] layer.widgets.each_with_index do |widget, widget_index| widget.id = stored_layer_ids[:widgets][widget_index] widget.layer_id = stored_layer_id end end end def for_presentation mapcapped? ? latest_mapcap.regenerate_visualization : self end # TODO: we should make visualization privacy/security methods aware of mapcaps and make those # deal with all the different the cases internally. # See https://github.com/CartoDB/cartodb/pull/9678 def non_mapcapped mapcapped? ? latest_mapcap.visualization : self end def mark_as_vizjson2 $tables_metadata.SADD(V2_VISUALIZATIONS_REDIS_KEY, id) end def uses_vizjson2? $tables_metadata.SISMEMBER(V2_VISUALIZATIONS_REDIS_KEY, id) > 0 end def open_in_editor? !builder? && (uses_vizjson2? || layers.any?(&:gmapsbase?)) end def can_be_automatically_migrated_to_v3? overlays.builder_incompatible.none? end def state super ? super : build_state end def can_be_private? derived? ? user.try(:private_maps_enabled) : user.try(:private_tables_enabled) end # TODO: Backward compatibility with Sequel def store_using_table(_table_privacy_changed = false) store end def store save! self end def is_owner?(user) user.id == user_id end private def remove_password self.password_salt = nil self.encrypted_password = nil end def invalidate # previously we used 'invalidate_cache' but due to public_map displaying all the user public visualizations, # now we need to purgue everything to avoid cached stale data or public->priv still showing scenarios if privacy_changed? || name_changed? || cached_data_changed? invalidate_cache end # When a table's relevant data is changed, propagate to all who use it or relate to it if cached_data_changed? && table user_table.dependent_visualizations.each(&:invalidate_cache) end end # Attributes that cause an invalidation to be triggered (they are presented in public pages) def cached_data_changed? description_changed? || attributions_changed? || version_changed? || encrypted_password_changed? end def propagate_privacy_and_name_to raise "Empty table sent to Visualization::Member propagate_privacy_and_name_to()" unless table propagate_privacy if privacy_changed? && canonical? propagate_name if name_changed? end def propagate_privacy table.reload if table.privacy_text.casecmp(privacy) != 0 # privacy is different, case insensitive CartoDB::TablePrivacyManager.new(table).set_from_visualization(self).update_cdb_tablemetadata end end def propagate_name table.reload # Needed to avoid double renames table.register_table_only = register_table_only table.name = name table.update(name: name) if name_changed? support_tables.rename(name_was, name, true, name_was) end self rescue => exception if name_changed? && !(exception.to_s =~ /relation.*does not exist/) revert_name_change(name_was) end raise CartoDB::InvalidMember.new(exception.to_s) end def revert_name_change(previous_name) self.name = previous_name store rescue => exception raise CartoDB::InvalidMember.new(exception.to_s) end def propagate_attribution_change table.propagate_attribution_change(attributions) if table && attributions_changed? end def support_tables @support_tables ||= CartoDB::Visualization::SupportTables.new( user.in_database, parent_id: id, parent_kind: kind, public_user_roles: user.db_service.public_user_roles ) end def auto_generate_indices_for_all_layers user_tables = data_layers.map(&:user_tables).flatten.uniq user_tables.each do |ut| ::Resque.enqueue(::Resque::UserDBJobs::UserDBMaintenance::AutoIndexTable, ut.id) end end def set_random_id # This should be done with a DB default self.id ||= random_uuid end def set_default_permission self.permission ||= Carto::Permission.create(owner: user, owner_username: user.username) end def delay_saving_tags @cached_tags = tags self.tags = nil end def save_tags update_attribute(:tags, @cached_tags) end def named_maps_api Carto::NamedMaps::Api.new(self) end def redis_vizjson_cache @redis_vizjson_cache ||= CartoDB::Visualization::RedisVizjsonCache.new end def embed_redis_cache @embed_redis_cache ||= EmbedRedisCache.new($tables_metadata) end def password_digest(password, salt) digest = AUTH_DIGEST 10.times do digest = secure_digest(digest, salt, password, AUTH_DIGEST) end digest end def secure_digest(*args) #noinspection RubyArgCount Digest::SHA256.hexdigest(args.flatten.join) end def has_private_tables? !related_tables.index { |table| table.private? }.nil? end def sorted_related_table_names mapped_table_names = related_tables.map { |table| "#{user.database_schema}.#{table.name}" } mapped_table_names.sort { |i, j| i <=> j }.join(',') end def get_related_tables return [] unless map map.data_layers.flat_map(&:user_tables).uniq end def get_related_canonical_visualizations get_related_visualizations_by_types([TYPE_CANONICAL]) end def get_related_visualizations_by_types(types) Carto::Visualization.where(map_id: related_tables.map(&:map_id), type: types).all end def has_write_permission?(user) user && !user.viewer? && (owner?(user) || (permission && permission.user_has_write_permission?(user))) end def owner?(user) user_id == user.id end def varnish_vizjson_key ".*#{id}:vizjson" end def validate_password_presence errors.add(:password, 'required for protected visualization') if password_protected? && !has_password? end def remove_password_if_unprotected remove_password unless password_protected? end def validate_privacy_changes if derived? && is_privacy_private? && privacy_changed? && !user.try(:private_maps_enabled?) errors.add(:privacy, 'cannot be set to private') end end def save_named_map_or_rollback_privacy unless save_named_map # Explicitly set privacy to its previous value so the hooks run and the user db permissions are updated # TODO: It would be better to raise an exception to rollback the transaction, but that can break renames # as we don't explicitly rollback those in the user database. Consider an `after_rollback` hook in user table? self.privacy = privacy_was save end end end Revert incorrect change to save_named_map_or_rollback_privacy require 'active_record' require_relative '../visualization/stats' require_relative '../../helpers/embed_redis_cache' require_dependency 'cartodb/redis_vizjson_cache' require_dependency 'carto/named_maps/api' require_dependency 'carto/helpers/auth_token_generator' require_dependency 'carto/uuidhelper' module Carto::VisualizationDependencies def fully_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count == data_layers.count end def partially_dependent_on?(user_table) derived? && layers_dependent_on(user_table).count.between?(1, data_layers.count - 1) end def dependent_on?(user_table) derived? && layers_dependent_on(user_table).any? end private def layers_dependent_on(user_table) data_layers.select { |l| l.depends_on?(user_table) } end end class Carto::Visualization < ActiveRecord::Base include CacheHelper include Carto::UUIDHelper include Carto::AuthTokenGenerator include Carto::VisualizationDependencies AUTH_DIGEST = '1211b3e77138f6e1724721f1ab740c9c70e66ba6fec5e989bb6640c4541ed15d06dbd5fdcbd3052b'.freeze TYPE_CANONICAL = 'table'.freeze TYPE_DERIVED = 'derived'.freeze TYPE_SLIDE = 'slide'.freeze TYPE_REMOTE = 'remote'.freeze KIND_GEOM = 'geom'.freeze KIND_RASTER = 'raster'.freeze PRIVACY_PUBLIC = 'public'.freeze PRIVACY_PRIVATE = 'private'.freeze PRIVACY_LINK = 'link'.freeze PRIVACY_PROTECTED = 'password'.freeze VERSION_BUILDER = 3 V2_VISUALIZATIONS_REDIS_KEY = 'vizjson2_visualizations'.freeze # INFO: disable ActiveRecord inheritance column self.inheritance_column = :_type belongs_to :user, inverse_of: :visualizations, select: Carto::User::DEFAULT_SELECT belongs_to :full_user, class_name: Carto::User, foreign_key: :user_id, primary_key: :id, inverse_of: :visualizations, readonly: true belongs_to :permission, inverse_of: :visualization has_many :likes, foreign_key: :subject has_many :shared_entities, foreign_key: :entity_id, inverse_of: :visualization has_one :external_source has_many :unordered_children, class_name: Carto::Visualization, foreign_key: :parent_id has_many :overlays, order: '"order"' belongs_to :parent, class_name: Carto::Visualization, primary_key: :parent_id belongs_to :active_layer, class_name: Carto::Layer belongs_to :map, class_name: Carto::Map, inverse_of: :visualization has_many :related_templates, class_name: Carto::Template, foreign_key: :source_visualization_id has_one :synchronization, class_name: Carto::Synchronization has_many :external_sources, class_name: Carto::ExternalSource has_many :analyses, class_name: Carto::Analysis has_many :mapcaps, class_name: Carto::Mapcap, dependent: :destroy, order: 'created_at DESC' has_one :state, class_name: Carto::State, autosave: true has_many :snapshots, class_name: Carto::Snapshot, dependent: :destroy validates :version, presence: true validate :validate_password_presence validate :validate_privacy_changes before_validation :set_default_version, :set_register_table_only before_create :set_random_id, :set_default_permission before_save :remove_password_if_unprotected, :invalidate after_save :save_named_map_or_rollback_privacy, :propagate_attribution_change after_save :propagate_privacy_and_name_to, if: :table # INFO: workaround for array saves not working. There is a bug in `activerecord-postgresql-array` which # makes inserting including array fields to save, but updates work. Wo se insert without tags and add them # with an update after creation. This is fixed in Rails 4. before_create :delay_saving_tags after_create :save_tags attr_accessor :register_table_only def set_register_table_only self.register_table_only = false # This is a callback, returning `true` avoids halting because of assignment `false` return value true end def set_default_version self.version ||= user.try(:new_visualizations_version) end DELETED_COLUMNS = ['state_id', 'url_options'].freeze def self.columns super.reject { |c| DELETED_COLUMNS.include?(c.name) } end def ==(other_visualization) id == other_visualization.id end def size # Only canonical visualizations (Datasets) have a related table and then count against disk quota, # but we want to not break and even allow ordering by size multiple types if user_table user_table.size elsif remote? && external_source external_source.size else 0 end end def tags tags = super tags == nil ? [] : tags end def tags=(tags) tags.reject!(&:blank?) if tags super(tags) end def user_table map.user_table if map end def table @table ||= user_table.try(:service) end def layers_with_data_readable_by(user) return [] unless map map.layers.select { |l| l.data_readable_by?(user) } end def related_tables @related_tables ||= get_related_tables end def related_tables_readable_by(user) layers_with_data_readable_by(user).map { |l| l.user_tables_readable_by(user) }.flatten.uniq end def related_canonical_visualizations @related_canonical_visualizations ||= get_related_canonical_visualizations end def stats @stats ||= CartoDB::Visualization::Stats.new(self).to_poro end def transition_options @transition_options ||= (slide_transition_options.nil? ? {} : JSON.parse(slide_transition_options).symbolize_keys) end def children ordered = [] children_vis = self.unordered_children if children_vis.count > 0 ordered << children_vis.select { |vis| vis.prev_id.nil? }.first while !ordered.last.next_id.nil? target = ordered.last.next_id unless target.nil? ordered << children_vis.select { |vis| vis.id == target }.first end end end ordered end # TODO: refactor next methods, all have similar naming but some receive user and some others user_id def liked_by?(user_id) likes_by_user_id(user_id).any? end def likes_by_user_id(user_id) likes.where(actor: user_id) end def is_viewable_by_user?(user) is_publically_accesible? || has_read_permission?(user) end def is_accesible_by_user?(user) is_viewable_by_user?(user) || password_protected? end def is_publically_accesible? (public? || public_with_link?) && published? end def writable_by?(user) (user_id == user.id && !user.viewer?) || has_write_permission?(user) end def varnish_key "#{user.database_name}:#{sorted_related_table_names},#{id}" end def surrogate_key get_surrogate_key(CartoDB::SURROGATE_NAMESPACE_VISUALIZATION, id) end def qualified_name(viewer_user = nil) if viewer_user.nil? || owner?(viewer_user) name else "#{user.sql_safe_database_schema}.#{name}" end end # Despite storing always a named map, no need to retrieve it for "public" visualizations def retrieve_named_map? password_protected? || has_private_tables? end def has_password? !password_salt.nil? && !encrypted_password.nil? end def type_slide? type == TYPE_SLIDE end def kind_raster? kind == KIND_RASTER end def canonical? type == TYPE_CANONICAL end def derived? type == TYPE_DERIVED end def remote? type == TYPE_REMOTE end def layers map ? map.layers : [] end def data_layers map ? map.data_layers : [] end def carto_layers map ? map.carto_layers : [] end def user_layers map ? map.user_layers : [] end def torque_layers map ? map.torque_layers : [] end def other_layers map ? map.other_layers : [] end def base_layers map ? map.base_layers : [] end def named_map_layers map ? map.named_map_layers : [] end def password_valid?(password) has_password? && ( password_digest(password, password_salt) == encrypted_password ) end def organization? privacy == PRIVACY_PRIVATE && !permission.acl.empty? end def password_protected? privacy == PRIVACY_PROTECTED end def private? is_privacy_private? && !organization? end def is_privacy_private? privacy == PRIVACY_PRIVATE end def public? privacy == PRIVACY_PUBLIC end def public_with_link? self.privacy == PRIVACY_LINK end def editable? !(kind_raster? || type_slide?) end def get_auth_tokens [get_auth_token] end def mapviews @mapviews ||= CartoDB::Visualization::Stats.mapviews(stats) end def total_mapviews @total_mapviews ||= CartoDB::Visualization::Stats.new(self, nil).total_mapviews end def geometry_types @geometry_types ||= user_table.geometry_types if user_table end def table_service user_table.try(:service) end def has_read_permission?(user) user && (owner?(user) || (permission && permission.user_has_read_permission?(user))) end def estimated_row_count table_service.nil? ? nil : table_service.estimated_row_count end def actual_row_count table_service.nil? ? nil : table_service.actual_row_count end def license_info if !license.nil? Carto::License.find(license.to_sym) end end def can_be_cached? !is_privacy_private? end def likes_count likes.size end def widgets # Preload widgets for all layers ActiveRecord::Associations::Preloader.new(layers, :widgets).run layers.map(&:widgets).flatten end def analysis_widgets widgets.select { |w| w.source_id.present? } end def attributions_from_derived_visualizations related_canonical_visualizations.map(&:attributions).reject(&:blank?) end def get_named_map return false if remote? named_maps_api.show end def save_named_map return if remote? || mapcapped? get_named_map ? named_maps_api.update : named_maps_api.create end def invalidate_cache redis_vizjson_cache.invalidate(id) embed_redis_cache.invalidate(id) CartoDB::Varnish.new.purge(varnish_vizjson_key) end def allowed_auth_tokens entities = [user] + permission.entities_with_read_permission entities.map(&:get_auth_token) end # - v2 (Editor): not private # - v3 (Builder): not derived or not private, mapcapped # This Ruby code should match the SQL code at Carto::VisualizationQueryBuilder#build section for @only_published. def published? !is_privacy_private? && (!builder? || !derived? || mapcapped?) end def builder? version == VERSION_BUILDER end MAX_MAPCAPS_PER_VISUALIZATION = 1 def create_mapcap! unless mapcaps.count < MAX_MAPCAPS_PER_VISUALIZATION mapcaps.last.destroy end auto_generate_indices_for_all_layers mapcaps.create! end def mapcapped? latest_mapcap.present? end def latest_mapcap mapcaps.first end def uses_builder_features? builder? || analyses.any? || widgets.any? || mapcapped? end def add_source_analyses return unless analyses.empty? data_layers.each_with_index do |layer, index| analysis = Carto::Analysis.source_analysis_for_layer(layer, index) if analysis.save layer.options[:source] = analysis.natural_id layer.options[:letter] = analysis.natural_id.first layer.save else CartoDB::Logger.warning(message: 'Couldn\'t add source analysis for layer', user: user, layer: layer) end end # This is needed because Carto::Layer does not yet triggers invalidations on save # It can be safely removed once it does map.notify_map_change end def ids_json layers_for_hash = layers.map do |layer| { layer_id: layer.id, widgets: layer.widgets.map(&:id) } end { visualization_id: id, map_id: map.id, layers: layers_for_hash } end def populate_ids(ids_json) self.id = ids_json[:visualization_id] map.id = ids_json[:map_id] map.layers.each_with_index do |layer, index| stored_layer_ids = ids_json[:layers][index] stored_layer_id = stored_layer_ids[:layer_id] layer.id = stored_layer_id layer.maps = [map] layer.widgets.each_with_index do |widget, widget_index| widget.id = stored_layer_ids[:widgets][widget_index] widget.layer_id = stored_layer_id end end end def for_presentation mapcapped? ? latest_mapcap.regenerate_visualization : self end # TODO: we should make visualization privacy/security methods aware of mapcaps and make those # deal with all the different the cases internally. # See https://github.com/CartoDB/cartodb/pull/9678 def non_mapcapped mapcapped? ? latest_mapcap.visualization : self end def mark_as_vizjson2 $tables_metadata.SADD(V2_VISUALIZATIONS_REDIS_KEY, id) end def uses_vizjson2? $tables_metadata.SISMEMBER(V2_VISUALIZATIONS_REDIS_KEY, id) > 0 end def open_in_editor? !builder? && (uses_vizjson2? || layers.any?(&:gmapsbase?)) end def can_be_automatically_migrated_to_v3? overlays.builder_incompatible.none? end def state super ? super : build_state end def can_be_private? derived? ? user.try(:private_maps_enabled) : user.try(:private_tables_enabled) end # TODO: Backward compatibility with Sequel def store_using_table(_table_privacy_changed = false) store end def store save! self end def is_owner?(user) user.id == user_id end private def remove_password self.password_salt = nil self.encrypted_password = nil end def invalidate # previously we used 'invalidate_cache' but due to public_map displaying all the user public visualizations, # now we need to purgue everything to avoid cached stale data or public->priv still showing scenarios if privacy_changed? || name_changed? || cached_data_changed? invalidate_cache end # When a table's relevant data is changed, propagate to all who use it or relate to it if cached_data_changed? && table user_table.dependent_visualizations.each(&:invalidate_cache) end end # Attributes that cause an invalidation to be triggered (they are presented in public pages) def cached_data_changed? description_changed? || attributions_changed? || version_changed? || encrypted_password_changed? end def propagate_privacy_and_name_to raise "Empty table sent to Visualization::Member propagate_privacy_and_name_to()" unless table propagate_privacy if privacy_changed? && canonical? propagate_name if name_changed? end def propagate_privacy table.reload if table.privacy_text.casecmp(privacy) != 0 # privacy is different, case insensitive CartoDB::TablePrivacyManager.new(table).set_from_visualization(self).update_cdb_tablemetadata end end def propagate_name table.reload # Needed to avoid double renames table.register_table_only = register_table_only table.name = name table.update(name: name) if name_changed? support_tables.rename(name_was, name, true, name_was) end self rescue => exception if name_changed? && !(exception.to_s =~ /relation.*does not exist/) revert_name_change(name_was) end raise CartoDB::InvalidMember.new(exception.to_s) end def revert_name_change(previous_name) self.name = previous_name store rescue => exception raise CartoDB::InvalidMember.new(exception.to_s) end def propagate_attribution_change table.propagate_attribution_change(attributions) if table && attributions_changed? end def support_tables @support_tables ||= CartoDB::Visualization::SupportTables.new( user.in_database, parent_id: id, parent_kind: kind, public_user_roles: user.db_service.public_user_roles ) end def auto_generate_indices_for_all_layers user_tables = data_layers.map(&:user_tables).flatten.uniq user_tables.each do |ut| ::Resque.enqueue(::Resque::UserDBJobs::UserDBMaintenance::AutoIndexTable, ut.id) end end def set_random_id # This should be done with a DB default self.id ||= random_uuid end def set_default_permission self.permission ||= Carto::Permission.create(owner: user, owner_username: user.username) end def delay_saving_tags @cached_tags = tags self.tags = nil end def save_tags update_attribute(:tags, @cached_tags) end def named_maps_api Carto::NamedMaps::Api.new(self) end def redis_vizjson_cache @redis_vizjson_cache ||= CartoDB::Visualization::RedisVizjsonCache.new end def embed_redis_cache @embed_redis_cache ||= EmbedRedisCache.new($tables_metadata) end def password_digest(password, salt) digest = AUTH_DIGEST 10.times do digest = secure_digest(digest, salt, password, AUTH_DIGEST) end digest end def secure_digest(*args) #noinspection RubyArgCount Digest::SHA256.hexdigest(args.flatten.join) end def has_private_tables? !related_tables.index { |table| table.private? }.nil? end def sorted_related_table_names mapped_table_names = related_tables.map { |table| "#{user.database_schema}.#{table.name}" } mapped_table_names.sort { |i, j| i <=> j }.join(',') end def get_related_tables return [] unless map map.data_layers.flat_map(&:user_tables).uniq end def get_related_canonical_visualizations get_related_visualizations_by_types([TYPE_CANONICAL]) end def get_related_visualizations_by_types(types) Carto::Visualization.where(map_id: related_tables.map(&:map_id), type: types).all end def has_write_permission?(user) user && !user.viewer? && (owner?(user) || (permission && permission.user_has_write_permission?(user))) end def owner?(user) user_id == user.id end def varnish_vizjson_key ".*#{id}:vizjson" end def validate_password_presence errors.add(:password, 'required for protected visualization') if password_protected? && !has_password? end def remove_password_if_unprotected remove_password unless password_protected? end def validate_privacy_changes if derived? && is_privacy_private? && privacy_changed? && !user.try(:private_maps_enabled?) errors.add(:privacy, 'cannot be set to private') end end def save_named_map_or_rollback_privacy if !save_named_map && privacy_changed? # Explicitly set privacy to its previous value so the hooks run and the user db permissions are updated # TODO: It would be better to raise an exception to rollback the transaction, but that can break renames # as we don't explicitly rollback those in the user database. Consider an `after_rollback` hook in user table? self.privacy = privacy_was save end end end
class Chouette::TimeTable < Chouette::TridentActiveRecord # FIXME http://jira.codehaus.org/browse/JRUBY-6358 set_primary_key :id attr_accessible :objectid, :object_version, :creation_time, :creator_id, :version, :comment, :int_day_types,:monday,:tuesday,:wednesday,:thursday,:friday,:saturday,:sunday attr_accessor :monday,:tuesday,:wednesday,:thursday,:friday,:saturday,:sunday has_many :dates, :class_name => "Chouette::TimeTableDate", :order => :position, :dependent => :destroy has_many :periods, :class_name => "Chouette::TimeTablePeriod", :order => :position, :dependent => :destroy def self.object_id_key "Timetable" end accepts_nested_attributes_for :dates, :allow_destroy => :true accepts_nested_attributes_for :periods, :allow_destroy => :true validates_presence_of :comment def self.start_validity_period ( Chouette::TimeTableDate.select('min(date) as date').map(&:date).compact + Chouette::TimeTablePeriod.select('min(period_start) as period_start').map(&:period_start).compact).min end def self.end_validity_period ( Chouette::TimeTableDate.select('max(date) as date').map(&:date).compact + Chouette::TimeTablePeriod.select('max(period_end) as period_end').map(&:period_end).compact).max end def self.expired_on(expected_date,limit=0) expired = Array.new includes(:dates,:periods).find_each do |tm| max_date = (tm.dates.map(&:date) + tm.periods.map(&:period_end)).max if max_date.nil? || max_date <= expected_date expired << tm end if (limit > 0 && expired.size == limit) break; end end expired end def self.expired_between(after_date,expected_date,limit = 0) expired = Array.new includes(:dates,:periods).find_each do |tm| max_date = (tm.dates.map(&:date) + tm.periods.map(&:period_end)).max if !max_date.nil? && max_date <= expected_date && max_date > after_date expired << tm end if (limit > 0 && expired.size == limit) break; end end expired end def bounding_dates (self.dates.map(&:date) + self.periods.map(&:period_start) + self.periods.map(&:period_end)).compact end def day_by_mask(flag) int_day_types & flag == flag end def valid_days # Build an array with day of calendar week (1-7, Monday is 1). [].tap do |valid_days| valid_days << 1 if monday valid_days << 2 if tuesday valid_days << 3 if wednesday valid_days << 4 if thursday valid_days << 5 if friday valid_days << 6 if saturday valid_days << 7 if sunday end end def monday day_by_mask(4) end def tuesday day_by_mask(8) end def wednesday day_by_mask(16) end def thursday day_by_mask(32) end def friday day_by_mask(64) end def saturday day_by_mask(128) end def sunday day_by_mask(256) end def set_day(day,flag) if (day == '1') self.int_day_types |= flag else self.int_day_types &= ~flag end end def monday=(day) set_day(day,4) end def tuesday=(day) set_day(day,8) end def wednesday=(day) set_day(day,16) end def thursday=(day) set_day(day,32) end def friday=(day) set_day(day,64) end def saturday=(day) set_day(day,128) end def sunday=(day) set_day(day,256) end end use minimum and maximun function class Chouette::TimeTable < Chouette::TridentActiveRecord # FIXME http://jira.codehaus.org/browse/JRUBY-6358 set_primary_key :id attr_accessible :objectid, :object_version, :creation_time, :creator_id, :version, :comment, :int_day_types,:monday,:tuesday,:wednesday,:thursday,:friday,:saturday,:sunday attr_accessor :monday,:tuesday,:wednesday,:thursday,:friday,:saturday,:sunday has_many :dates, :class_name => "Chouette::TimeTableDate", :order => :position, :dependent => :destroy has_many :periods, :class_name => "Chouette::TimeTablePeriod", :order => :position, :dependent => :destroy def self.object_id_key "Timetable" end accepts_nested_attributes_for :dates, :allow_destroy => :true accepts_nested_attributes_for :periods, :allow_destroy => :true validates_presence_of :comment def self.start_validity_period [Chouette::TimeTableDate.minimum(:date),Chouette::TimeTablePeriod.minimum(:period_start)].compact.min end def self.end_validity_period [Chouette::TimeTableDate.maximum(:date),Chouette::TimeTablePeriod.maximum(:period_end)].compact.max end def self.expired_on(expected_date,limit=0) expired = Array.new includes(:dates,:periods).find_each do |tm| max_date = (tm.dates.map(&:date) + tm.periods.map(&:period_end)).max if max_date.nil? || max_date <= expected_date expired << tm end if (limit > 0 && expired.size == limit) break; end end expired end def self.expired_between(after_date,expected_date,limit = 0) expired = Array.new includes(:dates,:periods).find_each do |tm| max_date = (tm.dates.map(&:date) + tm.periods.map(&:period_end)).max if !max_date.nil? && max_date <= expected_date && max_date > after_date expired << tm end if (limit > 0 && expired.size == limit) break; end end expired end def bounding_dates (self.dates.map(&:date) + self.periods.map(&:period_start) + self.periods.map(&:period_end)).compact end def day_by_mask(flag) int_day_types & flag == flag end def valid_days # Build an array with day of calendar week (1-7, Monday is 1). [].tap do |valid_days| valid_days << 1 if monday valid_days << 2 if tuesday valid_days << 3 if wednesday valid_days << 4 if thursday valid_days << 5 if friday valid_days << 6 if saturday valid_days << 7 if sunday end end def monday day_by_mask(4) end def tuesday day_by_mask(8) end def wednesday day_by_mask(16) end def thursday day_by_mask(32) end def friday day_by_mask(64) end def saturday day_by_mask(128) end def sunday day_by_mask(256) end def set_day(day,flag) if (day == '1') self.int_day_types |= flag else self.int_day_types &= ~flag end end def monday=(day) set_day(day,4) end def tuesday=(day) set_day(day,8) end def wednesday=(day) set_day(day,16) end def thursday=(day) set_day(day,32) end def friday=(day) set_day(day,64) end def saturday=(day) set_day(day,128) end def sunday=(day) set_day(day,256) end end
module ExtraData extend ActiveSupport::Concern def detach_extra_data(frd=false) if !frd if !skip_extra_data_processing? && extra_data_too_big? schedule :detach_extra_data, true end return true end raise "extra_data_attribute not defined" unless self.extra_data_attribute if self.data['extra_data_nonce'] && !self.data[self.extra_data_attribute] self.assert_extra_data end # figure out a quick check to see if it's small enough to ignore if extra_data_too_big? || frd == 'force' # generate large nonce to protect self.data['extra_data_nonce'] ||= GoSecure.nonce('extra_data_storage') # for button_sets, pull out self.data['buttons'] # for logs, pull out self.data['events'] extra_data = self.data[extra_data_attribute] extra_data_version = 1 private_path, public_path = self.class.extra_data_remote_paths(self.data['extra_data_nonce'], self.global_id, extra_data_version) public_extra_data = extra_data && self.class.extra_data_public_transform(extra_data) if public_extra_data self.data['extra_data_public'] = true file = Tempfile.new("stash") file.write(public_extra_data.to_json) file.close Uploader.remote_upload(public_path, file.path, 'text/json') end # upload to "/extras/<global_id>/<nonce>/<global_id>.json" file = Tempfile.new("stash") file.write(extra_data.to_json) file.close Uploader.remote_upload(private_path, file.path, 'text/json') # persist the nonce and the url, remove the big-data attribute self.data['extra_data_version'] = extra_data_version self.data.delete(extra_data_attribute) @skip_extra_data_update = true self.save @skip_extra_data_update = false end true end def extra_data_attribute if self.is_a?(LogSession) 'events' elsif self.is_a?(BoardDownstreamButtonSet) 'buttons' else nil end end def extra_data_public_url return nil unless self.data && self.data['extra_data_nonce'] && self.data['extra_data_public'] path = self.class.extra_data_remote_paths(self.data['extra_data_nonce'], self.global_id, self.data['extra_data_version'] || 0)[1] "#{ENV['UPLOADS_S3_CDN']}/#{path}" end def extra_data_private_url return nil unless self.data && self.data['extra_data_nonce'] path = self.class.extra_data_remote_paths(self.data['extra_data_nonce'], self.global_id, self.data['extra_data_version'] || 0)[0] "https://#{ENV['UPLOADS_S3_BUCKET']}.s3.amazonaws.com/#{path}" end def skip_extra_data_processing? # don't process for any record that has the data remotely # but doesn't have the data locally if @skip_extra_data_update return true elsif self.data && !self.data[extra_data_attribute] && self.data['extra_data_nonce'] return true end false end def extra_data_too_big? return false unless ENV['REMOTE_EXTRA_DATA'] if self.is_a?(LogSession) && self.log_type == 'session' user = self.user if self.data && self.data['events'] && self.data['events'].length > 5 return true end elsif self.is_a?(BoardDownstreamButtonSet) return true end # default would be to stringify and check length, # but can be overridden to check .data['buttons'].length, etc. false end def assert_extra_data # if big-data attribute is missing and url is defined, # make a remote call to retrieve the data and set it # to the big-data attribute (without saving) # TODO: start adding support to extra_data retrieval # directly from the client, instead of having to hold up the server request url = self.extra_data_private_url if url && !self.data[self.extra_data_attribute] req = Typhoeus.get(url, timeout: 10) data = JSON.parse(req.body) self.data[self.extra_data_attribute] = data end end def clear_extra_data if self.data && self.data['extra_data_nonce'] self.class.schedule(:clear_extra_data, self.data['extra_data_nonce'], self.global_id, self.data['extra_data_version'] || 0) end true end included do after_save :detach_extra_data after_destroy :clear_extra_data end module ClassMethods def clear_extra_data_orphans # query the remote storage, search for records in batches # for any record that doesn't exist, remove the storage entry # for any record that no longer has the URL reference, remove the storage entry end def extra_data_public_transform(data) nil end def extra_data_remote_paths(nonce, global_id, version=1) private_key = GoSecure.hmac(nonce, 'extra_data_private_key', 1) dir = "extras/#{self.to_s}/#{global_id}/#{nonce}/" dir = "/" + dir if version==0 public_path = dir + "data-#{global_id}.json" private_path = dir + "data-#{private_key}.json" [private_path, public_path] end def clear_extra_data(nonce, global_id, version) private_path, public_path = extra_data_remote_paths(nonce, global_id, version) Uploader.remote_remove(private_path) Uploader.remote_remove(public_path) # remove them both end end end parsing error catch module ExtraData extend ActiveSupport::Concern def detach_extra_data(frd=false) if !frd if !skip_extra_data_processing? && extra_data_too_big? schedule :detach_extra_data, true end return true end raise "extra_data_attribute not defined" unless self.extra_data_attribute if self.data['extra_data_nonce'] && !self.data[self.extra_data_attribute] self.assert_extra_data end # figure out a quick check to see if it's small enough to ignore if extra_data_too_big? || frd == 'force' # generate large nonce to protect self.data['extra_data_nonce'] ||= GoSecure.nonce('extra_data_storage') # for button_sets, pull out self.data['buttons'] # for logs, pull out self.data['events'] extra_data = self.data[extra_data_attribute] extra_data_version = 1 private_path, public_path = self.class.extra_data_remote_paths(self.data['extra_data_nonce'], self.global_id, extra_data_version) public_extra_data = extra_data && self.class.extra_data_public_transform(extra_data) if public_extra_data self.data['extra_data_public'] = true file = Tempfile.new("stash") file.write(public_extra_data.to_json) file.close Uploader.remote_upload(public_path, file.path, 'text/json') end # upload to "/extras/<global_id>/<nonce>/<global_id>.json" file = Tempfile.new("stash") file.write(extra_data.to_json) file.close Uploader.remote_upload(private_path, file.path, 'text/json') # persist the nonce and the url, remove the big-data attribute self.data['extra_data_version'] = extra_data_version self.data.delete(extra_data_attribute) @skip_extra_data_update = true self.save @skip_extra_data_update = false end true end def extra_data_attribute if self.is_a?(LogSession) 'events' elsif self.is_a?(BoardDownstreamButtonSet) 'buttons' else nil end end def extra_data_public_url return nil unless self.data && self.data['extra_data_nonce'] && self.data['extra_data_public'] path = self.class.extra_data_remote_paths(self.data['extra_data_nonce'], self.global_id, self.data['extra_data_version'] || 0)[1] "#{ENV['UPLOADS_S3_CDN']}/#{path}" end def extra_data_private_url return nil unless self.data && self.data['extra_data_nonce'] path = self.class.extra_data_remote_paths(self.data['extra_data_nonce'], self.global_id, self.data['extra_data_version'] || 0)[0] "https://#{ENV['UPLOADS_S3_BUCKET']}.s3.amazonaws.com/#{path}" end def skip_extra_data_processing? # don't process for any record that has the data remotely # but doesn't have the data locally if @skip_extra_data_update return true elsif self.data && !self.data[extra_data_attribute] && self.data['extra_data_nonce'] return true end false end def extra_data_too_big? return false unless ENV['REMOTE_EXTRA_DATA'] if self.is_a?(LogSession) && self.log_type == 'session' user = self.user if self.data && self.data['events'] && self.data['events'].length > 5 return true end elsif self.is_a?(BoardDownstreamButtonSet) return true end # default would be to stringify and check length, # but can be overridden to check .data['buttons'].length, etc. false end def assert_extra_data # if big-data attribute is missing and url is defined, # make a remote call to retrieve the data and set it # to the big-data attribute (without saving) # TODO: start adding support to extra_data retrieval # directly from the client, instead of having to hold up the server request url = self.extra_data_private_url if url && !self.data[self.extra_data_attribute] req = Typhoeus.get(url, timeout: 10) data = JSON.parse(req.body) rescue nil self.data[self.extra_data_attribute] = data end end def clear_extra_data if self.data && self.data['extra_data_nonce'] self.class.schedule(:clear_extra_data, self.data['extra_data_nonce'], self.global_id, self.data['extra_data_version'] || 0) end true end included do after_save :detach_extra_data after_destroy :clear_extra_data end module ClassMethods def clear_extra_data_orphans # query the remote storage, search for records in batches # for any record that doesn't exist, remove the storage entry # for any record that no longer has the URL reference, remove the storage entry end def extra_data_public_transform(data) nil end def extra_data_remote_paths(nonce, global_id, version=1) private_key = GoSecure.hmac(nonce, 'extra_data_private_key', 1) dir = "extras/#{self.to_s}/#{global_id}/#{nonce}/" dir = "/" + dir if version==0 public_path = dir + "data-#{global_id}.json" private_path = dir + "data-#{private_key}.json" [private_path, public_path] end def clear_extra_data(nonce, global_id, version) private_path, public_path = extra_data_remote_paths(nonce, global_id, version) Uploader.remote_remove(private_path) Uploader.remote_remove(public_path) # remove them both end end end
module Effective class Datatable attr_accessor :total_records, :display_records, :view, :attributes delegate :render, :link_to, :mail_to, :to => :@view class << self def all EffectiveDatatables.datatables.map { |klass| klass.new() } end def find(obj, attributes = nil) obj = obj.respond_to?(:to_param) ? obj.to_param : obj EffectiveDatatables.datatables.find { |klass| klass.name.underscore.parameterize == obj }.try(:new, attributes.presence || {}) end def table_column(name, options = {}, proc = nil, &block) if block_given? raise "You cannot use :partial => '' with the block syntax" if options[:partial] raise "You cannot use :proc => ... with the block syntax" if options[:proc] options[:block] = block end raise "You cannot use both :partial => '' and proc => ..." if options[:partial] && options[:proc] (@table_columns ||= HashWithIndifferentAccess.new())[name] = options end def table_columns(*names) names.each { |name| table_column(name) } end def array_column(name, options = {}, proc = nil, &block) table_column(name, options.merge({:array_column => true}), proc, &block) end def array_columns(*names) names.each { |name| array_column(name) } end def default_order(name, direction = :asc) @default_order = {name => direction} end def default_entries(entries) @default_entries = entries end end def initialize(*args) if args.present? raise 'Effective::Datatable.new() can only be called with a Hash like arguments' unless args.first.kind_of?(Hash) args.first.each { |k, v| self.attributes[k] = v } end unless active_record_collection? || (collection.kind_of?(Array) && collection.first.kind_of?(Array)) raise "Unsupported collection type. Should be ActiveRecord class, ActiveRecord relation, or an Array of Arrays [[1, 'something'], [2, 'something else']]" end end # Any attributes set on initialize will be echoed back and available to the class def attributes @attributes ||= HashWithIndifferentAccess.new() end def to_param self.class.name.underscore.parameterize end def collection raise "You must define a collection. Something like an ActiveRecord User.all or an Array of Arrays [[1, 'something'], [2, 'something else']]" end def collection_class collection.respond_to?(:klass) ? collection.klass : self.class end def finalize(collection) # Override me if you like collection end # Select only col[:if] == true columns, and then set the col[:index] accordingly def table_columns @table_columns ||= table_columns_with_defaults().select do |_, col| col[:if] == nil || (col[:if].respond_to?(:call) ? (view || self).instance_exec(&col[:if]) : col[:if]) end.each_with_index { |(_, col), index| col[:index] = index } end def to_json raise 'Effective::Datatable to_json called with a nil view. Please call render_datatable(@datatable) or @datatable.view = view before this method' unless view.present? @json ||= { :sEcho => params[:sEcho].to_i, :aaData => table_data || [], :iTotalRecords => ( unless total_records.kind_of?(Hash) total_records.to_i else (total_records.keys.map(&:first).uniq.count) end), :iTotalDisplayRecords => ( unless display_records.kind_of?(Hash) display_records.to_i else (display_records.keys.map(&:first).uniq.count) end) } end # Wish these were protected def order_column_index if params[:iSortCol_0].present? params[:iSortCol_0].to_i elsif default_order.present? (table_columns[default_order.keys.first.to_s] || {}).fetch(:index, 0) else 0 end end def order_direction if params[:sSortDir_0].present? params[:sSortDir_0].try(:downcase) == 'desc' ? 'DESC' : 'ASC' elsif default_order.present? default_order.values.first.to_s.downcase == 'desc' ? 'DESC' : 'ASC' else 'ASC' end end def default_order self.class.instance_variable_get(:@default_order) end def default_entries @default_entries ||= begin entries = (self.class.instance_variable_get(:@default_entries).presence || EffectiveDatatables.default_entries) entries = -1 if entries.to_s.downcase == 'all' [10, 25, 50, 100, 250, 1000, -1].include?(entries) ? entries : 25 end end def search_terms @search_terms ||= HashWithIndifferentAccess.new().tap do |terms| if params[:sEcho].present? table_columns.keys.each_with_index do |col, x| unless (params["sVisible_#{x}"] == 'false' && table_columns[col][:filter][:when_hidden] != true) terms[col] = params["sSearch_#{x}"] if params["sSearch_#{x}"].present? end end else # We are in the initial render and have to apply default search terms only table_columns.each do |name, values| if (values[:filter][:selected].present?) && (values[:visible] != false || values[:filter][:when_hidden] == true) terms[name] = values[:filter][:selected] end end end end end # This is here so classes that inherit from Datatables can can override the specific where clauses on a search column def search_column(collection, table_column, search_term) if table_column[:array_column] array_tool.search_column_with_defaults(collection, table_column, search_term) else table_tool.search_column_with_defaults(collection, table_column, search_term) end end def per_page length = (params[:iDisplayLength].presence || default_entries).to_i if length == -1 9999999 elsif length > 0 length else 25 end end def page params[:iDisplayStart].to_i / per_page + 1 end def view=(view_context) @view = view_context @view.formats = [:html] # 'Just work' with attributes @view.class.send(:attr_accessor, :attributes) @view.attributes = self.attributes # "Copy & Paste" any additional methods defined on the datatable into the view_context begin methods_for_view = '' (self.class.instance_methods(false) - [:collection, :search_column]).each do |instance_method| methods_for_view << self.class.instance_method(instance_method).source end @view.class.module_eval(methods_for_view) rescue => e end end protected # So the idea here is that we want to do as much as possible on the database in ActiveRecord # And then run any array_columns through in post-processed results def table_data col = collection if active_record_collection? self.total_records = (collection_class.connection.execute("SELECT COUNT(*) FROM (#{col.to_sql}) AS datatables_total_count").first['count'] rescue 1) col = table_tool.order(col) col = table_tool.search(col) if table_tool.search_terms.present? && array_tool.search_terms.blank? self.display_records = (collection_class.connection.execute("SELECT COUNT(*) FROM (#{col.to_sql}) AS datatables_filtered_count").first['count'] rescue 1) end else self.total_records = col.size end if array_tool.search_terms.present? col = self.arrayize(col) col = array_tool.search(col) self.display_records = col.size end if array_tool.order_column.present? col = self.arrayize(col) col = array_tool.order(col) end self.display_records ||= total_records if col.kind_of?(Array) col = array_tool.paginate(col) else col = table_tool.paginate(col) col = self.arrayize(col) end col = self.finalize(col) end def arrayize(collection) return collection if @arrayized # Prevent the collection from being arrayized more than once @arrayized = true # We want to use the render :collection for each column that renders partials rendered = {} table_columns.each do |name, opts| if opts[:partial] rendered[name] = (render( :partial => opts[:partial], :as => opts[:partial_local], :collection => collection, :formats => :html, :locals => {:datatable => self}, :spacer_template => '/effective/datatables/spacer_template', ) || '').split('EFFECTIVEDATATABLESSPACER') end end collection.each_with_index.map do |obj, index| table_columns.map do |name, opts| value = if opts[:partial] rendered[name][index] elsif opts[:block] view.instance_exec(obj, collection, self, &opts[:block]) elsif opts[:proc] view.instance_exec(obj, collection, self, &opts[:proc]) elsif opts[:type] == :belongs_to val = (obj.send(name) rescue nil).to_s elsif opts[:type] == :obfuscated_id (obj.send(:to_param) rescue nil).to_s else val = (obj.send(name) rescue nil) val = (obj[opts[:array_index]] rescue nil) if val == nil val end # Last minute formatting of dates case value when Date value.strftime(EffectiveDatatables.date_format) when Time value.strftime(EffectiveDatatables.datetime_format) when DateTime value.strftime(EffectiveDatatables.datetime_format) else value end end end end private def params view.try(:params) || HashWithIndifferentAccess.new() end def table_tool @table_tool ||= ActiveRecordDatatableTool.new(self, table_columns.select { |_, col| col[:array_column] == false }) end def array_tool @array_tool ||= ArrayDatatableTool.new(self, table_columns.select { |_, col| col[:array_column] == true }) end def active_record_collection? @active_record_collection ||= (collection.ancestors.include?(ActiveRecord::Base) rescue false) end def table_columns_with_defaults unless self.class.instance_variable_get(:@table_columns_initialized) self.class.instance_variable_set(:@table_columns_initialized, true) initalize_table_columns(self.class.instance_variable_get(:@table_columns)) end self.class.instance_variable_get(:@table_columns) end def initalize_table_columns(cols) sql_table = (collection.table rescue nil) # Here we identify all belongs_to associations and build up a Hash like: # {:user => {:foreign_key => 'user_id', :klass => User}, :order => {:foreign_key => 'order_id', :klass => Effective::Order}} belong_tos = (collection.ancestors.first.reflect_on_all_associations(:belongs_to) rescue []).inject(HashWithIndifferentAccess.new()) do |retval, bt| unless bt.options[:polymorphic] begin klass = bt.klass || bt.foreign_type.gsub('_type', '').classify.constantize rescue => e klass = nil end retval[bt.name] = {:foreign_key => bt.foreign_key, :klass => klass} if bt.foreign_key.present? && klass.present? end retval end cols.each_with_index do |(name, _), index| # If this is a belongs_to, add an :if clause specifying a collection scope if if belong_tos.key?(name) cols[name][:if] ||= Proc.new { attributes[belong_tos[name][:foreign_key]].blank? } # :if => Proc.new { attributes[:user_id].blank? } end sql_column = (collection.columns rescue []).find do |column| column.name == name.to_s || (belong_tos.key?(name) && column.name == belong_tos[name][:foreign_key]) end cols[name][:array_column] ||= false cols[name][:array_index] = index # The index of this column in the collection, regardless of hidden table_columns cols[name][:name] ||= name cols[name][:label] ||= name.titleize cols[name][:column] ||= (sql_table && sql_column) ? "`#{sql_table.name}`.`#{sql_column.name}`" : name cols[name][:width] ||= nil cols[name][:sortable] = true if cols[name][:sortable] == nil cols[name][:type] ||= (belong_tos.key?(name) ? :belongs_to : (sql_column.try(:type).presence || :string)) cols[name][:class] = "col-#{cols[name][:type]} col-#{name} #{cols[name][:class]}".strip if name == 'id' && collection.respond_to?(:deobfuscate) cols[name][:sortable] = false cols[name][:type] = :obfuscated_id end cols[name][:filter] = initialize_table_column_filter(cols[name][:filter], cols[name][:type], belong_tos[name]) if cols[name][:partial] cols[name][:partial_local] ||= (sql_table.try(:name) || cols[name][:partial].split('/').last(2).first.presence || 'obj').singularize.to_sym end end end def initialize_table_column_filter(filter, col_type, belongs_to) return {:type => :null, :when_hidden => false} if filter == false if filter.kind_of?(Symbol) filter = {:type => filter} elsif filter.kind_of?(String) filter = {:type => filter.to_sym} elsif filter.kind_of?(Hash) == false filter = {} end case col_type # null, number, select, number-range, date-range, checkbox, text(default) when :belongs_to { :type => :select, :when_hidden => false, :values => Proc.new { belongs_to[:klass].all.map { |obj| [obj.id, obj.to_s] }.sort { |x, y| x[1] <=> y[1] } } }.merge(filter) when :integer {:type => :number, :when_hidden => false}.merge(filter) when :boolean {:type => :select, :when_hidden => false, :values => [true, false]}.merge(filter) else {:type => :text, :when_hidden => false}.merge(filter) end end end end oops, messed up the merge a bit module Effective class Datatable attr_accessor :total_records, :display_records, :view, :attributes delegate :render, :link_to, :mail_to, :to => :@view class << self def all EffectiveDatatables.datatables.map { |klass| klass.new() } end def find(obj, attributes = nil) obj = obj.respond_to?(:to_param) ? obj.to_param : obj EffectiveDatatables.datatables.find { |klass| klass.name.underscore.parameterize == obj }.try(:new, attributes.presence || {}) end def table_column(name, options = {}, proc = nil, &block) if block_given? raise "You cannot use :partial => '' with the block syntax" if options[:partial] raise "You cannot use :proc => ... with the block syntax" if options[:proc] options[:block] = block end raise "You cannot use both :partial => '' and proc => ..." if options[:partial] && options[:proc] (@table_columns ||= HashWithIndifferentAccess.new())[name] = options end def table_columns(*names) names.each { |name| table_column(name) } end def array_column(name, options = {}, proc = nil, &block) table_column(name, options.merge({:array_column => true}), proc, &block) end def array_columns(*names) names.each { |name| array_column(name) } end def default_order(name, direction = :asc) @default_order = {name => direction} end def default_entries(entries) @default_entries = entries end end def initialize(*args) if args.present? raise 'Effective::Datatable.new() can only be called with a Hash like arguments' unless args.first.kind_of?(Hash) args.first.each { |k, v| self.attributes[k] = v } end unless active_record_collection? || (collection.kind_of?(Array) && collection.first.kind_of?(Array)) raise "Unsupported collection type. Should be ActiveRecord class, ActiveRecord relation, or an Array of Arrays [[1, 'something'], [2, 'something else']]" end end # Any attributes set on initialize will be echoed back and available to the class def attributes @attributes ||= HashWithIndifferentAccess.new() end def to_param self.class.name.underscore.parameterize end def collection raise "You must define a collection. Something like an ActiveRecord User.all or an Array of Arrays [[1, 'something'], [2, 'something else']]" end def collection_class collection.respond_to?(:klass) ? collection.klass : self.class end def finalize(collection) # Override me if you like collection end # Select only col[:if] == true columns, and then set the col[:index] accordingly def table_columns @table_columns ||= table_columns_with_defaults().select do |_, col| col[:if] == nil || (col[:if].respond_to?(:call) ? (view || self).instance_exec(&col[:if]) : col[:if]) end.each_with_index { |(_, col), index| col[:index] = index } end def to_json raise 'Effective::Datatable to_json called with a nil view. Please call render_datatable(@datatable) or @datatable.view = view before this method' unless view.present? @json ||= { :sEcho => params[:sEcho].to_i, :aaData => table_data || [], :iTotalRecords => ( unless total_records.kind_of?(Hash) total_records.to_i else (total_records.keys.map(&:first).uniq.count) end), :iTotalDisplayRecords => ( unless display_records.kind_of?(Hash) display_records.to_i else (display_records.keys.map(&:first).uniq.count) end) } end def present?(view = nil) self.view = view unless view.nil? to_json[:iTotalDisplayRecords] > 0 end def empty?(view = nil) self.view = view unless view.nil? to_json[:iTotalDisplayRecords] == 0 end # Wish these were protected def order_column_index if params[:iSortCol_0].present? params[:iSortCol_0].to_i elsif default_order.present? (table_columns[default_order.keys.first.to_s] || {}).fetch(:index, 0) else 0 end end def order_direction if params[:sSortDir_0].present? params[:sSortDir_0].try(:downcase) == 'desc' ? 'DESC' : 'ASC' elsif default_order.present? default_order.values.first.to_s.downcase == 'desc' ? 'DESC' : 'ASC' else 'ASC' end end def default_order self.class.instance_variable_get(:@default_order) end def default_entries @default_entries ||= begin entries = (self.class.instance_variable_get(:@default_entries).presence || EffectiveDatatables.default_entries) entries = -1 if entries.to_s.downcase == 'all' [10, 25, 50, 100, 250, 1000, -1].include?(entries) ? entries : 25 end end def search_terms @search_terms ||= HashWithIndifferentAccess.new().tap do |terms| if params[:sEcho].present? table_columns.keys.each_with_index do |col, x| unless (params["sVisible_#{x}"] == 'false' && table_columns[col][:filter][:when_hidden] != true) terms[col] = params["sSearch_#{x}"] if params["sSearch_#{x}"].present? end end else # We are in the initial render and have to apply default search terms only table_columns.each do |name, values| if (values[:filter][:selected].present?) && (values[:visible] != false || values[:filter][:when_hidden] == true) terms[name] = values[:filter][:selected] end end end end end # This is here so classes that inherit from Datatables can can override the specific where clauses on a search column def search_column(collection, table_column, search_term) if table_column[:array_column] array_tool.search_column_with_defaults(collection, table_column, search_term) else table_tool.search_column_with_defaults(collection, table_column, search_term) end end def per_page length = (params[:iDisplayLength].presence || default_entries).to_i if length == -1 9999999 elsif length > 0 length else 25 end end def page params[:iDisplayStart].to_i / per_page + 1 end def view=(view_context) @view = view_context @view.formats = [:html] # 'Just work' with attributes @view.class.send(:attr_accessor, :attributes) @view.attributes = self.attributes # "Copy & Paste" any additional methods defined on the datatable into the view_context begin methods_for_view = '' (self.class.instance_methods(false) - [:collection, :search_column]).each do |instance_method| methods_for_view << self.class.instance_method(instance_method).source end @view.class.module_eval(methods_for_view) rescue => e end end protected # So the idea here is that we want to do as much as possible on the database in ActiveRecord # And then run any array_columns through in post-processed results def table_data col = collection if active_record_collection? self.total_records = (collection_class.connection.execute("SELECT COUNT(*) FROM (#{col.to_sql}) AS datatables_total_count").first['count'] rescue 1) col = table_tool.order(col) col = table_tool.search(col) if table_tool.search_terms.present? && array_tool.search_terms.blank? self.display_records = (collection_class.connection.execute("SELECT COUNT(*) FROM (#{col.to_sql}) AS datatables_filtered_count").first['count'] rescue 1) end else self.total_records = col.size end if array_tool.search_terms.present? col = self.arrayize(col) col = array_tool.search(col) self.display_records = col.size end if array_tool.order_column.present? col = self.arrayize(col) col = array_tool.order(col) end self.display_records ||= total_records if col.kind_of?(Array) col = array_tool.paginate(col) else col = table_tool.paginate(col) col = self.arrayize(col) end col = self.finalize(col) end def arrayize(collection) return collection if @arrayized # Prevent the collection from being arrayized more than once @arrayized = true # We want to use the render :collection for each column that renders partials rendered = {} table_columns.each do |name, opts| if opts[:partial] rendered[name] = (render( :partial => opts[:partial], :as => opts[:partial_local], :collection => collection, :formats => :html, :locals => {:datatable => self}, :spacer_template => '/effective/datatables/spacer_template', ) || '').split('EFFECTIVEDATATABLESSPACER') end end collection.each_with_index.map do |obj, index| table_columns.map do |name, opts| value = if opts[:partial] rendered[name][index] elsif opts[:block] view.instance_exec(obj, collection, self, &opts[:block]) elsif opts[:proc] view.instance_exec(obj, collection, self, &opts[:proc]) elsif opts[:type] == :belongs_to val = (obj.send(name) rescue nil).to_s elsif opts[:type] == :obfuscated_id (obj.send(:to_param) rescue nil).to_s else val = (obj.send(name) rescue nil) val = (obj[opts[:array_index]] rescue nil) if val == nil val end # Last minute formatting of dates case value when Date value.strftime(EffectiveDatatables.date_format) when Time value.strftime(EffectiveDatatables.datetime_format) when DateTime value.strftime(EffectiveDatatables.datetime_format) else value end end end end private def params view.try(:params) || HashWithIndifferentAccess.new() end def table_tool @table_tool ||= ActiveRecordDatatableTool.new(self, table_columns.select { |_, col| col[:array_column] == false }) end def array_tool @array_tool ||= ArrayDatatableTool.new(self, table_columns.select { |_, col| col[:array_column] == true }) end def active_record_collection? @active_record_collection ||= (collection.ancestors.include?(ActiveRecord::Base) rescue false) end def table_columns_with_defaults unless self.class.instance_variable_get(:@table_columns_initialized) self.class.instance_variable_set(:@table_columns_initialized, true) initalize_table_columns(self.class.instance_variable_get(:@table_columns)) end self.class.instance_variable_get(:@table_columns) end def initalize_table_columns(cols) sql_table = (collection.table rescue nil) # Here we identify all belongs_to associations and build up a Hash like: # {:user => {:foreign_key => 'user_id', :klass => User}, :order => {:foreign_key => 'order_id', :klass => Effective::Order}} belong_tos = (collection.ancestors.first.reflect_on_all_associations(:belongs_to) rescue []).inject(HashWithIndifferentAccess.new()) do |retval, bt| unless bt.options[:polymorphic] begin klass = bt.klass || bt.foreign_type.gsub('_type', '').classify.constantize rescue => e klass = nil end retval[bt.name] = {:foreign_key => bt.foreign_key, :klass => klass} if bt.foreign_key.present? && klass.present? end retval end cols.each_with_index do |(name, _), index| # If this is a belongs_to, add an :if clause specifying a collection scope if if belong_tos.key?(name) cols[name][:if] ||= Proc.new { attributes[belong_tos[name][:foreign_key]].blank? } # :if => Proc.new { attributes[:user_id].blank? } end sql_column = (collection.columns rescue []).find do |column| column.name == name.to_s || (belong_tos.key?(name) && column.name == belong_tos[name][:foreign_key]) end cols[name][:array_column] ||= false cols[name][:array_index] = index # The index of this column in the collection, regardless of hidden table_columns cols[name][:name] ||= name cols[name][:label] ||= name.titleize cols[name][:column] ||= (sql_table && sql_column) ? "`#{sql_table.name}`.`#{sql_column.name}`" : name cols[name][:width] ||= nil cols[name][:sortable] = true if cols[name][:sortable] == nil cols[name][:type] ||= (belong_tos.key?(name) ? :belongs_to : (sql_column.try(:type).presence || :string)) cols[name][:class] = "col-#{cols[name][:type]} col-#{name} #{cols[name][:class]}".strip if name == 'id' && collection.respond_to?(:deobfuscate) cols[name][:sortable] = false cols[name][:type] = :obfuscated_id end cols[name][:filter] = initialize_table_column_filter(cols[name][:filter], cols[name][:type], belong_tos[name]) if cols[name][:partial] cols[name][:partial_local] ||= (sql_table.try(:name) || cols[name][:partial].split('/').last(2).first.presence || 'obj').singularize.to_sym end end end def initialize_table_column_filter(filter, col_type, belongs_to) return {:type => :null, :when_hidden => false} if filter == false if filter.kind_of?(Symbol) filter = {:type => filter} elsif filter.kind_of?(String) filter = {:type => filter.to_sym} elsif filter.kind_of?(Hash) == false filter = {} end case col_type # null, number, select, number-range, date-range, checkbox, text(default) when :belongs_to { :type => :select, :when_hidden => false, :values => Proc.new { belongs_to[:klass].all.map { |obj| [obj.id, obj.to_s] }.sort { |x, y| x[1] <=> y[1] } } }.merge(filter) when :integer {:type => :number, :when_hidden => false}.merge(filter) when :boolean {:type => :select, :when_hidden => false, :values => [true, false]}.merge(filter) else {:type => :text, :when_hidden => false}.merge(filter) end end end end
class DeleteEvent < Event validates :repository, presence: true validates :ref_type, presence: true, inclusion: { in: %w{branch tag} } validates :ref, presence: true def github_client=(github_client) [:ref_type, :ref].each do |attr| self[attr] = github_client.payload[attr] end end def action_description "#{user.username} deleted the #{ref_type} #{ref} from #{repository.display_name}" end end Fix incorrect method name in DeleteEvent. class DeleteEvent < Event validates :repository, presence: true validates :ref_type, presence: true, inclusion: { in: %w{branch tag} } validates :ref, presence: true def github_event=(github_event) [:ref_type, :ref].each do |attr| self[attr] = github_event.payload[attr] end end def action_description "#{user.username} deleted the #{ref_type} #{ref} from #{repository.display_name}" end end