code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package ca.omny.request; public class ApiResponse { Object response; int statusCode; boolean encodeAsJson; String contentType; public ApiResponse(String response, int statusCode) { this.response = response; this.statusCode = statusCode; this.encodeAsJson = false; } public ApiResponse(Object response, int statusCode) { this.response = response; this.statusCode = statusCode; this.encodeAsJson = !(response instanceof byte[]); } public boolean shouldEncodeAsJson() { return encodeAsJson; } public void setEncodeAsJson(boolean encodeAsJson) { this.encodeAsJson = encodeAsJson; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public Object getResponse() { return response; } public void setResponse(Object response) { this.response = response; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } }
omnycms/omny-cms
libraries/omny-extension-points/src/main/java/ca/omny/request/ApiResponse.java
Java
agpl-3.0
1,197
# # DO NOT MODIFY!!!! # This file is automatically generated by racc 1.4.5 # from racc grammer file "ROR.racc". # require 'racc/parser' # # (generated by racc 1.4.5) # require '/usr/bin/ROR.rex.rb' require 'cgi' class ROTR < Racc::Parser ##### racc 1.4.5 generates ### racc_reduce_table = [ 0, 0, :racc_error, 4, 46, :_reduce_1, 0, 46, :_reduce_none, 1, 47, :_reduce_3, 1, 48, :_reduce_none, 0, 48, :_reduce_none, 1, 50, :_reduce_6, 2, 50, :_reduce_7, 3, 49, :_reduce_8, 2, 51, :_reduce_9, 2, 51, :_reduce_10, 2, 51, :_reduce_11, 2, 51, :_reduce_12, 0, 51, :_reduce_none, 4, 55, :_reduce_14, 9, 54, :_reduce_15, 9, 54, :_reduce_16, 8, 54, :_reduce_17, 1, 56, :_reduce_18, 1, 56, :_reduce_19, 3, 53, :_reduce_20, 3, 57, :_reduce_21, 3, 57, :_reduce_22, 6, 57, :_reduce_23, 5, 57, :_reduce_24, 6, 57, :_reduce_25, 7, 57, :_reduce_26, 6, 57, :_reduce_27, 7, 57, :_reduce_28, 8, 57, :_reduce_29, 8, 57, :_reduce_30, 9, 57, :_reduce_31, 3, 57, :_reduce_32, 0, 57, :_reduce_none, 2, 60, :_reduce_34, 0, 64, :_reduce_35, 0, 65, :_reduce_36, 8, 62, :_reduce_37, 1, 61, :_reduce_38, 3, 61, :_reduce_39, 1, 63, :_reduce_40, 1, 63, :_reduce_41, 4, 58, :_reduce_42, 0, 58, :_reduce_none, 1, 66, :_reduce_44, 4, 66, :_reduce_45, 1, 67, :_reduce_46, 1, 67, :_reduce_47, 1, 67, :_reduce_48, 1, 68, :_reduce_49, 1, 68, :_reduce_50, 1, 68, :_reduce_51, 1, 68, :_reduce_52, 1, 68, :_reduce_53, 1, 68, :_reduce_54, 1, 68, :_reduce_55, 1, 59, :_reduce_none, 1, 59, :_reduce_none, 2, 52, :_reduce_58, 0, 69, :_reduce_none, 2, 69, :_reduce_60, 2, 69, :_reduce_61 ] racc_reduce_n = 62 racc_shift_n = 98 racc_action_table = [ 15, 79, 15, 53, 17, 15, 17, 35, 51, 17, 21, 14, 21, 14, 15, 21, 14, 15, 17, 15, 56, 17, 73, 17, 21, 14, 50, 21, 14, 21, 14, 36, 15, 13, 55, 13, 17, 74, 13, 90, 91, 44, 21, 14, 15, 45, 47, 13, 17, 15, 13, 59, 13, 17, 21, 14, 27, 15, 29, 21, 14, 17, 15, 37, 60, 13, 17, 21, 14, 27, 42, 29, 21, 14, 38, 39, 40, 13, 27, 41, 29, 61, 13, 75, 76, 77, 27, 27, 29, 29, 13, 88, 89, 62, 63, 13, 64, 65, 43, 67, 69, 30, 25, 72, 3, 7, 78, 52, 11, 81, 82, 83, 10, 8, 86, 7, 4, 92, 93, 94, 95, 96, 97 ] racc_action_check = [ 10, 71, 59, 41, 10, 22, 59, 23, 39, 22, 10, 10, 59, 59, 79, 22, 22, 78, 79, 72, 43, 78, 68, 72, 79, 79, 38, 78, 78, 72, 72, 23, 20, 10, 41, 59, 20, 68, 22, 83, 83, 28, 20, 20, 64, 28, 37, 79, 64, 65, 78, 46, 72, 65, 64, 64, 21, 16, 21, 65, 65, 16, 19, 24, 47, 20, 19, 16, 16, 17, 24, 17, 19, 19, 24, 24, 24, 64, 44, 24, 44, 49, 65, 69, 69, 69, 45, 33, 45, 33, 16, 81, 81, 52, 54, 19, 57, 58, 25, 60, 63, 18, 15, 66, 0, 9, 70, 40, 6, 73, 75, 77, 5, 4, 80, 2, 1, 84, 85, 89, 90, 94, 96 ] racc_action_pointer = [ 97, 116, 107, nil, 113, 103, 100, nil, nil, 97, -11, nil, nil, nil, nil, 90, 46, 57, 91, 51, 21, 44, -6, -5, 51, 85, nil, nil, 25, nil, nil, nil, nil, 75, nil, nil, nil, 34, 14, -4, 95, -9, nil, 6, 66, 74, 34, 29, nil, 47, nil, nil, 67, nil, 65, nil, nil, 79, 80, -9, 87, nil, nil, 88, 33, 38, 85, nil, 10, 53, 88, -17, 8, 94, nil, 79, nil, 78, 6, 3, 95, 54, nil, 9, 98, 99, nil, nil, nil, 93, 89, nil, nil, nil, 107, nil, 95, nil ] racc_action_default = [ -2, -62, -5, -3, -62, -62, -4, -6, 98, -5, -13, -7, -1, -59, -33, -62, -13, -62, -62, -13, -13, -62, -13, -58, -62, -62, -12, -19, -62, -18, -8, -9, -10, -62, -11, -60, -61, -62, -62, -62, -62, -62, -20, -62, -62, -62, -62, -38, -32, -62, -21, -22, -62, -57, -62, -56, -14, -62, -62, -13, -62, -34, -43, -62, -13, -13, -62, -39, -62, -24, -62, -62, -13, -62, -23, -25, -27, -62, -13, -13, -62, -62, -26, -28, -62, -62, -17, -42, -44, -62, -29, -30, -15, -16, -62, -31, -62, -45 ] racc_goto_table = [ 18, 28, 24, 1, 5, 33, 26, 2, 9, 31, 32, 12, 34, 68, 54, 48, 49, 46, 87, 23, nil, nil, nil, nil, nil, nil, nil, nil, 57, 58, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 66, nil, nil, nil, nil, 70, 71, nil, nil, nil, nil, nil, nil, 80, nil, nil, nil, nil, nil, 84, 85 ] racc_goto_check = [ 6, 11, 12, 1, 3, 11, 6, 2, 4, 6, 6, 3, 6, 13, 14, 15, 16, 11, 21, 24, nil, nil, nil, nil, nil, nil, nil, nil, 11, 11, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 6, nil, nil, nil, nil, 6, 6, nil, nil, nil, nil, nil, nil, 6, nil, nil, nil, nil, nil, 6, 6 ] racc_goto_pointer = [ nil, 3, 7, 2, 3, nil, -10, nil, nil, nil, nil, -16, -12, -49, -27, -22, -21, nil, nil, nil, nil, -63, nil, nil, 6 ] racc_goto_default = [ nil, nil, nil, nil, nil, 6, nil, 19, 20, 22, 16, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil ] racc_token_table = { false => 0, Object.new => 1, :UMINUS => 2, "*" => 3, "/" => 4, "+" => 5, "-" => 6, :HASHBANG => 7, :NONLOL => 8, :HAI => 9, :KTHXBYE => 10, :IHASA => 11, :WORD => 12, :ITZ => 13, :POSINT => 14, :IZ => 15, :BIGGRTHAN => 16, :YARLY => 17, :NOWAI => 18, :KTHX => 19, :SMALLRTHAN => 20, :BOTHSAEM => 21, :MYSQL => 22, :MAEKDB => 23, :UZE => 24, :MAEKTABELZ => 25, :OP => 26, :CP => 27, :GIMMEH => 28, :FROM => 29, :EDIT => 30, :DEL => 31, :WHERE => 32, :GET_PARAMS => 33, :ADDZ => 34, :COMMA => 35, :STRING => 36, :NUMBR => 37, :YARN => 38, :EQ => 39, :GT => 40, :LT => 41, :LIEK => 42, :ASTERISK => 43, :VISIBLE => 44 } racc_use_result_var = false racc_nt_base = 45 Racc_arg = [ racc_action_table, racc_action_check, racc_action_default, racc_action_pointer, racc_goto_table, racc_goto_check, racc_goto_default, racc_goto_pointer, racc_nt_base, racc_reduce_table, racc_token_table, racc_shift_n, racc_reduce_n, racc_use_result_var ] Racc_token_to_s_table = [ '$end', 'error', 'UMINUS', '"*"', '"/"', '"+"', '"-"', 'HASHBANG', 'NONLOL', 'HAI', 'KTHXBYE', 'IHASA', 'WORD', 'ITZ', 'POSINT', 'IZ', 'BIGGRTHAN', 'YARLY', 'NOWAI', 'KTHX', 'SMALLRTHAN', 'BOTHSAEM', 'MYSQL', 'MAEKDB', 'UZE', 'MAEKTABELZ', 'OP', 'CP', 'GIMMEH', 'FROM', 'EDIT', 'DEL', 'WHERE', 'GET_PARAMS', 'ADDZ', 'COMMA', 'STRING', 'NUMBR', 'YARN', 'EQ', 'GT', 'LT', 'LIEK', 'ASTERISK', 'VISIBLE', '$start', 'target', 'hashbang', 'nonlol', 'lolprog', 'nonlollist', 'stmts', 'visible', 'sql', 'ifstmt', 'vardec', 'intorusrvar', 'sqlstmt', 'createtableargs', 'wordorasterisk', 'insertstringorint', 'wordcommalist', 'stringorintcommalist', 'stringorintforinsert', '@1', '@2', 'numbrorstring', 'wordorstringornum', 'comp', 'stringlist'] Racc_debug_parser = false ##### racc system variables end ##### # reduce 0 omitted module_eval <<'.,.,', 'ROR.racc', 39 def _reduce_1( val, _values) result = nil end .,., # reduce 2 omitted module_eval <<'.,.,', 'ROR.racc', 69 def _reduce_3( val, _values) # This is a hashmap relating integers to user defined variables @inthash = Hash.new { |h,k| h[k] = [] } username_and_password = File.new("/usr/bin/MySQL config.txt", "r") user_and_pass=[] iter = 0 username_and_password.each do |line| user_and_pass[iter] = line iter = iter + 1 end @mysql_username = user_and_pass[0][10..user_and_pass[0].length-2] @mysql_password = user_and_pass[1][10..user_and_pass[1].length-2] # Output valid HTML header, for the benifit of Apache2 cgi = CGI.new("html4") cgi.out {""} end .,., # reduce 4 omitted # reduce 5 omitted module_eval <<'.,.,', 'ROR.racc', 76 def _reduce_6( val, _values) puts val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 77 def _reduce_7( val, _values) puts val[1] end .,., module_eval <<'.,.,', 'ROR.racc', 82 def _reduce_8( val, _values) puts result = val[1] end .,., module_eval <<'.,.,', 'ROR.racc', 85 def _reduce_9( val, _values) result = val[0].to_s + val[1].to_s end .,., module_eval <<'.,.,', 'ROR.racc', 86 def _reduce_10( val, _values) result = val[0].to_s + val[1].to_s end .,., module_eval <<'.,.,', 'ROR.racc', 87 def _reduce_11( val, _values) result = val[0].to_s + val[1].to_s end .,., module_eval <<'.,.,', 'ROR.racc', 88 def _reduce_12( val, _values) result = val[0].to_s + val[1].to_s end .,., # reduce 13 omitted module_eval <<'.,.,', 'ROR.racc', 102 def _reduce_14( val, _values) # I need to create some kind of hashmap, or something between val[1] and val[3] @inthash[val[1]] << val[3] return nil end .,., module_eval <<'.,.,', 'ROR.racc', 114 def _reduce_15( val, _values) if val[1].to_i > val[3].to_i return val[5] else return val[7] end end .,., module_eval <<'.,.,', 'ROR.racc', 122 def _reduce_16( val, _values) if val[1] < val[3] return val[5] else return val[7] end end .,., module_eval <<'.,.,', 'ROR.racc', 130 def _reduce_17( val, _values) if val[1] == val[2] return val[4] else return val[6] end end .,., module_eval <<'.,.,', 'ROR.racc', 131 def _reduce_18( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 137 def _reduce_19( val, _values) usrvar = @inthash[val[0]] return usrvar.to_s end .,., module_eval <<'.,.,', 'ROR.racc', 142 def _reduce_20( val, _values) result = val[1] end .,., module_eval <<'.,.,', 'ROR.racc', 173 def _reduce_21( val, _values) # Create Database # MySQL Commands: stream = <<-end drop database if exists #{val[2]}; create database #{val[2]}; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write; i = 0 while temp = f.gets dave[i] = temp + "<br />" i += 1 end } dave.each { |d| puts d } end .,., module_eval <<'.,.,', 'ROR.racc', 180 def _reduce_22( val, _values) # Use Database @db = val[2] end .,., module_eval <<'.,.,', 'ROR.racc', 210 def _reduce_23( val, _values) # Make Table # MySQL Commands: stream = <<-end use #{@db}; create table #{val[2]} (#{val[4]}); grant all on website_db.* to #{`id -un`.strip}@localhost; end # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write; i = 0 while temp = f.gets dave[i] = temp + "<br />" i += 1 end } dave.each { |d| puts d } end .,., module_eval <<'.,.,', 'ROR.racc', 263 def _reduce_24( val, _values) # Select Query # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write i = 0 colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<br /><br />\n" else dave[i] = "<h3></h3>" end i += 1 end } dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 326 def _reduce_25( val, _values) # Select Query # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write i = 0 colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<table>\n<tr><td>\n<form action='./edit.php' method='post'>\n<input type='hidden' name='filename' value='#{file_name}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='colNames' value='"+colNames+"' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='hidden' name='datadata' value='" + temp[temp.index("\t")..temp.length] + "' />\n<input type='submit' value='Edit' />\n</form>\n</td></tr>\n</table>\n" else dave[i] = "<h3></h3>" end i += 1 end } dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 396 def _reduce_26( val, _values) # Select Query # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write i = 0 colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<table>\n<tr><td>\n<form action='./edit.php' method='post'>\n<input type='hidden' name='filename' value='#{file_name}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='colNames' value='"+colNames+"' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='hidden' name='datadata' value='" + temp[temp.index("\t")..temp.length] + "' />\n<input type='submit' value='Edit' />\n</form>\n</td><td>\n<form action='./delete.php' method='post'>\n<input type='hidden' name='filename' value='#{file_name}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='submit' value='Delete' />\n</form>\n</td></tr>\n</table>\n" else dave[i] = "<h3></h3>" end i += 1 end } dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 457 def _reduce_27( val, _values) # Select Query # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write i = 0 colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<table>\n<tr><td>\n<form action='./delete.php' method='post'>\n<input type='hidden' name='filename' value='#{file_name}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='submit' value='Delete' />\n</form>\n</td></tr>\n</table>\n" else dave[i] = "<h3></h3>" end i += 1 end } dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 529 def _reduce_28( val, _values) # Select Query # Get the parameters from the GET query this_uri = ENV["REQUEST_URI"] require "uri" uri = URI.parse(this_uri) uri_query = uri.query uri_query = uri_query.sub("+"," ") # Unescape the URI uri_query = URI.unescape(uri_query) uri_query = uri_query.sub("="," like '%") uri_query = uri_query + "%'" # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} where #{uri_query} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] i = 0 IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<br /><br />\n" else dave[i] = "<h3></h3>" end i += 1 end } if i == 0 puts "No record found" end dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 611 def _reduce_29( val, _values) # Select Query # Get the parameters from the GET query this_uri = ENV["REQUEST_URI"] require "uri" uri = URI.parse(this_uri) uri_query = uri.query uri_query = uri_query.sub("+"," ") # Unescape the URI uri_query = URI.unescape(uri_query) uri_query = uri_query.sub("="," like '%") uri_query = uri_query + "%'" # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} where #{uri_query} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] i = 0 IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<table>\n<tr><td>\n<form action='./edit.php' method='post'>\n<input type='hidden' name='filename' value='#{ENV["HTTP_REFERER"]}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='colNames' value='"+colNames+"' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='hidden' name='datadata' value='" + temp[temp.index("\t")..temp.length] + "' />\n<input type='submit' value='Edit' />\n</form>\n</td></tr>\n</table>\n" else dave[i] = "<h3></h3>" end i += 1 end } if i == 0 puts "No record found" end dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 690 def _reduce_30( val, _values) # Select Query # Get the parameters from the GET query this_uri = ENV["REQUEST_URI"] require "uri" uri = URI.parse(this_uri) uri_query = uri.query uri_query = uri_query.sub("+"," ") # Unescape the URI uri_query = URI.unescape(uri_query) uri_query = uri_query.sub("="," like '%") uri_query = uri_query + "%'" # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} where #{uri_query} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] i = 0 IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<table>\n<tr><td>\n<form action='./delete.php' method='post'>\n<input type='hidden' name='filename' value='#{file_name}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='submit' value='Delete' /></form>\n</td></tr>\n</table>\n" else dave[i] = "<h3></h3>" end i += 1 end } if i == 0 puts "No record found" end dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 778 def _reduce_31( val, _values) # Select Query # Get the parameters from the GET query this_uri = ENV["REQUEST_URI"] require "uri" uri = URI.parse(this_uri) uri_query = uri.query uri_query = uri_query.gsub("+"," ") # Unescape the URI uri_query = URI.unescape(uri_query) uri_query = uri_query.sub("="," like '%") uri_query = uri_query + "%'" # MySQL Commands: stream = <<-end use #{@db}; select #{val[2]} from #{val[4]} where #{uri_query} order by ID desc; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Get the file name file_name = ARGV[0] slash_index = file_name.rindex("/") if slash_index == nil slash_index = -1 end slash_index = slash_index + 1 file_name = file_name[slash_index..file_name.length] # Execute MySQL Commands dave = [] i = 0 IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write colNames = "" # Save the column titles temp = f.gets colNames = temp while temp = f.gets if i > -1 temp_comma = temp.gsub("\t",", ") space_comma = temp_comma.index(","); space_comma = space_comma + 1 dave[i] = temp_comma[space_comma..temp_comma.length] + "<table>\n<tr><td>\n<form action='./edit.php' method='post'>\n<input type='hidden' name='filename' value='#{ENV["HTTP_REFERER"]}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='colNames' value='"+colNames+"' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='hidden' name='datadata' value='" + temp[temp.index("\t")..temp.length] + "' />\n<input type='submit' value='Edit' />\n</form>\n</td><td>\n<form action='./delete.php' method='post'>\n<input type='hidden' name='filename' value='#{file_name}' />\n<input type='hidden' name='table' value='#{val[4]}' />\n<input type='hidden' name='iddata' value='" + temp[0..temp.index("\t")] + "' />\n<input type='submit' value='Delete' /></form>\n</td></tr>\n</table>\n" else dave[i] = "<h3></h3>" end i += 1 end } if i == 0 puts "No record found" end dave.each { |d| puts d } return nil end .,., module_eval <<'.,.,', 'ROR.racc', 805 def _reduce_32( val, _values) # Insert statement # MySQL Commands: stream = <<-end use #{@db}; insert into #{val[1]} #{val[2]}; grant all on website_db.* to #{`id -un`.strip}@localhost; end # Execute MySQL Commands dave = [] IO.popen("mysql -u #{@mysql_username} -p#{@mysql_password}", "r+") {|f| f.puts stream f.close_write; i = 0 while temp = f.gets dave[i] = temp + "<br />" i += 1 end } dave.each { |d| puts d } end .,., # reduce 33 omitted module_eval <<'.,.,', 'ROR.racc', 813 def _reduce_34( val, _values) return "(#{val[0]}) values (5, 4)" end .,., module_eval <<'.,.,', 'ROR.racc', 815 def _reduce_35( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 816 def _reduce_36( val, _values) return "#{val[0]} , " end .,., module_eval <<'.,.,', 'ROR.racc', 817 def _reduce_37( val, _values) return "#{val[0]} , #{val[2]}" end .,., module_eval <<'.,.,', 'ROR.racc', 820 def _reduce_38( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 821 def _reduce_39( val, _values) return "#{val[0]}, #{val[2]}" end .,., module_eval <<'.,.,', 'ROR.racc', 825 def _reduce_40( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 826 def _reduce_41( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 840 def _reduce_42( val, _values) if val[0] == nil return val[1].to_s + " " + val[3] + val[0].to_s else # More than one argument, a "," is required return val[1].to_s + " " + val[3] + "," + val[0].to_s end end .,., # reduce 43 omitted module_eval <<'.,.,', 'ROR.racc', 843 def _reduce_44( val, _values) return "int" end .,., module_eval <<'.,.,', 'ROR.racc', 844 def _reduce_45( val, _values) return "varchar(#{val[2].to_i})" end .,., module_eval <<'.,.,', 'ROR.racc', 847 def _reduce_46( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 848 def _reduce_47( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 849 def _reduce_48( val, _values) return val[0] end .,., module_eval <<'.,.,', 'ROR.racc', 852 def _reduce_49( val, _values) return "=" end .,., module_eval <<'.,.,', 'ROR.racc', 853 def _reduce_50( val, _values) return "=" end .,., module_eval <<'.,.,', 'ROR.racc', 854 def _reduce_51( val, _values) return ">" end .,., module_eval <<'.,.,', 'ROR.racc', 855 def _reduce_52( val, _values) return ">" end .,., module_eval <<'.,.,', 'ROR.racc', 856 def _reduce_53( val, _values) return "<" end .,., module_eval <<'.,.,', 'ROR.racc', 857 def _reduce_54( val, _values) return "<" end .,., module_eval <<'.,.,', 'ROR.racc', 858 def _reduce_55( val, _values) return "like" end .,., # reduce 56 omitted # reduce 57 omitted module_eval <<'.,.,', 'ROR.racc', 865 def _reduce_58( val, _values) return val[1] end .,., # reduce 59 omitted module_eval <<'.,.,', 'ROR.racc', 874 def _reduce_60( val, _values) # Print a variable usrvar = @inthash[val[1]] return val[0].to_s + usrvar.to_s end .,., module_eval <<'.,.,', 'ROR.racc', 879 def _reduce_61( val, _values) # remove first & last chars... they are " and " return val[0].to_s + val[1][1..val[1].size].chop end .,., def _reduce_none( val, _values) val[0] end end # class ROTR rotr = ROTR.new # Open MySQL config file for reading # aFile = File.new("/home/adam/Desktop/ROR\ 0.03/MySQL\ config.txt", "r") # TODO: this code will process the file, not just print it # Output each line of the file #aFile.each_line do |line| # puts line #end # Open source file for reading bFile = File.new(ARGV[0], "r") # Copy contents of input file into a string str = "" bFile.each_line do |line| str += line end # Parse begin rotr.scan_str(str) rescue ParseError puts 'parse error' end
Adjamo/ROFL-On-Rails
ROR/ROR.tab.rb
Ruby
agpl-3.0
30,563
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_71) on Tue Aug 04 22:15:38 BST 2015 --> <title>M-Index</title> <meta name="date" content="2015-08-04"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="M-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-8.html">Prev Letter</a></li> <li><a href="index-10.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-9.html" target="_top">Frames</a></li> <li><a href="index-9.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">M</a>&nbsp;<a href="index-10.html">N</a>&nbsp;<a href="index-11.html">P</a>&nbsp;<a href="index-12.html">Q</a>&nbsp;<a href="index-13.html">R</a>&nbsp;<a href="index-14.html">S</a>&nbsp;<a href="index-15.html">T</a>&nbsp;<a href="index-16.html">U</a>&nbsp;<a href="index-17.html">V</a>&nbsp;<a name="_M_"> <!-- --> </a> <h2 class="title">M</h2> <dl> <dt><span class="strong"><a href="../stockcontrol/services/StockControlExceptionMapper.ExceptionDAO.html#message">message</a></span> - Variable in class stockcontrol.services.<a href="../stockcontrol/services/StockControlExceptionMapper.ExceptionDAO.html" title="class in stockcontrol.services">StockControlExceptionMapper.ExceptionDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../stockcontrol/utilities/SCUtils.html#MIME_TYPES">MIME_TYPES</a></span> - Static variable in class stockcontrol.utilities.<a href="../stockcontrol/utilities/SCUtils.html" title="class in stockcontrol.utilities">SCUtils</a></dt> <dd> <div class="block">The mine types that are consumed and produces within the Stockcontrol system.</div> </dd> <dt><span class="strong"><a href="../stockcontrol/sessions/SupplierDAO.html#modified">modified</a></span> - Variable in class stockcontrol.sessions.<a href="../stockcontrol/sessions/SupplierDAO.html" title="class in stockcontrol.sessions">SupplierDAO</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../stockcontrol/services/ComponentBatchService.html#modifyBatch(stockcontrol.sessions.BatchDAO)">modifyBatch(BatchDAO)</a></span> - Method in class stockcontrol.services.<a href="../stockcontrol/services/ComponentBatchService.html" title="class in stockcontrol.services">ComponentBatchService</a></dt> <dd> <div class="block">Modifies a batch.</div> </dd> <dt><span class="strong"><a href="../stockcontrol/services/ComponentBatchService.html#modifyCompoment(stockcontrol.sessions.ComponentDAO)">modifyCompoment(ComponentDAO)</a></span> - Method in class stockcontrol.services.<a href="../stockcontrol/services/ComponentBatchService.html" title="class in stockcontrol.services">ComponentBatchService</a></dt> <dd> <div class="block">Modifies an existing Component.</div> </dd> <dt><span class="strong"><a href="../stockcontrol/services/ProductService.html#modifyProduct(stockcontrol.sessions.ProductDAO)">modifyProduct(ProductDAO)</a></span> - Method in class stockcontrol.services.<a href="../stockcontrol/services/ProductService.html" title="class in stockcontrol.services">ProductService</a></dt> <dd> <div class="block">Modifies an existing product.</div> </dd> <dt><span class="strong"><a href="../stockcontrol/services/SupplierService.html#modifySupplier(int,%20java.lang.String)">modifySupplier(int, String)</a></span> - Method in class stockcontrol.services.<a href="../stockcontrol/services/SupplierService.html" title="class in stockcontrol.services">SupplierService</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">M</a>&nbsp;<a href="index-10.html">N</a>&nbsp;<a href="index-11.html">P</a>&nbsp;<a href="index-12.html">Q</a>&nbsp;<a href="index-13.html">R</a>&nbsp;<a href="index-14.html">S</a>&nbsp;<a href="index-15.html">T</a>&nbsp;<a href="index-16.html">U</a>&nbsp;<a href="index-17.html">V</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-8.html">Prev Letter</a></li> <li><a href="index-10.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-9.html" target="_top">Frames</a></li> <li><a href="index-9.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
mmckenzie70/stockcontrol
doc/index-files/index-9.html
HTML
agpl-3.0
7,304
<?php /** * OpenEyes. * * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011 * (C) OpenEyes Foundation, 2011-2013 * This file is part of OpenEyes. * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * OpenEyes 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 OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.openeyes.org.uk * * @author OpenEyes <info@openeyes.org.uk> * @copyright Copyright (c) 2011-2013, OpenEyes Foundation * @license http://www.gnu.org/licenses/agpl-3.0.html The GNU Affero General Public License V3.0 */ class DrugSetTest extends CDbTestCase { /** * @var DrugSet */ protected $model; public $fixtures = array( 'drugsets' => 'DrugSet', ); /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { parent::setUp(); $this->model = new DrugSet(); } /** * @covers DrugSet::model */ public function testModel() { $this->assertEquals('DrugSet', get_class(DrugSet::model()), 'Class name should match model.'); } /** * @covers DrugForm::tableName */ public function testTableName() { $this->assertEquals('drug_set', $this->model->tableName()); } /** * @covers DrugForm::rules */ public function testRules() { $this->assertTrue($this->drugsets('drugset1')->validate()); $this->assertEmpty($this->drugsets('drugset1')->errors); } /** * @covers DrugSet::search */ public function testSearch() { $this->model->setAttributes($this->drugsets('drugset1')->getAttributes()); $results = $this->model->search(); $data = $results->getData(); $expectedKeys = array('drugset1'); $expectedResults = array(); if (!empty($expectedKeys)) { foreach ($expectedKeys as $key) { $expectedResults[] = $this->drugsets($key); } } $this->assertEquals(1, $results->getItemCount()); $this->assertEquals($expectedResults, $data); } }
FiviumAustralia/OpenEyes
protected/tests/unit/models/DrugSetTest.php
PHP
agpl-3.0
2,678
namespace Quest.Lib.Northgate { #if NG_RES_HANDLING public class ResourcePosition { public string Callsign { get; internal set; } public string Organisation { get; internal set; } public DateTime LastFix { get; internal set; } public Vector Vector { get; internal set; } } #endif }
Extentsoftware/Quest
src/Quest.Lib/Northgate/ResourcePosition.cs
C#
agpl-3.0
330
@charset "UTF-8"; /*=== GENERAL */ /*============*/ html, body { background: #fafafa; height: 100%; font-family: "OpenSans", "Cantarell", "Helvetica", "Arial", "PingFang SC", "Microsoft YaHei", sans-serif; } /*=== Links */ a, button.as-link { color: #2980b9; outline: none; } /*=== Forms */ legend { margin: 20px 0 5px; padding: 5px 20px; background: #ecf0f1; display: inline-block; width: auto; font-size: 1.4em; border-radius: 20px; clear: both; } label { min-height: 25px; padding: 5px 0; cursor: pointer; color: #444; } textarea { width: 360px; height: 100px; } input, select, textarea { padding: 5px; background: #fff; color: #666; border: none; border-bottom: 3px solid #ddd; border-right-color: #ddd; border-radius: 5px; min-height: 25px; line-height: 25px; vertical-align: middle; } option { padding: 0 .5em; } input:focus, select:focus, textarea:focus { color: #333; border-color: #2980b9; } input:invalid, select:invalid { color: #f00; border-color: #f00; box-shadow: none; } input:disabled, select:disabled { background: #eee; } input.extend { transition: width 200ms linear; } /*=== Tables */ table { border-collapse: collapse; } tr, th, td { padding: 0.5em; border: 1px solid #ddd; } th { background: #f6f6f6; } form td, form th { font-weight: normal; text-align: center; } /*=== COMPONENTS */ /*===============*/ /*=== Forms */ .form-group { padding: 5px; border: 1px solid transparent; border-radius: 3px; } .form-group::after { content: ""; display: block; clear: both; } .form-group:hover { background: #fff; border: 1px solid #eee; border-radius: 3px; } .form-group.form-actions { margin: 15px 0 25px; padding: 5px 0; background: #ecf0f1; border-top: 3px solid #bdc3c7; border-radius: 5px 5px 0 0; } .form-group.form-actions .btn { margin: 0 10px; } .form-group .group-name { padding: 10px 0; text-align: left; } .form-group .group-controls { min-height: 25px; padding: 5px 0; } .form-group .group-controls .control { line-height: 2.0em; } .form-group table { margin: 10px 220px 0 0; } /*=== Buttons */ .stick { vertical-align: middle; font-size: 0; } .stick input, .stick .btn { border-radius: 0; } .stick .btn:first-child, .stick input:first-child { border-radius: 0 5px 5px 0; } .stick .btn:last-child, .stick input:last-child, .stick .btn + .dropdown > .btn { border-radius: 5px 0 0 5px; } .stick .btn + .btn, .stick .btn + input, .stick .btn + .dropdown > .btn, .stick input + .btn, .stick input + input, .stick input + .dropdown > .btn, .stick .dropdown + .btn, .stick .dropdown + input, .stick .dropdown + .dropdown > .btn { border-right-width: 1px; border-right-style: solid; } .btn { margin: 0; padding: 5px 10px; background: #3498db; display: inline-block; color: #fff; font-size: 0.9rem; border: none; border-bottom: 3px solid #2980b9; border-right-color: #2980b9; border-radius: 5px; min-height: 38px; min-width: 15px; line-height: 25px; vertical-align: middle; cursor: pointer; overflow: hidden; } a.btn { min-height: 25px; line-height: 25px; } .btn:hover { text-decoration: none; } .btn.active, .btn:active, .btn:hover, .dropdown-target:target ~ .btn.dropdown-toggle { background: #2980b9; } .btn-important { font-weight: normal; background: #e67e22; color: #fff; border-bottom: 3px solid #d35400; border-right-color: #d35400; } .btn-important:hover, .btn-important:active { background: #d35400; } .btn-attention { background: #e74c3c; color: #fff; border-bottom: 3px solid #c0392b; border-right-color: #c0392b; } .btn-attention:hover, .btn-attention:active { background: #c0392b; } /*=== Navigation */ .nav-list .nav-header, .nav-list .item { height: 2.5em; line-height: 2.5em; font-size: 0.9rem; } .nav-list .item:hover, .nav-list .item.active { background: #2980b9; color: #fff; } .nav-list .item:hover a, .nav-list .item.active a { color: #fff; } .nav-list .disable { text-align: center; background: #fafafa; color: #aaa; } .nav-list .item > a { padding: 0 10px; } .nav-list a:hover { text-decoration: none; } .nav-list .item.empty a { color: #f39c12; } .nav-list .item:hover.empty a, .nav-list .item.active.empty a { background: #f39c12; color: #fff; } .nav-list .item.error a { color: #bd362f; } .nav-list .item:hover.error a, .nav-list .item.active.error a { background: #bd362f; color: #fff; } .nav-list .nav-header { padding: 0 10px; font-weight: bold; background: #34495e; color: #fff; } .nav-list .nav-form { padding: 3px; text-align: center; } .nav-head { margin: 0; text-align: left; background: #34495e; color: #fff; } .nav-head a { color: #fff; } .nav-head .item { padding: 5px 10px; font-size: 0.9rem; line-height: 1.5rem; } /*=== Horizontal-list */ .horizontal-list { margin: 0; padding: 0; } .horizontal-list .item { vertical-align: middle; } /*=== Dropdown */ .dropdown-menu { margin: 5px 0 0; padding: 5px 0; background: #fafafa; font-size: 0.8rem; border: 1px solid #95a5a6; border-radius: 3px; text-align: right; } .dropdown-menu::after { background: #fff; width: 10px; height: 10px; border-top: 1px solid #95a5a6; border-right: 1px solid #95a5a6; content: ""; position: absolute; top: -6px; left: 13px; z-index: -10; transform: rotate(-45deg); } .dropdown-header { padding: 0 5px 5px; font-weight: bold; text-align: right; color: #34495e; } .dropdown-menu > .item > a, .dropdown-menu > .item > span, .dropdown-menu > .item > .as-link { padding: 0 22px; line-height: 2.5em; font-size: 0.8rem; } .dropdown-menu > .item:hover { background: #2980b9; color: #fff; } .dropdown-menu > .item[aria-checked="true"] > a::before { font-weight: bold; margin: 0 -14px 0 0; } .dropdown-menu > .item:hover > a { text-decoration: none; color: #fff; } .dropdown-menu .input select, .dropdown-menu .input input { margin: 0 auto 5px; padding: 2px 5px; border-radius: 3px; } .separator { margin: 5px 0; border-bottom: 1px solid #ddd; } /*=== Alerts */ .alert { margin: 15px auto; padding: 10px 15px; background: #f4f4f4; color: #aaa; font-size: 0.9em; border: 1px solid #ccc; border-left: 1px solid #aaa; border-bottom: 1px solid #aaa; border-radius: 5px; text-shadow: 0 0 1px #eee; } .alert-head { font-size: 1.15em; } .alert > a { text-decoration: underline; color: inherit; } .alert-warn { background: #ffe; color: #c95; border: 1px solid #eeb; } .alert-success { background: #dfd; color: #484; border: 1px solid #cec; } .alert-error { background: #fdd; color: #844; border: 1px solid #ecc; } /*=== Pagination */ .pagination { background: #ecf0f1; color: #000; font-size: 0.8em; text-align: center; } .content .pagination { margin: 0; padding: 0; } .pagination .item.pager-current { background: #34495e; color: #ecf0f1; font-size: 1.5em; font-weight: bold; } .pagination .item a { display: block; font-style: italic; line-height: 3em; text-decoration: none; color: #000; } .pagination .item a:hover { background: #34495e; color: #ecf0f1; } .pagination .loading, .pagination a:hover.loading { background: url("loader.gif") center center no-repeat #34495e; font-size: 0; } /*=== Boxes */ .box { border: 1px solid #ddd; border-radius: 5px; } .box .box-title { margin: 0; padding: 5px 10px; background: #ecf0f1; color: #333; border-bottom: 1px solid #ddd; border-radius: 5px 5px 0 0; } .box .box-content { max-height: 260px; } .box .box-content .item { padding: 0 10px; font-size: 0.9rem; line-height: 2.5em; } .box .box-title .configure, .box .box-content .item .configure { visibility: hidden; } .box .box-title .configure .icon, .box .box-content .item .configure .icon { vertical-align: middle; background-color: #95a5a6; border-radius: 3px; } .box .box-title:hover .configure, .box .box-content .item:hover .configure { visibility: visible; } /*=== Tree */ .tree { margin: 10px 0; } .tree-folder-title { position: relative; padding: 0 10px; background: #34495e; line-height: 2.5rem; font-size: 1rem; } .tree-folder-title .title { background: inherit; color: #fff; } .tree-folder-title .title:hover { text-decoration: none; } .tree-folder.active .tree-folder-title { background: #2980b9; font-weight: bold; } .tree-folder-items { background: #2c3e50; } .tree-folder-items > .item { padding: 0 10px; line-height: 2.5rem; font-size: 0.8rem; } .tree-folder-items > .item.active { background: #2980b9; } .tree-folder-items > .item > a { text-decoration: none; color: #fff; } /*=== Scrollbar */ @supports (scrollbar-width: thin) { #sidebar { scrollbar-color: rgba(255, 255, 255, 0.05) rgba(0, 0, 0, 0.0); } #sidebar:hover { scrollbar-color: rgba(255, 255, 255, 0.3) rgba(0, 0, 0, 0.0); } } @supports not (scrollbar-width: thin) { #sidebar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); } #sidebar:hover::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.3); } } /*=== STRUCTURE */ /*===============*/ /*=== Header */ .header { background: #ecf0f1; height: 85px; } .header > .item { padding: 10px; vertical-align: middle; text-align: center; } .header > .item.title { width: 230px; } .header > .item.title h1 { margin: 0.5em 0; } .header > .item.title h1 a { text-decoration: none; } .header > .item.search input { width: 230px; } .header .item.search input:focus { width: 350px; } /*=== Body */ #global { height: calc(100% - 85px); } .aside { background: #ecf0f1; } .aside.aside_feed { padding: 10px 0; text-align: center; background: #34495e; border-radius: 10px 0 0 0; } .aside.aside_feed .tree { margin: 10px 0 50px; } /*=== Aside main page (categories) */ .aside_feed .tree-folder-title > .title:not([data-unread="0"])::after { margin: 10px 0; padding: 0 10px; background: inherit; font-size: 0.9rem; position: absolute; left: 0; line-height: 1.5rem; } /*=== Aside main page (feeds) */ .feed.item.empty.active { background: #f39c12; } .feed.item.error.active { background: #bd362f; } .feed.item.empty, .feed.item.empty > a { color: #e67e22; } .feed.item.error, .feed.item.error > a { color: #bd362f; } .feed.item.empty.active, .feed.item.error.active, .feed.item.empty.active > a, .feed.item.error.active > a { color: #fff; } .aside_feed .tree-folder-items .dropdown-menu::after { right: 2px; } .aside_feed .tree-folder-items .item .dropdown-target:target ~ .dropdown-toggle > .icon, .aside_feed .tree-folder-items .item:hover .dropdown-toggle > .icon, .aside_feed .tree-folder-items .item.active .dropdown-toggle > .icon { border-radius: 3px; } /*=== Configuration pages */ .post { padding: 10px 50px; font-size: 0.9em; } .post form { margin: 10px 0; } .post.content { max-width: 550px; } /*=== Prompt (centered) */ .prompt { max-width: 20rem; margin-right: auto; margin-left: auto; padding-right: .5rem; padding-left: .5rem; text-align: center; } .prompt form { margin-top: 2rem; margin-bottom: 3rem; text-align: right; } .prompt .form-group { margin-bottom: 1rem; } .prompt .form-group::after { display: none; } .prompt .form-group.form-group-actions { display: flex; margin-top: 2rem; align-items: center; justify-content: space-between; } .prompt .stick, .prompt input { width: 100%; box-sizing: border-box; } .prompt .btn.btn-important { padding-right: 1.5rem; padding-left: 1.5rem; font-size: 1.1rem; } .prompt p { margin: 20px 0; } /*=== New article notification */ #new-article { background: #3498db; font-size: 0.9em; text-align: center; } #new-article:hover { background: #2980b9; } #new-article > a { line-height: 3em; font-weight: bold; color: #fff; } #new-article > a:hover { text-decoration: none; } /*=== Day indication */ .day { padding: 0 10px; font-weight: bold; line-height: 3em; border-right: 2px solid #ecf0f1; } .day .name { padding: 0 0 0 10px; color: #aab; font-size: 1.8em; opacity: 0.3; font-style: italic; text-align: left; } /*=== Index menu */ .nav_menu { text-align: center; padding: 5px 0; } #dropdown-query ~ .dropdown-menu .dropdown-header .icon { vertical-align: middle; background-color: #95a5a6; border-radius: 3px; } /*=== Feed articles */ .flux { border-right: 2px solid #ecf0f1; } .flux:hover { background: #fff; } .flux.current { background: #fff; border-right-color: #3498db; } .flux.not_read { border-right-color: #ff5300; } .flux.not_read:not(.current) { background: #fff3ed; } .flux.not_read:not(.current):hover .item.title { background: inherit; } .flux.favorite { border-right-color: #ffc300; } .flux.favorite:not(.current) { background: #fff6da; } .flux.favorite:not(.current):hover .item.title { background: #fff6da; } .flux_header { font-size: 0.8rem; cursor: pointer; border-top: 1px solid #ecf0f1; } .flux_header .title { font-size: 0.9rem; } .flux .website .favicon { padding: 5px; } .flux .item.date { color: #666; font-size: 0.7rem; } .flux .bottom { font-size: 0.8rem; text-align: center; } /*=== Content of feed articles */ .content { padding: 20px 10px; } .content > h1.title > a { color: #000; } .content hr { margin: 30px 10px; background: #ddd; height: 1px; border: 0; box-shadow: 0 2px 5px #ccc; } .content pre { margin: 10px auto; padding: 10px 20px; overflow: auto; background: #222; color: #fff; font-size: 0.9rem; border-radius: 3px; } .content code { padding: 2px 5px; background: #fafafa; color: #d14; border: 1px solid #eee; border-radius: 3px; } .content pre code { background: transparent; color: #fff; border: none; } .content blockquote { margin: 0; padding: 5px 20px; background: #fafafa; display: block; color: #333; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; } .content blockquote p { margin: 0; } /*=== Notification and actualize notification */ .notification { padding: 0 5px 0 0; background: #ddd; color: #666; font-size: 0.9em; border: none; border-radius: 3px; text-align: center; font-weight: bold; line-height: 3em; z-index: 10; vertical-align: middle; } .notification.good { background: #1abc9c; color: #fff; } .notification.bad { background: #e74c3c; color: #fff; } .notification a.close { padding: 0 15px; line-height: 3em; border-radius: 3px 0 0 3px; } .notification.good a.close:hover { background: #16a085; } .notification.bad a.close:hover { background: #c0392b; } .notification#actualizeProgress { line-height: 2em; } /*=== "Load more" part */ #bigMarkAsRead { text-align: center; text-decoration: none; background: #ecf0f1; } #bigMarkAsRead:hover { background: #34495e; color: #fff; } /*=== Navigation menu (for articles) */ #nav_entries { margin: 0; text-align: center; line-height: 3em; table-layout: fixed; background: #34495e; } /*=== READER VIEW */ /*================*/ #stream.reader .flux { padding: 0 0 50px; background: #ecf0f1; color: #34495e; border: none; } #stream.reader .flux .author { margin: 0 0 10px; color: #999; font-size: 90%; } /*=== GLOBAL VIEW */ /*================*/ .box.category .box-title .title { font-weight: normal; text-decoration: none; text-align: right; } .box.category:not([data-unread="0"]) .box-title { background: #3498db; } .box.category:not([data-unread="0"]) .box-title:active { background: #2980b9; } .box.category:not([data-unread="0"]) .box-title .title { font-weight: bold; color: #fff; } .box.category .title:not([data-unread="0"])::after { background: none; border: 0; position: absolute; top: 5px; left: 10px; font-weight: bold; box-shadow: none; text-shadow: none; } .box.category .item.feed { padding: 2px 10px; font-size: 0.8rem; } /*=== DIVERS */ /*===========*/ .aside.aside_feed .nav-form input, .aside.aside_feed .nav-form select { width: 140px; } .aside.aside_feed .nav-form .dropdown .dropdown-menu { left: -20px; } .aside.aside_feed .nav-form .dropdown .dropdown-menu::after { left: 33px; } /*=== STATISTICS */ /*===============*/ .stat { margin: 10px 0 20px; } .stat th, .stat td, .stat tr { border: none; } .stat > table td, .stat > table th { border-bottom: 1px solid #ddd; } .stat > .horizontal-list { margin: 0 0 5px; } .stat > .horizontal-list .item { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .stat > .horizontal-list .item:first-child { width: 270px; } /*=== LOGS */ /*=========*/ .loglist { overflow: hidden; border: 1px solid #aaa; } .log { margin: 10px 0; padding: 5px 2%; background: #fafafa; color: #666; font-size: 0.8rem; overflow: auto; } .log > .date { margin: 0 0 0 10px; padding: 5px 10px; border-radius: 20px; } .log.error > .date { background: #e74c3c; color: #fff; } .log.warning > .date { background: #f39c12; } .log.notice > .date { background: #ecf0f1; } .log.debug > .date { background: #111; color: #eee; } /*=== MOBILE */ /*===========*/ @media (max-width: 840px) { .form-group .group-name { padding-bottom: 0; text-align: right; } .box .box-title .configure, .box .box-content .item .configure { visibility: visible; } .aside { transition: width 200ms linear; } .aside .toggle_aside, #panel .close { background: #2c3e50; display: block; width: 100%; height: 50px; line-height: 50px; text-align: center; } .aside.aside_feed { padding: 0; } .nav_menu .btn { margin: 5px 10px; padding: 3px 5px; min-height: 0; } .nav_menu .stick { margin: 0 10px; } .nav_menu .stick .btn { margin: 5px 0; } .nav_menu .search { display: inline-block; max-width: 97%; } .nav_menu .search input { padding: 3px 5px; max-width: 97%; width: 90px; } .nav_menu .search input:focus { width: 400px; } .day .name { font-size: 1.1rem; } .pagination { margin: 0 0 3.5em; } .notification { border-radius: 0; } .notification a.close { background: transparent; display: block; right: 0; } .notification a.close:hover { opacity: 0.5; } .notification a.close .icon { display: none; } .post { padding-right: 15px; padding-left: 15px; } #close-slider.active { background: #2c3e50; } }
aledeg/FreshRSS
p/themes/Flat/flat.rtl.css
CSS
agpl-3.0
18,119
/* * LIMES Core Library - LIMES – Link Discovery Framework for Metric Spaces. * Copyright © 2011 Data Science Group (DICE) (ngonga@uni-paderborn.de) * * 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 * (at your option) 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/>. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.aksw.limes.core.measures.mapper.topology; import org.aksw.limes.core.io.cache.ACache; import org.aksw.limes.core.io.mapping.AMapping; import org.aksw.limes.core.measures.mapper.AMapper; import org.aksw.limes.core.measures.mapper.pointsets.Polygon; import java.util.Set; /** * Mapper that checks for the topological relation crosses. * * @author psmeros */ public class CrossesMapper extends AMapper implements ITopologicRelationMapper { /** * @param sourceData * Set of Polygons * @param targetData * Set of Polygons * @return Mapping */ @Override public AMapping getMapping(Set<Polygon> sourceData, Set<Polygon> targetData) { return RADON.getMapping(sourceData, targetData, RADON.CROSSES); } @Override public AMapping getMapping(ACache source, ACache target, String sourceVar, String targetVar, String expression, double threshold) { return RADON.getMapping(source, target, sourceVar, targetVar, expression, threshold, RADON.CROSSES); } @Override public double getRuntimeApproximation(int sourceSize, int targetSize, double theta, Language language) { return 1000d; } @Override public double getMappingSizeApproximation(int sourceSize, int targetSize, double theta, Language language) { return 1000d; } @Override public String getName() { return "top_crosses"; } }
dice-group/LIMES
limes-core/src/main/java/org/aksw/limes/core/measures/mapper/topology/CrossesMapper.java
Java
agpl-3.0
2,374
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # 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 (at your option) 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/>. # ############################################################################## { 'name': 'Partners Persons Management', 'version': '1.0', 'category': 'Tools', 'sequence': 14, 'summary': '', 'description': """ Partners Persons Management =========================== Openerp consider a person those partners that have not "is_company" as true, now, those partners can have: ---------------------------------------------------------------------------------------------------------- * First Name and Last Name * Birthdate * Sex * Mother and Father * Childs * Age (functional field) * Nationality * Husband/Wife * National Identity * Passport * Marital Status It also adds a configuration menu for choosing which fields do you wanna see. """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'images': [ ], 'depends': [ 'base', ], 'data': [ 'res_partner_view.xml', 'res_config_view.xml', 'security/partner_person_security.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
maljac/odoo-addons
partner_person/__openerp__.py
Python
agpl-3.0
2,095
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'clipboard', 'ug', { copy: 'كۆچۈر', copyError: 'تور كۆرگۈڭىزنىڭ بىخەتەرلىك تەڭشىكى تەھرىرلىگۈچنىڭ كۆچۈر مەشغۇلاتىنى ئۆزلۈكىدىن ئىجرا قىلىشىغا يول قويمايدۇ، ھەرپتاختا تېز كۇنۇپكا (Ctrl/Cmd+C) ئارقىلىق تاماملاڭ', cut: 'كەس', cutError: 'تور كۆرگۈڭىزنىڭ بىخەتەرلىك تەڭشىكى تەھرىرلىگۈچنىڭ كەس مەشغۇلاتىنى ئۆزلۈكىدىن ئىجرا قىلىشىغا يول قويمايدۇ، ھەرپتاختا تېز كۇنۇپكا (Ctrl/Cmd+X) ئارقىلىق تاماملاڭ', paste: 'چاپلا', pasteArea: 'چاپلاش دائىرىسى', pasteMsg: 'ھەرپتاختا تېز كۇنۇپكا (<STRONG>Ctrl/Cmd+V</STRONG>) نى ئىشلىتىپ مەزمۇننى تۆۋەندىكى رامكىغا كۆچۈرۈڭ، ئاندىن <STRONG>جەزملە</STRONG>نى بېسىڭ', securityMsg: 'توركۆرگۈڭىزنىڭ بىخەتەرلىك تەڭشىكى سەۋەبىدىن بۇ تەھرىرلىگۈچ چاپلاش تاختىسىدىكى مەزمۇننى بىۋاستە زىيارەت قىلالمايدۇ، بۇ كۆزنەكتە قايتا بىر قېتىم چاپلىشىڭىز كېرەك.', title: 'چاپلا' } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/clipboard/lang/ug.js
JavaScript
agpl-3.0
1,499
package uk.ac.sanger.mig.aker.services; import java.io.File; import java.io.IOException; import uk.ac.sanger.mig.aker.domain.requests.OrderRequest; import uk.ac.sanger.mig.aker.messages.Order; /** * @author pi1 * @since February 2015 */ public interface WorkOrderService { /** * Send an order to a specific RabbitMQ queue * * @param order testing class... */ void sendOrder(Order order); /** * Handles messages received on a specific RabbitMQ queue * * @param message the message§ */ void receiveConfirmation(String message); /** * Process an order in the following manner: gets all relevant tags (options). * * @param order a work order partially filled */ OrderRequest processOrder(OrderRequest order); /** * Prints an order into a CSV format * * @param order to print */ File printOrder(OrderRequest order) throws IOException; /** * Save an order locally: * <ul> * <li>Update sample tags/options</li> * </ul> * * @param order */ void update(OrderRequest order); }
wtsi-mig/aker-prototype
src/main/java/uk/ac/sanger/mig/aker/services/WorkOrderService.java
Java
agpl-3.0
1,035
/** * Copyright (C) 2009-2014 BIMserver.org * * 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 (at your option) 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/>. */ package org.bimserver.models.ifc4; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * 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 (at your option) 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 {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ public interface IfcWorkSchedule extends IfcWorkControl { /** * Returns the value of the '<em><b>Predefined Type</b></em>' attribute. * The literals are from the enumeration {@link org.bimserver.models.ifc4.IfcWorkScheduleTypeEnum}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Predefined Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Predefined Type</em>' attribute. * @see org.bimserver.models.ifc4.IfcWorkScheduleTypeEnum * @see #isSetPredefinedType() * @see #unsetPredefinedType() * @see #setPredefinedType(IfcWorkScheduleTypeEnum) * @see org.bimserver.models.ifc4.Ifc4Package#getIfcWorkSchedule_PredefinedType() * @model unsettable="true" * @generated */ IfcWorkScheduleTypeEnum getPredefinedType(); /** * Sets the value of the '{@link org.bimserver.models.ifc4.IfcWorkSchedule#getPredefinedType <em>Predefined Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Predefined Type</em>' attribute. * @see org.bimserver.models.ifc4.IfcWorkScheduleTypeEnum * @see #isSetPredefinedType() * @see #unsetPredefinedType() * @see #getPredefinedType() * @generated */ void setPredefinedType(IfcWorkScheduleTypeEnum value); /** * Unsets the value of the '{@link org.bimserver.models.ifc4.IfcWorkSchedule#getPredefinedType <em>Predefined Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetPredefinedType() * @see #getPredefinedType() * @see #setPredefinedType(IfcWorkScheduleTypeEnum) * @generated */ void unsetPredefinedType(); /** * Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcWorkSchedule#getPredefinedType <em>Predefined Type</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Predefined Type</em>' attribute is set. * @see #unsetPredefinedType() * @see #getPredefinedType() * @see #setPredefinedType(IfcWorkScheduleTypeEnum) * @generated */ boolean isSetPredefinedType(); } // IfcWorkSchedule
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/IfcWorkSchedule.java
Java
agpl-3.0
3,936
package org.bimserver.database.actions; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * 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 (at your option) 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 {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import java.io.IOException; /****************************************************************************** * Copyright (C) 2009-2017 BIMserver.org * * 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 (at your option) 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 {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import java.util.HashSet; import java.util.List; import java.util.Set; import org.bimserver.BimserverDatabaseException; import org.bimserver.database.BimserverLockConflictException; import org.bimserver.database.DatabaseSession; import org.bimserver.database.OldQuery; import org.bimserver.models.log.AccessMethod; import org.bimserver.models.store.ConcreteRevision; import org.bimserver.models.store.Project; import org.bimserver.models.store.Revision; import org.bimserver.models.store.StorePackage; import org.bimserver.models.store.User; import org.bimserver.shared.exceptions.ServerException; import org.bimserver.shared.exceptions.UserException; public abstract class BimDatabaseAction<T> { private final Set<ProgressListener> progressListeners = new HashSet<ProgressListener>(); private DatabaseSession databaseSession; private final AccessMethod accessMethod; public abstract T execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException, ServerException; public BimDatabaseAction(DatabaseSession databaseSession, AccessMethod accessMethod) { this.databaseSession = databaseSession; this.accessMethod = accessMethod; } public AccessMethod getAccessMethod() { return accessMethod; } public DatabaseSession getDatabaseSession() { return databaseSession; } public Project getProjectByPoid(long poid) throws BimserverDatabaseException { return databaseSession.get(StorePackage.eINSTANCE.getProject(), poid, OldQuery.getDefault()); } public User getUserByUoid(long uoid) throws BimserverDatabaseException { return databaseSession.get(StorePackage.eINSTANCE.getUser(), uoid, OldQuery.getDefault()); } public User getAdminUser() throws BimserverDatabaseException, BimserverLockConflictException { return getUserByUserName("admin"); } public void setProgress(String state, int progress) { for (ProgressListener progressListener : progressListeners) { progressListener.updateProgress(state, progress); } } public void addProgressListener(ProgressListener progressListener) { progressListeners.add(progressListener); } public void removeProgressListener(ProgressListener progressListener) { progressListeners.remove(progressListener); } public User getSystemUser() throws BimserverDatabaseException, BimserverLockConflictException { return getUserByUserName("system"); } public Project getProjectById(int pid) throws BimserverDatabaseException, BimserverLockConflictException { return (Project) databaseSession.query(StorePackage.eINSTANCE.getProject_Id(), pid); } public List<Project> getProjectsByName(String projectName) throws BimserverDatabaseException, BimserverLockConflictException { return databaseSession.query(StorePackage.eINSTANCE.getProject_Name(), projectName); } public User getUserByUserName(String username) throws BimserverDatabaseException, BimserverLockConflictException { return (User) databaseSession.querySingle(StorePackage.eINSTANCE.getUser_Username(), username, OldQuery.getDefault().getPid(), OldQuery.getDefault().getRid()); } public Revision getRevisionByRoid(long roid) throws BimserverDatabaseException { return (Revision) databaseSession.get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault()); } public ConcreteRevision getConcreteRevision(long croid) throws BimserverLockConflictException, BimserverDatabaseException { return (ConcreteRevision) databaseSession.get(StorePackage.eINSTANCE.getConcreteRevision(), croid, OldQuery.getDefault()); } public void setDatabaseSession(DatabaseSession session) { this.databaseSession = session; } public void rollback() throws BimserverDatabaseException { } public void close() throws IOException { } }
opensourceBIM/BIMserver
BimServer/src/org/bimserver/database/actions/BimDatabaseAction.java
Java
agpl-3.0
5,624
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title></title> <link href="lib/ionic/css/ionic.css" rel="stylesheet"> <script src="lib/ionic/js/ionic.bundle.js"></script> <!-- very important you add it above the cordova.js line otherwise it will not work --> <script src="js/ng-cordova.min.js"></script> <!-- cordova script (this will be a 404 during development) --> <script src="cordova.js"></script> <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above <link href="css/ionic.app.css" rel="stylesheet"> --> <style type="text/css"> .platform-ios .manual-ios-statusbar-padding{ padding-top:20px; } .manual-remove-top-padding{ padding-top:0px; } .manual-remove-top-padding .scroll{ padding-top:0px !important; } </style> <script src="js/app.js"></script> <script src="js/controllers.js"></script> <script src="js/routes.js"></script> <script src="js/services.js"></script> <script src="js/directives.js"></script> <!-- Only required for Tab projects w/ pages in multiple tabs <script src="lib/ionicuirouter/ionicUIRouter.js"></script> --> </head> <body ng-app="app" animation="slide-left-right-ios7"> <div> <div> <ion-nav-bar class="bar-stable"> <ion-nav-back-button class="button-icon icon ion-ios-arrow-back">Back</ion-nav-back-button> </ion-nav-bar> <ion-nav-view></ion-nav-view> </div> </div> </body> </html>
ezzye/ucrecovery
www/index.html
HTML
agpl-3.0
1,679
Registrants = new Meteor.Collection("registrants"); Registrants.allow({ // User must be logged in to register insert: function (userId, doc) { return !! userId; } }); Registrants.attachSchema(new SimpleSchema({ 'first_name' : { type: String, label: "First Name", max: 200 }, 'last_name': { type: String, label: "Last Name", max: 200 }, 'age': { label: "Age at time of event", type: Number, max: 115, min: 0 }, 'ageGroup': { type: String, allowedValues: [ 'child', 'youth', 'teen', 'youngAdult', 'adult' ], optional: true, autoValue: function (doc) { // calculate age group based on age field return calculateAgeGroup(this.field("age").value); } }, 'gradeInSchool': { type: String, optional: true, label: "School grade in Fall", allowedValues: [ "K", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], autoform: { type: "select", options: function () { return [ {label: "K", value: "K"}, {label: "1", value: "1"}, {label: "2", value: "2"}, {label: "3", value: "3"}, {label: "4", value: "4"}, {label: "5", value: "5"}, {label: "6", value: "6"}, {label: "7", value: "7"}, {label: "8", value: "8"}, {label: "9", value: "9"}, {label: "10", value: "10"}, {label: "11", value: "11"}, {label: "12", value: "12"}, ]; } } }, 'postalAddress': { type: String, optional: true, label: "Primary postal address", autoform: { afFieldInput: { type: "textarea" } } }, 'telephone': { type: String, optional: true, label: "Primary telephone number", max: 20 }, 'registrationType': { type: String, allowedValues: [ 'commuter', 'daily', 'weekly', 'cancelled' ] }, 'accommodations': { type: String, allowedValues: [ 'camping', 'dorm', 'semiprivate', 'private', 'jym', 'yaf' ], optional: true, custom: function () { // Required if registration is daily or weekly if ( !this.isSet && ( this.field('registrationType').value === "daily" || this.field('registrationType').value === "weekly") ) { return "required"; } } }, days: { type: [String], optional: true, autoform: { type: "select-checkbox-inline", options: function () { return [ {label: "Monday", value: "Monday"}, {label: "Tuesday", value: "Tuesday"}, {label: "Wednesday", value: "Wednesday"}, {label: "Thursday", value: "Thursday"}, {label: "Friday", value: "Friday"}, {label: "Saturday", value: "Saturday"} ]; } } }, foodPreference: { type: [String], optional: true, autoform: { type: "select-checkbox-inline", allowedValues: [ 'Omnivore', 'Vegetarian', 'Vegan', 'Gluten-free', 'Dairy-free', 'Sugar-free', 'Soy-free', 'Raw vegetables', 'Low-salt' ], options: function () { return [ {label: "Omnivore", value: "Omnivore"}, {label: "Vegetarian", value: "Vegetarian"}, {label: "Vegan", value: "Vegan"}, {label: "Gluten-free", value: "Gluten-free"}, {label: "Dairy-free", value: "Dairy-free"}, {label: "Sugar-free", value: "Sugar-free"}, {label: "Soy-free", value: "Soy-free"}, {label: "Raw vegetables", value: "Raw vegetables"}, {label: "Low-salt", value: "Low-salt"} ]; } } }, 'registrantEmail': { type: String, regEx: SimpleSchema.RegEx.Email, label: "Registrant E-mail address", optional: true }, 'registrantAffiliation': { type: String, optional: true, label: "Affiliated Quaker meeting, worship group, or organization" }, 'firstTimeAttender': { type: Boolean, optional: true, defaultValue: false, label: "First time attender?" }, 'linens': { type: Boolean, optional: true, defaultValue: false, label: "Will you need linens? ($25 extra)" }, 'specialNeeds': { type: String, optional: true, label: "Tell us about any special needs that we can accommodate.", autoform: { afFieldInput: { type: "textarea" } } }, 'carbonTax': { type: Number, label: "Voluntary carbon tax ($USD)", optional: true }, 'donation': { type: Number, label: "Optional donation ($USD)", optional: true }, 'fee' : { type: Number, decimal: true, label: "Fee", optional: true, autoValue: function (doc) { // Set up an empty registration object // to hold values from the submitted registration var registration = {}; // get values from submitted registration and // set attributes on the registration object registration.age = this.field("age").value; registration.ageGroup = calculateAgeGroup(registration.age); registration.type = this.field("registrationType").value; registration.accommodations = this.field("accommodations").value; registration.days = this.field("days").value; registration.firstTimeAttender = this.field("firstTimeAttender").value; registration.linens = this.field("linens").value; registration.carbonTax = this.field("carbonTax").value; // calculate the registration fee // based on the submitted registration return calculateRegistrationPrice(registration); } } })); Registrants.before.insert(function (userId, doc){ // set registration created date to current date doc.createdAt = Date.now(); // Attach registration to Meteor user // for reporting, access control, etc doc.createdById = userId; // Add user email address to registration document doc.createdByEmail = Meteor.users.findOne(userId).emails[0].address; });
quaker-io/pym-2015
both/collections/registrants.js
JavaScript
agpl-3.0
7,333
""" Tests suite for the views of the private messages app. """ from django.test import TestCase, Client from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model from django.utils import timezone from ..models import (PrivateMessage, BlockedUser) class NotificationsViewsTestCase(TestCase): """ Tests suite for the views. """ def setUp(self): """ Create a new user named "johndoe" with password "illpassword". """ self.user1 = get_user_model().objects.create_user(username='johndoe1', password='johndoe1', email='john.doe@example.com') self.user2 = get_user_model().objects.create_user(username='johndoe2', password='johndoe2', email='john.doe@example.com') self.user3 = get_user_model().objects.create_user(username='johndoe3', password='johndoe3', email='john.doe@example.com') self.msg1 = PrivateMessage.objects.create(sender=self.user1, recipient=self.user2, subject='Test message 1', body='Test message') self.msg2 = PrivateMessage.objects.create(sender=self.user1, recipient=self.user2, read_at=timezone.now(), subject='Test message 2', body='Test message') self.msg3 = PrivateMessage.objects.create(sender=self.user1, recipient=self.user2, recipient_deleted_at=timezone.now(), subject='Test message 3', body='Test message') self.msg4 = PrivateMessage.objects.create(sender=self.user1, recipient=self.user2, recipient_permanently_deleted=True, subject='Test message 4', body='Test message') self.msg5 = PrivateMessage.objects.create(sender=self.user2, recipient=self.user3, subject='Test message 5', body='Test message') self.block1 = BlockedUser.objects.create(user=self.user1, blocked_user=self.user2) def test_private_msg_list_view_available(self): """ Test the availability of the "private messages list" view. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:inbox')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/inbox.html') self.assertIn('private_messages', response.context) self.assertQuerysetEqual(response.context['private_messages'], ['<PrivateMessage: Test message 2>', '<PrivateMessage: Test message 1>']) def test_read_private_msg_list_view_available(self): """ Test the availability of the "read private messages list" view. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:inbox_read')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/inbox.html') self.assertIn('private_messages', response.context) self.assertQuerysetEqual(response.context['private_messages'], ['<PrivateMessage: Test message 2>']) def test_unread_private_msg_list_view_available(self): """ Test the availability of the "unread private messages list" view. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:inbox_unread')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/inbox.html') self.assertIn('private_messages', response.context) self.assertQuerysetEqual(response.context['private_messages'], ['<PrivateMessage: Test message 1>']) def test_private_msg_list_view_redirect_not_login(self): """ Test the redirection of the "private messages list" view when not logged-in. """ client = Client() privatemsg_list_url = reverse('privatemsg:inbox') response = client.get(privatemsg_list_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, privatemsg_list_url)) def test_mark_all_private_msg_as_read_view_available(self): """ Test the availability of the "mark all private messages as read" view. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:inbox_mark_all_as_read')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/mark_all_as_read.html') def test_mark_all_private_msg_as_read_view_redirect_not_login(self): """ Test the redirection of the "mark all private messages as read" view when not logged-in. """ client = Client() mark_all_as_read_url = reverse('privatemsg:inbox_mark_all_as_read') response = client.get(mark_all_as_read_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, mark_all_as_read_url)) def test_outbox_list_view_available(self): """ Test the availability of the "sent private messages list" view. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:outbox')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/outbox.html') self.assertIn('private_messages', response.context) self.assertQuerysetEqual(response.context['private_messages'], ['<PrivateMessage: Test message 4>', '<PrivateMessage: Test message 3>', '<PrivateMessage: Test message 2>', '<PrivateMessage: Test message 1>']) def test_outbox_list_view_redirect_not_login(self): """ Test the redirection of the "sent private messages list" view when not logged-in. """ client = Client() outbox_url = reverse('privatemsg:outbox') response = client.get(outbox_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, outbox_url)) def test_trashbox_list_view_available(self): """ Test the availability of the "deleted private messages list" view. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:trash')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/trashbox.html') self.assertIn('private_messages', response.context) self.assertQuerysetEqual(response.context['private_messages'], ['<PrivateMessage: Test message 3>']) def test_trashbox_list_view_redirect_not_login(self): """ Test the redirection of the "deleted private messages list" view when not logged-in. """ client = Client() trashbox_url = reverse('privatemsg:trash') response = client.get(trashbox_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, trashbox_url)) def test_delete_all_deleted_msg_permanently_view_available(self): """ Test the availability of the "empty trash" view. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:delete_all_deleted_msg_permanently')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/trashbox_cleanup.html') def test_delete_all_deleted_msg_permanently_view_redirect_not_login(self): """ Test the redirection of the "empty trash" view when not logged-in. """ client = Client() delete_all_deleted_msg_url = reverse('privatemsg:delete_all_deleted_msg_permanently') response = client.get(delete_all_deleted_msg_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, delete_all_deleted_msg_url)) def test_msg_compose_view_available(self): """ Test the availability of the "compose message" view. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:compose')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_compose.html') def test_msg_compose_to_view_available(self): """ Test the availability of the "compose to message" view. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:compose_to', kwargs={'recipient': 'johndoe2'})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_compose.html') def test_msg_compose_view_redirect_not_login(self): """ Test the redirection of the "compose message" view when not logged-in. """ client = Client() compose_msg_url = reverse('privatemsg:compose') response = client.get(compose_msg_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, compose_msg_url)) def test_msg_detail_view_available_as_sender(self): """ Test the availability of the "message detail" view as sender. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_detail', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_detail.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) self.assertIn('is_sender', response.context) self.assertTrue(response.context['is_sender']) self.assertIn('is_recipient', response.context) self.assertFalse(response.context['is_recipient']) def test_msg_detail_view_available_as_recipient(self): """ Test the availability of the "message detail" view as recipient. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:msg_detail', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_detail.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) self.assertIn('is_recipient', response.context) self.assertTrue(response.context['is_recipient']) self.assertIn('is_sender', response.context) self.assertFalse(response.context['is_sender']) def test_msg_detail_view_not_available_as_thirdparty(self): """ Test the UN-availability of the "message detail" view as a third party. """ client = Client() client.login(username='johndoe3', password='johndoe3') response = client.get(reverse('privatemsg:msg_detail', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_detail_view_with_unknown_msg(self): """ Test the UN-availability of the "message detail" view with an unknown message PK. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_detail', kwargs={'pk': '1337'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_detail_view_redirect_not_login(self): """ Test the redirection of the "message detail" view when not logged-in. """ client = Client() msg_details_url = reverse('privatemsg:msg_detail', kwargs={'pk': self.msg1.pk}) response = client.get(msg_details_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_details_url)) def test_msg_reply_view_available_as_sender(self): """ Test the availability of the "message reply" view as sender. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_reply', kwargs={'parent_pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_reply.html') self.assertIn('parent_msg', response.context) self.assertEqual(response.context['parent_msg'], self.msg1) def test_msg_reply_view_available_as_recipient(self): """ Test the availability of the "message reply" view as sender. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:msg_reply', kwargs={'parent_pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_reply.html') self.assertIn('parent_msg', response.context) self.assertEqual(response.context['parent_msg'], self.msg1) def test_msg_reply_view_not_available_as_thirdparty(self): """ Test the UN-availability of the "message reply" view as a third party. """ client = Client() client.login(username='johndoe3', password='johndoe3') response = client.get(reverse('privatemsg:msg_reply', kwargs={'parent_pk': self.msg1.pk})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_reply_view_with_unknown_msg(self): """ Test the UN-availability of the "message reply" view with an unknown message PK. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_reply', kwargs={'parent_pk': '1337'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_reply_view_redirect_not_login(self): """ Test the redirection of the "message reply" view when not logged-in. """ client = Client() msg_reply_url = reverse('privatemsg:msg_reply', kwargs={'parent_pk': self.msg1.pk}) response = client.get(msg_reply_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_reply_url)) def test_my_account_view_redirect_not_login(self): """ Test the redirection of the "my account" view when not logged-in. """ client = Client() myaccount_url = reverse('privatemsg:myaccount') response = client.get(myaccount_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, myaccount_url)) def test_my_account_view_available(self): """ Test the availability of the "my account" view when logged-in. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:myaccount')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/my_account.html') def test_msg_delete_view_available_as_sender(self): """ Test the availability of the "delete message" view as sender. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_delete', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_delete_confirm.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) def test_msg_delete_view_available_as_recipient(self): """ Test the availability of the "delete message" view as sender. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:msg_delete', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_delete_confirm.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) def test_msg_delete_view_not_available_as_thirdparty(self): """ Test the UN-availability of the "delete message" view as a third party. """ client = Client() client.login(username='johndoe3', password='johndoe3') response = client.get(reverse('privatemsg:msg_delete', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_delete_view_with_unknown_msg(self): """ Test the UN-availability of the "delete message" view with an unknown message PK. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_delete', kwargs={'pk': '1337'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_delete_view_redirect_not_login(self): """ Test the redirection of the "delete message" view when not logged-in. """ client = Client() msg_delete_url = reverse('privatemsg:msg_delete', kwargs={'pk': self.msg1.pk}) response = client.get(msg_delete_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_delete_url)) def test_msg_delete_permanent_view_available_as_sender(self): """ Test the availability of the "permanently delete message" view as sender. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_delete_permanent', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_delete_permanent_confirm.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) def test_msg_delete_permanent_view_available_as_recipient(self): """ Test the availability of the "permanently delete message" view as sender. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:msg_delete_permanent', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_delete_permanent_confirm.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) def test_msg_delete_permanent_view_not_available_as_thirdparty(self): """ Test the UN-availability of the "permanently delete message" view as a third party. """ client = Client() client.login(username='johndoe3', password='johndoe3') response = client.get(reverse('privatemsg:msg_delete_permanent', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_delete_permanent_view_with_unknown_msg(self): """ Test the UN-availability of the "permanently delete message" view with an unknown message PK. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_delete_permanent', kwargs={'pk': '1337'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_delete_permanent_view_redirect_not_login(self): """ Test the redirection of the "permanently delete message" view when not logged-in. """ client = Client() msg_reply_url = reverse('privatemsg:msg_delete_permanent', kwargs={'pk': self.msg1.pk}) response = client.get(msg_reply_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_reply_url)) def test_msg_undelete_view_available_as_sender(self): """ Test the availability of the "undelete message" view as sender. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_undelete', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_undelete_confirm.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) def test_msg_undelete_view_available_as_recipient(self): """ Test the availability of the "undelete message" view as sender. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:msg_undelete', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/msg_undelete_confirm.html') self.assertIn('message', response.context) self.assertEqual(response.context['message'], self.msg1) def test_msg_undelete_view_not_available_as_thirdparty(self): """ Test the UN-availability of the "undelete message" view as a third party. """ client = Client() client.login(username='johndoe3', password='johndoe3') response = client.get(reverse('privatemsg:msg_undelete', kwargs={'pk': self.msg1.pk})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_undelete_view_with_unknown_msg(self): """ Test the UN-availability of the "undelete message" view with an unknown message PK. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:msg_undelete', kwargs={'pk': '1337'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_undelete_view_with_permanently_deleted_msg(self): """ Test the UN-availability of the "undelete message" view with an already permanently deleted message PK. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:msg_undelete', kwargs={'pk': self.msg4.pk})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_msg_undelete_view_redirect_not_login(self): """ Test the redirection of the "undelete message" view when not logged-in. """ client = Client() msg_undelete_url = reverse('privatemsg:msg_undelete', kwargs={'pk': self.msg1.pk}) response = client.get(msg_undelete_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_undelete_url)) def test_blocked_user_list_view_available(self): """ Test the availability of the "blocked user list" view. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:blocked_users')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/blocked_user_list.html') self.assertIn('blocked_users', response.context) self.assertQuerysetEqual(response.context['blocked_users'], ['<BlockedUser: User "johndoe1" blocking "johndoe2">']) def test_blocked_user_list_view_redirect_not_login(self): """ Test the redirection of the "undelete message" view when not logged-in. """ client = Client() msg_undelete_url = reverse('privatemsg:blocked_users') response = client.get(msg_undelete_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_undelete_url)) def test_block_user_view_available(self): """ Test the availability of the "block user" view. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:block_user', kwargs={'username': self.user2})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/block_user.html') self.assertIn('blocked_user', response.context) self.assertEqual(response.context['blocked_user'], self.user2) self.assertIn('trying_self_block', response.context) self.assertFalse(response.context['trying_self_block']) def test_block_user_view_available_self_block(self): """ Test the availability of the "block user" view when trying to block himself. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:block_user', kwargs={'username': self.user1})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/block_user.html') self.assertIn('blocked_user', response.context) self.assertEqual(response.context['blocked_user'], self.user1) self.assertIn('trying_self_block', response.context) self.assertTrue(response.context['trying_self_block']) def test_block_user_view_available_staff_block(self): """ Test the availability of the "block user" view when trying to block an admin. """ client = Client() client.login(username='johndoe1', password='johndoe1') self.user3.is_staff = True self.user3.save() response = client.get(reverse('privatemsg:block_user', kwargs={'username': self.user3})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/block_user.html') self.assertIn('blocked_user', response.context) self.assertEqual(response.context['blocked_user'], self.user3) self.assertIn('trying_block_staff', response.context) self.assertTrue(response.context['trying_block_staff']) def test_block_user_view_with_unknown_nickname(self): """ Test the UN-availability of the "block user" view with an unknown user name. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:block_user', kwargs={'username': 'unknown'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_block_user_view_redirect_not_login(self): """ Test the redirection of the "undelete message" view when not logged-in. """ client = Client() msg_undelete_url = reverse('privatemsg:block_user', kwargs={'username': self.user1}) response = client.get(msg_undelete_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_undelete_url)) def test_unblock_user_view_available(self): """ Test the availability of the "unblock user" view. """ client = Client() client.login(username='johndoe1', password='johndoe1') response = client.get(reverse('privatemsg:unblock_user', kwargs={'username': self.user2})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'privatemsg/unblock_user.html') self.assertIn('blocked_user', response.context) self.assertEqual(response.context['blocked_user'], self.user2) def test_unblock_user_view_with_unknown_nickname(self): """ Test the UN-availability of the "block user" view with an unknown user name. """ client = Client() client.login(username='johndoe2', password='johndoe2') response = client.get(reverse('privatemsg:unblock_user', kwargs={'username': 'unknown'})) self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, '404.html') def test_unblock_user_view_redirect_not_login(self): """ Test the redirection of the "undelete message" view when not logged-in. """ client = Client() msg_undelete_url = reverse('privatemsg:unblock_user', kwargs={'username': self.user1}) response = client.get(msg_undelete_url) self.assertRedirects(response, '%s?next=%s' % (settings.LOGIN_URL, msg_undelete_url))
TamiaLab/carnetdumaker
apps/privatemsg/tests/test_views.py
Python
agpl-3.0
30,624
using System; using System.Xml.Serialization; namespace OfflineServer.Servers.Http.Responses { public static class VirtualItemType { public static readonly String powerup = "powerup"; public static readonly String amplifier = "amplifier"; public static readonly String skillMod = "skillmodpart"; public static readonly String presetCar = "presetcar"; public static readonly String vinyl = "vinyl"; } [Serializable()] [XmlRoot("InventoryItemTrans")] public class InventoryItemTrans { [XmlElement("EntitlementTag")] public String entitlementTag; [XmlElement("ExpirationDate", IsNullable = true)] public String expirationDate = null; [XmlElement("Hash")] public Int64 hash; [XmlElement("InventoryId")] public Int64 inventoryId; [XmlElement("ProductId")] public String productId = "DO NOT USE ME"; [XmlElement("RemainingUseCount")] public Int32 remainingUseCount; [XmlElement("ResellPrice")] public Int32 resellPrice = 0; [XmlElement("Status")] public String status = "ACTIVE"; [XmlElement("StringHash")] public String stringHash; [XmlElement("VirtualItemType")] public String virtualItemType; public void setTag(String entitlementTag, Boolean alsoSetHash = true) { this.entitlementTag = entitlementTag; if (alsoSetHash) setHash(entitlementTag); } public void setHash(String entitlementTag) { String hexHash = Engine.getHexHash(entitlementTag); hash = Convert.ToInt32(hexHash, 16); stringHash = "0x" + hexHash; } } }
berkay2578/nfsw-server
OfflineServer/Servers/Http/Responses/InventoryItemTrans.cs
C#
agpl-3.0
1,775
/* * mudraw -- command line tool for drawing and converting documents */ #include "mupdf/fitz.h" #if FZ_ENABLE_PDF #include "mupdf/pdf.h" /* for pdf output */ #endif #ifndef DISABLE_MUTHREADS #include "mupdf/helpers/mu-threads.h" #endif #include <string.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #ifdef _MSC_VER struct timeval; struct timezone; int gettimeofday(struct timeval *tv, struct timezone *tz); #else #include <sys/time.h> #endif #ifdef _WIN32 #include <windows.h> #include <direct.h> /* for getcwd */ #else #include <unistd.h> /* for getcwd */ #endif #ifndef PATH_MAX #define PATH_MAX 4096 #endif /* Allow for windows stdout being made binary */ #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif /* Enable for helpful threading debug */ /* #define DEBUG_THREADS(A) do { printf A; fflush(stdout); } while (0) */ #define DEBUG_THREADS(A) do { } while (0) enum { OUT_BBOX, OUT_HTML, OUT_NONE, OUT_OCR_HTML, OUT_OCR_PDF, OUT_OCR_STEXT_JSON, OUT_OCR_STEXT_XML, OUT_OCR_TEXT, OUT_OCR_TRACE, OUT_OCR_XHTML, OUT_PAM, OUT_PBM, OUT_PCL, OUT_PCLM, OUT_PGM, OUT_PKM, OUT_PNG, OUT_PNM, OUT_PPM, OUT_PS, OUT_PSD, OUT_PWG, OUT_STEXT_JSON, OUT_STEXT_XML, OUT_SVG, OUT_TEXT, OUT_TRACE, OUT_XHTML, OUT_XMLTEXT, #if FZ_ENABLE_PDF OUT_PDF, #endif }; enum { CS_INVALID, CS_UNSET, CS_MONO, CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA, CS_CMYK, CS_CMYK_ALPHA, CS_ICC }; enum { SPOTS_NONE, SPOTS_OVERPRINT_SIM, SPOTS_FULL }; typedef struct { char *suffix; int format; int spots; } suffix_t; static const suffix_t suffix_table[] = { /* All the 'triple extension' ones must go first. */ { ".ocr.stext.json", OUT_OCR_STEXT_JSON, 0 }, /* All the 'double extension' ones must go next. */ { ".ocr.txt", OUT_OCR_TEXT, 0 }, { ".ocr.text", OUT_OCR_TEXT, 0 }, { ".ocr.html", OUT_OCR_HTML, 0 }, { ".ocr.xhtml", OUT_OCR_XHTML, 0 }, { ".ocr.stext", OUT_OCR_STEXT_XML, 0 }, { ".ocr.pdf", OUT_OCR_PDF, 0 }, { ".ocr.trace", OUT_OCR_TRACE, 0 }, { ".stext.json", OUT_STEXT_JSON, 0 }, /* And the 'single extension' ones go last. */ { ".png", OUT_PNG, 0 }, { ".pgm", OUT_PGM, 0 }, { ".ppm", OUT_PPM, 0 }, { ".pnm", OUT_PNM, 0 }, { ".pam", OUT_PAM, 0 }, { ".pbm", OUT_PBM, 0 }, { ".pkm", OUT_PKM, 0 }, { ".svg", OUT_SVG, 0 }, { ".pwg", OUT_PWG, 0 }, { ".pclm", OUT_PCLM, 0 }, { ".pcl", OUT_PCL, 0 }, #if FZ_ENABLE_PDF { ".pdf", OUT_PDF, 0 }, #endif { ".psd", OUT_PSD, 1 }, { ".ps", OUT_PS, 0 }, { ".txt", OUT_TEXT, 0 }, { ".text", OUT_TEXT, 0 }, { ".html", OUT_HTML, 0 }, { ".xhtml", OUT_XHTML, 0 }, { ".stext", OUT_STEXT_XML, 0 }, { ".trace", OUT_TRACE, 0 }, { ".xmltext", OUT_XMLTEXT, 0 }, { ".bbox", OUT_BBOX, 0 }, }; typedef struct { char *name; int colorspace; } cs_name_t; static const cs_name_t cs_name_table[] = { { "m", CS_MONO }, { "mono", CS_MONO }, { "g", CS_GRAY }, { "gray", CS_GRAY }, { "grey", CS_GRAY }, { "ga", CS_GRAY_ALPHA }, { "grayalpha", CS_GRAY_ALPHA }, { "greyalpha", CS_GRAY_ALPHA }, { "rgb", CS_RGB }, { "rgba", CS_RGB_ALPHA }, { "rgbalpha", CS_RGB_ALPHA }, { "cmyk", CS_CMYK }, { "cmyka", CS_CMYK_ALPHA }, { "cmykalpha", CS_CMYK_ALPHA }, }; typedef struct { int format; int default_cs; int permitted_cs[7]; } format_cs_table_t; static const format_cs_table_t format_cs_table[] = { { OUT_PNG, CS_RGB, { CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA, CS_ICC } }, { OUT_PPM, CS_RGB, { CS_GRAY, CS_RGB } }, { OUT_PNM, CS_GRAY, { CS_GRAY, CS_RGB } }, { OUT_PAM, CS_RGB_ALPHA, { CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA, CS_CMYK, CS_CMYK_ALPHA } }, { OUT_PGM, CS_GRAY, { CS_GRAY, CS_RGB } }, { OUT_PBM, CS_MONO, { CS_MONO } }, { OUT_PKM, CS_CMYK, { CS_CMYK } }, { OUT_PWG, CS_RGB, { CS_MONO, CS_GRAY, CS_RGB, CS_CMYK } }, { OUT_PCL, CS_MONO, { CS_MONO, CS_RGB } }, { OUT_PCLM, CS_RGB, { CS_RGB, CS_GRAY } }, { OUT_PS, CS_RGB, { CS_GRAY, CS_RGB, CS_CMYK } }, { OUT_PSD, CS_CMYK, { CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA, CS_CMYK, CS_CMYK_ALPHA, CS_ICC } }, { OUT_TRACE, CS_RGB, { CS_RGB } }, { OUT_XMLTEXT, CS_RGB, { CS_RGB } }, { OUT_BBOX, CS_RGB, { CS_RGB } }, { OUT_SVG, CS_RGB, { CS_RGB } }, { OUT_OCR_PDF, CS_RGB, { CS_RGB, CS_GRAY } }, #if FZ_ENABLE_PDF { OUT_PDF, CS_RGB, { CS_RGB } }, #endif { OUT_TEXT, CS_RGB, { CS_RGB } }, { OUT_HTML, CS_RGB, { CS_RGB } }, { OUT_XHTML, CS_RGB, { CS_RGB } }, { OUT_STEXT_XML, CS_RGB, { CS_RGB } }, { OUT_STEXT_JSON, CS_RGB, { CS_RGB } }, { OUT_OCR_TEXT, CS_GRAY, { CS_GRAY } }, { OUT_OCR_HTML, CS_GRAY, { CS_GRAY } }, { OUT_OCR_XHTML, CS_GRAY, { CS_GRAY } }, { OUT_OCR_STEXT_XML, CS_GRAY, { CS_GRAY } }, { OUT_OCR_STEXT_JSON, CS_GRAY, { CS_GRAY } }, { OUT_OCR_TRACE, CS_GRAY, { CS_GRAY } }, }; time_t stat_mtime(const char *path) { struct stat info; if (stat(path, &info) < 0) return 0; return info.st_mtime; } /* In the presence of pthreads or Windows threads, we can offer a multi-threaded option. In the absence, of such, we degrade nicely. */ #ifndef DISABLE_MUTHREADS static mu_mutex mutexes[FZ_LOCK_MAX]; static void mudraw_lock(void *user, int lock) { mu_lock_mutex(&mutexes[lock]); } static void mudraw_unlock(void *user, int lock) { mu_unlock_mutex(&mutexes[lock]); } static fz_locks_context mudraw_locks = { NULL, mudraw_lock, mudraw_unlock }; static void fin_mudraw_locks(void) { int i; for (i = 0; i < FZ_LOCK_MAX; i++) mu_destroy_mutex(&mutexes[i]); } static fz_locks_context *init_mudraw_locks(void) { int i; int failed = 0; for (i = 0; i < FZ_LOCK_MAX; i++) failed |= mu_create_mutex(&mutexes[i]); if (failed) { fin_mudraw_locks(); return NULL; } return &mudraw_locks; } #endif typedef struct worker_t { fz_context *ctx; int num; int band; /* -1 to shutdown, or band to render */ int error; int running; /* set to 1 by main thread when it thinks the worker is running, 0 when it thinks it is not running */ fz_display_list *list; fz_matrix ctm; fz_rect tbounds; fz_pixmap *pix; fz_bitmap *bit; fz_cookie cookie; #ifndef DISABLE_MUTHREADS mu_semaphore start; mu_semaphore stop; mu_thread thread; #endif } worker_t; static char *output = NULL; static fz_output *out = NULL; static int output_pagenum = 0; static int output_file_per_page = 0; static char *format = NULL; static int output_format = OUT_NONE; static float rotation = 0; static float resolution = 72; static int res_specified = 0; static int width = 0; static int height = 0; static int fit = 0; static float layout_w = FZ_DEFAULT_LAYOUT_W; static float layout_h = FZ_DEFAULT_LAYOUT_H; static float layout_em = FZ_DEFAULT_LAYOUT_EM; static char *layout_css = NULL; static int layout_use_doc_css = 1; static float min_line_width = 0.0f; static int showfeatures = 0; static int showtime = 0; static int showmemory = 0; static int showmd5 = 0; #if FZ_ENABLE_PDF static pdf_document *pdfout = NULL; #endif static int no_icc = 0; static int ignore_errors = 0; static int uselist = 1; static int alphabits_text = 8; static int alphabits_graphics = 8; static int out_cs = CS_UNSET; static const char *proof_filename = NULL; fz_colorspace *proof_cs = NULL; static const char *icc_filename = NULL; static float gamma_value = 1; static int invert = 0; static int band_height = 0; static int lowmemory = 0; static int quiet = 0; static int errored = 0; static fz_colorspace *colorspace = NULL; static fz_colorspace *oi = NULL; #if FZ_ENABLE_SPOT_RENDERING static int spots = SPOTS_OVERPRINT_SIM; #else static int spots = SPOTS_NONE; #endif static int alpha; static int useaccel = 1; static char *filename; static int files = 0; static int num_workers = 0; static worker_t *workers; static fz_band_writer *bander = NULL; static const char *layer_config = NULL; static const char ocr_language_default[] = "eng"; static const char *ocr_language = ocr_language_default; static struct { int active; int started; fz_context *ctx; #ifndef DISABLE_MUTHREADS mu_thread thread; mu_semaphore start; mu_semaphore stop; #endif int pagenum; int error; char *filename; fz_display_list *list; fz_page *page; int interptime; fz_separations *seps; } bgprint; static struct { int count, total; int min, max; int mininterp, maxinterp; int minpage, maxpage; char *minfilename; char *maxfilename; int layout; int minlayout, maxlayout; char *minlayoutfilename; char *maxlayoutfilename; } timing; static void usage(void) { fprintf(stderr, "mudraw version " FZ_VERSION "\n" "Usage: mudraw [options] file [pages]\n" "\t-p -\tpassword\n" "\n" "\t-o -\toutput file name (%%d for page number)\n" "\t-F -\toutput format (default inferred from output file name)\n" "\t\traster: png, pnm, pam, pbm, pkm, pwg, pcl, ps\n" "\t\tvector: svg, pdf, trace, ocr.trace\n" "\t\ttext: txt, html, xhtml, stext\n" #ifndef OCR_DISABLED "\t\tocr'd text: ocr.txt, ocr.html, ocr.xhtml, ocr.stext\n" #else "\t\tocr'd text: ocr.txt, ocr.html, ocr.xhtml, ocr.stext (disabled)\n" #endif "\t\tbitmap-wrapped-as-pdf: pclm, ocr.pdf\n" "\n" "\t-q\tbe quiet (don't print progress messages)\n" "\t-s -\tshow extra information:\n" "\t\tm - show memory use\n" "\t\tt - show timings\n" "\t\tf - show page features\n" "\t\t5 - show md5 checksum of rendered image\n" "\n" "\t-R -\trotate clockwise (default: 0 degrees)\n" "\t-r -\tresolution in dpi (default: 72)\n" "\t-w -\twidth (in pixels) (maximum width if -r is specified)\n" "\t-h -\theight (in pixels) (maximum height if -r is specified)\n" "\t-f -\tfit width and/or height exactly; ignore original aspect ratio\n" "\t-B -\tmaximum band_height (pXm, pcl, pclm, ocr.pdf, ps, psd and png output only)\n" #ifndef DISABLE_MUTHREADS "\t-T -\tnumber of threads to use for rendering (banded mode only)\n" #else "\t-T -\tnumber of threads to use for rendering (disabled in this non-threading build)\n" #endif "\n" "\t-W -\tpage width for EPUB layout\n" "\t-H -\tpage height for EPUB layout\n" "\t-S -\tfont size for EPUB layout\n" "\t-U -\tfile name of user stylesheet for EPUB layout\n" "\t-X\tdisable document styles for EPUB layout\n" "\t-a\tdisable usage of accelerator file\n" "\n" "\t-c -\tcolorspace (mono, gray, grayalpha, rgb, rgba, cmyk, cmykalpha, filename of ICC profile)\n" "\t-e -\tproof icc profile (filename of ICC profile)\n" "\t-G -\tapply gamma correction\n" "\t-I\tinvert colors\n" "\n" "\t-A -\tnumber of bits of antialiasing (0 to 8)\n" "\t-A -/-\tnumber of bits of antialiasing (0 to 8) (graphics, text)\n" "\t-l -\tminimum stroked line width (in pixels)\n" "\t-D\tdisable use of display list\n" "\t-i\tignore errors\n" "\t-L\tlow memory mode (avoid caching, clear objects after each page)\n" #ifndef DISABLE_MUTHREADS "\t-P\tparallel interpretation/rendering\n" #else "\t-P\tparallel interpretation/rendering (disabled in this non-threading build)\n" #endif "\t-N\tdisable ICC workflow (\"N\"o color management)\n" "\t-O -\tControl spot/overprint rendering\n" #if FZ_ENABLE_SPOT_RENDERING "\t\t 0 = No spot rendering\n" "\t\t 1 = Overprint simulation (default)\n" "\t\t 2 = Full spot rendering\n" #else "\t\t 0 = No spot rendering (default)\n" "\t\t 1 = Overprint simulation (Disabled in this build)\n" "\t\t 2 = Full spot rendering (Disabled in this build)\n" #endif #ifndef OCR_DISABLED "\t-t -\tSpecify language/script for OCR (default: eng)\n" #else "\t-t -\tSpecify language/script for OCR (default: eng) (disabled)\n" #endif "\n" "\t-y l\tList the layer configs to stderr\n" "\t-y -\tSelect layer config (by number)\n" "\t-y -{,-}*\tSelect layer config (by number), and toggle the listed entries\n" "\n" "\tpages\tcomma separated list of page numbers and ranges\n" ); exit(1); } static int gettime(void) { static struct timeval first; static int once = 1; struct timeval now; if (once) { gettimeofday(&first, NULL); once = 0; } gettimeofday(&now, NULL); return (now.tv_sec - first.tv_sec) * 1000 + (now.tv_usec - first.tv_usec) / 1000; } static int has_percent_d(char *s) { /* find '%[0-9]*d' */ while (*s) { if (*s++ == '%') { while (*s >= '0' && *s <= '9') ++s; if (*s == 'd') return 1; } } return 0; } /* Output file level (as opposed to page level) headers */ static void file_level_headers(fz_context *ctx) { if (output_format == OUT_STEXT_XML || output_format == OUT_TRACE || output_format == OUT_BBOX || output_format == OUT_OCR_STEXT_XML || output_format == OUT_XMLTEXT) fz_write_printf(ctx, out, "<?xml version=\"1.0\"?>\n"); if (output_format == OUT_HTML || output_format == OUT_OCR_HTML) fz_print_stext_header_as_html(ctx, out); if (output_format == OUT_XHTML || output_format == OUT_OCR_XHTML) fz_print_stext_header_as_xhtml(ctx, out); if (output_format == OUT_STEXT_XML || output_format == OUT_TRACE || output_format == OUT_BBOX || output_format == OUT_OCR_STEXT_XML) fz_write_printf(ctx, out, "<document name=\"%s\">\n", filename); if (output_format == OUT_STEXT_JSON || output_format == OUT_OCR_STEXT_JSON) fz_write_printf(ctx, out, "{%q:%q,%q:[", "file", filename, "pages"); if (output_format == OUT_PS) fz_write_ps_file_header(ctx, out); if (output_format == OUT_PWG) fz_write_pwg_file_header(ctx, out); if (output_format == OUT_PCLM) { fz_pclm_options opts = { 0 }; fz_parse_pclm_options(ctx, &opts, "compression=flate"); bander = fz_new_pclm_band_writer(ctx, out, &opts); } if (output_format == OUT_OCR_PDF) { char options[300]; fz_pdfocr_options opts = { 0 }; fz_snprintf(options, sizeof(options), "compression=flate,ocr-language=%s", ocr_language); fz_parse_pdfocr_options(ctx, &opts, options); bander = fz_new_pdfocr_band_writer(ctx, out, &opts); } } static void file_level_trailers(fz_context *ctx) { if (output_format == OUT_STEXT_XML || output_format == OUT_TRACE || output_format == OUT_OCR_TRACE || output_format == OUT_BBOX || output_format == OUT_OCR_STEXT_XML) fz_write_printf(ctx, out, "</document>\n"); if (output_format == OUT_STEXT_JSON || output_format == OUT_OCR_STEXT_JSON) fz_write_printf(ctx, out, "]}"); if (output_format == OUT_HTML || output_format == OUT_OCR_HTML) fz_print_stext_trailer_as_html(ctx, out); if (output_format == OUT_XHTML || output_format == OUT_OCR_HTML) fz_print_stext_trailer_as_xhtml(ctx, out); if (output_format == OUT_PS) fz_write_ps_file_trailer(ctx, out, output_pagenum); if (output_format == OUT_PCLM || output_format == OUT_OCR_PDF) fz_drop_band_writer(ctx, bander); } static void drawband(fz_context *ctx, fz_page *page, fz_display_list *list, fz_matrix ctm, fz_rect tbounds, fz_cookie *cookie, int band_start, fz_pixmap *pix, fz_bitmap **bit) { fz_device *dev = NULL; fz_var(dev); *bit = NULL; fz_try(ctx) { if (pix->alpha) fz_clear_pixmap(ctx, pix); else fz_clear_pixmap_with_value(ctx, pix, 255); dev = fz_new_draw_device_with_proof(ctx, fz_identity, pix, proof_cs); if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); if (alphabits_graphics == 0) fz_enable_device_hints(ctx, dev, FZ_DONT_INTERPOLATE_IMAGES); if (list) fz_run_display_list(ctx, list, dev, ctm, tbounds, cookie); else fz_run_page(ctx, page, dev, ctm, cookie); fz_close_device(ctx, dev); fz_drop_device(ctx, dev); dev = NULL; if (invert) fz_invert_pixmap(ctx, pix); if (gamma_value != 1) fz_gamma_pixmap(ctx, pix, gamma_value); if (((output_format == OUT_PCL || output_format == OUT_PWG) && out_cs == CS_MONO) || (output_format == OUT_PBM) || (output_format == OUT_PKM)) *bit = fz_new_bitmap_from_pixmap_band(ctx, pix, NULL, band_start); } fz_catch(ctx) { fz_drop_device(ctx, dev); fz_rethrow(ctx); } } static void dodrawpage(fz_context *ctx, fz_page *page, fz_display_list *list, int pagenum, fz_cookie *cookie, int start, int interptime, char *fname, int bg, fz_separations *seps) { fz_rect mediabox; fz_device *dev = NULL; fz_var(dev); if (output_file_per_page) file_level_headers(ctx); if (list) mediabox = fz_bound_display_list(ctx, list); else mediabox = fz_bound_page(ctx, page); if (output_format == OUT_TRACE || output_format == OUT_OCR_TRACE) { float zoom; fz_matrix ctm; fz_device *pre_ocr_dev = NULL; zoom = resolution / 72; ctm = fz_pre_scale(fz_rotate(rotation), zoom, zoom); fz_var(pre_ocr_dev); fz_try(ctx) { fz_write_printf(ctx, out, "<page mediabox=\"%g %g %g %g\">\n", mediabox.x0, mediabox.y0, mediabox.x1, mediabox.y1); dev = fz_new_trace_device(ctx, out); if (output_format == OUT_OCR_TRACE) { pre_ocr_dev = dev; dev = NULL; dev = fz_new_ocr_device(ctx, pre_ocr_dev, ctm, mediabox, 1, ocr_language); } if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); if (list) fz_run_display_list(ctx, list, dev, ctm, fz_infinite_rect, cookie); else fz_run_page(ctx, page, dev, ctm, cookie); fz_close_device(ctx, dev); fz_drop_device(ctx, dev); dev = NULL; fz_close_device(ctx, pre_ocr_dev); fz_drop_device(ctx, pre_ocr_dev); pre_ocr_dev = NULL; fz_write_printf(ctx, out, "</page>\n"); } fz_always(ctx) { fz_drop_device(ctx, pre_ocr_dev); fz_drop_device(ctx, dev); } fz_catch(ctx) { fz_rethrow(ctx); } } if (output_format == OUT_XMLTEXT) { fz_try(ctx) { fz_write_printf(ctx, out, "<page mediabox=\"%g %g %g %g\">\n", mediabox.x0, mediabox.y0, mediabox.x1, mediabox.y1); dev = fz_new_xmltext_device(ctx, out); if (list) fz_run_display_list(ctx, list, dev, fz_identity, fz_infinite_rect, cookie); else fz_run_page(ctx, page, dev, fz_identity, cookie); fz_write_printf(ctx, out, "</page>\n"); fz_close_device(ctx, dev); } fz_always(ctx) { fz_drop_device(ctx, dev); } fz_catch(ctx) { fz_rethrow(ctx); } } else if (output_format == OUT_BBOX) { fz_try(ctx) { fz_rect bbox = fz_empty_rect; dev = fz_new_bbox_device(ctx, &bbox); if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); if (list) fz_run_display_list(ctx, list, dev, fz_identity, fz_infinite_rect, cookie); else fz_run_page(ctx, page, dev, fz_identity, cookie); fz_close_device(ctx, dev); fz_write_printf(ctx, out, "<page bbox=\"%R\" mediabox=\"%R\" />\n", &bbox, &mediabox); } fz_always(ctx) { fz_drop_device(ctx, dev); } fz_catch(ctx) { fz_rethrow(ctx); } } else if (output_format == OUT_TEXT || output_format == OUT_HTML || output_format == OUT_XHTML || output_format == OUT_STEXT_XML || output_format == OUT_STEXT_JSON || output_format == OUT_OCR_TEXT || output_format == OUT_OCR_HTML || output_format == OUT_OCR_XHTML || output_format == OUT_OCR_STEXT_XML || output_format == OUT_OCR_STEXT_JSON) { fz_stext_page *text = NULL; float zoom; fz_matrix ctm; fz_device *pre_ocr_dev = NULL; zoom = resolution / 72; ctm = fz_pre_scale(fz_rotate(rotation), zoom, zoom); fz_var(text); fz_var(pre_ocr_dev); fz_try(ctx) { fz_stext_options stext_options; stext_options.flags = (output_format == OUT_HTML || output_format == OUT_XHTML || output_format == OUT_OCR_HTML || output_format == OUT_OCR_XHTML ) ? FZ_STEXT_PRESERVE_IMAGES : 0; if (output_format == OUT_STEXT_JSON || output_format == OUT_OCR_STEXT_JSON) stext_options.flags |= FZ_STEXT_PRESERVE_SPANS; text = fz_new_stext_page(ctx, mediabox); dev = fz_new_stext_device(ctx, text, &stext_options); if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); if (output_format == OUT_OCR_TEXT || output_format == OUT_OCR_STEXT_JSON || output_format == OUT_OCR_STEXT_XML || output_format == OUT_OCR_HTML || output_format == OUT_OCR_XHTML) { pre_ocr_dev = dev; dev = NULL; dev = fz_new_ocr_device(ctx, pre_ocr_dev, ctm, mediabox, 1, ocr_language); } if (list) fz_run_display_list(ctx, list, dev, ctm, fz_infinite_rect, cookie); else fz_run_page(ctx, page, dev, ctm, cookie); fz_close_device(ctx, dev); fz_drop_device(ctx, dev); dev = NULL; fz_close_device(ctx, pre_ocr_dev); fz_drop_device(ctx, pre_ocr_dev); pre_ocr_dev = NULL; if (output_format == OUT_STEXT_XML || output_format == OUT_OCR_STEXT_XML) { fz_print_stext_page_as_xml(ctx, out, text, pagenum); } else if (output_format == OUT_STEXT_JSON || output_format == OUT_OCR_STEXT_JSON) { static int first = 1; if (first) first = 0; else fz_write_string(ctx, out, ","); fz_print_stext_page_as_json(ctx, out, text, 1); } else if (output_format == OUT_HTML || output_format == OUT_OCR_HTML) { fz_print_stext_page_as_html(ctx, out, text, pagenum); } else if (output_format == OUT_XHTML || output_format == OUT_OCR_XHTML) { fz_print_stext_page_as_xhtml(ctx, out, text, pagenum); } else if (output_format == OUT_TEXT || output_format == OUT_OCR_TEXT) { fz_print_stext_page_as_text(ctx, out, text); fz_write_printf(ctx, out, "\f\n"); } } fz_always(ctx) { fz_drop_device(ctx, pre_ocr_dev); fz_drop_device(ctx, dev); fz_drop_stext_page(ctx, text); } fz_catch(ctx) { fz_rethrow(ctx); } } #if FZ_ENABLE_PDF else if (output_format == OUT_PDF) { fz_buffer *contents = NULL; pdf_obj *resources = NULL; fz_var(contents); fz_var(resources); fz_try(ctx) { pdf_obj *page_obj; dev = pdf_page_write(ctx, pdfout, mediabox, &resources, &contents); if (list) fz_run_display_list(ctx, list, dev, fz_identity, fz_infinite_rect, cookie); else fz_run_page(ctx, page, dev, fz_identity, cookie); fz_close_device(ctx, dev); fz_drop_device(ctx, dev); dev = NULL; page_obj = pdf_add_page(ctx, pdfout, mediabox, rotation, resources, contents); pdf_insert_page(ctx, pdfout, -1, page_obj); pdf_drop_obj(ctx, page_obj); } fz_always(ctx) { pdf_drop_obj(ctx, resources); fz_drop_buffer(ctx, contents); fz_drop_device(ctx, dev); } fz_catch(ctx) { fz_rethrow(ctx); } } #endif else if (output_format == OUT_SVG) { float zoom; fz_matrix ctm; fz_rect tbounds; char buf[512]; fz_output *outs = NULL; fz_var(outs); zoom = resolution / 72; ctm = fz_pre_rotate(fz_scale(zoom, zoom), rotation); tbounds = fz_transform_rect(mediabox, ctm); fz_try(ctx) { if (!output || !strcmp(output, "-")) outs = fz_stdout(ctx); else { fz_format_output_path(ctx, buf, sizeof buf, output, pagenum); outs = fz_new_output_with_path(ctx, buf, 0); } dev = fz_new_svg_device(ctx, outs, tbounds.x1-tbounds.x0, tbounds.y1-tbounds.y0, FZ_SVG_TEXT_AS_PATH, 1); if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); if (list) fz_run_display_list(ctx, list, dev, ctm, tbounds, cookie); else fz_run_page(ctx, page, dev, ctm, cookie); fz_close_device(ctx, dev); fz_close_output(ctx, outs); } fz_always(ctx) { fz_drop_device(ctx, dev); fz_drop_output(ctx, outs); } fz_catch(ctx) { fz_rethrow(ctx); } } else { float zoom; fz_matrix ctm; fz_rect tbounds; fz_irect ibounds; fz_pixmap *pix = NULL; int w, h; fz_bitmap *bit = NULL; fz_var(pix); fz_var(bander); fz_var(bit); zoom = resolution / 72; ctm = fz_pre_scale(fz_rotate(rotation), zoom, zoom); tbounds = fz_transform_rect(mediabox, ctm); ibounds = fz_round_rect(tbounds); /* Make local copies of our width/height */ w = width; h = height; /* If a resolution is specified, check to see whether w/h are * exceeded; if not, unset them. */ if (res_specified) { int t; t = ibounds.x1 - ibounds.x0; if (w && t <= w) w = 0; t = ibounds.y1 - ibounds.y0; if (h && t <= h) h = 0; } /* Now w or h will be 0 unless they need to be enforced. */ if (w || h) { float scalex = w / (tbounds.x1 - tbounds.x0); float scaley = h / (tbounds.y1 - tbounds.y0); fz_matrix scale_mat; if (fit) { if (w == 0) scalex = 1.0f; if (h == 0) scaley = 1.0f; } else { if (w == 0) scalex = scaley; if (h == 0) scaley = scalex; } if (!fit) { if (scalex > scaley) scalex = scaley; else scaley = scalex; } scale_mat = fz_scale(scalex, scaley); ctm = fz_concat(ctm, scale_mat); tbounds = fz_transform_rect(mediabox, ctm); } ibounds = fz_round_rect(tbounds); tbounds = fz_rect_from_irect(ibounds); fz_try(ctx) { fz_irect band_ibounds = ibounds; int band, bands = 1; int totalheight = ibounds.y1 - ibounds.y0; int drawheight = totalheight; if (band_height != 0) { /* Banded rendering; we'll only render to a * given height at a time. */ drawheight = band_height; if (totalheight > band_height) band_ibounds.y1 = band_ibounds.y0 + band_height; bands = (totalheight + band_height-1)/band_height; tbounds.y1 = tbounds.y0 + band_height + 2; DEBUG_THREADS(("Using %d Bands\n", bands)); } if (num_workers > 0) { for (band = 0; band < fz_mini(num_workers, bands); band++) { workers[band].band = band; workers[band].error = 0; workers[band].ctm = ctm; workers[band].tbounds = tbounds; memset(&workers[band].cookie, 0, sizeof(fz_cookie)); workers[band].list = list; workers[band].pix = fz_new_pixmap_with_bbox(ctx, colorspace, band_ibounds, seps, alpha); fz_set_pixmap_resolution(ctx, workers[band].pix, resolution, resolution); workers[band].running = 1; #ifndef DISABLE_MUTHREADS DEBUG_THREADS(("Worker %d, Pre-triggering band %d\n", band, band)); mu_trigger_semaphore(&workers[band].start); #endif ctm.f -= drawheight; } pix = workers[0].pix; } else { pix = fz_new_pixmap_with_bbox(ctx, colorspace, band_ibounds, seps, alpha); fz_set_pixmap_resolution(ctx, pix, resolution, resolution); } /* Output any page level headers (for banded formats) */ if (output) { if (output_format == OUT_PGM || output_format == OUT_PPM || output_format == OUT_PNM) bander = fz_new_pnm_band_writer(ctx, out); else if (output_format == OUT_PAM) bander = fz_new_pam_band_writer(ctx, out); else if (output_format == OUT_PNG) bander = fz_new_png_band_writer(ctx, out); else if (output_format == OUT_PBM) bander = fz_new_pbm_band_writer(ctx, out); else if (output_format == OUT_PKM) bander = fz_new_pkm_band_writer(ctx, out); else if (output_format == OUT_PS) bander = fz_new_ps_band_writer(ctx, out); else if (output_format == OUT_PSD) bander = fz_new_psd_band_writer(ctx, out); else if (output_format == OUT_PWG) { if (out_cs == CS_MONO) bander = fz_new_mono_pwg_band_writer(ctx, out, NULL); else bander = fz_new_pwg_band_writer(ctx, out, NULL); } else if (output_format == OUT_PCL) { if (out_cs == CS_MONO) bander = fz_new_mono_pcl_band_writer(ctx, out, NULL); else bander = fz_new_color_pcl_band_writer(ctx, out, NULL); } if (bander) { fz_write_header(ctx, bander, pix->w, totalheight, pix->n, pix->alpha, pix->xres, pix->yres, output_pagenum++, pix->colorspace, pix->seps); } } for (band = 0; band < bands; band++) { if (num_workers > 0) { worker_t *w = &workers[band % num_workers]; #ifndef DISABLE_MUTHREADS DEBUG_THREADS(("Waiting for worker %d to complete band %d\n", w->num, band)); mu_wait_semaphore(&w->stop); #endif w->running = 0; cookie->errors += w->cookie.errors; pix = w->pix; bit = w->bit; w->bit = NULL; if (w->error) fz_throw(ctx, FZ_ERROR_GENERIC, "worker %d failed to render band %d", w->num, band); } else drawband(ctx, page, list, ctm, tbounds, cookie, band * band_height, pix, &bit); if (output) { if (bander && (pix || bit)) fz_write_band(ctx, bander, bit ? bit->stride : pix->stride, drawheight, bit ? bit->samples : pix->samples); fz_drop_bitmap(ctx, bit); bit = NULL; } if (num_workers > 0 && band + num_workers < bands) { worker_t *w = &workers[band % num_workers]; w->band = band + num_workers; w->ctm = ctm; w->tbounds = tbounds; memset(&w->cookie, 0, sizeof(fz_cookie)); w->running = 1; #ifndef DISABLE_MUTHREADS DEBUG_THREADS(("Triggering worker %d for band %d\n", w->num, w->band)); mu_trigger_semaphore(&w->start); #endif } ctm.f -= drawheight; } /* FIXME */ if (showmd5 && pix) { unsigned char digest[16]; int i; fz_md5_pixmap(ctx, pix, digest); fprintf(stderr, " "); for (i = 0; i < 16; i++) fprintf(stderr, "%02x", digest[i]); } } fz_always(ctx) { if (output_format != OUT_PCLM && output_format != OUT_OCR_PDF) { fz_drop_band_writer(ctx, bander); /* bander must be set to NULL to avoid use-after-frees. A use-after-free * would occur when a valid page was followed by a page with invalid * pixmap dimensions, causing bander -- a static -- to point to previously * freed memory instead of a new band_writer. */ bander = NULL; } fz_drop_bitmap(ctx, bit); bit = NULL; if (num_workers > 0) { int i; DEBUG_THREADS(("Stopping workers and removing their pixmaps\n")); for (i = 0; i < num_workers; i++) { if (workers[i].running) { #ifndef DISABLE_MUTHREADS DEBUG_THREADS(("Waiting on worker %d to finish processing\n", i)); mu_wait_semaphore(&workers[i].stop); #endif workers[i].running = 0; } else DEBUG_THREADS(("Worker %d not processing anything\n", i)); fz_drop_pixmap(ctx, workers[i].pix); workers[i].pix = NULL; } } else fz_drop_pixmap(ctx, pix); } fz_catch(ctx) { fz_rethrow(ctx); } } if (output_file_per_page) file_level_trailers(ctx); if (showtime) { int end = gettime(); int diff = end - start; if (bg) { if (diff + interptime < timing.min) { timing.min = diff + interptime; timing.mininterp = interptime; timing.minpage = pagenum; timing.minfilename = fname; } if (diff + interptime > timing.max) { timing.max = diff + interptime; timing.maxinterp = interptime; timing.maxpage = pagenum; timing.maxfilename = fname; } timing.count ++; fprintf(stderr, " %dms (interpretation) %dms (rendering) %dms (total)", interptime, diff, diff + interptime); } else { if (diff < timing.min) { timing.min = diff; timing.minpage = pagenum; timing.minfilename = fname; } if (diff > timing.max) { timing.max = diff; timing.maxpage = pagenum; timing.maxfilename = fname; } timing.total += diff; timing.count ++; fprintf(stderr, " %dms", diff); } } if (!quiet || showfeatures || showtime || showmd5) fprintf(stderr, "\n"); if (lowmemory) fz_empty_store(ctx); if (showmemory) fz_dump_glyph_cache_stats(ctx, fz_stderr(ctx)); fz_flush_warnings(ctx); if (cookie->errors) errored = 1; } static void bgprint_flush(void) { if (!bgprint.active || !bgprint.started) return; #ifndef DISABLE_MUTHREADS mu_wait_semaphore(&bgprint.stop); #endif bgprint.started = 0; } static void drawpage(fz_context *ctx, fz_document *doc, int pagenum) { fz_page *page; fz_display_list *list = NULL; fz_device *dev = NULL; int start; fz_cookie cookie = { 0 }; fz_separations *seps = NULL; const char *features = ""; fz_var(list); fz_var(dev); fz_var(seps); start = (showtime ? gettime() : 0); page = fz_load_page(ctx, doc, pagenum - 1); if (spots != SPOTS_NONE) { fz_try(ctx) { seps = fz_page_separations(ctx, page); if (seps) { int i, n = fz_count_separations(ctx, seps); if (spots == SPOTS_FULL) for (i = 0; i < n; i++) fz_set_separation_behavior(ctx, seps, i, FZ_SEPARATION_SPOT); else for (i = 0; i < n; i++) fz_set_separation_behavior(ctx, seps, i, FZ_SEPARATION_COMPOSITE); } else if (fz_page_uses_overprint(ctx, page)) { /* This page uses overprint, so we need an empty * sep object to force the overprint simulation on. */ seps = fz_new_separations(ctx, 0); } else if (oi && fz_colorspace_n(ctx, oi) != fz_colorspace_n(ctx, colorspace)) { /* We have an output intent, and it's incompatible * with the colorspace our device needs. Force the * overprint simulation on, because this ensures that * we 'simulate' the output intent too. */ seps = fz_new_separations(ctx, 0); } } fz_catch(ctx) { fz_drop_page(ctx, page); fz_rethrow(ctx); } } if (uselist) { fz_try(ctx) { list = fz_new_display_list(ctx, fz_bound_page(ctx, page)); dev = fz_new_list_device(ctx, list); if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); fz_run_page(ctx, page, dev, fz_identity, &cookie); fz_close_device(ctx, dev); } fz_always(ctx) { fz_drop_device(ctx, dev); dev = NULL; } fz_catch(ctx) { fz_drop_display_list(ctx, list); fz_drop_separations(ctx, seps); fz_drop_page(ctx, page); fz_rethrow(ctx); } if (bgprint.active && showtime) { int end = gettime(); start = end - start; } } if (showfeatures) { int iscolor; dev = fz_new_test_device(ctx, &iscolor, 0.02f, 0, NULL); if (lowmemory) fz_enable_device_hints(ctx, dev, FZ_NO_CACHE); fz_try(ctx) { if (list) fz_run_display_list(ctx, list, dev, fz_identity, fz_infinite_rect, NULL); else fz_run_page(ctx, page, dev, fz_identity, &cookie); fz_close_device(ctx, dev); } fz_always(ctx) { fz_drop_device(ctx, dev); dev = NULL; } fz_catch(ctx) { fz_drop_display_list(ctx, list); fz_drop_separations(ctx, seps); fz_drop_page(ctx, page); fz_rethrow(ctx); } features = iscolor ? " color" : " grayscale"; } if (output_file_per_page) { char text_buffer[512]; bgprint_flush(); if (out) { fz_close_output(ctx, out); fz_drop_output(ctx, out); } fz_format_output_path(ctx, text_buffer, sizeof text_buffer, output, pagenum); out = fz_new_output_with_path(ctx, text_buffer, 0); } if (bgprint.active) { bgprint_flush(); if (bgprint.error) { fz_drop_display_list(ctx, list); fz_drop_separations(ctx, seps); fz_drop_page(ctx, page); /* it failed, do not continue trying */ bgprint.active = 0; } else if (bgprint.active) { if (!quiet || showfeatures || showtime || showmd5) fprintf(stderr, "page %s %d%s", filename, pagenum, features); bgprint.started = 1; bgprint.page = page; bgprint.list = list; bgprint.seps = seps; bgprint.filename = filename; bgprint.pagenum = pagenum; bgprint.interptime = start; bgprint.error = 0; #ifndef DISABLE_MUTHREADS mu_trigger_semaphore(&bgprint.start); #else fz_drop_display_list(ctx, list); fz_drop_separations(ctx, seps); fz_drop_page(ctx, page); #endif } } else { if (!quiet || showfeatures || showtime || showmd5) fprintf(stderr, "page %s %d%s", filename, pagenum, features); fz_try(ctx) dodrawpage(ctx, page, list, pagenum, &cookie, start, 0, filename, 0, seps); fz_always(ctx) { fz_drop_display_list(ctx, list); fz_drop_separations(ctx, seps); fz_drop_page(ctx, page); } fz_catch(ctx) { fz_rethrow(ctx); } } } static void drawrange(fz_context *ctx, fz_document *doc, const char *range) { int page, spage, epage, pagecount; pagecount = fz_count_pages(ctx, doc); while ((range = fz_parse_page_range(ctx, range, &spage, &epage, pagecount))) { if (spage < epage) for (page = spage; page <= epage; page++) { fz_try(ctx) drawpage(ctx, doc, page); fz_catch(ctx) { if (ignore_errors) fz_warn(ctx, "ignoring error on page %d in '%s'", page, filename); else fz_rethrow(ctx); } } else for (page = spage; page >= epage; page--) { fz_try(ctx) drawpage(ctx, doc, page); fz_catch(ctx) { if (ignore_errors) fz_warn(ctx, "ignoring error on page %d in '%s'", page, filename); else fz_rethrow(ctx); } } } } static int parse_colorspace(const char *name) { int i; for (i = 0; i < (int)nelem(cs_name_table); i++) { if (!strcmp(name, cs_name_table[i].name)) return cs_name_table[i].colorspace; } /* Assume ICC. We will error out later if not the case. */ icc_filename = name; return CS_ICC; } typedef struct { size_t size; #if defined(_M_IA64) || defined(_M_AMD64) size_t align; #endif } trace_header; typedef struct { size_t current; size_t peak; size_t total; size_t allocs; size_t mem_limit; size_t alloc_limit; } trace_info; static void *hit_limit(void *val) { return val; } static void *hit_memory_limit(trace_info *info, int is_malloc, size_t oldsize, size_t size) { if (is_malloc) printf("Memory limit (%zu) hit upon malloc(%zu) when %zu already allocated.\n", info->mem_limit, size, info->current); else printf("Memory limit (%zu) hit upon realloc(%zu) from %zu bytes when %zu already allocated.\n", info->mem_limit, size, oldsize, info->current); return hit_limit(NULL); } static void *hit_alloc_limit(trace_info *info, int is_malloc, size_t oldsize, size_t size) { if (is_malloc) printf("Allocation limit (%zu) hit upon malloc(%zu) when %zu already allocated.\n", info->alloc_limit, size, info->current); else printf("Allocation limit (%zu) hit upon realloc(%zu) from %zu bytes when %zu already allocated.\n", info->alloc_limit, size, oldsize, info->current); return hit_limit(NULL); } static void * trace_malloc(void *arg, size_t size) { trace_info *info = (trace_info *) arg; trace_header *p; if (size == 0) return NULL; if (size > SIZE_MAX - sizeof(trace_header)) return NULL; if (info->mem_limit > 0 && size > info->mem_limit - info->current) return hit_memory_limit(info, 1, 0, size); if (info->alloc_limit > 0 && info->allocs > info->alloc_limit) return hit_alloc_limit(info, 1, 0, size); p = malloc(size + sizeof(trace_header)); if (p == NULL) return NULL; p[0].size = size; info->current += size; info->total += size; if (info->current > info->peak) info->peak = info->current; info->allocs++; return (void *)&p[1]; } static void trace_free(void *arg, void *p_) { trace_info *info = (trace_info *) arg; trace_header *p = (trace_header *)p_; if (p == NULL) return; info->current -= p[-1].size; free(&p[-1]); } static void * trace_realloc(void *arg, void *p_, size_t size) { trace_info *info = (trace_info *) arg; trace_header *p = (trace_header *)p_; size_t oldsize; if (size == 0) { trace_free(arg, p_); return NULL; } if (p == NULL) return trace_malloc(arg, size); if (size > SIZE_MAX - sizeof(trace_header)) return NULL; oldsize = p[-1].size; if (info->mem_limit > 0 && size > info->mem_limit - info->current + oldsize) return hit_memory_limit(info, 0, oldsize, size); if (info->alloc_limit > 0 && info->allocs > info->alloc_limit) return hit_alloc_limit(info, 0, oldsize, size); p = realloc(&p[-1], size + sizeof(trace_header)); if (p == NULL) return NULL; info->current += size - oldsize; if (size > oldsize) info->total += size - oldsize; if (info->current > info->peak) info->peak = info->current; p[0].size = size; info->allocs++; return &p[1]; } #ifndef DISABLE_MUTHREADS static void worker_thread(void *arg) { worker_t *me = (worker_t *)arg; int band; do { DEBUG_THREADS(("Worker %d waiting\n", me->num)); mu_wait_semaphore(&me->start); band = me->band; DEBUG_THREADS(("Worker %d woken for band %d\n", me->num, band)); if (band >= 0) { fz_try(me->ctx) { drawband(me->ctx, NULL, me->list, me->ctm, me->tbounds, &me->cookie, band * band_height, me->pix, &me->bit); DEBUG_THREADS(("Worker %d completed band %d\n", me->num, band)); } fz_catch(me->ctx) { DEBUG_THREADS(("Worker %d failed on band %d\n", me->num, band)); me->error = 1; } } mu_trigger_semaphore(&me->stop); } while (band >= 0); DEBUG_THREADS(("Worker %d shutting down\n", me->num)); } static void bgprint_worker(void *arg) { fz_cookie cookie = { 0 }; int pagenum; (void)arg; do { DEBUG_THREADS(("BGPrint waiting\n")); mu_wait_semaphore(&bgprint.start); pagenum = bgprint.pagenum; DEBUG_THREADS(("BGPrint woken for pagenum %d\n", pagenum)); if (pagenum >= 0) { int start = gettime(); memset(&cookie, 0, sizeof(cookie)); fz_try(bgprint.ctx) { dodrawpage(bgprint.ctx, bgprint.page, bgprint.list, pagenum, &cookie, start, bgprint.interptime, bgprint.filename, 1, bgprint.seps); DEBUG_THREADS(("BGPrint completed page %d\n", pagenum)); } fz_always(bgprint.ctx) { fz_drop_display_list(bgprint.ctx, bgprint.list); fz_drop_separations(bgprint.ctx, bgprint.seps); fz_drop_page(bgprint.ctx, bgprint.page); } fz_catch(bgprint.ctx) { DEBUG_THREADS(("BGPrint failed on page %d\n", pagenum)); bgprint.error = 1; } } mu_trigger_semaphore(&bgprint.stop); } while (pagenum >= 0); DEBUG_THREADS(("BGPrint shutting down\n")); } #endif static inline int iswhite(int ch) { return ch == '\011' || ch == '\012' || ch == '\014' || ch == '\015' || ch == '\040'; } static void apply_layer_config(fz_context *ctx, fz_document *doc, const char *lc) { #if FZ_ENABLE_PDF pdf_document *pdoc = pdf_specifics(ctx, doc); int config; int n, j; pdf_layer_config info; if (!pdoc) { fz_warn(ctx, "Only PDF files have layers"); return; } while (iswhite(*lc)) lc++; if (*lc == 0 || *lc == 'l') { int num_configs = pdf_count_layer_configs(ctx, pdoc); fprintf(stderr, "Layer configs:\n"); for (config = 0; config < num_configs; config++) { fprintf(stderr, " %s%d:", config < 10 ? " " : "", config); pdf_layer_config_info(ctx, pdoc, config, &info); if (info.name) fprintf(stderr, " Name=\"%s\"", info.name); if (info.creator) fprintf(stderr, " Creator=\"%s\"", info.creator); fprintf(stderr, "\n"); } return; } /* Read the config number */ if (*lc < '0' || *lc > '9') { fprintf(stderr, "cannot find number expected for -y\n"); return; } config = fz_atoi(lc); pdf_select_layer_config(ctx, pdoc, config); while (*lc) { int item; /* Skip over the last number we read (in the fz_atoi) */ while (*lc >= '0' && *lc <= '9') lc++; while (iswhite(*lc)) lc++; if (*lc != ',') break; lc++; while (iswhite(*lc)) lc++; if (*lc < '0' || *lc > '9') { fprintf(stderr, "Expected a number for UI item to toggle\n"); return; } item = fz_atoi(lc); pdf_toggle_layer_config_ui(ctx, pdoc, item); } /* Now list the final state of the config */ fprintf(stderr, "Layer Config %d:\n", config); pdf_layer_config_info(ctx, pdoc, config, &info); if (info.name) fprintf(stderr, " Name=\"%s\"", info.name); if (info.creator) fprintf(stderr, " Creator=\"%s\"", info.creator); fprintf(stderr, "\n"); n = pdf_count_layer_config_ui(ctx, pdoc); for (j = 0; j < n; j++) { pdf_layer_config_ui ui; pdf_layer_config_ui_info(ctx, pdoc, j, &ui); fprintf(stderr, "%s%d: ", j < 10 ? " " : "", j); while (ui.depth > 0) { ui.depth--; fprintf(stderr, " "); } if (ui.type == PDF_LAYER_UI_CHECKBOX) fprintf(stderr, " [%c] ", ui.selected ? 'x' : ' '); else if (ui.type == PDF_LAYER_UI_RADIOBOX) fprintf(stderr, " (%c) ", ui.selected ? 'x' : ' '); if (ui.text) fprintf(stderr, "%s", ui.text); if (ui.type != PDF_LAYER_UI_LABEL && ui.locked) fprintf(stderr, " <locked>"); fprintf(stderr, "\n"); } #endif } static int convert_to_accel_path(fz_context *ctx, char outname[], char *absname, size_t len) { char *tmpdir; char *s; tmpdir = getenv("TEMP"); if (!tmpdir) tmpdir = getenv("TMP"); if (!tmpdir) tmpdir = "/var/tmp"; if (!fz_is_directory(ctx, tmpdir)) tmpdir = "/tmp"; if (absname[0] == '/' || absname[0] == '\\') ++absname; s = absname; while (*s) { if (*s == '/' || *s == '\\' || *s == ':') *s = '%'; ++s; } if (fz_snprintf(outname, len, "%s/%s.accel", tmpdir, absname) >= len) return 0; return 1; } static int get_accelerator_filename(fz_context *ctx, char outname[], size_t len, const char *fname) { char absname[PATH_MAX]; if (!fz_realpath(fname, absname)) return 0; if (!convert_to_accel_path(ctx, outname, absname, len)) return 0; return 1; } static void save_accelerator(fz_context *ctx, fz_document *doc, const char *fname) { char absname[PATH_MAX]; if (!doc) return; if (!fz_document_supports_accelerator(ctx, doc)) return; if (!get_accelerator_filename(ctx, absname, sizeof(absname), fname)) return; fz_save_accelerator(ctx, doc, absname); } #ifdef MUDRAW_STANDALONE int main(int argc, char **argv) #else int mudraw_main(int argc, char **argv) #endif { char *password = ""; fz_document *doc = NULL; int c; fz_context *ctx; trace_info trace_info = { 0, 0, 0, 0, 0, 0 }; fz_alloc_context trace_alloc_ctx = { &trace_info, trace_malloc, trace_realloc, trace_free }; fz_alloc_context *alloc_ctx = NULL; fz_locks_context *locks = NULL; size_t max_store = FZ_STORE_DEFAULT; fz_var(doc); while ((c = fz_getopt(argc, argv, "qp:o:F:R:r:w:h:fB:c:e:G:Is:A:DiW:H:S:T:t:U:XLvPl:y:NO:am:")) != -1) { switch (c) { default: usage(); break; case 'q': quiet = 1; break; case 'p': password = fz_optarg; break; case 'o': output = fz_optarg; break; case 'F': format = fz_optarg; break; case 'R': rotation = fz_atof(fz_optarg); break; case 'r': resolution = fz_atof(fz_optarg); res_specified = 1; break; case 'w': width = fz_atof(fz_optarg); break; case 'h': height = fz_atof(fz_optarg); break; case 'f': fit = 1; break; case 'B': band_height = atoi(fz_optarg); break; case 'c': out_cs = parse_colorspace(fz_optarg); break; case 'e': proof_filename = fz_optarg; break; case 'G': gamma_value = fz_atof(fz_optarg); break; case 'I': invert++; break; case 'W': layout_w = fz_atof(fz_optarg); break; case 'H': layout_h = fz_atof(fz_optarg); break; case 'S': layout_em = fz_atof(fz_optarg); break; case 'U': layout_css = fz_optarg; break; case 'X': layout_use_doc_css = 0; break; case 'O': spots = fz_atof(fz_optarg); #ifndef FZ_ENABLE_SPOT_RENDERING fprintf(stderr, "Spot rendering/Overprint/Overprint simulation not enabled in this build\n"); spots = SPOTS_NONE; #endif break; case 's': if (strchr(fz_optarg, 't')) ++showtime; if (strchr(fz_optarg, 'm')) ++showmemory; if (strchr(fz_optarg, 'f')) ++showfeatures; if (strchr(fz_optarg, '5')) ++showmd5; break; case 'A': { char *sep; alphabits_graphics = atoi(fz_optarg); sep = strchr(fz_optarg, '/'); if (sep) alphabits_text = atoi(sep+1); else alphabits_text = alphabits_graphics; break; } case 'D': uselist = 0; break; case 'l': min_line_width = fz_atof(fz_optarg); break; case 'i': ignore_errors = 1; break; case 'N': no_icc = 1; break; case 'T': #ifndef DISABLE_MUTHREADS num_workers = atoi(fz_optarg); break; #else fprintf(stderr, "Threads not enabled in this build\n"); break; #endif case 't': #ifndef OCR_DISABLED ocr_language = fz_optarg; break; #else fprintf(stderr, "OCR functionality not enabled in this build\n"); break; #endif case 'm': if (fz_optarg[0] == 's') trace_info.mem_limit = fz_atoi64(&fz_optarg[1]); else if (fz_optarg[0] == 'a') trace_info.alloc_limit = fz_atoi64(&fz_optarg[1]); else trace_info.mem_limit = fz_atoi64(fz_optarg); break; case 'L': lowmemory = 1; break; case 'P': #ifndef DISABLE_MUTHREADS bgprint.active = 1; break; #else fprintf(stderr, "Threads not enabled in this build\n"); break; #endif case 'y': layer_config = fz_optarg; break; case 'a': useaccel = 0; break; case 'v': fprintf(stderr, "mudraw version %s\n", FZ_VERSION); return 1; } } if (fz_optind == argc) usage(); if (num_workers > 0) { if (uselist == 0) { fprintf(stderr, "cannot use multiple threads without using display list\n"); exit(1); } if (band_height == 0) { fprintf(stderr, "Using multiple threads without banding is pointless\n"); } } if (bgprint.active) { if (uselist == 0) { fprintf(stderr, "cannot bgprint without using display list\n"); exit(1); } } #ifndef DISABLE_MUTHREADS locks = init_mudraw_locks(); if (locks == NULL) { fprintf(stderr, "mutex initialisation failed\n"); exit(1); } #endif if (trace_info.mem_limit || trace_info.alloc_limit || showmemory) alloc_ctx = &trace_alloc_ctx; if (lowmemory) max_store = 1; ctx = fz_new_context(alloc_ctx, locks, max_store); if (!ctx) { fprintf(stderr, "cannot initialise context\n"); exit(1); } fz_try(ctx) { if (proof_filename) { fz_buffer *proof_buffer = fz_read_file(ctx, proof_filename); proof_cs = fz_new_icc_colorspace(ctx, FZ_COLORSPACE_NONE, 0, NULL, proof_buffer); fz_drop_buffer(ctx, proof_buffer); } fz_set_text_aa_level(ctx, alphabits_text); fz_set_graphics_aa_level(ctx, alphabits_graphics); fz_set_graphics_min_line_width(ctx, min_line_width); if (no_icc) fz_disable_icc(ctx); else fz_enable_icc(ctx); #ifndef DISABLE_MUTHREADS if (bgprint.active) { int fail = 0; bgprint.ctx = fz_clone_context(ctx); fail |= mu_create_semaphore(&bgprint.start); fail |= mu_create_semaphore(&bgprint.stop); fail |= mu_create_thread(&bgprint.thread, bgprint_worker, NULL); if (fail) { fprintf(stderr, "bgprint startup failed\n"); exit(1); } } if (num_workers > 0) { int i; int fail = 0; workers = fz_calloc(ctx, num_workers, sizeof(*workers)); for (i = 0; i < num_workers; i++) { workers[i].ctx = fz_clone_context(ctx); workers[i].num = i; fail |= mu_create_semaphore(&workers[i].start); fail |= mu_create_semaphore(&workers[i].stop); fail |= mu_create_thread(&workers[i].thread, worker_thread, &workers[i]); } if (fail) { fprintf(stderr, "worker startup failed\n"); exit(1); } } #endif /* DISABLE_MUTHREADS */ if (layout_css) { fz_buffer *buf = fz_read_file(ctx, layout_css); fz_set_user_css(ctx, fz_string_from_buffer(ctx, buf)); fz_drop_buffer(ctx, buf); } fz_set_use_document_css(ctx, layout_use_doc_css); /* Determine output type */ if (band_height < 0) { fprintf(stderr, "Bandheight must be > 0\n"); exit(1); } output_format = OUT_PNG; if (format) { int i; for (i = 0; i < (int)nelem(suffix_table); i++) { if (!strcmp(format, suffix_table[i].suffix+1)) { output_format = suffix_table[i].format; if (spots == SPOTS_FULL && suffix_table[i].spots == 0) { fprintf(stderr, "Output format '%s' does not support spot rendering.\nDoing overprint simulation instead.\n", suffix_table[i].suffix+1); spots = SPOTS_OVERPRINT_SIM; } break; } } if (i == (int)nelem(suffix_table)) { fprintf(stderr, "Unknown output format '%s'\n", format); exit(1); } } else if (output) { char *suffix = output; int i; for (i = 0; i < (int)nelem(suffix_table); i++) { char *s = strstr(suffix, suffix_table[i].suffix); if (s != NULL) { suffix = s+strlen(suffix_table[i].suffix); output_format = suffix_table[i].format; if (spots == SPOTS_FULL && suffix_table[i].spots == 0) { fprintf(stderr, "Output format '%s' does not support spot rendering.\nDoing overprint simulation instead.\n", suffix_table[i].suffix+1); spots = SPOTS_OVERPRINT_SIM; } i = -1; } } } if (band_height) { if (output_format != OUT_PAM && output_format != OUT_PGM && output_format != OUT_PPM && output_format != OUT_PNM && output_format != OUT_PNG && output_format != OUT_PBM && output_format != OUT_PKM && output_format != OUT_PCL && output_format != OUT_PCLM && output_format != OUT_PS && output_format != OUT_PSD && output_format != OUT_OCR_PDF) { fprintf(stderr, "Banded operation only possible with PxM, PCL, PCLM, PDFOCR, PS, PSD, and PNG outputs\n"); exit(1); } if (showmd5) { fprintf(stderr, "Banded operation not compatible with MD5\n"); exit(1); } } { int i, j; for (i = 0; i < (int)nelem(format_cs_table); i++) { if (format_cs_table[i].format == output_format) { if (out_cs == CS_UNSET) out_cs = format_cs_table[i].default_cs; for (j = 0; j < (int)nelem(format_cs_table[i].permitted_cs); j++) { if (format_cs_table[i].permitted_cs[j] == out_cs) break; } if (j == (int)nelem(format_cs_table[i].permitted_cs)) { fprintf(stderr, "Unsupported colorspace for this format\n"); exit(1); } } } } alpha = 1; switch (out_cs) { case CS_MONO: case CS_GRAY: case CS_GRAY_ALPHA: colorspace = fz_device_gray(ctx); alpha = (out_cs == CS_GRAY_ALPHA); break; case CS_RGB: case CS_RGB_ALPHA: colorspace = fz_device_rgb(ctx); alpha = (out_cs == CS_RGB_ALPHA); break; case CS_CMYK: case CS_CMYK_ALPHA: colorspace = fz_device_cmyk(ctx); alpha = (out_cs == CS_CMYK_ALPHA); break; case CS_ICC: fz_try(ctx) { fz_buffer *icc_buffer = fz_read_file(ctx, icc_filename); colorspace = fz_new_icc_colorspace(ctx, FZ_COLORSPACE_NONE, 0, NULL, icc_buffer); fz_drop_buffer(ctx, icc_buffer); } fz_catch(ctx) { fprintf(stderr, "Invalid ICC destination color space\n"); exit(1); } if (colorspace == NULL) { fprintf(stderr, "Invalid ICC destination color space\n"); exit(1); } alpha = 0; break; default: fprintf(stderr, "Unknown colorspace!\n"); exit(1); break; } if (out_cs != CS_ICC) colorspace = fz_keep_colorspace(ctx, colorspace); else { int i, j, okay; /* Check to make sure this icc profile is ok with the output format */ okay = 0; for (i = 0; i < (int)nelem(format_cs_table); i++) { if (format_cs_table[i].format == output_format) { for (j = 0; j < (int)nelem(format_cs_table[i].permitted_cs); j++) { switch (format_cs_table[i].permitted_cs[j]) { case CS_MONO: case CS_GRAY: case CS_GRAY_ALPHA: if (fz_colorspace_is_gray(ctx, colorspace)) okay = 1; break; case CS_RGB: case CS_RGB_ALPHA: if (fz_colorspace_is_rgb(ctx, colorspace)) okay = 1; break; case CS_CMYK: case CS_CMYK_ALPHA: if (fz_colorspace_is_cmyk(ctx, colorspace)) okay = 1; break; } } } } if (!okay) { fprintf(stderr, "ICC profile uses a colorspace that cannot be used for this format\n"); exit(1); } } #if FZ_ENABLE_PDF if (output_format == OUT_PDF) { pdfout = pdf_create_document(ctx); } else #endif if (output_format == OUT_SVG) { /* SVG files are always opened for each page. Do not open "output". */ } else if (output && (output[0] != '-' || output[1] != 0) && *output != 0) { if (has_percent_d(output)) output_file_per_page = 1; else out = fz_new_output_with_path(ctx, output, 0); } else { quiet = 1; /* automatically be quiet if printing to stdout */ #ifdef _WIN32 /* Windows specific code to make stdout binary. */ if (output_format != OUT_TEXT && output_format != OUT_STEXT_XML && output_format != OUT_STEXT_JSON && output_format != OUT_HTML && output_format != OUT_XHTML && output_format != OUT_TRACE && output_format != OUT_OCR_TRACE && output_format != OUT_BBOX && output_format != OUT_OCR_TEXT && output_format != OUT_OCR_STEXT_XML && output_format != OUT_OCR_STEXT_JSON && output_format != OUT_OCR_HTML && output_format != OUT_OCR_XHTML && output_format != OUT_XMLTEXT) { setmode(fileno(stdout), O_BINARY); } #endif out = fz_stdout(ctx); } filename = argv[fz_optind]; timing.count = 0; timing.total = 0; timing.min = 1 << 30; timing.max = 0; timing.mininterp = 1 << 30; timing.maxinterp = 0; timing.minpage = 0; timing.maxpage = 0; timing.minfilename = ""; timing.maxfilename = ""; timing.layout = 0; timing.minlayout = 1 << 30; timing.maxlayout = 0; timing.minlayoutfilename = ""; timing.maxlayoutfilename = ""; if (showtime && bgprint.active) timing.total = gettime(); fz_try(ctx) { if (!output_file_per_page) file_level_headers(ctx); fz_register_document_handlers(ctx); while (fz_optind < argc) { char accelpath[PATH_MAX]; char *accel = NULL; time_t atime; time_t dtime; int layouttime; fz_try(ctx) { filename = argv[fz_optind++]; files++; if (!useaccel) accel = NULL; /* If there was an accelerator to load, what would it be called? */ else if (get_accelerator_filename(ctx, accelpath, sizeof(accelpath), filename)) { /* Check whether that file exists, and isn't older than * the document. */ atime = stat_mtime(accelpath); dtime = stat_mtime(filename); if (atime == 0) { /* No accelerator */ } else if (atime > dtime) accel = accelpath; else { /* Accelerator data is out of date */ unlink(accelpath); accel = NULL; /* In case we have jumped up from below */ } } doc = fz_open_accelerated_document(ctx, filename, accel); if (fz_needs_password(ctx, doc)) { if (!fz_authenticate_password(ctx, doc, password)) fz_throw(ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", filename); } /* Once document is open check for output intent colorspace */ oi = fz_document_output_intent(ctx, doc); if (oi) { /* See if we had explicitly set a profile to render */ if (out_cs != CS_ICC) { /* In this case, we want to render to the output intent * color space if the number of channels is the same */ if (fz_colorspace_n(ctx, oi) == fz_colorspace_n(ctx, colorspace)) { fz_drop_colorspace(ctx, colorspace); colorspace = fz_keep_colorspace(ctx, oi); } } } layouttime = gettime(); fz_layout_document(ctx, doc, layout_w, layout_h, layout_em); (void) fz_count_pages(ctx, doc); layouttime = gettime() - layouttime; timing.layout += layouttime; if (layouttime < timing.minlayout) { timing.minlayout = layouttime; timing.minlayoutfilename = filename; } if (layouttime > timing.maxlayout) { timing.maxlayout = layouttime; timing.maxlayoutfilename = filename; } if (layer_config) apply_layer_config(ctx, doc, layer_config); if (fz_optind == argc || !fz_is_page_range(ctx, argv[fz_optind])) drawrange(ctx, doc, "1-N"); if (fz_optind < argc && fz_is_page_range(ctx, argv[fz_optind])) drawrange(ctx, doc, argv[fz_optind++]); bgprint_flush(); if (bgprint.error) fz_throw(ctx, FZ_ERROR_GENERIC, "failed to parse page"); if (useaccel) save_accelerator(ctx, doc, filename); } fz_always(ctx) { fz_drop_document(ctx, doc); doc = NULL; } fz_catch(ctx) { if (!ignore_errors) fz_rethrow(ctx); bgprint_flush(); fz_warn(ctx, "ignoring error in '%s'", filename); } } } fz_catch(ctx) { bgprint_flush(); fz_drop_document(ctx, doc); fprintf(stderr, "error: cannot draw '%s'\n", filename); errored = 1; } if (!output_file_per_page) file_level_trailers(ctx); #if FZ_ENABLE_PDF if (output_format == OUT_PDF) { if (!output) output = "out.pdf"; pdf_save_document(ctx, pdfout, output, NULL); pdf_drop_document(ctx, pdfout); } else #endif { fz_close_output(ctx, out); fz_drop_output(ctx, out); out = NULL; } if (showtime && timing.count > 0) { if (bgprint.active) timing.total = gettime() - timing.total; if (files == 1) { fprintf(stderr, "total %dms (%dms layout) / %d pages for an average of %dms\n", timing.total, timing.layout, timing.count, timing.total / timing.count); if (bgprint.active) { fprintf(stderr, "fastest page %d: %dms (interpretation) %dms (rendering) %dms(total)\n", timing.minpage, timing.mininterp, timing.min - timing.mininterp, timing.min); fprintf(stderr, "slowest page %d: %dms (interpretation) %dms (rendering) %dms(total)\n", timing.maxpage, timing.maxinterp, timing.max - timing.maxinterp, timing.max); } else { fprintf(stderr, "fastest page %d: %dms\n", timing.minpage, timing.min); fprintf(stderr, "slowest page %d: %dms\n", timing.maxpage, timing.max); } } else { fprintf(stderr, "total %dms (%dms layout) / %d pages for an average of %dms in %d files\n", timing.total, timing.layout, timing.count, timing.total / timing.count, files); fprintf(stderr, "fastest layout: %dms (%s)\n", timing.minlayout, timing.minlayoutfilename); fprintf(stderr, "slowest layout: %dms (%s)\n", timing.maxlayout, timing.maxlayoutfilename); fprintf(stderr, "fastest page %d: %dms (%s)\n", timing.minpage, timing.min, timing.minfilename); fprintf(stderr, "slowest page %d: %dms (%s)\n", timing.maxpage, timing.max, timing.maxfilename); } } #ifndef DISABLE_MUTHREADS if (num_workers > 0) { int i; DEBUG_THREADS(("Asking workers to shutdown, then destroy their resources\n")); for (i = 0; i < num_workers; i++) { workers[i].band = -1; mu_trigger_semaphore(&workers[i].start); mu_wait_semaphore(&workers[i].stop); mu_destroy_semaphore(&workers[i].start); mu_destroy_semaphore(&workers[i].stop); mu_destroy_thread(&workers[i].thread); fz_drop_context(workers[i].ctx); } fz_free(ctx, workers); } if (bgprint.active) { bgprint.pagenum = -1; mu_trigger_semaphore(&bgprint.start); mu_wait_semaphore(&bgprint.stop); mu_destroy_semaphore(&bgprint.start); mu_destroy_semaphore(&bgprint.stop); mu_destroy_thread(&bgprint.thread); fz_drop_context(bgprint.ctx); } #endif /* DISABLE_MUTHREADS */ } fz_always(ctx) { fz_drop_colorspace(ctx, colorspace); fz_drop_colorspace(ctx, proof_cs); } fz_catch(ctx) { if (!errored) { fprintf(stderr, "Rendering failed\n"); errored = 1; } } fz_drop_context(ctx); #ifndef DISABLE_MUTHREADS fin_mudraw_locks(); #endif /* DISABLE_MUTHREADS */ if (trace_info.mem_limit || trace_info.alloc_limit || showmemory) { char buf[100]; fz_snprintf(buf, sizeof buf, "Memory use total=%zu peak=%zu current=%zu", trace_info.total, trace_info.peak, trace_info.current); fz_snprintf(buf, sizeof buf, "Allocations total=%zu", trace_info.allocs); fprintf(stderr, "%s\n", buf); } return (errored != 0); }
sebras/mupdf
source/tools/mudraw.c
C
agpl-3.0
62,849
/* * Copyright (C) 2011-2017 Cojen.org * * 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 (at your option) 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/>. */ package org.cojen.tupl.io; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.EnumSet; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import com.sun.jna.Native; import com.sun.jna.Platform; /** * Lowest I/O interface to a file or device. * * @author Brian S O'Neill */ public abstract class FileIO implements CauseCloseable { private static final String USE_JNA = FileIO.class.getName() + ".useJNA"; private static final int IO_TYPE; // 0: platform independent, 1: POSIX private static final boolean NEEDS_DIR_SYNC; static { int type = 0; String jnaProp = System.getProperty(USE_JNA, null); if (jnaProp == null || Boolean.parseBoolean(jnaProp)) { try { if (Native.SIZE_T_SIZE >= 8 && !Platform.isWindows()) { type = 1; } } catch (Throwable e) { if (jnaProp != null) { throw e; } } } IO_TYPE = type; NEEDS_DIR_SYNC = !System.getProperty("os.name").startsWith("Windows"); } public static FileIO open(File file, EnumSet<OpenOption> options) throws IOException { return open(file, options, 32); } public static FileIO open(File file, EnumSet<OpenOption> options, int openFileCount) throws IOException { if (options == null) { options = EnumSet.noneOf(OpenOption.class); } if (IO_TYPE == 1 && (!options.contains(OpenOption.MAPPED) || DirectAccess.isSupported())) { return new PosixFileIO(file, options); } return new JavaFileIO(file, options, openFileCount); } public abstract boolean isDirectIO(); public abstract boolean isReadOnly(); public abstract long length() throws IOException; /** * Attempt to truncate the length of the file. It isn't critical that the operation * succeed, and so any exceptions can be suppressed. */ public abstract void truncateLength(long length) throws IOException; /** * Attempt to expand the length of the file. It isn't critical that the operation succeed, * and so any exceptions can be suppressed. */ public void expandLength(long length) throws IOException { expandLength(length, LengthOption.PREALLOCATE_NEVER); } /** * Attempt to expand the length of the file. It isn't critical that the operation succeed, * and so any exceptions can be suppressed. */ public abstract void expandLength(long length, LengthOption option) throws IOException; /** * @param pos zero-based position in file * @param buf receives read data * @param offset offset into data buffer * @param length amount of data to read * @throws IllegalArgumentException */ public abstract void read(long pos, byte[] buf, int offset, int length) throws IOException; /** * @param pos zero-based position in file * @param buf receives read data * @param offset offset into data buffer * @param length amount of data to read * @param tail receives additional data * @throws IllegalArgumentException */ public abstract void read(long pos, byte[] buf, int offset, int length, ByteBuffer tail) throws IOException; /** * @param pos zero-based position in file * @param bb receives read data * @throws IllegalArgumentException */ public abstract void read(long pos, ByteBuffer bb) throws IOException; /** * @param pos zero-based position in file * @param bb receives read data * @param tail receives additional data * @throws IllegalArgumentException */ public abstract void read(long pos, ByteBuffer bb, ByteBuffer tail) throws IOException; public void read(long pos, long ptr, int offset, int length) throws IOException { throw new UnsupportedOperationException(); } public void read(long pos, long ptr, int offset, int length, ByteBuffer tail) throws IOException { throw new UnsupportedOperationException(); } /** * @param pos zero-based position in file * @param buf data to write * @param offset offset into data buffer * @param length amount of data * @throws IllegalArgumentException */ public abstract void write(long pos, byte[] buf, int offset, int length) throws IOException; /** * @param pos zero-based position in file * @param buf data to write * @param offset offset into data buffer * @param length amount of data * @param tail additional data to write * @throws IllegalArgumentException */ public abstract void write(long pos, byte[] buf, int offset, int length, ByteBuffer tail) throws IOException; /** * @param pos zero-based position in file * @param bb data to write * @throws IllegalArgumentException */ public abstract void write(long pos, ByteBuffer bb) throws IOException; /** * @param pos zero-based position in file * @param bb data to write * @param tail additional data to write * @throws IllegalArgumentException */ public abstract void write(long pos, ByteBuffer bb, ByteBuffer tail) throws IOException; public void write(long pos, long ptr, int offset, int length) throws IOException { throw new UnsupportedOperationException(); } public void write(long pos, long ptr, int offset, int length, ByteBuffer tail) throws IOException { throw new UnsupportedOperationException(); } /** * Maps or remaps the file into main memory, up to the current file length. */ public abstract void map() throws IOException; /** * If file is mapped, remaps it if the file length has changed. Method does nothing if not * already mapped. */ public abstract void remap() throws IOException; /** * Unmaps the file from main memory, leaving the file open. Method does nothing if not * already mapped. */ public abstract void unmap() throws IOException; /** * Durably flushes all writes to the underlying device. * * @param metadata pass true to flush all file metadata */ public abstract void sync(boolean metadata) throws IOException; @Override public void close() throws IOException { close(null); } /** * Durably flushes the given directory, if required. If the given file is not a directory, * the parent directory is flushed. */ public static void dirSync(File file) throws IOException { if (!NEEDS_DIR_SYNC) { return; } while (!file.isDirectory()) { file = file.getParentFile(); if (file == null) { return; } } if (IO_TYPE == 1) { int fd = PosixFileIO.openFd(file, EnumSet.of(OpenOption.READ_ONLY)); try { PosixFileIO.fsyncFd(fd); } finally { PosixFileIO.closeFd(fd); } } else { try (FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.READ)) { fc.force(true); } } } }
cojen/Tupl
src/main/java/org/cojen/tupl/io/FileIO.java
Java
agpl-3.0
8,110
<?php /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ class UserPreferencesController extends SugarController { function action_save_rich_text_preferences() { $this->view = 'ajax'; global $current_user; if(!empty($current_user)) { $height = isset($_REQUEST['height']) ? $_REQUEST['height'] : '325px'; $width = isset($_REQUEST['width']) ? $_REQUEST['width'] : '95%'; $current_user->setPreference('text_editor_height', $height); $current_user->setPreference('text_editor_width', $width); $current_user->savePreferencesToDB(); $json = getJSONobj(); $retArray = array(); $retArray['height'] = $height; $retArray['width'] = $width; echo 'result = ' . $json->encode($retArray); } } } ?>
yinhm/sugarcrm
modules/UserPreferences/controller.php
PHP
agpl-3.0
2,758
# -*- coding: utf-8 -*- # Copyright 2019 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.multi @api.depends( "product_id", ) def _compute_allowed_purchase_uom_ids(self): obj_product_uom =\ self.env["product.uom"] for document in self: uom_po = document.product_id.uom_po_id if document.product_id: if document.product_id.limit_product_uom_selection: allowed_purchase_uom_ids =\ document.product_id.allowed_purchase_uom_ids.ids if uom_po.id not in allowed_purchase_uom_ids: allowed_purchase_uom_ids.append(uom_po.id) document.allowed_purchase_uom_ids =\ allowed_purchase_uom_ids else: category_id =\ uom_po.category_id.id criteria = [ ("category_id", "=", category_id) ] document.allowed_purchase_uom_ids =\ obj_product_uom.search(criteria) allowed_purchase_uom_ids = fields.Many2many( string="Allowed Invoices", comodel_name="product.uom", compute="_compute_allowed_purchase_uom_ids", store=False, ) @api.onchange( "product_id", "product_uom", "product_qty", ) @api.depends( "order_id.pricelist_id", "product_id", "product_qty", "product_uom", "order_id.partner_id", "order_id.date_order", "order_id.fiscal_position", "date_planned", "name", "order_id.state", ) def onchange_product_id_new_api(self): _super = super(PurchaseOrderLine, self) result = _super.onchange_product_id( self.order_id.pricelist_id.id, self.product_id.id, self.product_qty, self.product_uom.id, self.order_id.partner_id.id, self.order_id.date_order, self.order_id.fiscal_position.id, self.date_planned, self.name, False, self.order_id.state, ) if type(result) is dict and "value" in result: for field, value in result.get('value').items(): if hasattr(self, field): setattr(self, field, value)
open-synergy/opnsynid-purchase-workflow
purchase_order_line_allowed_uom/models/purchase_order_line.py
Python
agpl-3.0
2,605
import { ArcaneIntellect, CancelledCasts, DivertedEnergy, ElementalBarrier, FocusMagic, GroundingSurge, IreOfTheAscended, MirrorImage, RuneOfPower, ShiftingPower, SiphonedMalice, TempestBarrier, } from '@wowanalyzer/mage'; import CoreCombatLogParser from 'parser/core/CombatLogParser'; import ArcaneTorrent from 'parser/shared/modules/racials/bloodelf/ArcaneTorrent'; import Checklist from './modules/checklist/Module'; import Buffs from './modules/features/Buffs'; //Normalizers //Features import Abilities from './modules/features/Abilities'; import AlwaysBeCasting from './modules/features/AlwaysBeCasting'; import CooldownThroughputTracker from './modules/features/CooldownThroughputTracker'; import WintersChill from './modules/features/WintersChill'; import BrainFreeze from './modules/features/BrainFreeze'; import IceLance from './modules/features/IceLance'; import IcyVeins from './modules/features/IcyVeins'; import FrozenOrb from './modules/cooldowns/FrozenOrb'; import ColdSnap from './modules/cooldowns/ColdSnap'; //Talents import WaterElemental from './modules/features/WaterElemental'; import LonelyWinter from './modules/talents/LonelyWinter'; import SplittingIce from './modules/talents/SplittingIce'; import ThermalVoid from './modules/talents/ThermalVoid'; import GlacialSpike from './modules/talents/GlacialSpike'; import BoneChilling from './modules/talents/BoneChilling'; //Legendaries import ColdFront from './modules/items/ColdFront'; import GlacialFragments from './modules/items/GlacialFragments'; //Conduits import IceBite from './modules/items/IceBite'; import IcyPropulsion from './modules/items/IcyPropulsion'; import ShiveringCore from './modules/items/ShiveringCore'; import UnrelentingCold from './modules/items/UnrelentingCold'; class CombatLogParser extends CoreCombatLogParser { static specModules = { checklist: Checklist, buffs: Buffs, //Normalizers // Features abilities: Abilities, alwaysBeCasting: AlwaysBeCasting, cancelledCasts: CancelledCasts, cooldownThroughputTracker: CooldownThroughputTracker, wintersChill: WintersChill, brainFreeze: BrainFreeze, iceLance: IceLance, icyVeins: IcyVeins, arcaneIntellect: ArcaneIntellect, mirrorImage: MirrorImage, elementalBarrier: ElementalBarrier, waterElemental: WaterElemental, // Talents boneChilling: BoneChilling, lonelyWinter: LonelyWinter, focusMagic: FocusMagic, runeOfPower: RuneOfPower, splittingIce: SplittingIce, thermalVoid: ThermalVoid, glacialSpike: GlacialSpike, // Cooldowns frozenOrb: FrozenOrb, coldSnap: ColdSnap, //Legendaries coldFront: ColdFront, glacialFragments: GlacialFragments, //Covenants shiftingPower: ShiftingPower, //Conduits iceBite: IceBite, icyPropulsion: IcyPropulsion, shiveringCore: ShiveringCore, unrelentingCold: UnrelentingCold, divertedEnergy: DivertedEnergy, groundingSurge: GroundingSurge, ireOfTheAscended: IreOfTheAscended, tempestBarrier: TempestBarrier, siphonedMalice: SiphonedMalice, // There's no throughput benefit from casting Arcane Torrent on cooldown arcaneTorrent: [ArcaneTorrent, { castEfficiency: null }] as const, }; } export default CombatLogParser;
yajinni/WoWAnalyzer
analysis/magefrost/src/CombatLogParser.ts
TypeScript
agpl-3.0
3,317
/* * Axelor Business Solutions * * Copyright (C) 2019 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ package com.axelor.apps.account.service.payment.paymentvoucher; import com.axelor.apps.account.db.Invoice; import com.axelor.apps.account.db.MoveLine; import com.axelor.apps.account.db.PayVoucherElementToPay; import com.axelor.apps.account.db.PaymentVoucher; import java.lang.invoke.MethodHandles; import java.math.BigDecimal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PayVoucherElementToPayService { private final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); /** * Generic method for creating invoice to pay lines (2nd O2M in the view) * * @param pv * @param seq * @return */ public PayVoucherElementToPay createPayVoucherElementToPay( PaymentVoucher paymentVoucher, int seq, Invoice invoice, MoveLine moveLine, BigDecimal totalAmount, BigDecimal remainingAmount, BigDecimal amountToPay) { log.debug("In createPayVoucherElementToPay...."); if (paymentVoucher != null && moveLine != null) { PayVoucherElementToPay piToPay = new PayVoucherElementToPay(); piToPay.setSequence(seq); piToPay.setMoveLine(moveLine); piToPay.setTotalAmount(totalAmount); piToPay.setRemainingAmount(remainingAmount); piToPay.setAmountToPay(amountToPay); piToPay.setPaymentVoucher(paymentVoucher); log.debug("End createPayVoucherElementToPay IF."); return piToPay; } else { log.debug("End createPayVoucherElementToPay ELSE."); return null; } } }
ama-axelor/axelor-business-suite
axelor-account/src/main/java/com/axelor/apps/account/service/payment/paymentvoucher/PayVoucherElementToPayService.java
Java
agpl-3.0
2,238
define(['handlebars', 'marked'], function(Handlebars, marked) { return function(value) { return new Handlebars.SafeString(marked(value)); }; });
grouan/udata
js/templates/helpers/md.js
JavaScript
agpl-3.0
163
package com.tesora.dve.server.messaging; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. * #L% */ import com.tesora.dve.comms.client.messages.RequestMessage; import com.tesora.dve.comms.client.messages.ResponseMessage; import com.tesora.dve.exceptions.PEException; import com.tesora.dve.worker.WorkerManager; import com.tesora.dve.worker.agent.Envelope; @SuppressWarnings("serial") public abstract class WorkerManagerRequest extends RequestMessage { public abstract ResponseMessage executeRequest(Envelope e, WorkerManager wm) throws PEException; }
Tesora/tesora-dve-pub
tesora-dve-core/src/main/java/com/tesora/dve/server/messaging/WorkerManagerRequest.java
Java
agpl-3.0
1,226
/** * This file is part of mycollab-services. * * mycollab-services is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * mycollab-services is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.project.dao; import com.esofthead.mycollab.core.persistence.ICrudGenericDAO; import com.esofthead.mycollab.module.project.domain.ItemTimeLogging; import com.esofthead.mycollab.module.project.domain.ItemTimeLoggingExample; import java.util.List; import org.apache.ibatis.annotations.Param; @SuppressWarnings({ "ucd", "rawtypes" }) public interface ItemTimeLoggingMapper extends ICrudGenericDAO { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int countByExample(ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int deleteByExample(ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int insert(ItemTimeLogging record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int insertSelective(ItemTimeLogging record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ List<ItemTimeLogging> selectByExampleWithBLOBs(ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ List<ItemTimeLogging> selectByExample(ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ ItemTimeLogging selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int updateByExampleSelective(@Param("record") ItemTimeLogging record, @Param("example") ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int updateByExampleWithBLOBs(@Param("record") ItemTimeLogging record, @Param("example") ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int updateByExample(@Param("record") ItemTimeLogging record, @Param("example") ItemTimeLoggingExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int updateByPrimaryKeySelective(ItemTimeLogging record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int updateByPrimaryKeyWithBLOBs(ItemTimeLogging record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ int updateByPrimaryKey(ItemTimeLogging record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ Integer insertAndReturnKey(ItemTimeLogging value); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ void removeKeysWithSession(List primaryKeys); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_prj_time_logging * * @mbggenerated Thu Jul 16 10:50:12 ICT 2015 */ void massUpdateWithSession(@Param("record") ItemTimeLogging record, @Param("primaryKeys") List primaryKeys); }
uniteddiversity/mycollab
mycollab-services/src/main/java/com/esofthead/mycollab/module/project/dao/ItemTimeLoggingMapper.java
Java
agpl-3.0
5,778
<?php // created: 2012-09-05 05:35:43 $mod_strings = array ( 'LBL_ID' => 'ID', 'LBL_DATE_ENTERED' => 'Date Created', 'LBL_DATE_MODIFIED' => 'Date Modified', 'LBL_MODIFIED' => 'Modified By', 'LBL_MODIFIED_ID' => 'Modified By Id', 'LBL_MODIFIED_NAME' => 'Modified By Name', 'LBL_CREATED' => 'Created By', 'LBL_CREATED_ID' => 'Created By Id', 'LBL_DESCRIPTION' => 'Description:', 'LBL_DELETED' => 'Deleted', 'LBL_NAME' => 'Name', 'LBL_CREATED_USER' => 'Created User', 'LBL_MODIFIED_USER' => 'Modified User', 'LBL_LIST_NAME' => 'Name', 'LBL_ASSIGNED_TO_ID' => 'Assigned User Id', 'LBL_ASSIGNED_TO_NAME' => 'Assigned to:', 'ERR_DELETE_RECORD' => 'A record number must be specified to delete the meeting.', 'LBL_ACCEPT_THIS' => 'Accept?', 'LBL_ADD_BUTTON' => 'Add', 'LBL_ADD_INVITEE' => 'Add Invitees', 'LBL_COLON' => ':', 'LBL_CONTACT_NAME' => 'Contact:', 'LBL_CONTACTS_SUBPANEL_TITLE' => 'Contacts', 'LBL_CREATED_BY' => 'Created by', 'LBL_DATE_END' => 'Date End', 'LBL_DATE_TIME' => 'Start Date & Time:', 'LBL_DATE' => 'Start Date:', 'LBL_DEFAULT_SUBPANEL_TITLE' => 'Meetings', 'LBL_DEL' => 'Del', 'LBL_DESCRIPTION_INFORMATION' => 'Description Information', 'LBL_DURATION_HOURS' => 'Duration Hours:', 'LBL_DURATION_MINUTES' => 'Duration Minutes:', 'LBL_DURATION' => 'Duration:', 'LBL_EMAIL' => 'Email', 'LBL_FIRST_NAME' => 'First Name', 'LBL_HISTORY_SUBPANEL_TITLE' => 'Notes', 'LBL_HOURS_ABBREV' => 'h', 'LBL_HOURS_MINS' => '(hours/minutes)', 'LBL_INVITEE' => 'Invitees', 'LBL_LAST_NAME' => 'Last Name', 'LBL_LIST_ASSIGNED_TO_NAME' => 'Assigned User', 'LBL_LIST_CLOSE' => 'Close', 'LBL_LIST_CONTACT' => 'Contact', 'LBL_LIST_DATE_MODIFIED' => 'Date Modified', 'LBL_LIST_DATE' => 'Start Date', 'LBL_LIST_DIRECTION' => 'Direction', 'LBL_LIST_DUE_DATE' => 'Due Date', 'LBL_LIST_FORM_TITLE' => 'Meeting List', 'LBL_LIST_MY_MEETINGS' => 'My Meetings', 'LBL_LIST_RELATED_TO' => 'Related to', 'LBL_LIST_STATUS' => 'Status', 'LBL_LIST_SUBJECT' => 'Subject', 'LBL_LIST_TIME' => 'Start Time', 'LBL_LEADS_SUBPANEL_TITLE' => 'Leads', 'LBL_LOCATION' => 'Location:', 'LBL_MEETING' => 'Meeting:', 'LBL_MINSS_ABBREV' => 'm', 'LBL_MODIFIED_BY' => 'Modified by', 'LBL_MODULE_NAME' => 'Meetings', 'LBL_MODULE_TITLE' => 'Meetings: Home', 'LBL_NEW_FORM_TITLE' => 'Create Appointment', 'LBL_OUTLOOK_ID' => 'Outlook ID', 'LBL_PHONE' => 'Phone Office:', 'LBL_REMINDER_TIME' => 'Reminder Time', 'LBL_REMINDER' => 'Reminder:', 'LBL_REMOVE' => 'rem', 'LBL_SCHEDULING_FORM_TITLE' => 'Scheduling', 'LBL_SEARCH_BUTTON' => 'Search', 'LBL_SEARCH_FORM_TITLE' => 'Meeting Search', 'LBL_SEND_BUTTON_KEY' => 'I', 'LBL_SEND_BUTTON_LABEL' => 'Send Invites', 'LBL_SEND_BUTTON_TITLE' => 'Send Invites [Alt+I]', 'LBL_STATUS' => 'Status:', 'LBL_TYPE' => 'Meeting Type', 'LBL_PASSWORD' => 'Meeting Password', 'LBL_URL' => 'Start/Join Meeting', 'LBL_CREATOR' => 'Meeting Creator', 'LBL_EXTERNALID' => 'External App ID', 'LBL_SUBJECT' => 'Subject:', 'LBL_TIME' => 'Start Time:', 'LBL_USERS_SUBPANEL_TITLE' => 'Users', 'LBL_ACTIVITIES_REPORTS' => 'Activities Report', 'LNK_MEETING_LIST' => 'View Meetings', 'LNK_NEW_APPOINTMENT' => 'Create Appointment', 'LNK_NEW_MEETING' => 'Schedule Meeting', 'LNK_IMPORT_MEETINGS' => 'Import Meetings', 'NTC_REMOVE_INVITEE' => 'Are you sure you want to remove this invitee from the meeting?', 'NOTICE_DURATION_TIME' => 'Duration time must be greater than 0', 'LBL_MEETING_INFORMATION' => 'Meeting Overview', 'LBL_LIST_JOIN_MEETING' => 'Join Meeting', 'LBL_JOIN_EXT_MEETING' => 'Join Meeting', 'LBL_HOST_EXT_MEETING' => 'Start Meeting', 'LBL_EXTNOT_HEADER' => 'Error: Not Invited', 'LBL_EXTNOT_MAIN' => 'You are not able to join this meeting because you are not an Invitee.', 'LBL_EXTNOT_RECORD_LINK' => 'View Meeting', 'LBL_EXTNOT_GO_BACK' => 'Go back to the previous record', 'LBL_EXTNOSTART_HEADER' => 'Error: Cannot Start Meeting', 'LBL_EXTNOSTART_MAIN' => 'You cannot start this meeting because you are not an Administrator or the owner of the meeting.', ); ?>
minh10huy/HiringBossCRM
cache/modules/Meetings/language/en_us.lang.php
PHP
agpl-3.0
4,147
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * The contents of this file are subject to the SugarCRM Master Subscription * Agreement ("License") which can be viewed at * http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf * By installing or using this file, You have unconditionally agreed to the * terms and conditions of the License, and You may not use this file except in * compliance with the License. Under the terms of the license, You shall not, * among other things: 1) sublicense, resell, rent, lease, redistribute, assign * or otherwise transfer Your rights to the Software, and 2) use the Software * for timesharing or service bureau purposes such as hosting the Software for * commercial gain and/or for the benefit of a third party. Use of the Software * may be subject to applicable fees and any use of the Software without first * paying applicable fees is strictly prohibited. You do not have the right to * remove SugarCRM copyrights from the source code or user interface. * * All copies of the Covered Code must include on each user interface screen: * (i) the "Powered by SugarCRM" logo and * (ii) the SugarCRM copyright notice * in the same form as they appear in the distribution. See full license for * requirements. * * Your Warranty, Limitations of liability and Indemnity are expressly stated * in the License. Please refer to the License for the specific language * governing these rights and limitations under the License. Portions created * by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved. ********************************************************************************/ /********************************************************************************* * Description: ********************************************************************************/ $focus = new Release(); $focus->retrieve($_REQUEST['record']); foreach($focus->column_fields as $field) { if(isset($_REQUEST[$field])) { $focus->$field = $_REQUEST[$field]; } } foreach($focus->additional_column_fields as $field) { if(isset($_REQUEST[$field])) { $value = $_REQUEST[$field]; $focus->$field = $value; } } $focus->save(); $return_id = $focus->id; $edit=''; if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = $_REQUEST['return_module']; else $return_module = "Releases"; if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = $_REQUEST['return_action']; else $return_action = "DetailView"; if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = $_REQUEST['return_id']; if(!empty($_REQUEST['edit'])) { $return_id=''; $edit='&edit=true'; } $GLOBALS['log']->debug("Saved record with id of ".$return_id); header("Location: index.php?action=$return_action&module=$return_module&record=$return_id$edit"); ?>
harish-patel/ecrm
modules/Releases/Save.php
PHP
agpl-3.0
3,041
// ----------> GENERATED FILE - DON'T TOUCH! <---------- // generator: ilarkesto.mda.legacy.generator.GwtServiceCallGenerator package scrum.client.communication; import java.util.*; @com.google.gwt.user.client.rpc.RemoteServiceRelativePath("scrum") public class TouchLastActivityServiceCall extends ilarkesto.gwt.client.AServiceCall<scrum.client.DataTransferObject> { private static scrum.client.ScrumServiceAsync service; public TouchLastActivityServiceCall() { } @Override protected synchronized void onExecute(int conversationNumber, com.google.gwt.user.client.rpc.AsyncCallback<scrum.client.DataTransferObject> callback) { if (service==null) { service = (scrum.client.ScrumServiceAsync) com.google.gwt.core.client.GWT.create(scrum.client.ScrumService.class); initializeService(service, "scrum"); } service.touchLastActivity(conversationNumber, callback); } @Override public String toString() { return "touchLastActivity"; } }
JavierPeris/kunagi
src/generated/java/scrum/client/communication/TouchLastActivityServiceCall.java
Java
agpl-3.0
1,052
/* * Radio device interface with sample rate conversion * * Copyright (C) 2011-2014 Free Software Foundation, Inc. * Copyright (C) 2015 Ettus Research LLC * * Author: Tom Tsou <tom@tsou.cc> * * 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 * (at your option) 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/>. * See the COPYING file in the main directory for details. */ #include <radioInterface.h> #include <Logger.h> #include "Resampler.h" extern "C" { #include "convert.h" } /* Resampling parameters for 64 MHz clocking */ #define RESAMP_64M_INRATE 65 #define RESAMP_64M_OUTRATE 96 /* Resampling parameters for 100 MHz clocking */ #define RESAMP_100M_INRATE 52 #define RESAMP_100M_OUTRATE 75 /* Universal resampling parameters */ #define NUMCHUNKS 24 /* * Resampling filter bandwidth scaling factor * This narrows the filter cutoff relative to the output bandwidth * of the polyphase resampler. At 4 samples-per-symbol using the * 2 pulse Laurent GMSK approximation gives us below 0.5 degrees * RMS phase error at the resampler output. */ #define RESAMP_TX4_FILTER 0.45 static Resampler *upsampler = NULL; static Resampler *dnsampler = NULL; static size_t resamp_inrate = 0; static size_t resamp_inchunk = 0; static size_t resamp_outrate = 0; static size_t resamp_outchunk = 0; RadioInterfaceResamp::RadioInterfaceResamp(RadioDevice *wRadio, size_t tx_sps, size_t rx_sps) : RadioInterface(wRadio, tx_sps, rx_sps, 1), outerSendBuffer(NULL), outerRecvBuffer(NULL) { } RadioInterfaceResamp::~RadioInterfaceResamp() { close(); } void RadioInterfaceResamp::close() { delete outerSendBuffer; delete outerRecvBuffer; delete upsampler; delete dnsampler; outerSendBuffer = NULL; outerRecvBuffer = NULL; upsampler = NULL; dnsampler = NULL; if (sendBuffer.size()) sendBuffer[0] = NULL; if (recvBuffer.size()) recvBuffer[0] = NULL; RadioInterface::close(); } /* Initialize I/O specific objects */ bool RadioInterfaceResamp::init(int type) { float cutoff = 1.0f; close(); sendBuffer.resize(1); recvBuffer.resize(1); convertSendBuffer.resize(1); convertRecvBuffer.resize(1); mReceiveFIFO.resize(1); powerScaling.resize(1); switch (type) { case RadioDevice::RESAMP_64M: resamp_inrate = RESAMP_64M_INRATE; resamp_outrate = RESAMP_64M_OUTRATE; break; case RadioDevice::RESAMP_100M: resamp_inrate = RESAMP_100M_INRATE; resamp_outrate = RESAMP_100M_OUTRATE; break; case RadioDevice::NORMAL: default: LOG(ALERT) << "Invalid device configuration"; return false; } resamp_inchunk = resamp_inrate * 4 * mSPSRx; resamp_outchunk = resamp_outrate * 4 * mSPSRx; if (mSPSTx == 4) cutoff = RESAMP_TX4_FILTER; dnsampler = new Resampler(resamp_inrate, resamp_outrate); if (!dnsampler->init()) { LOG(ALERT) << "Rx resampler failed to initialize"; return false; } upsampler = new Resampler(resamp_outrate, resamp_inrate); if (!upsampler->init(cutoff)) { LOG(ALERT) << "Tx resampler failed to initialize"; return false; } /* * Allocate high and low rate buffers. The high rate receive * buffer and low rate transmit vectors feed into the resampler * and requires headroom equivalent to the filter length. Low * rate buffers are allocated in the main radio interface code. */ sendBuffer[0] = new RadioBuffer(NUMCHUNKS, resamp_inchunk, upsampler->len(), true); recvBuffer[0] = new RadioBuffer(NUMCHUNKS * 20, resamp_inchunk, 0, false); outerSendBuffer = new signalVector(NUMCHUNKS * resamp_outchunk); outerRecvBuffer = new signalVector(resamp_outchunk, dnsampler->len()); convertSendBuffer[0] = new short[outerSendBuffer->size() * 2]; convertRecvBuffer[0] = new short[outerRecvBuffer->size() * 2]; return true; } /* Receive a timestamped chunk from the device */ int RadioInterfaceResamp::pullBuffer() { bool local_underrun; int rc, num_recv; if (recvBuffer[0]->getFreeSegments() <= 0) return -1; /* Outer buffer access size is fixed */ num_recv = mRadio->readSamples(convertRecvBuffer, resamp_outchunk, &overrun, readTimestamp, &local_underrun); if (num_recv != (int) resamp_outchunk) { LOG(ALERT) << "Receive error " << num_recv; return -1; } convert_short_float((float *) outerRecvBuffer->begin(), convertRecvBuffer[0], 2 * resamp_outchunk); underrun |= local_underrun; readTimestamp += (TIMESTAMP) resamp_outchunk; /* Write to the end of the inner receive buffer */ rc = dnsampler->rotate((float *) outerRecvBuffer->begin(), resamp_outchunk, recvBuffer[0]->getWriteSegment(), resamp_inchunk); if (rc < 0) { LOG(ALERT) << "Sample rate upsampling error"; } /* Set history for the next chunk */ outerRecvBuffer->updateHistory(); return 0; } /* Send a timestamped chunk to the device */ bool RadioInterfaceResamp::pushBuffer() { int rc; size_t numSent; if (sendBuffer[0]->getAvailSegments() <= 0) return false; /* Always send from the beginning of the buffer */ rc = upsampler->rotate(sendBuffer[0]->getReadSegment(), resamp_inchunk, (float *) outerSendBuffer->begin(), resamp_outchunk); if (rc < 0) { LOG(ALERT) << "Sample rate downsampling error"; } convert_float_short(convertSendBuffer[0], (float *) outerSendBuffer->begin(), powerScaling[0], 2 * resamp_outchunk); numSent = mRadio->writeSamples(convertSendBuffer, resamp_outchunk, &underrun, writeTimestamp); if (numSent != resamp_outchunk) { LOG(ALERT) << "Transmit error " << numSent; } writeTimestamp += resamp_outchunk; return true; }
ttsou/osmo-trx
Transceiver52M/radioInterfaceResamp.cpp
C++
agpl-3.0
6,195
/* * The Exomiser - A tool to annotate and prioritize genomic variants * * Copyright (c) 2016-2021 Queen Mary University of London. * Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd. * * 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 (at your option) 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/>. */ package org.monarchinitiative.exomiser.data.genome.config; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.Test; import org.monarchinitiative.exomiser.core.genome.GenomeAssembly; import org.monarchinitiative.exomiser.data.genome.model.AlleleResource; import org.monarchinitiative.exomiser.data.genome.model.archive.*; import org.monarchinitiative.exomiser.data.genome.model.parsers.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import java.nio.file.Paths; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Jules Jacobsen <j.jacobsen@qmul.ac.uk> */ @SpringJUnitConfig(classes = {Hg19Config.class}) @TestPropertySource("/application-test.properties") public class Hg19ConfigTest { @Autowired Hg19Config instance; @Test void assemblyResources() { AssemblyResources assemblyResources = instance.hg19AssemblyResources(); assertThat(assemblyResources.getGenomeAssembly(), equalTo(GenomeAssembly.HG19)); assertFalse(assemblyResources.getAlleleResources().isEmpty()); assertThat(assemblyResources.getGenomeDataPath(), equalTo(instance.genomeDataPath())); } @Test public void testResources() { Map<String, AlleleResource> actualResources = instance.hg19AlleleResources(); ImmutableMap.Builder<String, AlleleResource> alleleResources = new ImmutableMap.Builder<>(); alleleResources.put("gnomad-genome", instance.gnomadGenomeAlleleResource()); alleleResources.put("gnomad-exome", instance.gnomadExomeAlleleResource()); alleleResources.put("dbsnp", instance.dbSnpAlleleResource()); alleleResources.put("uk10k", instance.uk10kAlleleResource()); alleleResources.put("exac", instance.exacAlleleResource()); alleleResources.put("esp", instance.espAlleleResource()); alleleResources.put("dbnsfp", instance.dbnsfpAlleleResource()); alleleResources.put("clinvar", instance.clinVarAlleleResource()); Map<String, AlleleResource> expectedResources = alleleResources.build(); assertThat(actualResources.keySet(), equalTo(expectedResources.keySet())); for (String key : expectedResources.keySet()) { AlleleResource actual = actualResources.get(key); AlleleResource expected = expectedResources.get(key); assertThat(actual.getName(), equalTo(expected.getName())); assertThat(actual.getParser(), instanceOf(expected.getParser().getClass())); assertThat(actual.getArchive(), equalTo(expected.getArchive())); } } @Test public void dbSnpAlleleResource() throws Exception { AlleleResource alleleResource = instance.dbSnpAlleleResource(); Archive expectedArchive = new DbSnpArchive(Paths.get("src/test/resources/hg19/variants/00-All.vcf.gz")); assertThat(alleleResource.getParser(), instanceOf(DbSnpAlleleParser.class)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void testEspAlleleResource() throws Exception { AlleleResource alleleResource = instance.espAlleleResource(); Archive expectedArchive = new EspArchive(Paths.get("src/test/resources/hg19/variants/ESP6500SI-V2-SSA137.GRCh38-liftover.snps_indels.vcf.tar.gz")); assertThat(alleleResource.getParser(), instanceOf(EspHg19AlleleParser.class)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void testDbNsfpAlleleResource() throws Exception { AlleleResource alleleResource = instance.dbnsfpAlleleResource(); Archive expectedArchive = new DbNsfp3Archive(Paths.get("src/test/resources/hg19/variants/dbNSFPv3.4a.zip")); assertThat(alleleResource.getParser(), instanceOf(DbNsfpAlleleParser.class)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void exacAlleleResource() throws Exception { AlleleResource alleleResource = instance.exacAlleleResource(); Archive expectedArchive = new TabixArchive(Paths.get("src/test/resources/hg19/variants/ExAC.r0.3.1.sites.vep.vcf.gz")); assertThat(alleleResource.getParser(), instanceOf(ExacAlleleParser.class)); ExacExomeAlleleParser exacAlleleParser = (ExacExomeAlleleParser) alleleResource.getParser(); assertThat(exacAlleleParser.getPopulationKeys(), equalTo(ExacPopulationKey.EXAC_EXOMES)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void gnomadGenomeAlleleResource() throws Exception { AlleleResource alleleResource = instance.gnomadGenomeAlleleResource(); Archive expectedArchive = new TabixArchive(Paths.get("src/test/resources/hg19/variants/gnomad.genomes.r2.0.1.sites.noVEP.vcf.gz")); assertThat(alleleResource.getParser(), instanceOf(ExacAlleleParser.class)); GnomadGenomeAlleleParser exacAlleleParser = (GnomadGenomeAlleleParser) alleleResource.getParser(); assertThat(exacAlleleParser.getPopulationKeys(), equalTo(ExacPopulationKey.GNOMAD_GENOMES)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void gnomadExomeAlleleResource() throws Exception { AlleleResource alleleResource = instance.gnomadExomeAlleleResource(); Archive expectedArchive = new TabixArchive(Paths.get("src/test/resources/hg19/variants/gnomad.exomes.r2.0.1.sites.noVEP.vcf.gz")); assertThat(alleleResource.getParser(), instanceOf(ExacAlleleParser.class)); GnomadExomeAlleleParser exacAlleleParser = (GnomadExomeAlleleParser) alleleResource.getParser(); assertThat(exacAlleleParser.getPopulationKeys(), equalTo(ExacPopulationKey.GNOMAD_EXOMES)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void testTopmedAlleleResource() throws Exception { AlleleResource alleleResource = instance.topmedAlleleResource(); Archive expectedArchive = new TabixArchive(Paths.get("src/test/resources/hg19/variants/TOPMED_GRCh37.vcf.gz")); assertThat(alleleResource.getParser(), instanceOf(TopMedAlleleParser.class)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } @Test public void testU10kAlleleResource() throws Exception { AlleleResource alleleResource = instance.uk10kAlleleResource(); Archive expectedArchive = new TabixArchive(Paths.get("src/test/resources/hg19/variants/UK10K_COHORT.20160215.sites.vcf.gz")); assertThat(alleleResource.getParser(), instanceOf(Uk10kAlleleParser.class)); assertThat(alleleResource.getArchive(), equalTo(expectedArchive)); } }
exomiser/Exomiser
exomiser-data-genome/src/test/java/org/monarchinitiative/exomiser/data/genome/config/Hg19ConfigTest.java
Java
agpl-3.0
7,963
/* Code for Life Copyright (C) 2016, Ocado Innovation Limited 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 (at your option) 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/>. ADDITIONAL TERMS – Section 7 GNU General Public Licence This licence does not grant any right, title or interest in any “Ocado” logos, trade names or the trademark “Ocado” or any other trademarks or domain names owned by Ocado Innovation Limited or the Ocado group of companies or any other distinctive brand features of “Ocado” as may be secured from time to time. You must not distribute any modification of this program using the trademark “Ocado” or claim any affiliation or association with Ocado or its employees. You are not authorised to use the name Ocado (or any of its trade names) or the names of any author or contributor in advertising or for publicity purposes pertaining to the distribution of this program, without the prior written authorisation of Ocado. Any propagation, distribution or conveyance of this program must include this copyright notice and these terms. You must not misrepresent the origins of this program; modified versions of the program must be marked as such and not identified as the original program. */ var ocargo = ocargo || {}; // Object containing helper js objects (buttons etc). ocargo.jsElements = { image: function(url, class_) { return "<img src='" + url + "'class='" + class_ + "'>"; } }; //FIXME: actually use Django's internationalisation framework. ocargo.messages = { tooManyBlocks: "Whoops. You used too many blocks.", terminated: "Program terminated.", crashed: "Your program crashed.", stoppingTitle: "Stopping...", // Level editor. trafficLightsWarning: "You need to complete level 44 before using a traffic light. ", shareSuccessful: "Your level has been successfully shared! " };
CelineBoudier/rapid-router
game/static/game/js/messages.js
JavaScript
agpl-3.0
2,408
# frozen_string_literal: true module Decidim module Admin # A command with all the business logic to transfer a managed user. class TransferUser < Rectify::Command # Public: Initializes the command. # # form # user - The current user # managed_user - The managed User def initialize(form) @form = form end # Executes the command. Broadcasts these events: # # - :ok when everything is valid. # - :invalid if the impersonation is not valid. # # Returns nothing. def call return broadcast(:invalid) unless form.valid? transaction do update_managed_user mark_conflict_as_solved create_action_log end broadcast(:ok) end private attr_reader :form def new_user form.conflict.current_user end def managed_user form.conflict.managed_user end def current_user form.current_user end def update_managed_user clean_email_and_delete_new_user if form.email == new_user.email managed_user.email = form.email managed_user.encrypted_password = new_user.encrypted_password managed_user.confirmed_at = new_user.confirmed_at managed_user.managed = false managed_user.skip_reconfirmation! managed_user.save! end def clean_email_and_delete_new_user new_user.update(deleted_at: Time.now.utc, email: "") end def mark_conflict_as_solved form.conflict.update(solved: true) end def create_action_log Decidim.traceability.perform_action!( "transfer", form.conflict.managed_user, current_user, visibility: "admin-only" ) end end end end
AjuntamentdeBarcelona/decidim
decidim-admin/app/commands/decidim/admin/transfer_user.rb
Ruby
agpl-3.0
1,852
import { Box } from './Box'; export const ColorBox = props => { const { color, ...rest } = props; return ( <Box inline width={2} height={2} lineHeight={2} color={color} backgroundColor={color} content="." {...rest} /> ); };
AnturK/-tg-station
tgui-next/packages/tgui/components/ColorBox.js
JavaScript
agpl-3.0
283
<?php /* Copyright (C) 2016 Stephan Kreutzer * * This file is part of refugee-it.de. * * refugee-it.de is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 or any later version, * as published by the Free Software Foundation. * * refugee-it.de 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 3 for more details. * * You should have received a copy of the GNU Affero General Public License 3 * along with refugee-it.de. If not, see <http://www.gnu.org/licenses/>. */ if (empty($_SESSION) === true) { @session_start(); } $_SESSION['page'] = "index"; unset($_SESSION['subpage']); require_once("./libraries/languagelib.inc.php"); require_once(getLanguageFile("index")); $direction = getCurrentLanguageDirection(); echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n". "<!DOCTYPE html\n". " PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n". " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n". "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"".getCurrentLanguage()."\" lang=\"".getCurrentLanguage()."\">\n". " <head>\n". " <meta http-equiv=\"content-type\" content=\"application/xhtml+xml; charset=UTF-8\"/>\n". " <title>".LANG_PAGETITLE."</title>\n". " <link rel=\"stylesheet\" type=\"text/css\" href=\"mainstyle.css\"/>\n". " <meta http-equiv=\"expires\" content=\"1296000\"/>\n". " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n". " </head>\n". " <body>\n"; include(dirname(__FILE__)."/navigation.inc.php"); echo GetNavigation(); if ($direction === LanguageDefinition::DirectionRTL) { echo " <div id=\"content_rtl\">\n"; } else { echo " <div id=\"content\">\n"; } require_once("./language_selector.inc.php"); echo getHTMLLanguageSelector("index.php"); echo " <div>\n". " <h1>".LANG_ABOUT_HEADER."</h1>\n". " <p>\n". " ".LANG_ABOUT_TEXT."\n". " </p>\n". " </div>\n". " <div>\n". " <p>\n". " ".LANG_SOURCE_ON."<a href=\"https://github.com/refugee-it/website\">GitHub</a>".LANG_SOURCE_POST."\n". " </p>\n". " </div>\n"; echo " </div>\n". " </body>\n". "</html>\n". "\n"; ?>
refugee-it/website
index.php
PHP
agpl-3.0
2,613
import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import SPECS from 'common/SPECS'; import { calculateSecondaryStatDefault, calculatePrimaryStat } from 'common/stats'; import { formatMilliseconds } from 'common/format'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import { STAT_TRACKER_BUFFS as DARKMOON_DECK_IMMORTALITY_BUFFS } from 'Parser/Core/Modules/Items/Legion/DarkmoonDeckImmortality'; const debug = false; // TODO: stat constants somewhere else? they're largely copied from combatant class StatTracker extends Analyzer { static dependencies = { combatants: Combatants, }; // These are multipliers to the stats applied *on pull* that are not // included in the stats reported by WCL. These are *baked in* and do // not multiply temporary buffs. // // In general, it looks like armor is the only one that isn't applied // by WCL. static SPEC_MULTIPLIERS = { [SPECS.BREWMASTER_MONK.id]: { armor: 1.25 }, }; // These are multipliers from *binary* (have it or don't) artifact // traits. These are *baked in* and do not multiply temporary buffs. static ARTIFACT_MULTIPLIERS = { [SPELLS.ENDURANCE_OF_THE_BROKEN_TEMPLE_TRAIT.id]: { armor: 0.35 }, [SPELLS.WANDERERS_HARDINESS_TRAIT.id]: { armor: 0.17 }, }; static STAT_BUFFS = { // region Potions [SPELLS.POTION_OF_PROLONGED_POWER.id]: { stamina: 2500, strength: 2500, agility: 2500, intellect: 2500 }, // endregion // region Runes [SPELLS.DEFILED_AUGMENT_RUNE.id]: { strength: 325, agility: 325, intellect: 325 }, // endregion //region Flasks [SPELLS.FLASK_OF_THE_WHISPERED_PACT.id]: { intellect: 1300 }, [SPELLS.FLASK_OF_THE_SEVENTH_DEMON.id]: { agility: 1300 }, [SPELLS.FLASK_OF_THE_COUNTLESS_ARMIES.id]: { strength: 1300 }, [SPELLS.FLASK_OF_TEN_THOUSAND_SCARS.id]: { stamina: 1950 }, // endregion //region Food [SPELLS.THE_HUNGRY_MAGISTER.id]: { crit: 375 }, [SPELLS.AZSHARI_SALAD.id]: { haste: 375 }, [SPELLS.NIGHTBORNE_DELICACY_PLATTER.id]: { mastery: 375 }, [SPELLS.SEED_BATTERED_FISH_PLATE.id]: { versatility: 375 }, [SPELLS.STAM_FEAST.id]: { stamina: 600 }, [SPELLS.STR_FEAST.id]: { strength: 500 }, [SPELLS.AGI_FEAST.id]: { agility: 500 }, [SPELLS.INT_FEAST.id]: { intellect: 500 }, //endregion // region Dungeon Trinkets [SPELLS.SHADOWS_STRIKE.id]: { itemId: ITEMS.DREADSTONE_OF_ENDLESS_SHADOWS.id, crit: (_, item) => calculateSecondaryStatDefault(845, 3480, item.itemLevel), }, [SPELLS.SHADOW_MASTER.id]: { itemId: ITEMS.DREADSTONE_OF_ENDLESS_SHADOWS.id, mastery: (_, item) => calculateSecondaryStatDefault(845, 3480, item.itemLevel), }, [SPELLS.SWARMING_SHADOWS.id]: { itemId: ITEMS.DREADSTONE_OF_ENDLESS_SHADOWS.id, haste: (_, item) => calculateSecondaryStatDefault(845, 3480, item.itemLevel), }, [SPELLS.QUITE_SATISFIED_VERSATILITY.id]: { itemId: ITEMS.MAJORDOMOS_DINNER_BELL.id, versatility: (_, item) => calculateSecondaryStatDefault(845, 5252, item.itemLevel), }, [SPELLS.QUITE_SATISFIED_CRIT.id]: { itemId: ITEMS.MAJORDOMOS_DINNER_BELL.id, crit: (_, item) => calculateSecondaryStatDefault(845, 5252, item.itemLevel), }, [SPELLS.QUITE_SATISFIED_HASTE.id]: { itemId: ITEMS.MAJORDOMOS_DINNER_BELL.id, haste: (_, item) => calculateSecondaryStatDefault(845, 5252, item.itemLevel), }, [SPELLS.QUITE_SATISFIED_MASTERY.id]: { itemId: ITEMS.MAJORDOMOS_DINNER_BELL.id, mastery: (_, item) => calculateSecondaryStatDefault(845, 5252, item.itemLevel), }, [SPELLS.HOWL_OF_INGVAR.id]: { itemId: ITEMS.MEMENTO_OF_ANGERBODA.id, crit: (_, item) => calculateSecondaryStatDefault(845, 4207, item.itemLevel), }, [SPELLS.DIRGE_OF_ANGERBODA.id]: { itemId: ITEMS.MEMENTO_OF_ANGERBODA.id, mastery: (_, item) => calculateSecondaryStatDefault(845, 4207, item.itemLevel), }, [SPELLS.WAIL_OF_SVALA.id]: { itemId: ITEMS.MEMENTO_OF_ANGERBODA.id, haste: (_, item) => calculateSecondaryStatDefault(845, 4207, item.itemLevel), }, [SPELLS.DOWN_DRAFT.id]: { itemId: ITEMS.NIGHTMARE_EGG_SHELL.id, haste: (_, item) => calculateSecondaryStatDefault(845, 361, item.itemLevel), }, [SPELLS.ACCELERATION.id]: { itemId: ITEMS.CHRONO_SHARD.id, haste: (_, item) => calculateSecondaryStatDefault(845, 5269, item.itemLevel), }, [SPELLS.GREASE_THE_GEARS.id]: { itemId: ITEMS.FELOILED_INFERNAL_MACHINE.id, haste: (_, item) => calculateSecondaryStatDefault(845, 3074, item.itemLevel), }, //endregion // region Raid Trinkets // Event weirdness makes it impossible to handle CotRT normally, it's handled instead by the CharmOfTheRisingTide module //[SPELLS.RISING_TIDES.id]: { // itemId: ITEMS.CHARM_OF_THE_RISING_TIDE.id, // haste: (_, item) => calculateSecondaryStatDefault(900, 576, item.itemLevel), //}, [SPELLS.ACCELERANDO.id]: { itemId: ITEMS.ERRATIC_METRONOME.id, haste: (_, item) => calculateSecondaryStatDefault(870, 657, item.itemLevel), }, [SPELLS.SOLAR_INFUSION.id]: { itemId: ITEMS.CHALICE_OF_MOONLIGHT.id, crit: (_, item) => calculateSecondaryStatDefault(900, 3619, item.itemLevel), }, [SPELLS.LUNAR_INFUSION.id]: { itemId: ITEMS.CHALICE_OF_MOONLIGHT.id, haste: (_, item) => calculateSecondaryStatDefault(900, 3619, item.itemLevel), }, [SPELLS.TOME_OF_UNRAVELING_SANITY_BUFF.id]: { itemId: ITEMS.TOME_OF_UNRAVELING_SANITY.id, crit: (_, item) => calculateSecondaryStatDefault(910, 2756, item.itemLevel), }, [SPELLS.BRUTALITY_OF_THE_LEGION.id]: { itemId: ITEMS.ACRID_CATALYST_INJECTOR.id, crit: (_, item) => calculateSecondaryStatDefault(955, 210, item.itemLevel), }, [SPELLS.FERVOR_OF_THE_LEGION.id]: { itemId: ITEMS.ACRID_CATALYST_INJECTOR.id, haste: (_, item) => calculateSecondaryStatDefault(955, 210, item.itemLevel), }, [SPELLS.MALICE_OF_THE_LEGION.id]: { itemId: ITEMS.ACRID_CATALYST_INJECTOR.id, mastery: (_, item) => calculateSecondaryStatDefault(955, 210, item.itemLevel), }, [SPELLS.CYCLE_OF_THE_LEGION.id]: { itemId: ITEMS.ACRID_CATALYST_INJECTOR.id, crit: (_, item) => calculateSecondaryStatDefault(955, 2397, item.itemLevel), haste: (_, item) => calculateSecondaryStatDefault(955, 2397, item.itemLevel), mastery: (_, item) => calculateSecondaryStatDefault(955, 2397, item.itemLevel), }, [SPELLS.FEEDBACK_LOOP.id]: { itemId: ITEMS.GAROTHI_FEEDBACK_CONDUIT.id, haste: (_, item) => calculateSecondaryStatDefault(930, 856, item.itemLevel), }, [SPELLS.RUSH_OF_KNOWLEDGE.id]: { itemId: ITEMS.NORGANNONS_PROWESS.id, intellect: (_, item) => calculatePrimaryStat(940, 11483, item.itemLevel), }, // Khaz'goroth's Courage is handled in it's own module since all 4 stat buffs use the same ID. //[SPELLS.KHAZGOROTHS_SHAPING.id]: { // itemId: ITEMS.KHAZGOROTHS_COURAGE.id, // haste: (_, item) => calculateSecondaryStatDefault(940, 4219, item.itemLevel), //}, // endregion // region Crafted Trinkets ...DARKMOON_DECK_IMMORTALITY_BUFFS, // endregion // region Misc [SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_STRENGTH.id]: { // check numbers strength: combatant => 4000 + (combatant.traitsBySpellId[SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_TRAIT.id] - 1) * 300, }, [SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_AGILITY.id]: { // check numbers agility: combatant => 4000 + (combatant.traitsBySpellId[SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_TRAIT.id] - 1) * 300, }, [SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_INTELLECT.id]: { // check numbers intellect: combatant => 4000 + (combatant.traitsBySpellId[SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_TRAIT.id] - 1) * 300, }, [SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_VERSATILITY.id]: { versatility: combatant => 1500 + (combatant.traitsBySpellId[SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_TRAIT.id] - 1) * 300, }, [SPELLS.JACINS_RUSE.id]: { mastery: 3000 }, [SPELLS.MASTER_OF_COMBINATIONS.id]: { mastery: 600 }, [SPELLS.MARK_OF_THE_CLAW.id]: { crit: 1000, haste: 1000 }, [SPELLS.FURY_OF_ASHAMANE.id]: { versatility: 600 }, // Antorus: Argus the Unmaker debuffs [SPELLS.STRENGTH_OF_THE_SKY.id]: { crit: 2000, mastery: 2000 }, [SPELLS.STRENGTH_OF_THE_SEA.id]: { haste: 2000, versatility: 2000 }, // endregion // region Death Knight [SPELLS.VAMPIRIC_AURA.id]: { leech: (23000 * 0.20) }, // TODO make non static so can use this.leechRatingPerPercent ?? // endregion // region Druid [SPELLS.ASTRAL_HARMONY.id]: { mastery: 4000 }, // endregion // region Mage [SPELLS.WARMTH_OF_THE_PHOENIX.id]: { crit: 800 }, // endregion // region Priest [SPELLS.MIND_QUICKENING.id]: { haste: 800 }, // endregion // region Paladin [SPELLS.SERAPHIM_TALENT.id]: { crit: 5500, haste: 5500, mastery: 5500, versatility: 5500 }, // endregion }; _pullStats = {}; _currentStats = {}; on_initialized() { // TODO: Use combatantinfo event directly this._pullStats = { strength: this.combatants.selected._combatantInfo.strength, agility: this.combatants.selected._combatantInfo.agility, intellect: this.combatants.selected._combatantInfo.intellect, stamina: this.combatants.selected._combatantInfo.stamina, crit: this.combatants.selected._combatantInfo.critSpell, haste: this.combatants.selected._combatantInfo.hasteSpell, mastery: this.combatants.selected._combatantInfo.mastery, versatility: this.combatants.selected._combatantInfo.versatilityHealingDone, avoidance: this.combatants.selected._combatantInfo.avoidance, leech: this.combatants.selected._combatantInfo.leech, speed: this.combatants.selected._combatantInfo.speed, armor: this.combatants.selected._combatantInfo.armor, }; this.applySpecModifiers(); this.applyArtifactModifiers(); this._currentStats = { ...this._pullStats, }; debug && this._debugPrintStats(this._currentStats); } applySpecModifiers() { const modifiers = this.constructor.SPEC_MULTIPLIERS[this.combatants.selected.spec.id] || {}; Object.entries(modifiers).forEach(([stat, multiplier]) => this._pullStats[stat] *= multiplier); } applyArtifactModifiers() { Object.entries(this.constructor.ARTIFACT_MULTIPLIERS).forEach(([spellId, modifiers]) => { const rank = this.combatants.selected.traitsBySpellId[spellId] || 0; Object.entries(modifiers).forEach(([stat, multiplier]) => this._pullStats[stat] *= 1 + multiplier * rank); }); } /* * Stat rating at pull. * Should be identical to what you get from Combatant. */ get startingStrengthRating() { return this._pullStats.strength; } get startingAgilityRating() { return this._pullStats.agility; } get startingIntellectRating() { return this._pullStats.intellect; } get startingStaminaRating() { return this._pullStats.stamina; } get startingCritRating() { return this._pullStats.crit; } get startingHasteRating() { return this._pullStats.haste; } get startingMasteryRating() { return this._pullStats.mastery; } get startingVersatilityRating() { return this._pullStats.versatility; } get startingAvoidanceRating() { return this._pullStats.avoidance; } get startingLeechRating() { return this._pullStats.leech; } get startingSpeedRating() { return this._pullStats.speed; } get startingArmorRating() { return this._pullStats.armor; } /* * Current stat rating, as tracked by this module. */ get currentStrengthRating() { return this._currentStats.strength; } get currentAgilityRating() { return this._currentStats.agility; } get currentIntellectRating() { return this._currentStats.intellect; } get currentStaminaRating() { return this._currentStats.stamina; } get currentCritRating() { return this._currentStats.crit; } get currentHasteRating() { return this._currentStats.haste; } get currentMasteryRating() { return this._currentStats.mastery; } get currentVersatilityRating() { return this._currentStats.versatility; } get currentAvoidanceRating() { return this._currentStats.avoidance; } get currentLeechRating() { return this._currentStats.leech; } get currentSpeedRating() { return this._currentStats.speed; } get currentArmorRating() { return this._currentStats.armor; } // TODO: I think these should be ratings. They behave like ratings and I think the only reason they're percentages here is because that's how they're **displayed** in-game, but not because it's more correct. /* * For percentage stats, the percentage you'd have with zero rating. * These values don't change. */ get baseCritPercentage() { const standard = 0.05; switch (this.combatants.selected.spec) { case SPECS.HOLY_PALADIN: return standard + 0.03; // 3% from a trait everyone has. TODO: Make traits conditional case SPECS.FIRE_MAGE: return standard + 0.15; // an additional 15% is gained from the passive Critical Mass case SPECS.BEAST_MASTERY_HUNTER : return standard + 0.05; //baseline +5% case SPECS.MARKSMANSHIP_HUNTER : return standard + 0.05; //baseline +5% case SPECS.SURVIVAL_HUNTER : return standard + 0.06; //baseline +6% case SPECS.WINDWALKER_MONK: return standard + 0.05; //baseline +5% case SPECS.HAVOC_DEMON_HUNTER: return standard + 0.06; //baseline +6% case SPECS.SUBTLETY_ROGUE: return standard + 0.05; //baseline +5% case SPECS.ASSASSINATION_ROGUE: return standard + 0.05; //baseline +5% case SPECS.OUTLAW_ROGUE: return standard + 0.05; //baseline +5% default: return standard; } } get baseHastePercentage() { return 0; } get baseMasteryPercentage() { switch (this.combatants.selected.spec) { case SPECS.HOLY_PALADIN: return 0.12; case SPECS.HOLY_PRIEST: return 0.10; case SPECS.SHADOW_PRIEST: return 0.2; case SPECS.DISCIPLINE_PRIEST: return 0.128; case SPECS.RESTORATION_SHAMAN: return 0.24; case SPECS.ENHANCEMENT_SHAMAN: return 0.2; case SPECS.ELEMENTAL_SHAMAN: return 0.15; case SPECS.GUARDIAN_DRUID: return 0.04; case SPECS.RESTORATION_DRUID: return 0.048; case SPECS.BALANCE_DRUID: return 0.18; case SPECS.RETRIBUTION_PALADIN: return 0.14; case SPECS.PROTECTION_PALADIN: return 0.08; case SPECS.WINDWALKER_MONK: return 0.1; case SPECS.BEAST_MASTERY_HUNTER: return 0.18; case SPECS.MARKSMANSHIP_HUNTER: return 0.05; case SPECS.SURVIVAL_HUNTER: return 0.04; case SPECS.FROST_MAGE: return 0.18; case SPECS.FIRE_MAGE: return 0.06; case SPECS.ARCANE_MAGE: return 0.0960; case SPECS.SUBTLETY_ROGUE: return 0.2208; case SPECS.ASSASSINATION_ROGUE: return 0.32; case SPECS.OUTLAW_ROGUE: return 0.1760; case SPECS.UNHOLY_DEATH_KNIGHT: return 0.18; case SPECS.MISTWEAVER_MONK: return 1.04; case SPECS.BREWMASTER_MONK: return 0.08; case SPECS.FURY_WARRIOR: return 0.11; case SPECS.AFFLICTION_WARLOCK: return 0.25; case SPECS.FROST_DEATH_KNIGHT: return 0.12; case SPECS.BLOOD_DEATH_KNIGHT: return 0.12; case SPECS.HAVOC_DEMON_HUNTER: return 0.12; default: console.error('Mastery hasn\'t been implemented for this spec yet.'); return 0.0; } } get baseVersatilityPercentage() { return 0; } get baseAvoidancePercentage() { return 0; } get baseLeechPercentage() { return 0; } get baseSpeedPercentage() { return 0; } /* * For percentage stats, this is the divider to go from rating to percent (expressed from 0 to 1) * These values don't change. */ get critRatingPerPercent() { return 40000; } critPercentage(rating, withBase = false) { return (withBase ? this.baseCritPercentage : 0) + rating / this.critRatingPerPercent; } get hasteRatingPerPercent() { return 37500; } hastePercentage(rating, withBase = false) { return (withBase ? this.baseHastePercentage : 0) + rating / this.hasteRatingPerPercent; } get masteryRatingPerPercent() { return 40000 / this.combatants.selected.spec.masteryCoefficient; } masteryPercentage(rating, withBase = false) { return (withBase ? this.baseMasteryPercentage : 0) + rating / this.masteryRatingPerPercent; } get versatilityRatingPerPercent() { return 47500; } versatilityPercentage(rating, withBase = false) { return (withBase ? this.baseVersatilityPercentage : 0) + rating / this.versatilityRatingPerPercent; } get avoidanceRatingPerPercent() { return 11000; } avoidancePercentage(rating, withBase = false) { return (withBase ? this.baseAvoidancePercentage : 0) + rating / this.avoidanceRatingPerPercent; } get leechRatingPerPercent() { return 23000; } leechPercentage(rating, withBase = false) { return (withBase ? this.baseLeechPercentage : 0) + rating / this.leechRatingPerPercent; } get speedRatingPerPercent() { return 8000; } speedPercentage(rating, withBase = false) { return (withBase ? this.baseSpeedPercentage : 0) + rating / this.speedRatingPerPercent; } armorPercentage(rating) { // tfw you get a formula from a rando on the wow forums return rating / (rating + 7390); } /* * For percentage stats, the current stat percentage as tracked by this module. */ get currentCritPercentage() { return this.critPercentage(this.currentCritRating, true); } // This is only the percentage from BASE + RATING. // If you're looking for current haste percentage including buffs like Bloodlust, check the Haste module. get currentHastePercentage() { return this.hastePercentage(this.currentHasteRating, true); } get currentMasteryPercentage() { return this.masteryPercentage(this.currentMasteryRating, true); } get currentVersatilityPercentage() { return this.versatilityPercentage(this.currentVersatilityRating, true); } get currentAvoidancePercentage() { return this.avoidancePercentage(this.currentAvoidanceRating, true); } get currentLeechPercentage() { return this.leechPercentage(this.currentLeechRating, true); } get currentSpeedPercentage() { return this.speedPercentage(this.currentSpeedRating, true); } get currentArmorPercentage() { return this.armorPercentage(this.currentArmorRating); } on_toPlayer_changebuffstack(event) { this._changeBuffStack(event); } on_toPlayer_changedebuffstack(event) { this._changeBuffStack(event); } /** * This interface allows an external analyzer to force a stat change. * It should ONLY be used if a stat buff is so non-standard that it can't be handled by the buff format in this module. * change is a stat buff object just like those in the STAT_BUFFS structure above, it is required. * eventReason is the WCL event object that caused this change, it is not required. */ // For an example of how / why this function would be used, see the CharmOfTheRisingTide module. forceChangeStats(change, eventReason) { const before = Object.assign({}, this._currentStats); const delta = this._changeStats(change, 1); const after = Object.assign({}, this._currentStats); this._triggerChangeStats(eventReason, before, delta, after); if (debug) { const spellName = eventReason && eventReason.ability ? eventReason.ability.name : 'unspecified'; console.log(`StatTracker: FORCED CHANGE from ${spellName} - Change: ${this._statPrint(delta)}`); debug && this._debugPrintStats(this._currentStats); } } _changeBuffStack(event) { const spellId = event.ability.guid; const statBuff = this.constructor.STAT_BUFFS[spellId]; if (statBuff) { // ignore prepull buff application, as they're already accounted for in combatantinfo // we have to check the stacks count because Entities incorrectly copies the prepull property onto changes and removal following the application if (event.oldStacks === 0 && event.prepull) { debug && console.log(`StatTracker prepull application IGNORED for ${SPELLS[spellId] ? SPELLS[spellId].name : spellId}`); return; } const before = Object.assign({}, this._currentStats); const delta = this._changeStats(statBuff, event.newStacks - event.oldStacks); const after = Object.assign({}, this._currentStats); this._triggerChangeStats(event, before, delta, after); debug && console.log(`StatTracker: (${event.oldStacks} -> ${event.newStacks}) ${SPELLS[spellId] ? SPELLS[spellId].name : spellId} @ ${formatMilliseconds(this.owner.fightDuration)} - Change: ${this._statPrint(delta)}`); debug && this._debugPrintStats(this._currentStats); } } _changeStats(change, factor) { const delta = { strength: this._getBuffValue(change, change.strength) * factor, agility: this._getBuffValue(change, change.agility) * factor, intellect: this._getBuffValue(change, change.intellect) * factor, stamina: this._getBuffValue(change, change.stamina) * factor, crit: this._getBuffValue(change, change.crit) * factor, haste: this._getBuffValue(change, change.haste) * factor, mastery: this._getBuffValue(change, change.mastery) * factor, versatility: this._getBuffValue(change, change.versatility) * factor, avoidance: this._getBuffValue(change, change.avoidance) * factor, leech: this._getBuffValue(change, change.leech) * factor, speed: this._getBuffValue(change, change.speed) * factor, armor: this._getBuffValue(change, change.armor) * factor, }; Object.keys(this._currentStats).forEach(key => { this._currentStats[key] += delta[key]; }); return delta; } /* * Fabricates an event indicating when stats change */ _triggerChangeStats(event, before, delta, after) { this.owner.triggerEvent('changestats', { timestamp: event ? event.timestamp : this.owner.currentTimestamp, type: 'changestats', sourceID: event ? event.sourceID : this.owner.playerId, targetID: this.owner.playerId, reason: event, before, delta, after, }); } /** * Gets the actual stat value in whatever format it is. * a number value will be returned as is * a function value will be called with (selectedCombatant, itemDetails) and the result returned * an undefined stat will default to 0. */ _getBuffValue(buffObj, statVal) { if (statVal === undefined) { return 0; } else if (typeof statVal === 'function') { const selectedCombatant = this.combatants.selected; let itemDetails; if (buffObj.itemId) { itemDetails = this.combatants.selected.getItem(buffObj.itemId); if (!itemDetails) { console.warn('Failed to retrieve item information for item with ID:', buffObj.itemId, ' ...unable to handle stats buff, making no stat change.'); return 0; } } return statVal(selectedCombatant, itemDetails); } else { return statVal; } } _debugPrintStats(stats) { console.log(`StatTracker: ${formatMilliseconds(this.owner.fightDuration)} - ${this._statPrint(stats)}`); } _statPrint(stats) { return `STR=${stats.strength} AGI=${stats.agility} INT=${stats.intellect} STM=${stats.stamina} CRT=${stats.crit} HST=${stats.haste} MST=${stats.mastery} VRS=${stats.versatility} AVD=${this._currentStats.avoidance} LCH=${stats.leech} SPD=${stats.speed} ARMOR=${this._currentStats.armor}`; } } export default StatTracker;
hasseboulen/WoWAnalyzer
src/Parser/Core/Modules/StatTracker.js
JavaScript
agpl-3.0
24,273
from openerp.osv import fields,osv import time import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ from openerp import pooler from openerp import netsvc import base64 from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from openerp.addons.Edumedia_India import config class sale_order(osv.osv): def history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, email_from=False, message_id=False, attach=[], context=None): mailgate_pool = self.pool.get('mailgate.thread') return mailgate_pool.history(cr, uid, cases, keyword, history=history,\ subject=subject, email=email, \ details=details, email_from=email_from,\ message_id=message_id, attach=attach, \ context=context) def _get_partner_default_addr(self, cr, uid, ids, name, arg, context=None): res = {} for case in self.browse(cr, uid, ids, context=context): addr = self.pool.get('res.partner').address_get(cr, uid, [case.partner_id.id], ['default']) res[case.id] = addr['default'] return res # def _amount_all(self, cr, uid, ids, field_name, arg, context=None): # return super(sale_order,self)._amount_all(cr, uid, ids,field_name,arg,context=context) def _get_class_details(self, cr, uid, ids, field_name, arg, context=None): res = {} for case in self.browse(cr, uid, ids, context=context): res[case.id] = { 'tot_class': 0, 'low_std': 0, 'high_std': 0, 'tot_student' : 0, 'tot_sectn':0 } cnt_class = l_std = h_std = studnts = sectns = 0 class_std = [] if case.class_ids: for line in case.class_ids: cnt_class += 1 class_std.append(line.ed_class) studnts += line.ed_students sectns += line.ed_sec if class_std: l_std = min(class_std) h_std = max(class_std) res[case.id]['tot_class'] = cnt_class res[case.id]['low_std'] = l_std res[case.id]['high_std'] = h_std res[case.id]['tot_student'] = studnts res[case.id]['tot_sectn'] = sectns return res # def _get_order(self, cr, uid, ids, context=None): # result = {} # for line in self.pool.get('sale.order.line').browse(cr, uid, ids, context=context): # result[line.order_id.id] = True # return result.keys() def _get_delivry_ids(self, cr, uid, ids, field_name, arg, context=None): delivry_obj = self.pool.get("stock.picking") res = {} for case in self.browse(cr,uid,ids,context): res[case.id] = delivry_obj.search(cr, uid, [('sale_id', '=', case.id),('state','=','done')]) return res _inherit='sale.order' _columns={ # Overridden 'product_id': fields.many2one('product.product', 'Product', change_default=True,states={'draft': [('readonly', False)]}), # 'amount_untaxed': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Sale Price'), string='Untaxed Amount', # store = { # 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), # 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), # }, # multi='sums', help="The amount without tax."), # 'amount_tax': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Sale Price'), string='Taxes', # store = { # 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), # 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), # }, # multi='sums', help="The tax amount."), # 'amount_total': fields.function(_amount_all, method=True, digits_compute= dp.get_precision('Sale Price'), string='Total', # store = { # 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), # 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), # }, # multi='sums', help="The total amount."), 'state': fields.selection([ ('draft', 'Quotation'), # ('waiting_date', 'Waiting Schedule'), # ('proposal_sent', 'Proposal Sent'), # ('proposal_accept','Proposal Accepted'), ('manual', 'Manual In Progress'), ('progress', 'In Progress'), ('shipping_except', 'Shipping Exception'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), ('cancel', 'Cancelled'), ],'State',readonly=True), # Extra Fields 'films_only':fields.boolean('Film License Only',readonly=True ,states={'draft': [('readonly', False)]}), 'address_ids':fields.many2many('res.partner','address_sale_rel','sale_id','address_id','Coordinator Details'), 'class_ids':fields.one2many('ed.class.details','sale_id','Class Details'), 'cap1_terms' : fields.char('Caption 1',size=100), 'cap1_text':fields.text('Caption Text',size=500), 'cap2_terms' : fields.char('Caption 2',size=100), 'cap2_text':fields.text('Caption Text',size=500), 'cap3_terms' : fields.char('Caption 3',size=100), 'cap3_text':fields.text('Caption Text',size=500), 'cap4_terms' : fields.char('Caption 4',size=100), 'cap4_text':fields.text('Caption Text',size=500), 'ed_type':fields.selection([('so','Sale Order'),('crm','CRM')],'Type'), 'ed_license':fields.selection(config.CLASS_STD,'License',readonly=True ,states={'draft': [('readonly', False)]}), 'rsn_reject' : fields.text('Relationship Manager Remarks',readonly=True ,states={'draft': [('readonly', False)]}), 'ed_proj':fields.char('Project',size=100), 'ed_cdd':fields.integer('No.Of.CDD',readonly=True ,states={'draft': [('readonly', False)]}), 'ed_rate':fields.integer('Rate',readonly=True ,states={'draft': [('readonly', False)]}), 'license_rate':fields.integer('Rate',readonly=True ,states={'draft': [('readonly', False)]}), 'nxt_payment_date' : fields.date('Next Payment Date'), 'licen_stdate' : fields.date('Start Date',readonly=True ,states={'draft': [('readonly', False)]}), 'licen_eddate' : fields.date('End Date',readonly=True ,states={'draft': [('readonly', False)]}), 'invoice_id' : fields.many2one('account.invoice','Invoice No',readonly=True), 'training_ids':fields.one2many('ed.training.grid','sale_id','Training'), 'message_ids': fields.one2many('mail.message', 'res_id', 'Messages', domain=[('model','=',_inherit)]), 'vw_address_ids':fields.one2many('vw.res.partner','sale_id','View Coordinator Details'), 'vw_class_ids':fields.one2many('vw.ed.class.details','sale_id','view class details'), 'payment_ids' : fields.one2many('ed.payment','sale_id','ed.payment'), 'feedback_ids':fields.one2many('ed.feedback','sale_id','Feedback'), 'ed_pod_ids':fields.one2many('ed.product','sale_id','Product',states={'draft': [('readonly', False)]}), 'ed_serv_ids':fields.one2many('ed.service','sale_id','service',states={'draft': [('readonly', False)]}), 'hub_id' : fields.many2one('ed.hub','HUB',readonly=True,states={'draft': [('readonly', False)]}), 'partner_default_id': fields.function(_get_partner_default_addr, method=True, relation='res.partner', type="many2one", string='Default Contact', strore=True), 'tot_class' : fields.function(_get_class_details, string="Total Classes", method=True, store=True, type="integer", multi="class_details"), 'low_std' : fields.function(_get_class_details, string="Lowest Standard", method=True, store=True, type="integer", multi="class_details"), 'high_std' : fields.function(_get_class_details, string="Highest Standard", method=True, store=True, type="integer", multi="class_details"), 'tot_student' : fields.function(_get_class_details, string="Total Students", method=True, store=True, type="integer", multi="class_details"), 'tot_sectn' : fields.function(_get_class_details, string="Total Sections", method=True, store=True, type="integer", multi="class_details"), 'delivery_ids': fields.function(_get_delivry_ids, method=True, type='one2many', obj='stock.picking', string='Delivery Orders' ,readonly=True), } def _create_session(self, cr, uid, ids, context=None): ses_obj = self.pool.get('ed.sessions') for case in self.browse(cr, uid, ids): ses_vals={ 'sale_id':case.id, 'ed_so': case.name, 'ed_school':case.partner_id.name, } ses_obj.create(cr, uid,ses_vals) return True def _open_crm_form(self, cr, uid, ids, context=None): models_data = self.pool.get('ir.model.data') sale_order_form = models_data._get_id( cr, uid, 'Edumedia_India', 'view_ed_sale_crm_form') sale_order_tree = models_data._get_id( cr, uid, 'Edumedia_India', 'view_ed_sale_tree') if sale_order_form: sale_order_form = models_data.browse( cr, uid, sale_order_form, context=context).res_id if sale_order_tree: sale_order_tree = models_data.browse( cr, uid, sale_order_tree, context=context).res_id return { 'view_type': 'form', 'view_mode': 'form', 'res_model': 'sale.order', 'view_id' : False, 'views' : [(sale_order_form, 'form'), (sale_order_tree, 'tree'), ], 'type': 'ir.actions.act_window', 'res_id': ids[0] } # *************** Overwritten standard function ***************** def action_wait(self, cr, uid, ids, *args): self.button_dummy(cr, uid, ids) for o in self.browse(cr, uid, ids): if (o.order_policy == 'manual'): self.write(cr, uid, [o.id], {'state': 'manual', 'date_confirm': time.strftime('%Y-%m-%d')}) else: self.write(cr, uid, [o.id], {'state': 'progress', 'date_confirm': time.strftime('%Y-%m-%d')}) self.pool.get('sale.order.line').button_confirm(cr, uid, [x.id for x in o.order_line]) message = _("The quotation '%s' has been converted to a sales order.") % (o.name,) self.log(cr, uid, o.id, message) self._create_session(cr, uid, ids) partner_obj = self.pool.get('res.partner') partner_obj.write(cr,uid,[o.partner_id.id],{'ed_sh_cinema':True}) # self._open_crm_form(cr, uid, ids) return True def button_2populateLines(self, cr, uid, ids, context=None): ordln_obj = self.pool.get('sale.order.line') edProd_obj = self.pool.get('ed.product') edServ_obj = self.pool.get('ed.service') class_obj = self.pool.get('ed.class.details') prod_obj = self.pool.get('product.product') prod_id = [] for case in self.browse(cr, uid, ids): cr.execute("delete from sale_order_line where order_id = %d"%(case.id)) cr.execute("delete from ed_product where sale_id = %d"%(case.id)) cr.execute("delete from ed_service where sale_id = %d"%(case.id)) cr.execute("delete from address_sale_rel where sale_id=%d"%(case.id)) prod_films = prod_obj.search(cr,uid,[('name_template','=','Films')],limit=1) prod_license = prod_obj.search(cr,uid,[('name_template','=','License')],limit=1) prod_id.append(case.product_id.id) if prod_films: prod_id.append(prod_films[0]) if prod_license: prod_id.append(prod_license[0]) # to create sale order lines on select of product for prod in self.pool.get('product.product').browse(cr,uid,prod_id): result = ordln_obj.product_id_change(cr, uid, ids, case.pricelist_id.id, prod.id, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=case.partner_id.id, lang='lang' in context and context.get('lang')or False, update_tax=True, date_order=case.date_order, packaging=False, fiscal_position=False, flag=False) prod_name = '' if prod.name == 'Films': prod_name = str(prod.name) + ' - License Fee' lnvals = { 'product_id':prod.id, 'product_uom':prod.uom_id.id, 'name':prod_name or prod.name, 'price_unit':prod.list_price, 'order_id':case.id, 'tax_id' :[(6, 0, result['value']['tax_id'])], } ordln_id = ordln_obj.create(cr, uid, lnvals) #to create lines of subproducts and service of main product if prod.prod_ids: for subprod in prod.prod_ids: edProd_obj.create(cr, uid, { 'product_id':subprod.product_id.id, 'ed_qty': subprod.ed_qty, 'ed_per_id':subprod.ed_per_id.id, 'ed_class':subprod.ed_class, 'display_unit':subprod.product_id.display_unit, 'sale_id':case.id }) for serv in prod.sevice_ids: edServ_obj.create(cr, uid, { 'name':serv.name, 'sale_id':case.id }) ordln_obj.write(cr,uid,[ordln_id],{}) #to create lines of address for selected customer for add in case.partner_id.address: if add.type == 'contact': cr.execute("insert into address_sale_rel(sale_id, address_id) values(%d,%d)"%(case.id, add.id)) #to create class lines if not case.class_ids: for i in range(1,9): class_obj.create(cr,uid,{'sale_id' : case.id, 'ed_class' : i, 'ed_boys':0, 'ed_girls':0, 'ed_sec':0, 'ed_students':0 },context) return True # ************************************ button to generate sale Dispatch order report*************************** def print_order_report(self, cr, uid, ids, context=None): for case in self.browse(cr, uid, ids): cr.execute(""" CREATE OR REPLACE VIEW vw_res_partner_address AS select pa.id , pa.name , pa.mobile , pa.email , pa.ed_desig_id , """ + str(case.id) + """ as sale_id from res_partner_address pa where pa.id in (select address_id from address_sale_rel where sale_id = """ + str(case.id) + """); CREATE OR REPLACE VIEW vw_ed_class_details AS select cl.id , cl.ed_class , cl.ed_sec , cl.ed_students , cl.ed_boys , case when cl.ed_class = 6 then sum(cl.ed_girls) else 0 end as girls , case when cl.ed_class = 7 then sum(cl.ed_boys) else 0 end as boys , cl.ed_girls , """ + str(case.id) + """ as sale_id from ed_class_details cl where cl.id in (select cls_id from class_sale_rel where sale_id = """ + str(case.id) + """) group by cl.id,cl.ed_class ,cl.ed_sec, cl.ed_students, cl.ed_boys, cl.ed_girls """); data = {} data['ids'] = ids data['model'] = 'sale.order' return { 'report_name': 'sale.order.dispatch.order', 'type': 'ir.actions.report.xml', 'target': 'new', 'datas': data, } def print_proposal_report(self, cr, uid, ids, context=None): """ button to generate proposal report """ # self._get_proposal_report(cr, uid, ids, context=None) data = {} data['ids'] = ids data['model'] = 'sale.order' return { 'report_name': 'sale.order.proposal', 'type': 'ir.actions.report.xml', 'target': 'new', 'datas': data, } # Modifying Standard Shipping create from Sale Order # to create deliveries for school cinema process def action_ship_create(self, cr, uid, ids, *args): wf_service = netsvc.LocalService("workflow") prod_obj = self.pool.get('product.product') company = self.pool.get('res.users').browse(cr, uid, uid).company_id for order in self.browse(cr, uid, ids, context={}): proc_ids = [] output_id = order.shop_id.warehouse_id.lot_output_id.id val = {} val['ed_type']='crm' self.write(cr, uid, [order.id], val) return True def _create_delivery_order(self, cr, uid, ids, context=None): picking_id = False move_obj = self.pool.get('stock.move') proc_obj = self.pool.get('procurement.order') prod_obj = self.pool.get('product.product') company = self.pool.get('res.users').browse(cr, uid, uid).company_id for order in self.browse(cr, uid, ids, context={}): proc_ids = [] output_id = order.shop_id.warehouse_id.lot_output_id.id picking_id = move_id = False cls_txt1 = '' count = 0 for line in order.order_line: count += 1 proc_id = False date_planned = datetime.now() + relativedelta(days=line.delay or 0.0) date_planned = (date_planned - timedelta(days=company.security_lead)).strftime('%Y-%m-%d %H:%M:%S') if line.product_id and line.product_id.product_tmpl_id.type in ('product', 'consu'): location_id = order.shop_id.warehouse_id.lot_stock_id.id if not picking_id and line.product_id == order.product_id and line.price_unit > 0: pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out') picking_id = self.pool.get('stock.picking').create(cr, uid, { 'name': pick_name, 'origin': order.name, 'type': 'out', 'state': 'draft', 'move_type': order.picking_policy, 'sale_id': order.id, 'address_id': order.partner_shipping_id.id, 'note': order.note, 'invoice_state': (order.order_policy=='picking' and '2binvoiced') or 'none', 'company_id': order.company_id.id, 'service_type':'shl_cinema' }) #Selecting the no of classes, sections and students nof_class = nof_sec = nof_stud = 0 cr.execute('SELECT count(c.ed_class) as cls_count, sum(ed_sec) as sec, sum(ed_students) as stud FROM ed_class_details c WHERE c.sale_id = %d'%(order.id)) cls = cr.fetchone() if cls: if cls[0] == 0: raise osv.except_osv(_('Warning'),_("Add Data in other details")) nof_class = cls[0] nof_sec = cls[1] nof_stud = cls[2] #Looping through sub products against the option selected cls_txt = '' if not move_id: for cl in order.class_ids: if cl.ed_students > 0 and cl.wrk_bk_rate > 0 : cls_txt += str(cl.ed_class) + ',' for subprod in order.ed_pod_ids: qty = 0 if subprod.ed_class == cl.ed_class: if subprod.ed_per_id.name == 'Student': qty = cl.ed_students * subprod.ed_qty if subprod.ed_per_id.name == 'Class': qty = nof_class * subprod.ed_qty if subprod.ed_per_id.name == 'Section': qty = cl.ed_sec * subprod.ed_qty if subprod.ed_per_id.name == 'Boys' and cl.ed_boys > 0 : qty = cl.ed_boys * subprod.ed_qty if subprod.ed_per_id.name == 'Girls' and cl.ed_girls > 0 : qty = cl.ed_girls * subprod.ed_qty #if subprod.ed_per_id.name: if qty > 0: move_id = self.pool.get('stock.move').create(cr, uid, { 'name': line.name[:64], 'picking_id': picking_id, 'product_id': subprod.product_id.id, 'date': date_planned, 'date_expected': date_planned, 'product_qty': qty, 'product_uom': subprod.product_id.uom_id.id, 'product_uos_qty': qty, 'product_uos': subprod.product_id.uom_id.id, #'product_packaging': line.product_packaging.id, #'address_id': line.address_allotment_id.id or order.partner_shipping_id.id, 'location_id': location_id, 'location_dest_id': output_id, 'sale_line_id': line.id, 'tracking_id': False, 'state': 'draft', #'state': 'waiting', 'note': line.notes, 'company_id': order.company_id.id, }) #updating license details to stock picking cls_txt = cls_txt[0:(len(cls_txt) - 1)] if picking_id: self.pool.get('stock.picking').write(cr, uid, [picking_id],{'license_detls':"License Start Date :" + str(order.licen_stdate) + ", License End Date :" + str(order.licen_eddate) + ", Class :" + cls_txt}) if count == 3: cls_txt = '' for cl in order.class_ids: if cl.films_rate > 0 : cls_txt += str(cl.ed_class) + ',' cls_txt = cls_txt[0:(len(cls_txt) - 1)] # creating additional deliver order for HDD media pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out') picking_id = self.pool.get('stock.picking').create(cr, uid, { 'name': pick_name, 'origin': order.name, 'type': 'out', 'state': 'draft', 'move_type': order.picking_policy, 'sale_id': order.id, 'address_id': order.partner_shipping_id.id, 'note': order.note, 'invoice_state': (order.order_policy=='picking' and '2binvoiced') or 'none', 'company_id': order.company_id.id, 'license_detls' :"License Start Date :" + str(order.licen_stdate) + ", License End Date :" + str(order.licen_eddate) + ", Class :" + cls_txt, 'service_type':'shl_cinema' }) products = prod_obj.search(cr,uid,[('categ_id', '=', 'HDD')],limit=1) for prod in prod_obj.browse(cr,uid,products): move_id = self.pool.get('stock.move').create(cr, uid, { 'name': line.name[:64], 'picking_id': picking_id, 'product_id': prod.id, 'date': date_planned, 'date_expected': date_planned, 'product_qty': order.ed_cdd, 'product_uom': prod.uom_id.id, 'product_uos_qty': order.ed_cdd, 'product_uos': prod.uom_id.id, #'product_packaging': line.product_packaging.id, #'address_id': line.address_allotment_id.id or order.partner_shipping_id.id, 'location_id': location_id, 'location_dest_id': output_id, 'sale_line_id': line.id, 'tracking_id': False, 'state': 'draft', #'state': 'waiting', 'note': line.notes, 'company_id': order.company_id.id, }) if line.product_id: proc_id = self.pool.get('procurement.order').create(cr, uid, { 'name': line.name, 'origin': order.name, 'date_planned': date_planned, 'product_id': line.product_id.id, 'product_qty': line.product_uom_qty, 'product_uom': line.product_uom.id, 'product_uos_qty': (line.product_uos and line.product_uos_qty)\ or line.product_uom_qty, 'product_uos': (line.product_uos and line.product_uos.id)\ or line.product_uom.id, 'location_id': order.shop_id.warehouse_id.lot_stock_id.id, 'procure_method': line.type, 'move_id': move_id, 'property_ids': [(6, 0, [x.id for x in line.property_ids])], 'company_id': order.company_id.id, }) proc_ids.append(proc_id) self.pool.get('sale.order.line').write(cr, uid, [line.id], {'procurement_id': proc_id}) if order.state == 'shipping_except': for pick in order.picking_ids: for move in pick.move_lines: if move.state == 'cancel': mov_ids = move_obj.search(cr, uid, [('state', '=', 'cancel'),('sale_line_id', '=', line.id),('picking_id', '=', pick.id)]) if mov_ids: for mov in move_obj.browse(cr, uid, mov_ids): move_obj.write(cr, uid, [move_id], {'product_qty': mov.product_qty, 'product_uos_qty': mov.product_uos_qty}) proc_obj.write(cr, uid, [proc_id], {'product_qty': mov.product_qty, 'product_uos_qty': mov.product_uos_qty}) if order.state == 'shipping_except': val['state'] = 'progress' val['shipped'] = False if (order.order_policy == 'manual'): for line in order.order_line: if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break return True #inherited def _make_invoice(self, cr, uid, order, lines, context=None): accinv_obj = self.pool.get('account.invoice') invln_obj = self.pool.get('account.invoice.line') res = super(sale_order, self)._make_invoice(cr, uid, order,lines, context=context) accinv_obj.write(cr,uid,[res],{'sale_id':order.id}) invln_ids = invln_obj.search(cr,uid,[('invoice_id','=',res)]) invln_obj.write(cr,uid,invln_ids,{}) return res # Overridden def manual_invoice(self, cr, uid, ids, context=None): mod_obj = self.pool.get('ir.model.data') wf_service = netsvc.LocalService("workflow") inv_ids = set() inv_ids1 = set() for id in ids: for record in self.pool.get('sale.order').browse(cr, uid, id).invoice_ids: inv_ids.add(record.id) # inv_ids would have old invoices if any for id in ids: wf_service.trg_validate(uid, 'sale.order', id, 'manual_invoice', cr) for record in self.pool.get('sale.order').browse(cr, uid, id).invoice_ids: inv_ids1.add(record.id) inv_ids = list(inv_ids1.difference(inv_ids)) res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form') res_id = res and res[1] or False, self.write(cr, uid, [id], {'invoice_id':inv_ids[0]}) self._create_delivery_order(cr, uid, ids, context) return True #overriden def action_invoice_create(self, cr, uid, ids, grouped=False, states=['confirmed', 'done', 'exception'], date_inv = False, context=None): res = False invoices = {} invoice_ids = [] picking_obj = self.pool.get('stock.picking') invoice = self.pool.get('account.invoice') obj_sale_order_line = self.pool.get('sale.order.line') if context is None: context = {} # If date was specified, use it as date invoiced, usefull when invoices are generated this month and put the # last day of the last month as invoice date if date_inv: context['date_inv'] = date_inv for o in self.browse(cr, uid, ids, context=context): lines = [] for line in o.order_line: if line.price_unit > 0: if line.invoiced: continue elif (line.state in states): lines.append(line.id) created_lines = obj_sale_order_line.invoice_line_create(cr, uid, lines) if created_lines: invoices.setdefault(o.partner_id.id, []).append((o, created_lines)) if not invoices: for o in self.browse(cr, uid, ids, context=context): for i in o.invoice_ids: if i.state == 'draft': return i.id for val in invoices.values(): if grouped: res = self._make_invoice(cr, uid, val[0][0], reduce(lambda x, y: x + y, [l for o, l in val], []), context=context) invoice_ref = '' for o, l in val: invoice_ref += o.name + '|' self.write(cr, uid, [o.id], {'state': 'progress'}) if o.order_policy == 'picking': picking_obj.write(cr, uid, map(lambda x: x.id, o.picking_ids), {'invoice_state': 'invoiced'}) cr.execute('insert into sale_order_invoice_rel (order_id,invoice_id) values (%s,%s)', (o.id, res)) invoice.write(cr, uid, [res], {'origin': invoice_ref, 'name': invoice_ref}) else: for order, il in val: for lin in il:#to split sale order lines and create seprate invoices res = self._make_invoice(cr, uid, order, [lin], context=context) invoice_ids.append(res) self.write(cr, uid, [order.id], {'state': 'progress'}) if order.order_policy == 'picking': picking_obj.write(cr, uid, map(lambda x: x.id, order.picking_ids), {'invoice_state': 'invoiced'}) cr.execute('insert into sale_order_invoice_rel (order_id,invoice_id) values (%s,%s)', (order.id, res)) return res # Overridden def button_dummy(self, cr, uid, ids, context=None): ordln_obj=self.pool.get('sale.order.line') edprod_obj=self.pool.get('ed.product') for case in self.browse(cr,uid,ids): if case.order_line: for line in case.order_line: ordln_obj.write(cr,uid,[line.id],{}) if case.ed_pod_ids: for ep in case.ed_pod_ids: edprod_obj.write(cr, uid, [ep.id], {}) self.write(cr, uid, [case.id], {}) return True def button_proposal_sent(self,cr,uid,ids,context=None): for case in self.browse(cr,uid,ids): # self._get_proposal_report(cr, uid, ids, context=None) data = {} data['ids'] = ids data['model'] = 'sale.order' obj = netsvc.LocalService('report.' + 'sale.order.dispatch.order') (result, format) = obj.create(cr, uid, ids, data, context) doc_parent_id = self.pool.get('document.directory')._get_root_directory(cr,uid) attachment_obj = self.pool.get('ir.attachment') attval = {} cr.execute("select id from ir_attachment where res_id = " + str(case.id) + " and res_model = 'sale.order' and name = '"+ str(case.name) +".pdf'") file_att = cr.fetchall() if not file_att: attval = { 'res_model' : 'sale.order', 'res_name' : str(case.name), 'res_id' : str(case.id), 'db_datas' : str(result), 'type' : 'binary', 'file_type' : 'application/pdf', 'datas_fname': str(case.name) + ".pdf", 'name' : str(case.name) + ".pdf", 'file_size' : len(result), 'parent_id' : doc_parent_id, 'partner_id' : case.partner_id.id, } attachment_obj.create(cr,uid,attval) else: for f in file_att: attval = { 'db_datas' : str(result), 'file_size' : len(result), } attachment_obj.write(cr,uid, [f[0]],attval) return True def button_proposal_accepted(self,cr,uid,ids,context=None): self.write(cr, uid, ids, {'state':'proposal_accept'}) return True def _open_sale_form(self, cr, uid, ids, context=None): models_data = self.pool.get('ir.model.data') sale_order_form = models_data._get_id( cr, uid, 'Edumedia_India', 'view_ed_sale_form') sale_order_tree = models_data._get_id( cr, uid, 'Edumedia_India', 'view_ed_sale_tree') if sale_order_form: sale_order_form = models_data.browse( cr, uid, sale_order_form, context=context).res_id if sale_order_tree: sale_order_tree = models_data.browse( cr, uid, sale_order_tree, context=context).res_id return { 'view_type': 'form', 'view_mode': 'form', 'res_model': 'sale.order', 'view_id' : False, 'views' : [(sale_order_form, 'form'), (sale_order_tree, 'tree'), ], 'type': 'ir.actions.act_window', 'res_id': ids[0] } # Overridden: def action_cancel_draft(self, cr, uid, ids, *args): if not len(ids): return False for sale in self.browse(cr, uid, ids): if sale.state == 'cancel': l = len(sale.name) if l > 5: nxt_no = int(sale.name[8:(l-1)]) + 1 sale_name = sale.name[0:8] + str(nxt_no) + sale.name[(l-1):l] else: sale_name = str(sale.name) + ' (R1)' self.write(cr, uid, ids, {'state': 'draft','ed_type':'so','name':sale_name, 'invoice_ids': [], 'shipped': 0}) else: self.write(cr, uid, ids, {'state': 'draft','ed_type':'so', 'invoice_ids': [], 'shipped': 0}) cr.execute('select id from sale_order_line where order_id IN %s and state=%s', (tuple(ids), 'cancel')) line_ids = map(lambda x: x[0], cr.fetchall()) self.pool.get('sale.order.line').write(cr, uid, line_ids, {'invoiced': False, 'state': 'draft', 'invoice_lines': [(6, 0, [])]}) wf_service = netsvc.LocalService("workflow") for inv_id in ids: # Deleting the existing instance of workflow for SO wf_service.trg_delete(uid, 'sale.order', inv_id, cr) wf_service.trg_create(uid, 'sale.order', inv_id, cr) for (id,name) in self.name_get(cr, uid, ids): message = _("The sales order '%s' has been set in draft state.") %(name,) self.log(cr, uid, id, message) # self._open_sale_form(cr, uid, ids) return True # Overridden: def action_cancel(self, cr, uid, ids, context=None): wf_service = netsvc.LocalService("workflow") if context is None: context = {} sale_order_line_obj = self.pool.get('sale.order.line') proc_obj = self.pool.get('procurement.order') for sale in self.browse(cr, uid, ids, context=context): for pick in sale.picking_ids: if pick.state not in ('draft', 'cancel'): raise osv.except_osv( _('Could not cancel sales order !'), _('You must first cancel all picking attached to this sales order.')) if pick.state == 'cancel': for mov in pick.move_lines: proc_ids = proc_obj.search(cr, uid, [('move_id', '=', mov.id)]) if proc_ids: for proc in proc_ids: wf_service.trg_validate(uid, 'procurement.order', proc, 'button_check', cr) for r in self.read(cr, uid, ids, ['picking_ids']): for pick in r['picking_ids']: wf_service.trg_validate(uid, 'stock.picking', pick, 'button_cancel', cr) for inv in sale.invoice_ids: if inv.state not in ('draft', 'cancel'): raise osv.except_osv( _('Could not cancel this sales order !'), _('You must first cancel all invoices attached to this sales order.')) for r in self.read(cr, uid, ids, ['invoice_ids']): for inv in r['invoice_ids']: wf_service.trg_validate(uid, 'account.invoice', inv, 'invoice_cancel', cr) sale_order_line_obj.write(cr, uid, [l.id for l in sale.order_line], {'state': 'cancel'}) message = _("The sales order '%s' has been cancelled.") % (sale.name,) self.log(cr, uid, sale.id, message) if sale.ed_type == 'crm': cr.execute("delete from ed_sessions where sale_id = %d"%(sale.id)) self.write(cr, uid, ids, {'state': 'cancel','ed_type':'so'}) return True def write(self, cr, uid, ids,vals,context=None): addr_obj = self.pool.get('res.partner') partner_obj = self.pool.get('res.partner') class_obj = self.pool.get('ed.class.details') line_obj = self.pool.get('sale.order.line') result = super(sale_order, self).write(cr, uid, ids, vals, context=context) for case in self.browse(cr, uid, ids): if case.address_ids: for a in case.address_ids: if not a.partner_id: addr_obj.write(cr, uid, [a.id], {'partner_id': case.partner_id.id}) # sale_cls_ids = set() # if case.class_ids: # for c in case.class_ids: # sale_cls_ids.add(c.id) # # part_cls_ids = new_cls_ids = set() # # partner = partner_obj.browse(cr,uid, case.partner_id.id) # for pc in partner.ed_cls_ids: # part_cls_ids.add(pc.id) # new_cls_ids = sale_cls_ids - part_cls_ids # class_ids = class_obj.search(cr,uid,[('sale_id','=',case.id)],order='ed_class') tot_wb_price = tot_fl_price = avg_wb_price = avg_fl_price = 0.00 tot_stu = 0 id for cl in case.class_ids: if not case.films_only: tot_wb_price += cl.wrk_bk_rate * cl.ed_students tot_fl_price += cl.films_rate * cl.ed_students tot_stu += cl.ed_students if case.films_only: tot_fl_price += cl.films_rate avg_wb_price = tot_wb_price / (tot_stu or 1) avg_fl_price = tot_fl_price / (tot_stu or 1) lvals = {} line_ids = line_obj.search(cr,uid,[('order_id','=',case.id)]) for ln in line_obj.browse(cr,uid,line_ids): if ln.product_id.name_template == case.product_id.name: lvals = {'price_unit':avg_wb_price,'ed_units':case.ed_cdd,'ed_per_depo':0} if ln.product_id.name_template == 'Films': lvals = {'price_unit':avg_fl_price} if ln.product_id.name_template == 'License': lvals = {'price_unit':case.license_rate} line_obj.write(cr,uid,[ln.id],lvals) #partner_obj.write(cr, uid, [partner.id], {'ed_cls_ids': [(6, 0, new_cls_ids)]}) # for n in new_cls_ids: # cr.execute("insert into ed_partner_cls_rel(partner_id, class_id) values(%d,%d)"%(case.partner_id.id, n)) return result sale_order() class sale_order_line(osv.osv): _inherit='sale.order.line' # def _amount_line(self, cr, uid, ids, field_name, arg, context=None): # tax_obj = self.pool.get('account.tax') # cur_obj = self.pool.get('res.currency') # res = {} # if context is None: # context = {} # for line in self.browse(cr, uid, ids, context=context): # price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) # taxes = tax_obj.compute_all(cr, uid, line.tax_id, price,line.product_uom_qty ,line.order_id.partner_invoice_id.id, line.product_id, line.order_id.partner_id) # # cur = line.order_id.pricelist_id.currency_id # res[line.id] = cur_obj.round(cr, uid, cur, taxes['total']+line.ed_total) # return res def get_deposit_Total(self,cr,uid,ids,field_name,arg,context=None): res = {} sale_obj = self.pool.get('sale.order') for case in self.browse(cr,uid,ids): deposit = 0.00 if case.order_id: sale = sale_obj.browse(cr,uid,case.order_id.id) deposit = sale.ed_cdd * sale.ed_rate res[case.id] = deposit return res def _get_students(self,cr,uid,ids,field_name,arg,context=None): res={} for case in self.browse(cr, uid, ids): res[case.id]= 1 if case.product_id.name != 'License' and not case.order_id.films_only: cr.execute('SELECT sum(ed_students) as stud FROM ed_class_details c \ WHERE c.sale_id =%d'%(case.order_id.id)) cls = cr.fetchone() res[case.id]= cls and cls[0] or 1 return res def _default_qty(self, cr, uid, context=None): sale_id = context.get('sale_id', False) if sale_id: cr.execute('SELECT sum(ed_students) as stud FROM ed_class_details c \ WHERE c.sale_id =%d'%(sale_id)) cls = cr.fetchone() return cls and cls[0] or 1 else: return 1 _columns={ # Inherited # 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal', digits_compute= dp.get_precision('Sale Price')), # 'ed_total':fields.function(get_deposit_Total, method=True, string='Total Deposit', type='float', store=True, readonly=True), 'product_uom_qty':fields.function(_get_students, method=True, string='NO.Of Students', type='float', store=True), 'ed_units':fields.integer('No.Of.Units'), 'ed_per_depo':fields.integer('Deposit Per Unit'), 'notes': fields.text('Notes'), } _defaults={ 'product_uom_qty':_default_qty } _order = 'id' def invoice_line_create(self, cr, uid, ids, context=None): if context is None: context = {} def _get_line_qty(line): if (line.order_id.invoice_quantity=='order') or not line.procurement_id: if line.product_uos: return line.product_uos_qty or 0.0 return line.product_uom_qty else: return self.pool.get('procurement.order').quantity_get(cr, uid, line.procurement_id.id, context=context) def _get_line_uom(line): if (line.order_id.invoice_quantity=='order') or not line.procurement_id: if line.product_uos: return line.product_uos.id return line.product_uom.id else: return self.pool.get('procurement.order').uom_get(cr, uid, line.procurement_id.id, context=context) create_ids = [] sales = {} for line in self.browse(cr, uid, ids, context=context): if not line.invoiced: if line.product_id: a = line.product_id.product_tmpl_id.property_account_income.id if not a: a = line.product_id.categ_id.property_account_income_categ.id if not a: raise osv.except_osv(_('Error !'), _('There is no income account defined ' \ 'for this product: "%s" (id:%d)') % \ (line.product_id.name, line.product_id.id,)) else: prop = self.pool.get('ir.property').get(cr, uid, 'property_account_income_categ', 'product.category', context=context) a = prop and prop.id or False uosqty = _get_line_qty(line) uos_id = _get_line_uom(line) pu = 0.0 if uosqty: pu = round(line.price_unit * line.product_uom_qty / uosqty, self.pool.get('decimal.precision').precision_get(cr, uid, 'Sale Price')) fpos = line.order_id.fiscal_position or False a = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, a) if not a: raise osv.except_osv(_('Error !'), _('There is no income category account defined in default Properties for Product Category or Fiscal Position is not defined !')) inv_id = self.pool.get('account.invoice.line').create(cr, uid, { 'name': line.name, 'origin': line.order_id.name, 'account_id': a, 'price_unit': pu, 'quantity': uosqty, 'discount': line.discount, 'uos_id': uos_id, 'product_id': line.product_id.id or False, 'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])], 'note': line.notes, 'account_analytic_id': line.order_id.project_id and line.order_id.project_id.id or False, }) cr.execute('insert into sale_order_line_invoice_rel (order_line_id,invoice_id) values (%s,%s)', (line.id, inv_id)) self.write(cr, uid, [line.id], {'invoiced': True}) sales[line.order_id.id] = True create_ids.append(inv_id) # Trigger workflow events wf_service = netsvc.LocalService("workflow") for sid in sales.keys(): wf_service.trg_write(uid, 'sale.order', sid, cr) return create_ids def onchange_Total(self, cr, uid, ids, ed_per_depo,ed_units): res = {} total_dep = 0 if ed_per_depo and ed_units: total_dep = ed_per_depo * ed_units res['ed_total'] = total_dep return {'value':res} # def onchange_subtotal(self, cr, uid, ids, price_unit,ed_total): # res = {} # subtotal_dep = 0 # # if price_unit and ed_total: # subtotal_dep = price_unit # # res['price_subtotal'] = subtotal_dep # # return {'value':res} def create(self, cr, uid, vals, context=None): return super(sale_order_line, self).create(cr, uid, vals, context=context) def write(self, cr, uid, ids,vals,context=None): return super(sale_order_line, self).write(cr, uid, ids, vals, context=context) sale_order_line()
trabacus-softapps/docker-edumedia
additional_addons/Edumedia_India/ed_sale.py
Python
agpl-3.0
56,005
<?php /** * Enlight * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://enlight.de/license * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@shopware.de so we can send you a copy immediately. * * @category Enlight * @package Enlight_Template_Plugins * @copyright Copyright (c) 2011, shopware AG (http://www.shopware.de) * @license http://enlight.de/license New BSD License * @version $Id$ * @author Heiner Lohaus * @author $Author$ */ /** * Returns known translations. * * @link http://framework.zend.com/manual/de/zend.locale.functions.html * @param string $value * @param string $path * @param string $locale * @return string|null */ function smarty_modifier_translate($value = null, $path = null, $locale = null) { if (!Enlight_Application::Instance()->Bootstrap()->hasResource('Locale')) { return $value; } if ($locale === null) { $locale = Enlight_Application::Instance()->Locale(); } if ($path == 'currency') { $path = 'nametocurrency'; } return $locale->getTranslation($value, $path, $locale); }
lmaslag/test
engine/Library/Enlight/Template/Plugins/modifier.translate.php
PHP
agpl-3.0
1,390
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Taken from https://tip.golang.org/src/cmd/internal/browser/browser.go?m=text // Package browser provides utilities for interacting with users' browsers. package browser import ( "os" "os/exec" "runtime" ) // Commands returns a list of possible commands to use to open a url. func Commands() [][]string { var cmds [][]string if exe := os.Getenv("BROWSER"); exe != "" { cmds = append(cmds, []string{exe}) } switch runtime.GOOS { case "darwin": cmds = append(cmds, []string{"/usr/bin/open"}) case "windows": cmds = append(cmds, []string{"cmd", "/c", "start"}) default: cmds = append(cmds, []string{"xdg-open"}) } cmds = append(cmds, []string{"chrome"}, []string{"google-chrome"}, []string{"chromium"}, []string{"firefox"}, ) return cmds } // Open tries to open url in a browser and reports whether it succeeded. func Open(url string) bool { for _, args := range Commands() { cmd := exec.Command(args[0], append(args[1:], url)...) // #nosec if cmd.Start() == nil { return true } } return false }
sebn/cozy-stack
cmd/browser/browser.go
GO
agpl-3.0
1,201
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-IEs" * found in "../support/s1ap-r16.4.0/36413-g40.asn" * `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps -no-gen-BER -no-gen-XER -no-gen-OER -no-gen-UPER` */ #include "S1AP_HFNModified.h" int S1AP_HFNModified_constraint(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= 0L && value <= 131071L)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using NativeInteger, * so here we adjust the DEF accordingly. */ #if !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) asn_per_constraints_t asn_PER_type_S1AP_HFNModified_constr_1 CC_NOTUSED = { { APC_CONSTRAINED, 17, -1, 0, 131071 } /* (0..131071) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; #endif /* !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) */ static const ber_tlv_tag_t asn_DEF_S1AP_HFNModified_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) }; asn_TYPE_descriptor_t asn_DEF_S1AP_HFNModified = { "HFNModified", "HFNModified", &asn_OP_NativeInteger, asn_DEF_S1AP_HFNModified_tags_1, sizeof(asn_DEF_S1AP_HFNModified_tags_1) /sizeof(asn_DEF_S1AP_HFNModified_tags_1[0]), /* 1 */ asn_DEF_S1AP_HFNModified_tags_1, /* Same as above */ sizeof(asn_DEF_S1AP_HFNModified_tags_1) /sizeof(asn_DEF_S1AP_HFNModified_tags_1[0]), /* 1 */ { #if !defined(ASN_DISABLE_OER_SUPPORT) 0, #endif /* !defined(ASN_DISABLE_OER_SUPPORT) */ #if !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) &asn_PER_type_S1AP_HFNModified_constr_1, #endif /* !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) */ S1AP_HFNModified_constraint }, 0, 0, /* No members */ 0 /* No specifics */ };
acetcom/nextepc
lib/asn1c/s1ap/S1AP_HFNModified.c
C
agpl-3.0
2,194
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.tools.simulator.tests.lcs; import org.restcomm.protocols.ss7.map.api.service.lsm.LCSClientType; import org.restcomm.protocols.ss7.tools.simulator.common.EnumeratedBase; import java.util.Hashtable; /** * @author <a href="mailto:serg.vetyutnev@gmail.com"> Sergey Vetyutnev </a> * @author <a href="mailto:fernando.mendioroz@gmail.com"> Fernando Mendioroz </a> */ public class LCSClientTypeEnumerated extends EnumeratedBase { private static Hashtable<String, Integer> stringMap = new Hashtable<String, Integer>(); private static Hashtable<Integer, String> intMap = new Hashtable<Integer, String>(); static { intMap.put(LCSClientType.emergencyServices.getType(), LCSClientType.emergencyServices.toString()); intMap.put(LCSClientType.valueAddedServices.getType(), LCSClientType.valueAddedServices.toString()); intMap.put(LCSClientType.plmnOperatorServices.getType(), LCSClientType.plmnOperatorServices.toString()); intMap.put(LCSClientType.lawfulInterceptServices.getType(), LCSClientType.lawfulInterceptServices.toString()); stringMap.put(LCSClientType.emergencyServices.toString(), LCSClientType.emergencyServices.getType()); stringMap.put(LCSClientType.valueAddedServices.toString(), LCSClientType.valueAddedServices.getType()); stringMap.put(LCSClientType.plmnOperatorServices.toString(), LCSClientType.plmnOperatorServices.getType()); stringMap.put(LCSClientType.lawfulInterceptServices.toString(), LCSClientType.lawfulInterceptServices.getType()); } public LCSClientTypeEnumerated() { } public LCSClientTypeEnumerated(int val) throws java.lang.IllegalArgumentException { super(val); } public LCSClientTypeEnumerated(Integer val) throws java.lang.IllegalArgumentException { super(val); } public LCSClientTypeEnumerated(String val) throws java.lang.IllegalArgumentException { super(val); } public static LCSClientTypeEnumerated createInstance(String s) { Integer instance = doCreateInstance(s, stringMap, intMap); if (instance == null) return new LCSClientTypeEnumerated(LCSClientType.emergencyServices.getType()); else return new LCSClientTypeEnumerated(instance); } @Override protected Hashtable<Integer, String> getIntTable() { return intMap; } @Override protected Hashtable<String, Integer> getStringTable() { return stringMap; } }
RestComm/jss7
tools/simulator/core/src/main/java/org/restcomm/protocols/ss7/tools/simulator/tests/lcs/LCSClientTypeEnumerated.java
Java
agpl-3.0
3,436
//==> //==> MessageBar helper function MessageBar() { this.show = function(className, text, interval, isHtml) { var id = "loadingWidget_" + className; if ($('#'+id).length == 0) $('<div id="'+id+'" class="messageBar"></div>').prependTo("body").click(function(){messageBar.hide(className)}); var $el = $('#'+id); if (isHtml) $el.html(text); else $el.text(text); $el.addClass(className).slideDown(); if (interval) setInterval(function() { messageBar.hide(className); }, interval); }; this.hide = function(className) { $("#loadingWidget_"+className).slideUp(); }; var loading = $("<div class='progressBar'></div>").prependTo("body").hide(); $(document).ajaxStart(function() { loading.show(); }); $(document).ajaxStop(function() { loading.hide(); }); $(document).ajaxError(function(event, jqxhr, settings, thrownError) { console.log("ajaxError",event,jqxhr,thrownError); if (event.data) { messageBar.show("error", "Fehler: " + event.data.error, 3000); } else if (jqxhr.status) { messageBar.show("error", "Allgemeiner Fehler: " + jqxhr.status + " " + jqxhr.statusText, 3000); } else { messageBar.show("error", "Exception: " + thrownError, 3000); } }); }; //==> //==> Context menu helper function ShowContextMenu(event, menuItems) { $(".ddmenu.context").remove(); var menu = $("<div class='ddmenu context'></div>"); for(var k in menuItems) { var item = $("<div>"+k+"</div>").appendTo(menu); item.click(menuItems[k]); } $(document.body).append(menu); var x = event.pageX, y = event.pageY, xx = menu.width(), yy = menu.outerHeight(); if (x+xx > window.innerWidth) x -= xx; if (y+yy > window.innerHeight) y -= yy; menu.css({ top: y + "px", left: x + "px" }).slideDown(); setTimeout(function() { $(document).one("click", function(e) { menu.remove(); e.preventDefault(); }) $(document).one("contextmenu", function(e) { menu.remove(); e.preventDefault(); }) },1) } function CloseContextMenu(event, menuItems) { $(".ddmenu.context").remove(); } //==> //==> make new stuff red // Converts a #ffffff hex string into an [r,g,b] array var h2r = function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if( result ) return [ parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16) ]; var result = /^rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)$/i.exec(hex); if( result ) return [ parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10) ]; return null; }; var _interpolateColor = function(color1, color2, factor) { if (arguments.length < 3) { factor = 0.5; } var result = color1.slice(); for (var i=0;i<3;i++) { result[i] = Math.round(result[i] + factor*(color2[i]-color1[i])); } return result; }; function make_new_stuff_red($el) { var age = parseInt($el.attr("data-age")); var oldAge = parseInt($el.attr("data-old")); if (!oldAge) oldAge = 21600; var curColorAttr = $el.css("background-color"); var curColor = h2r(curColorAttr); var redColor = [255,0,0]; //TODO var newColor = _interpolateColor(curColor, redColor, Math.max(0, age - oldAge) } function newRandomBarcode(){ code = "" + (Math.floor(Math.random()*999999)+2000000); weighed_sum = parseInt(code[0])*3 + parseInt(code[1])*1 + parseInt(code[2])*3 + parseInt(code[3])*1 + parseInt(code[4])*3 + parseInt(code[5])*1 + parseInt(code[6])*3; checksum = (10 - (weighed_sum % 10)) % 10; code = "" + code + checksum; return code; } //==> //==> Startup Code OPLAN $(function() { window.messageBar = new MessageBar(); function ddlink_open(e) { var targetSel = $(this).attr("data-target"); if (targetSel == "#raumliste" && !$("#raumliste").length) { var $lst = $("<div id=raumliste class=ddmenu></div>").appendTo(this); $.get("/plan/api/room/?visible="+oplan.is_staff, function(rooms) { rooms.forEach(function(room) { $lst.append( (oplan.is_staff=="True" ? "<a class='right' href='/admin/oplan/room/"+escape(room.id)+"/change/'>(edit)</a> ":"") + "<a href='/plan/roomcalendar/"+escape(room.number)+"'>"+room.number+"</a> " + ""); }); }); } $(targetSel).css({'left': $(this).offset().left, 'display': 'block'}); return false; } function ddlink_close() { var targetSel = $(this).attr("data-target"); $(targetSel).hide(); } if (!('ontouchstart' in window)) $(".menuddlink").mouseenter(ddlink_open).mouseleave(ddlink_close); //$("[data-age]").each(make_new_stuff_red); $("#kdvuserbarcode_set-group .add-row a").click(function() { $(".dynamic-kdvuserbarcode_set").last().find(".field-code input.vTextField").val( newRandomBarcode()); }); $("#oplan").on('mouseenter', '.fc-event', function(e) { var eventObj = $(this).data("event"); if (!eventObj) eventObj = $(this).data("fcSeg").event; console.log("dom item: ",this); console.log("event: ",eventObj); var $h = $("#hoverhelp"); if ($h.length == 0) { $h=$("<div id=hoverhelp style='position:fixed;background:white;right:5px;top:60px;border:1px solid black'><b></b><br><span></span></div>").appendTo("body"); } $h.find("b").text(eventObj.title); $h.find("span").text(eventObj.constraints_freetext); $h.show(); }); }); function calendarDefaultOptions(extendOptions) { return $.extend({ schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', timezone: 'local', allDaySlot: false, lang: 'de', views: { timelineDay: { titleFormat: 'dddd DD.MM.YYYY' }, agendaDay: { titleFormat: 'dddd DD.MM.YYYY' }, }, buttonText: { timelineDay: 'Tag quer', agendaDay: 'Tag längs' }, defaultDate: localStorage.calendarDate, editable: true, droppable: true, // this allows things to be dropped onto the calendar selectable: true, selectHelper: true, firstDay: 1, businessHours:{ start: '09:00', end: '19:00', dow: [ 4,5,6,7] }, drop: function() { $(this).remove(); // remove the element from the "Draggable Events" list }, }, extendOptions); } function getEventContextMenu(event, jsEvent) { var menu = {}; if (event.view_url) { menu["Detailansicht"] = function() { location = event.view_url; }; } if (event.termin_id) { menu["Als interessant markieren"] = function() { alert("foobar"); }; } if (oplan.mode != "akreadonly") { menu["Bearbeiten"] = function() { window.open(event.edit_url+"?_popup=1", "", "width=800,height=600,scrollbars=yes"); }; if (event.termin_id) { menu["AK bearbeiten"] = function() { window.open(event.edit_ak_url+"?_popup=1", "", "width=800,height=600,scrollbars=yes"); }; menu["Auf Änderung hinweisen"] = function() { $.post("/plan/api/akmodified/", { aktermin_id: event.termin_id }, function(data) { messageBar.show("success", "Der AK wurde als verändert markiert. "+data.number+" Push-Benachrichtigungen wurden versandt.", 2000); }); }; } if (event.editable && event.avail_id) { menu["Löschen"] = function() { oplan.api.deleteRoomAvailabilityItem(event.avail_id); }; } if (event.editable && event.termin_id) { menu["Aus Plan entfernen"] = function() { oplan.api.saveAkTerminRaw(event.termin_id, { room: null, start_time: null, end_time: null, }); }; } } if (event.wikilink) { menu["Wikiseite öffnen"] = function() { location = event.wikilink; }; } return menu; } //==> //==> Model code OPLAN var oplan = {}; var STATUS = { 'OK': 1, 'BLOCKED': 2, 'SHOULD_RQ': 3, 'REQUESTED': 4, 'SLOT': 5 }; oplan.api = { loadUnschedAkTermine: function() { var $out = $("#unsched_aktermine").html(""); $.get("/plan/api/aktermin/?only_unscheduled=True&ordering=ak", function(aktermins) { aktermins.forEach(function(akt) { var title = akt.ak_titel; if(akt.ak_track != null) title = "[" + akt.ak_track + "] " + title; $("<div class='fc-event'></div>") .text(title) .appendTo($out) .draggable({ zIndex: 999, revert: true, }) .css('background', akt.ak_color) .data('event', { termin_id: akt.id, title: title, duration: akt.duration, constraints_freetext: akt.ak_constraints_freetext, }); }); }); }, createRoomAvailability: function(start, end, room_id) { if (oplan.mode == "slots") { var desc = prompt("Slot von "+start.format("HH:mm")+" bis "+end.format("HH:mm")+" eintragen?"); if (desc !== null) { $.post("/plan/roomevents/", { start: start.toISOString(), end: end.toISOString(), room: room_id, kommentar: desc, status: 5, }, "json") .success(function() { $('#calendar').fullCalendar('unselect'); $('#calendar').fullCalendar('refetchEvents'); }) .error(function(data) { $('#calendar').fullCalendar('unselect'); }); return; } } else if (oplan.mode == "availability") { messageBar.show("error", "Not supported...", 1000); } else if (oplan.mode == "aktermin") { var desc = prompt("Neuen AK mit Termin von "+start.format("HH:mm")+" bis "+end.format("HH:mm")+" eintragen?"); if (desc !== null) { $.post("/plan/api/ak/", { 'titel': desc, 'beschreibung': desc, 'leiter': '?', }, function(ok) { $.post("/plan/api/aktermin/", { ak: ok.id, room: room_id, start_time: start.toISOString(), end_time: end.toISOString(), duration: (end-start)/1000, status: 4, last_highlighted: moment().toISOString(), }, function(ok2) { $('#calendar').fullCalendar('unselect'); $('#calendar').fullCalendar('refetchEvents'); }); }); return; } } $('#calendar').fullCalendar('unselect'); }, onCalendarEventChange: function(event, delta, revertFunc, jsEvent, ui, view ) { if (oplan.mode == "slots" || oplan.mode == "availability") { $.post("/plan/roomevents/", { event_id: event.avail_id, start: event.start.toISOString(), end: event.end.toISOString(), room: event.resourceId, }, "json") .success(function(data) { $('#calendar').fullCalendar('unselect'); $('#calendar').fullCalendar('refetchEvents'); messageBar.show('success', ''+data.modifications+' Einträge verschoben', 1500); }) .error(function(data) { revertFunc(); }); } else if (oplan.mode == "aktermin") { oplan.api.saveAkTermin(event); } }, loadCalendarEvents: function(start, end, room_id, callback) { $.ajax({ url: '/plan/roomevents/', dataType: 'json', cache: false, data: { // our hypothetical feed requires UNIX timestamps start: start.format('YYYY-MM-DD')+' 00:00:00', end: end.format('YYYY-MM-DD')+' 23:59:59', room: room_id, }, success: function(doc) { var o=[]; for(var i in doc.events) { var e = doc.events[i]; if (e.termin_id) { e.editable = (oplan.mode == "aktermin"); e.color = "#000000"; if (oplan.mode == "akreadonly") e.url = e.view_url; e.borderColor=e.ak_color+" #000000 #000000 #000000"; e.className='bigtop'; } else { e.editable = false; e.rendering = "background"; switch(e.status) { case STATUS.OK: e.color = "#339933"; if (oplan.mode == "availability") {e.rendering=""; } if (oplan.mode == "availability" && !e.mgmt_id) {e.editable=true; } break; case STATUS.BLOCKED: e.color = "#dd2222"; if (oplan.mode == "availability") {e.rendering=""; } if (oplan.mode == "availability" && !e.mgmt_id) {e.editable=true; } break; case STATUS.SLOT: e.color = "#113399"; //e.rendering=""; if (oplan.mode == "slots") {e.rendering=""; e.editable=true;} break; case STATUS.SHOULD_REQUEST: e.color = "#999933"; case STATUS.REQUESTED: e.color = "#66bb33"; if (oplan.mode == "availability") {e.rendering=""; } break; } } o.push(e); } callback(o); } }); }, saveAkTermin: function (event) { console.log(event.start,event.end,event.duration); if (!event.end) event.end = moment(event.start).add(moment.duration(event.duration)); oplan.api.saveAkTerminRaw(event.termin_id, { room: event.resourceId, start_time: event.start.toISOString(), end_time: event.end.toISOString(), last_highlighted: moment().toISOString(), }); }, saveAkTerminRaw: function(terminId, postData) { $.ajax({ url: "/plan/api/aktermin/"+terminId+"/", data: postData, method: "PATCH", success: function(ok) {console.log(ok); $('#calendar').fullCalendar('unselect'); oplan.api.checkConflicts(terminId); $('#calendar').fullCalendar('refetchEvents'); messageBar.show('success', 'Änderungen am AK-Termin #'+ok.id+' '+ok.ak_titel+' wurden gespeichert', 1500); oplan.api.loadUnschedAkTermine(); } }); }, checkConflicts: function(terminId) { messageBar.hide('warning'); $.get("/plan/api/aktermin/"+terminId+"/check_constraints", function(result) { var out = []; if (result.constraints.fail.length > 0) { out.push( "Folgende Einschränkungen dieses Termins werden verletzt:" ); for(var i in result.constraints.fail) { var ctr = result.constraints.fail[i]; out.push( " - " + ctr[2] ); } } if (result.constraints.reverse_fail.length > 0) { out.push( "Folgende Einschränkungen anderer Termine werden verletzt:" ); for(var i in result.constraints.reverse_fail) { var ctr = result.constraints.reverse_fail[i]; out.push( " - " + ctr[0] + " *** " + ctr[1][2] ); } } if (out.length > 0) { messageBar.hide('success'); messageBar.show("warning", out.join("<br>"), null, true); } }); }, deleteRoomAvailabilityItem: function(terminId) { $.ajax({ url: "/plan/api/slot/"+terminId+"/", data: {}, method: "DELETE", success: function(ok) { $('#calendar').fullCalendar('unselect'); $('#calendar').fullCalendar('refetchEvents'); messageBar.show('success', 'Raumverfügbarkeitseintrag wurde gelöscht.', 1500); } }); }, }; //end oplan.api //==> //==> Django CSRF shit function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $(function() { var languageForm = $("form[name='language-form']"); $(":submit", languageForm).hide(); $("select", languageForm).change(function(){languageForm.submit()}); $("#site-name a").click(function() { if (!$("#header .ml").is(":visible")) { $("#header").addClass("expand"); return false; } else if ($("#header").is(".expand")) { $("#header").removeClass("expand"); return false; } }) });
d120/pyophase
ophasebase/static/ophasebase/js/helper.js
JavaScript
agpl-3.0
19,869
/*************************************************************************\ * Copyright (C) Michael Kerrisk, 2016. * * * * This program is free software. You may use, modify, and redistribute it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation, either version 3 or (at your option) any * * later version. This program is distributed without any warranty. See * * the file COPYING.gpl-v3 for details. * \*************************************************************************/ /* Listing 63-3 */ /* demo_sigio.c A trivial example of the use of signal-driven I/O. */ #include <signal.h> #include <ctype.h> #include <fcntl.h> #include <termios.h> #include "tty_functions.h" /* Declaration of ttySetCbreak() */ #include "tlpi_hdr.h" static volatile sig_atomic_t gotSigio = 0; /* Set nonzero on receipt of SIGIO */ static void sigioHandler(int sig) { gotSigio = 1; } int main(int argc, char *argv[]) { int flags, j, cnt; struct termios origTermios; char ch; struct sigaction sa; Boolean done; /* Establish handler for "I/O possible" signal */ sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sa.sa_handler = sigioHandler; if (sigaction(SIGIO, &sa, NULL) == -1) errExit("sigaction"); /* Set owner process that is to receive "I/O possible" signal */ if (fcntl(STDIN_FILENO, F_SETOWN, getpid()) == -1) errExit("fcntl(F_SETOWN)"); /* Enable "I/O possible" signaling and make I/O nonblocking for file descriptor */ flags = fcntl(STDIN_FILENO, F_GETFL); if (fcntl(STDIN_FILENO, F_SETFL, flags | O_ASYNC | O_NONBLOCK) == -1) errExit("fcntl(F_SETFL)"); /* Place terminal in cbreak mode */ if (ttySetCbreak(STDIN_FILENO, &origTermios) == -1) errExit("ttySetCbreak"); for (done = FALSE, cnt = 0; !done ; cnt++) { for (j = 0; j < 100000000; j++) continue; /* Slow main loop down a little */ if (gotSigio) { /* Is input available? */ gotSigio = 0; /* Read all available input until error (probably EAGAIN) or EOF (not actually possible in cbreak mode) or a hash (#) character is read */ while (read(STDIN_FILENO, &ch, 1) > 0 && !done) { printf("cnt=%d; read %c\n", cnt, ch); done = ch == '#'; } } } /* Restore original terminal settings */ if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &origTermios) == -1) errExit("tcsetattr"); exit(EXIT_SUCCESS); }
jetm/tlpi
altio/demo_sigio.c
C
agpl-3.0
2,817
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2015 Kaltura Inc. // // 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 (at your option) 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/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import org.w3c.dom.Element; import com.kaltura.client.KalturaParams; import com.kaltura.client.KalturaApiException; import com.kaltura.client.enums.KalturaContainerFormat; import com.kaltura.client.utils.ParseUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaAssetParamsOutput extends KalturaAssetParams { public int assetParamsId = Integer.MIN_VALUE; public String assetParamsVersion; public String assetId; public String assetVersion; public int readyBehavior = Integer.MIN_VALUE; /** The container format of the Flavor Params */ public KalturaContainerFormat format; public KalturaAssetParamsOutput() { } public KalturaAssetParamsOutput(Element node) throws KalturaApiException { super(node); NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node aNode = childNodes.item(i); String nodeName = aNode.getNodeName(); String txt = aNode.getTextContent(); if (nodeName.equals("assetParamsId")) { this.assetParamsId = ParseUtils.parseInt(txt); continue; } else if (nodeName.equals("assetParamsVersion")) { this.assetParamsVersion = ParseUtils.parseString(txt); continue; } else if (nodeName.equals("assetId")) { this.assetId = ParseUtils.parseString(txt); continue; } else if (nodeName.equals("assetVersion")) { this.assetVersion = ParseUtils.parseString(txt); continue; } else if (nodeName.equals("readyBehavior")) { this.readyBehavior = ParseUtils.parseInt(txt); continue; } else if (nodeName.equals("format")) { this.format = KalturaContainerFormat.get(ParseUtils.parseString(txt)); continue; } } } public KalturaParams toParams() throws KalturaApiException { KalturaParams kparams = super.toParams(); kparams.add("objectType", "KalturaAssetParamsOutput"); kparams.add("assetParamsId", this.assetParamsId); kparams.add("assetParamsVersion", this.assetParamsVersion); kparams.add("assetId", this.assetId); kparams.add("assetVersion", this.assetVersion); kparams.add("readyBehavior", this.readyBehavior); kparams.add("format", this.format); return kparams; } }
moskiteau/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/types/KalturaAssetParamsOutput.java
Java
agpl-3.0
4,069
/* * log.js * * Copyright (C) 2009-13 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ var log4js = require('log4js'); global.logger = log4js.getLogger('shiny-server'); global.logger.setLevel(process.env.SHINY_LOG_LEVEL || 'TRACE');
ekergy/shiny-ekergy
lib/core/log.js
JavaScript
agpl-3.0
578
/* Copyright 2016 icasdri This file is part of PostMaker. PostMaker is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PostMaker 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 PostMaker. If not, see <http://www.gnu.org/licenses/>. */ Workers.gmail = { /* * This function needs to store title and p (the content, whether blurb or full text), * and anything from conf that might be needed (e.g. website url, CC field) * somewhere of its choosing in dat that'll be used by the go() function. * This allows the function to process the contet as it sees fit. * The primaryUrl token %%% will already have been replaced. */ prep: function(primaryUrl, conf, dat, title, contentP) { console.log("Got to Workers.gmail.prep()"); dat.jsoConfig = { providerID: "google", client_id: "853943586263-f2ondnhfv7nbnk6m0ia64qr807of7i0k.apps.googleusercontent.com", redirect_uri: "https://postmaker.surge.sh", authorization: "https://accounts.google.com/o/oauth2/auth", scopes: { request: ["https://www.googleapis.com/auth/gmail.send"] } } dat.content = contentP; dat.subject = title; dat.to = conf.toField.trim(); dat.cc= conf.ccField.trim(); dat.bcc= conf.bccField.trim(); }, go: function(primaryUrl, dat, jso, progress) { if (typeof(primaryUrl) == "function") { // We are primary console.warn("[Workers.gmail] We will be unable to provide a primaryUrl even though we are primary!!!"); } else { // We are secondary } console.log("Got to Workers.gmail.go()"); console.log(jso); console.log(jso.ajax); progress(0); progress("Constructing message..."); message = "To: " + dat.to + "\n"; if (dat.cc) { message += "Cc: " + dat.cc + "\n"; } if (dat.bcc) { message += "Bcc: " + dat.bcc + "\n"; } if (dat.subject) { message += "Subject: " + dat.subject + "\n"; } message += "\n" + dat.content; progress(12); progress("Encoding message..."); var encoded = btoa(message); progress(24); progress("Sending message..."); var scopes = [ "https://mail.google.com/", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.send" ]; jso.ajax({ url: "https://www.googleapis.com/gmail/v1/users/me/messages/send", oauth: { scopes: { request: scopes, require: scopes } }, type: "POST", data: JSON.stringify({ raw: encoded }), contentType: "application/json", dataType: "json", success: function() { progress(100); progress("Sent!"); progress({ color: App.COLORS.SUCCESS }); }, error: function(x) { progress(100); progress("Sending failed."); progress({ color: App.COLORS.ERROR }); console.error("[Workers.gmail] Gmail responded with error: " + x); } }); } };
icasdri/PostMaker
workers/gmail.js
JavaScript
agpl-3.0
3,408
<?php class smpl_HopDongDichVu_Sample{ function getType() { return 'Contracts'; } function getBody() { $d_image = explode('?',SugarThemeRegistry::current()->getImageURL('company_logo.png')); return ' <table cellpadding="0" cellspacing="0" border="1" style="border-collapse: collapse;margin-left:30;" width="100%" class="table_add" id="giatrihopdong"> <thead> <tr bgcolor="#CCCCCC"> <td align="center" style="border-style: solid; border-width: 0.5px;">Độ Tuổi</td> <td align="center" style="border-style: solid; border-width: 0.5px;"> Số lượng</td> <td align="center" style="border-style: solid; border-width: 0.5px;"> Giá tour</td> <td align="center" style="border-style: solid; border-width: 0.5px;"> Thuế</td> <td align="center" style="border-style: solid; border-width: 0.5px;"> Thành tiền</td> </tr> </thead> <tbody> <tr> <td align="center" style="border-style: solid; border-width: 0.5px;"> $contractvalues_age </td> <td align="center" style="border-style: solid; border-width: 0.5px;"> $contractvalues_num_of_cus </td> <td align="center" style="border-style: solid; border-width: 0.5px;"> $contractvalues_tour_cost </td> <td align="center" style="border-style: solid; border-width: 0.5px;"> $contractvalues_tax </td> <td align="center" style="border-style: solid; border-width: 0.5px;"> $contractvalues_money USD </td> </tr> </tbody> </table> <p> </p> <table cellpadding="0" cellspacing="0" style="margin-left:30;" width="100%" class="table_add tabDetailViewDF" id="dieukhoanthanhtoan" > <tbody> <tr> <td style="padding-top:5px;" > $contractconditions_contract_phase - $contractconditions_event, bên B thanh toán cho bên A $contractconditions_percent số tiền là $contractconditions_money $contractconditions_currency </td> </tr> <tr> <td style="padding-left:50px;"> <i>(Bằng chữ: <b> $contractconditions_in_word</b>)</i> </td> </tr> </tbody> </table> '; } function getHeader() { return ''; } function getFooter() { global $locale; return '<table style="width: 100%; border: 0pt none; border-spacing: 0pt;"> <tbody> <tr> <td>'.translate('LBL_PAGE','AOS_PDF_Templates').' {PAGENO}</td> <td style="text-align: right;">{DATE '.$locale->getPrecedentPreference('default_date_format').'}</td> </tr> </tbody> </table>'; } } ?>
sysraj86/carnivalcrm
modules/AOS_PDF_Templates/samples/smpl_HopDongDichVu_Sample.php
PHP
agpl-3.0
3,479
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SAMPLEFMT_H #define AVUTIL_SAMPLEFMT_H /** * all in native-endian format */ enum AVSampleFormat { AV_SAMPLE_FMT_NONE = -1, AV_SAMPLE_FMT_U8, ///< unsigned 8 bits AV_SAMPLE_FMT_S16, ///< signed 16 bits AV_SAMPLE_FMT_S32, ///< signed 32 bits AV_SAMPLE_FMT_FLT, ///< float AV_SAMPLE_FMT_DBL, ///< double AV_SAMPLE_FMT_NB ///< Number of sample formats. DO NOT USE if linking dynamically }; /** * Return the name of sample_fmt, or NULL if sample_fmt is not * recognized. */ const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt); /** * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE * on error. */ enum AVSampleFormat av_get_sample_fmt(const char *name); /** * Generate a string corresponding to the sample format with * sample_fmt, or a header if sample_fmt is negative. * * @param buf the buffer where to write the string * @param buf_size the size of buf * @param sample_fmt the number of the sample format to print the * corresponding info string, or a negative value to print the * corresponding header. * @return the pointer to the filled buffer or NULL if sample_fmt is * unknown or in case of other errors */ char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt); /** * Return sample format bits per sample. * * @param sample_fmt the sample format * @return number of bits per sample or zero if unknown for the given * sample format */ int av_get_bits_per_sample_fmt(enum AVSampleFormat sample_fmt); #endif /* AVUTIL_SAMPLEFMT_H */
ging/isabel
lib/ffmpeg/Win32/src/ffmpeg/libavutil/samplefmt.h
C
agpl-3.0
2,391
from requests import post import io import base64 class ZivService(object): def __init__(self, cnc_url, user=None, password=None, sync=True): self.cnc_url = cnc_url self.sync = sync self.auth = None if user and password: self.auth = (user,password) def send_cycle(self, filename, cycle_filedata): """Send a cycle file to the concentrator service Keyword arguments: filename -- the name of our file (doesn't matter) cycle_filedata -- the file to send, encoded as a base64 string """ filecontent = base64.b64decode(cycle_filedata) url = self.cnc_url + ('/' if (self.cnc_url[-1] != '/') else '') +'cct/cycles/' result = None if self.auth: result = post(url, files={'file': (filename, filecontent)}, auth=self.auth) else: result = post(url, files={'file': (filename, filecontent)}) return result
gisce/primestg
primestg/ziv_service.py
Python
agpl-3.0
959
/* * COMA 3.0 Community Edition * * 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 * (at your option) 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/. */ package de.wdilab.coma.center.reuse; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import org.antlr.runtime.tree.Tree; import de.wdilab.coma.center.Manager; import de.wdilab.coma.insert.metadata.XDRParser; import de.wdilab.coma.insert.relationships.MatchResultParser; import de.wdilab.coma.matching.Combination; import de.wdilab.coma.center.reuse.MappingReuse; import de.wdilab.coma.matching.validation.TreeToWorkflow; import de.wdilab.coma.repository.TRepository; import de.wdilab.coma.structure.EvaluationMeasure; import de.wdilab.coma.structure.Graph; import de.wdilab.coma.structure.MatchResult; import junit.framework.TestCase; /** * @author Sabine Massmann */ public class TMappingReuse extends TestCase { // coma-project\coma-engine\resources\Sources\CSV String directory = (new File ("")).getAbsolutePath().replace("\\", "/") + "/resources/Sources/"; String providerSrc = directory+"Po_xdr/Apertum.xdr"; String providerTrg = directory+"Po_xdr/CIDXPOSCHEMA.xdr"; Manager manager = null; MatchResult intended = null; private void reusePathLength1(Graph sourceGraph, Graph targetGraph){ boolean exact = true; int topKPaths= 1 , maxPathLen= 1, combination = Combination.COM_MAX, composition = MatchResult.COMPOSITION_MAX; boolean usePivotSchema = false; MappingReuse reuse = new MappingReuse(topKPaths, maxPathLen, exact, composition, combination, usePivotSchema); MatchResult result1 = reuse.executeReuse(manager, sourceGraph, targetGraph); System.out.println(result1.toString()); MatchResult result2 = reuse.executeReuse(manager, targetGraph, sourceGraph); System.out.println(result2.toString()); assertEquals(result1.getMatchCount(), result2.getMatchCount()); assertEquals(result1.getSrcMatchObjectsCount(), result2.getTrgMatchObjectsCount()); assertEquals(result1.getTrgMatchObjectsCount(), result2.getSrcMatchObjectsCount()); if (intended!=null){ EvaluationMeasure values1 = intended.compare(result1); EvaluationMeasure values2 = MatchResult.transpose(intended).compare(result2); assertEquals(values1, values2); } } public void testReuse(){ TRepository.setDatabaseProperties(); manager = new Manager(); manager.getImporter().dropRepositorySchema(); manager.getImporter().createRepositorySchema(); boolean dbInsert = true; XDRParser xdrPar = new XDRParser(dbInsert); xdrPar.parseMultipleSources(directory.replace("/", "\\")+"PO_xdr"); manager.loadRepository(); MatchResultParser mrParser = new MatchResultParser(manager, dbInsert); mrParser.loadMatchResultFile(directory+"Mappings/mappings-PO.txt"); Graph sourceGraph = manager.loadGraph(manager.getAccessor().getSourceId(providerSrc)); Graph targetGraph = manager.loadGraph(manager.getAccessor().getSourceId(providerTrg)); HashSet<Integer> relIds = manager.getAccessor().getSourceRelIds(sourceGraph.getSource().getId(), targetGraph.getSource().getId()); if (relIds!=null){ intended = manager.loadMatchResult(manager.getSourceRel(relIds.iterator().next())); if (!intended.getSourceGraph().equals(sourceGraph)){ intended = MatchResult.transpose(intended); } } System.out.println(); System.out.println("*****************"); reusePathLength1(sourceGraph, targetGraph); System.out.println("*****************"); reuse_Length2Top1(sourceGraph, targetGraph); System.out.println("*****************"); reuseMaxPath(sourceGraph, targetGraph); System.out.println("*****************"); reuseTopK(sourceGraph, targetGraph); System.out.println("*****************"); reuseExact(sourceGraph, targetGraph); System.out.println("*****************"); } private void reuse_Length2Top1(Graph sourceGraph, Graph targetGraph){ boolean exact = true; int topKPaths= 1 , maxPathLen= 2, combination = Combination.COM_MAX; MatchResult min=null, max=null, avg=null; boolean usePivotSchema = false; for (int i = 0; i < MatchResult.COMPOSE_IDS.length; i++) { int composition = MatchResult.COMPOSE_IDS[i]; MappingReuse reuse = new MappingReuse(topKPaths, maxPathLen, exact, composition, combination, usePivotSchema); MatchResult result1 = reuse.executeReuse(manager, sourceGraph, targetGraph); switch (composition) { case MatchResult.COMPOSITION_MIN: min = result1; break; case MatchResult.COMPOSITION_MAX: max = result1; break; case MatchResult.COMPOSITION_AVERAGE: avg = result1; break; } } int minCnt = min.getMatchCount(); int maxCnt = max.getMatchCount(); int avgCnt = avg.getMatchCount(); assertEquals(minCnt, maxCnt); assertEquals(minCnt, avgCnt); assertEquals(min.getSrcMatchObjectsCount(), max.getSrcMatchObjectsCount()); assertEquals(min.getSrcMatchObjectsCount(), avg.getSrcMatchObjectsCount()); assertEquals(min.getTrgMatchObjectsCount(), max.getTrgMatchObjectsCount()); assertEquals(min.getTrgMatchObjectsCount(), avg.getTrgMatchObjectsCount()); ArrayList<Object> srcObjects = min.getSrcMatchObjects(); ArrayList<Object> trgObjects = min.getTrgMatchObjects(); for (Object srcObject : srcObjects) { for (Object trgObject : trgObjects) { float minSim = min.getSimilarity(srcObject, trgObject); float maxSim = max.getSimilarity(srcObject, trgObject); float avgSim = avg.getSimilarity(srcObject, trgObject); assertTrue(minSim==avgSim); assertTrue(avgSim==maxSim); } } } private void reuseMaxPath(Graph sourceGraph, Graph targetGraph){ boolean exact = true, usePivotSchema = false; int topKPaths= 1 , combination = Combination.COM_MAX, composition = MatchResult.COMPOSITION_AVERAGE; float[][] expected={ {1f, 1f, 1f}, {0.98f, 0.93f, 0.95f}, {0.98f, 0.93f, 0.95f}, {0.98f, 0.87f, 0.92f}, }; for (int maxPathLen= 1; maxPathLen <= 4; maxPathLen++) { MappingReuse reuse = new MappingReuse(topKPaths, maxPathLen, exact, composition, combination, usePivotSchema); MatchResult result1 = reuse.executeReuse(manager, sourceGraph, targetGraph); EvaluationMeasure r = intended.compare(result1); assertEquals(expected[maxPathLen-1][0], r.getPrecision(), 0.01f); assertEquals(expected[maxPathLen-1][1], r.getRecall(), 0.01f); assertEquals(expected[maxPathLen-1][2], r.getFmeasure(), 0.01f); // System.out.println(r.getPrecision() + "\t" + r.getRecall() + "\t" + r.getFmeasure()); }; } private void reuseExact(Graph sourceGraph, Graph targetGraph){ boolean exact = true, usePivotSchema = false; int topKPaths= 4 , maxPathLen= 3, combination = Combination.COM_MAX, composition = MatchResult.COMPOSITION_AVERAGE; float[][] expected={ {0.96f, 0.98f, 0.97f}, {0.98f, 1f, 0.99f}, }; MappingReuse reuse = new MappingReuse(topKPaths, maxPathLen, exact, composition, combination, usePivotSchema); MatchResult result = reuse.executeReuse(manager, sourceGraph, targetGraph); EvaluationMeasure r = intended.compare(result); assertEquals(expected[0][0], r.getPrecision(), 0.01f); assertEquals(expected[0][1], r.getRecall(), 0.01f); assertEquals(expected[0][2], r.getFmeasure(), 0.01f); // System.out.println(r.getPrecision() + "\t" + r.getRecall() + "\t" + r.getFmeasure()); exact= false; reuse = new MappingReuse(topKPaths, maxPathLen, exact, composition, combination, usePivotSchema); result = reuse.executeReuse(manager, sourceGraph, targetGraph); r = intended.compare(result); assertEquals(expected[1][0], r.getPrecision(), 0.01f); assertEquals(expected[1][1], r.getRecall(), 0.01f); assertEquals(expected[1][2], r.getFmeasure(), 0.01f); // System.out.println(r.getPrecision() + "\t" + r.getRecall() + "\t" + r.getFmeasure()); } private void reuseTopK(Graph sourceGraph, Graph targetGraph){ boolean exact = true, usePivotSchema = false; int maxPathLen=2, combination = Combination.COM_MAX, composition = MatchResult.COMPOSITION_AVERAGE; float[][] expected={ {0.98f, 0.93f, 0.95f}, {0.98f, 0.94f, 0.96f}, {0.96f, 0.98f, 0.97f}, }; for (int topKPaths= 1; topKPaths < 4; topKPaths++) { MappingReuse reuse = new MappingReuse(topKPaths, maxPathLen, exact, composition, combination, usePivotSchema); MatchResult result1 = reuse.executeReuse(manager, sourceGraph, targetGraph); EvaluationMeasure r = intended.compare(result1); assertEquals(expected[topKPaths-1][0], r.getPrecision(), 0.01f); assertEquals(expected[topKPaths-1][1], r.getRecall(), 0.01f); assertEquals(expected[topKPaths-1][2], r.getFmeasure(), 0.01f); // System.out.println(r.getPrecision() + "\t" + r.getRecall() + "\t" + r.getFmeasure()); }; } public void testValidate(){ for (int i = 0; i < MappingReuse.REUSE.length; i++) { MappingReuse r = new MappingReuse(MappingReuse.REUSE[i]); String name = r.getName(); String value = r.toString(); System.out.println(name +" -> " + value); Tree tree = TreeToWorkflow.getTree(value); System.out.println(tree.toString()); System.out.println(tree.toStringTree()); MappingReuse reuse = MappingReuse.buildWorkflow(tree); System.out.println(reuse.toString()); } } }
epu-ntua/FITMAN-SeMa
coma-engine/src/test/java/de/wdilab/coma/center/reuse/TMappingReuse.java
Java
agpl-3.0
9,833
<?php use humhub\widgets\ActiveForm; use yii\helpers\Url; $animation = $model->hasErrors() ? 'shake' : 'fadeIn'; ?> <div class="modal-dialog modal-dialog-small animated <?= $animation ?>"> <div class="modal-content"> <?php $form = ActiveForm::begin(); ?> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel"><?php echo Yii::t('SpaceModule.views_create_create', '<strong>Create</strong> new space'); ?></h4> </div> <div class="modal-body"> <?= humhub\modules\space\widgets\SpaceNameColorInput::widget(['form' => $form, 'model' => $model])?> <?php echo $form->field($model, 'description')->textarea(['placeholder' => Yii::t('SpaceModule.views_create_create', 'space description'), 'rows' => '3']); ?> <a data-toggle="collapse" id="access-settings-link" href="#collapse-access-settings" style="font-size: 11px;"><i class="fa fa-caret-right"></i> <?php echo Yii::t('SpaceModule.views_create_create', 'Advanced access settings'); ?> </a> <div id="collapse-access-settings" class="panel-collapse collapse"> <br/> <div class="row"> <div class="col-md-6"> <?= $form->field($model, 'join_policy')->radioList($joinPolicyOptions); ?> </div> <div class="col-md-6"> <?= $form->field($model, 'visibility')->radioList($visibilityOptions); ?> </div> </div> </div> </div> <div class="modal-footer"> <a href="#" class="btn btn-primary" data-action-click="ui.modal.submit" data-ui-loader data-action-url="<?= Url::to(['/space/create/create']) ?>"> <?= Yii::t('SpaceModule.views_create_create', 'Next'); ?> </a> </div> <?php ActiveForm::end(); ?> </div> </div> <script type="text/javascript"> $('#collapse-access-settings').on('show.bs.collapse', function () { // change link arrow $('#access-settings-link i').removeClass('fa-caret-right'); $('#access-settings-link i').addClass('fa-caret-down'); }); $('#collapse-access-settings').on('hide.bs.collapse', function () { // change link arrow $('#access-settings-link i').removeClass('fa-caret-down'); $('#access-settings-link i').addClass('fa-caret-right'); }); </script>
GreenVolume/humhub-themes-MadeHub
views/space/create/create.php
PHP
agpl-3.0
2,793
/** @file * @brief PostList class implementing unweighted Query::OP_OR */ // Copyright 2017,2018 Olly Betts // @license GNU GPL // #include <xapian-internal.h> #pragma hdrstop #include "boolorpostlist.h" #include "heap.h" #include "postlisttree.h" using namespace std; BoolOrPostList::~BoolOrPostList() { if(plist) { for(size_t i = 0; i < n_kids; ++i) { delete plist[i].pl; } delete [] plist; } } Xapian::doccount BoolOrPostList::get_termfreq_min() const { Assert(n_kids != 0); Xapian::doccount res = plist[0].pl->get_termfreq_min(); for(size_t i = 1; i < n_kids; ++i) { res = max(res, plist[i].pl->get_termfreq_min()); } return res; } Xapian::docid BoolOrPostList::get_docid() const { Assert(did != 0); return did; } double BoolOrPostList::get_weight(Xapian::termcount, Xapian::termcount, Xapian::termcount) const { return 0; } double BoolOrPostList::recalc_maxweight() { return 0; } PostList* BoolOrPostList::next(double) { while(plist[0].did == did) { PostList* res = plist[0].pl->next(0); if(res) { delete plist[0].pl; plist[0].pl = res; } if(plist[0].pl->at_end()) { if(n_kids == 1) { // We've reached the end of all posting lists - prune // returning an at_end postlist. n_kids = 0; return plist[0].pl; } Heap::pop(plist, plist + n_kids, std::greater<PostListAndDocID>()); delete plist[--n_kids].pl; continue; } plist[0].did = plist[0].pl->get_docid(); Heap::replace(plist, plist + n_kids, std::greater<PostListAndDocID>()); } if(n_kids == 1) { n_kids = 0; return plist[0].pl; } did = plist[0].did; return NULL; } PostList* BoolOrPostList::skip_to(Xapian::docid did_min, double) { if(UNLIKELY(did_min <= did)) return NULL; did = Xapian::docid(-1); size_t j = 0; for(size_t i = 0; i < n_kids; ++i) { if(plist[i].did < did_min) { PostList * res = plist[i].pl->skip_to(did_min, 0); if(res) { delete plist[i].pl; plist[j].pl = res; } else { plist[j].pl = plist[i].pl; } if(plist[j].pl->at_end()) { if(j == 0 && i == n_kids - 1) { // We've reached the end of all posting lists - prune // returning an at_end postlist. n_kids = 0; return plist[j].pl; } delete plist[j].pl; continue; } plist[j].did = plist[j].pl->get_docid(); } else if(j != i) { plist[j] = plist[i]; } did = min(did, plist[j].did); ++j; } Assert(j != 0); n_kids = j; if(n_kids == 1) { n_kids = 0; return plist[0].pl; } // Restore the heap invariant. Heap::make(plist, plist + n_kids, std::greater<PostListAndDocID>()); return NULL; } Xapian::doccount BoolOrPostList::get_termfreq_max() const { Assert(n_kids != 0); // Maximum is if all sub-postlists are disjoint. Xapian::doccount result = plist[0].pl->get_termfreq_max(); for(size_t i = 1; i < n_kids; ++i) { Xapian::doccount tf_max = plist[i].pl->get_termfreq_max(); Xapian::doccount old_result = result; result += tf_max; // Catch overflowing the type too. if(result >= db_size || result < old_result) return db_size; } return result; } Xapian::doccount BoolOrPostList::get_termfreq_est() const { if(UNLIKELY(db_size == 0)) return 0; Assert(n_kids != 0); // We calculate the estimate assuming independence. The simplest // way to calculate this seems to be a series of (n_kids - 1) pairwise // calculations, which gives the same answer regardless of the order. double scale = 1.0 / db_size; double P_est = plist[0].pl->get_termfreq_est() * scale; for(size_t i = 1; i < n_kids; ++i) { double P_i = plist[i].pl->get_termfreq_est() * scale; P_est += P_i - P_est * P_i; } return static_cast<Xapian::doccount>(P_est * db_size + 0.5); } TermFreqs BoolOrPostList::get_termfreq_est_using_stats(const Xapian::Weight::Internal& stats) const { Assert(n_kids != 0); // We calculate the estimate assuming independence. The simplest // way to calculate this seems to be a series of (n_kids - 1) pairwise // calculations, which gives the same answer regardless of the order. TermFreqs freqs(plist[0].pl->get_termfreq_est_using_stats(stats)); // Our caller should have ensured this. Assert(stats.collection_size); double scale = 1.0 / stats.collection_size; double P_est = freqs.termfreq * scale; double rtf_scale = 0.0; if(stats.rset_size != 0) { rtf_scale = 1.0 / stats.rset_size; } double Pr_est = freqs.reltermfreq * rtf_scale; // If total_length is 0, cf must always be 0 so cf_scale is irrelevant. double cf_scale = 0.0; if(LIKELY(stats.total_length != 0)) { cf_scale = 1.0 / stats.total_length; } double Pc_est = freqs.collfreq * cf_scale; for(size_t i = 1; i < n_kids; ++i) { freqs = plist[i].pl->get_termfreq_est_using_stats(stats); double P_i = freqs.termfreq * scale; P_est += P_i - P_est * P_i; double Pc_i = freqs.collfreq * cf_scale; Pc_est += Pc_i - Pc_est * Pc_i; // If the rset is empty, Pr_est should be 0 already, so leave // it alone. if(stats.rset_size != 0) { double Pr_i = freqs.reltermfreq * rtf_scale; Pr_est += Pr_i - Pr_est * Pr_i; } } return TermFreqs(Xapian::doccount(P_est * stats.collection_size + 0.5), Xapian::doccount(Pr_est * stats.rset_size + 0.5), Xapian::termcount(Pc_est * stats.total_length + 0.5)); } bool BoolOrPostList::at_end() const { // We never need to return true here - if all but one child reaches // at_end(), we prune to leave just that child. If all children reach // at_end() together, we prune to leave one of them which will then // indicate at_end() for us. return false; } std::string BoolOrPostList::get_description() const { string desc = "BoolOrPostList("; desc += plist[0].pl->get_description(); for(size_t i = 1; i < n_kids; ++i) { desc += ", "; desc += plist[i].pl->get_description(); } desc += ')'; return desc; } Xapian::termcount BoolOrPostList::get_wdf() const { return for_all_matches([](PostList* pl) { return pl->get_wdf(); }); } Xapian::termcount BoolOrPostList::count_matching_subqs() const { return for_all_matches([](PostList* pl) { return pl->count_matching_subqs(); }); } void BoolOrPostList::gather_position_lists(OrPositionList* orposlist) { for_all_matches([&orposlist](PostList* pl) { pl->gather_position_lists(orposlist); return 0; }); }
papyrussolution/OpenPapyrus
Src/OSF/xapian/xapian-core/matcher/boolorpostlist.cc
C++
agpl-3.0
6,263
# frozen_string_literal: true require "spec_helper" require "decidim/api/test/type_context" require "decidim/core/test/shared_examples/attachable_interface_examples" module Decidim module Conferences describe ConferenceType, type: :graphql do include_context "with a graphql class type" let(:model) { create(:conference) } include_examples "attachable interface" include_examples "categories container interface" describe "id" do let(:query) { "{ id }" } it "returns the id field" do expect(response).to include("id" => model.id.to_s) end end describe "title" do let(:query) { '{ title { translation(locale: "en")}}' } it "returns the title field" do expect(response["title"]["translation"]).to eq(model.title["en"]) end end describe "slug" do let(:query) { "{ slug }" } it "returns the conference' slug" do expect(response["slug"]).to eq(model.slug) end end describe "shortDescription" do let(:query) { '{ shortDescription { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["shortDescription"]["translation"]).to eq(model.short_description["en"]) end end describe "description" do let(:query) { '{ description { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["description"]["translation"]).to eq(model.description["en"]) end end describe "hashtag" do let(:query) { "{ hashtag }" } it "returns the conference' hashtag" do expect(response["hashtag"]).to eq(model.hashtag) end end describe "slogan" do let(:query) { '{ slogan { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["slogan"]["translation"]).to eq(model.slogan["en"]) end end describe "location" do let(:query) { "{ location }" } it "returns the conference' location" do expect(response["location"]).to eq(model.location) end end describe "createdAt" do let(:query) { "{ createdAt }" } it "returns when the conference was created" do expect(response["createdAt"]).to eq(model.created_at.to_time.iso8601) end end describe "updatedAt" do let(:query) { "{ updatedAt }" } it "returns when the conference was updated" do expect(response["updatedAt"]).to eq(model.updated_at.to_time.iso8601) end end describe "publishedAt" do let(:query) { "{ publishedAt }" } it "returns when the conference was published" do expect(response["publishedAt"]).to eq(model.published_at.to_time.iso8601) end end describe "reference" do let(:query) { "{ reference }" } it "returns the conference' reference" do expect(response["reference"]).to eq(model.reference) end end describe "heroImage" do let(:query) { "{ heroImage }" } it "returns the hero image field" do expect(response["heroImage"]).to eq(model.attached_uploader(:hero_image).path) end end describe "bannerImage" do let(:query) { "{ bannerImage }" } it "returns the banner image field" do expect(response["bannerImage"]).to eq(model.attached_uploader(:banner_image).path) end end describe "promoted" do let(:query) { "{ promoted }" } it "returns the promoted field" do expect(response["promoted"]).to eq(model.promoted) end end describe "objectives" do let(:query) { '{ objectives { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["objectives"]["translation"]).to eq(model.objectives["en"]) end end describe "showStatistics" do let(:query) { " { showStatistics } " } it "returns the showStatistics field" do expect(response["showStatistics"]).to eq(model.show_statistics) end end describe "startDate" do let(:query) { "{ startDate }" } it "returns the start date of the conference " do expect(response["startDate"]).to eq(model.start_date.to_date.iso8601) end end describe "endDate" do let(:query) { "{ endDate }" } it "returns the date the conference ends" do expect(response["endDate"]).to eq(model.end_date.to_date.iso8601) end end describe "registrationsEnabled" do let(:query) { " { registrationsEnabled } " } it "returns the registrationsEnabled field" do expect(response["registrationsEnabled"]).to eq(model.registrations_enabled) end end describe "availableSlots" do let(:query) { " { availableSlots } " } it "returns the availableSlots field" do expect(response["availableSlots"]).to eq(model.available_slots) end end describe "registrationTerms" do let(:query) { '{ registrationTerms { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["registrationTerms"]["translation"]).to eq(model.registration_terms["en"]) end end end end end
decidim/decidim
decidim-conferences/spec/types/conference_type_spec.rb
Ruby
agpl-3.0
5,524
;************************* memcmp64.asm ************************************* ; Author: Agner Fog ; Date created: 2013-10-03 ; Last modified: 2013-10-03 ; Description: ; Faster version of the standard memcmp function: ; ; int A_memcmp (const void * ptr1, const void * ptr2, size_t count); ; ; Compares two memory blocks of size num. ; The return value is zero if the two memory blocks ptr1 and ptr2 are equal ; The return value is positive if the first differing byte of ptr1 is bigger ; than ptr2 when compared as unsigned bytes. ; The return value is negative if the first differing byte of ptr1 is smaller ; than ptr2 when compared as unsigned bytes. ; ; Overriding standard function memcmp: ; The alias ?OVR_memcmp is changed to _memcmp in the object file if ; it is desired to override the standard library function memcmp. ; ; Optimization: ; Uses XMM registers if SSE2 is available, uses YMM registers if AVX2. ; ; The latest version of this file is available at: ; www.agner.org/optimize/asmexamples.zip ; Copyright (c) 2013 GNU General Public License www.gnu.org/licenses ;****************************************************************************** global A_memcmp: function ; Function memcmp global ?OVR_memcmp: function ; ?OVR_ removed if standard function memcmp overridden ; Direct entries to CPU-specific versions global memcmpSSE2: function ; SSE2 version global memcmpAVX2: function ; AVX2 version ; Imported from instrset64.asm extern InstructionSet ; Instruction set for CPU dispatcher default rel ; define registers used for parameters %IFDEF WINDOWS %define par1 rcx ; function parameter 1 %define par2 rdx ; function parameter 2 %define par3 r8 ; function parameter 3 %define par4 r9 ; scratch register %define par4d r9d ; scratch register %ENDIF %IFDEF UNIX %define par1 rdi ; function parameter 1 %define par2 rsi ; function parameter 2 %define par3 rdx ; function parameter 3 %define par4 rcx ; scratch register %define par4d ecx ; scratch register %ENDIF SECTION .text align=16 ; extern "C" int A_memcmp (const void * ptr1, const void * ptr2, size_t count); ; Function entry: A_memcmp: ?OVR_memcmp: jmp qword [memcmpDispatch] ; Go to appropriate version, depending on instruction set align 16 memcmpAVX2: ; AVX2 version. Use ymm register memcmpAVX2@: ; internal reference add par1, par3 ; use negative index from end of memory block add par2, par3 neg par3 jz A900 mov par4d, 0FFFFH cmp par3, -32 ja A100 A000: ; loop comparing 32 bytes vmovdqu ymm1, [par1+par3] vpcmpeqb ymm0, ymm1, [par2+par3] ; compare 32 bytes vpmovmskb eax, ymm0 ; get byte mask xor eax, -1 ; not eax would not set flags jnz A700 ; difference found add par3, 32 jz A900 ; finished, equal cmp par3, -32 jna A000 ; next 32 bytes vzeroupper ; end ymm state A100: ; less than 32 bytes left cmp par3, -16 ja A200 movdqu xmm1, [par1+par3] movdqu xmm2, [par2+par3] pcmpeqb xmm1, xmm2 ; compare 16 bytes pmovmskb eax, xmm1 ; get byte mask xor eax, par4d ; invert lower 16 bits jnz A701 ; difference found add par3, 16 jz A901 ; finished, equal A200: ; less than 16 bytes left cmp par3, -8 ja A300 ; compare 8 bytes movq xmm1, [par1+par3] movq xmm2, [par2+par3] pcmpeqb xmm1, xmm2 ; compare 8 bytes pmovmskb eax, xmm1 ; get byte mask xor eax, par4d jnz A701 ; difference found add par3, 8 jz A901 A300: ; less than 8 bytes left cmp par3, -4 ja A400 ; compare 4 bytes movd xmm1, [par1+par3] movd xmm2, [par2+par3] pcmpeqb xmm1, xmm2 ; compare 4 bytes pmovmskb eax, xmm1 ; get byte mask xor eax, par4d ; not ax jnz A701 ; difference found add par3, 4 jz A901 A400: ; less than 4 bytes left cmp par3, -2 ja A500 movzx eax, word [par1+par3] movzx par4d, word [par2+par3] sub eax, par4d jnz A800 ; difference in byte 0 or 1 add par3, 2 jz A901 A500: ; less than 2 bytes left test par3, par3 jz A901 ; no bytes left A600: ; one byte left movzx eax, byte [par1+par3] movzx par4d, byte [par2+par3] sub eax, par4d ; return result ret A700: ; difference found. find position vzeroupper A701: bsf eax, eax add par3, rax movzx eax, byte [par1+par3] movzx par4d, byte [par2+par3] sub eax, par4d ; return result ret A800: ; difference in byte 0 or 1 neg al sbb par3, -1 ; add 1 to par3 if al == 0 movzx eax, byte [par1+par3] movzx par4d, byte [par2+par3] sub eax, par4d ; return result ret A900: ; equal vzeroupper A901: xor eax, eax ret memcmpSSE2: ; SSE2 version. Use xmm register memcmpSSE2@: ; internal reference add par1, par3 ; use negative index from end of memory block add par2, par3 neg par3 jz S900 mov par4d, 0FFFFH cmp par3, -16 ja S200 S100: ; loop comparing 16 bytes movdqu xmm1, [par1+par3] movdqu xmm2, [par2+par3] pcmpeqb xmm1, xmm2 ; compare 16 bytes pmovmskb eax, xmm1 ; get byte mask xor eax, par4d ; not ax jnz S700 ; difference found add par3, 16 jz S900 ; finished, equal cmp par3, -16 jna S100 ; next 16 bytes S200: ; less than 16 bytes left cmp par3, -8 ja S300 ; compare 8 bytes movq xmm1, [par1+par3] movq xmm2, [par2+par3] pcmpeqb xmm1, xmm2 ; compare 8 bytes pmovmskb eax, xmm1 ; get byte mask xor eax, par4d ; not ax jnz S700 ; difference found add par3, 8 jz S900 S300: ; less than 8 bytes left cmp par3, -4 ja S400 ; compare 4 bytes movd xmm1, [par1+par3] movd xmm2, [par2+par3] pcmpeqb xmm1, xmm2 ; compare 4 bytes pmovmskb eax, xmm1 ; get byte mask xor eax, par4d ; not ax jnz S700 ; difference found add par3, 4 jz S900 S400: ; less than 4 bytes left cmp par3, -2 ja S500 movzx eax, word [par1+par3] movzx par4d, word [par2+par3] sub eax, par4d jnz S800 ; difference in byte 0 or 1 add par3, 2 jz S900 S500: ; less than 2 bytes left test par3, par3 jz S900 ; no bytes left ; one byte left movzx eax, byte [par1+par3] movzx par4d, byte [par2+par3] sub eax, par4d ; return result ret S700: ; difference found. find position bsf eax, eax add par3, rax movzx eax, byte [par1+par3] movzx par4d, byte [par2+par3] sub eax, par4d ; return result ret S800: ; difference in byte 0 or 1 neg al sbb par3, -1 ; add 1 to par3 if al == 0 S820: movzx eax, byte [par1+par3] movzx par4d, byte [par2+par3] sub eax, par4d ; return result ret S900: ; equal xor eax, eax ret ; CPU dispatching for memcmp. This is executed only once memcmpCPUDispatch: push par1 push par2 push par3 call InstructionSet ; get supported instruction set ; SSE2 always supported lea par4, [memcmpSSE2@] cmp eax, 13 ; check AVX2 jb Q100 ; AVX2 supported lea par4, [memcmpAVX2@] Q100: ; save pointer mov qword [memcmpDispatch], par4 ; Continue in appropriate version of memcmp pop par3 pop par2 pop par1 jmp par4 SECTION .data align 16 ; Pointer to appropriate version. ; This initially points to memcmpCPUDispatch. memcmpCPUDispatch will ; change this to the appropriate version of memcmp, so that ; memcmpCPUDispatch is only executed once: memcmpDispatch DQ memcmpCPUDispatch
papyrussolution/OpenPapyrus
Src/OSF/ASMLIB/memcmp64.asm
Assembly
agpl-3.0
10,258
nashal_race_coordinator = Creature:new { objectName = "@event_perk:name_race_droid", socialGroup = "", faction = "", level = 100, chanceHit = 1, damageMin = 645, damageMax = 1000, baseXp = 9429, baseHAM = 24000, baseHAMmax = 30000, armor = 0, resists = {0,0,0,0,0,0,0,0,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = NONE, creatureBitmask = PACK, optionsBitmask = 264, diet = HERBIVORE, templates = {"object/mobile/3po_protocol_droid.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "nashal_conversationtemplate", attacks = { } } CreatureTemplates:addCreatureTemplate(nashal_race_coordinator, "nashal_race_coordinator")
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/mobile/misc/nashalracecoordinator.lua
Lua
agpl-3.0
771
/** * Created by JetBrains PhpStorm. * User: JK * Date: 1/12/12 * Time: 10:04 AM */ (function () { tinymce.create("tinymce.plugins.fixed", { init:function (editor, url) { var color, classes; //get color color = editor.getParam("fixed_content_color", "yellow"); //get classes classes = editor.getParam("noneditable_noneditable_class", "jkNonEditAble"); editor.formatter.register("fixed", {inline:"span", classes:"%classes", styles:{background:"%color"}}) editor.addCommand("mceFixed", function () { editor.formatter.apply("fixed", {color:color, classes:classes}); }); editor.addButton("fixed", { title:"Fixed", image:"modules/images/fixed.png", cmd:"mceFixed" }); }, getInfo:function () { return { longname:'Fixed Content', author:'JK', authorurl:'http://jkaveri.com', infourl:'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/noneditable', version:tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.PluginManager.add("fixed_content", tinymce.plugins.fixed); })();
sysraj86/carnivalcrm
modules/Tours/js/tinymce/plugins/fixed/editor_plugin_src.js
JavaScript
agpl-3.0
1,366
<?php trace(__FILE__,'begin'); set_page_title(lang('project links')); project_tabbed_navigation(PROJECT_TAB_LINKS); project_crumbs(array( array(lang('links'), get_url('links', 'index')), array(lang('index')) )); if (ProjectLink::canAdd(logged_user(), active_project())) { add_page_action(lang('add link'), get_url('links', 'add_link')); } // if add_stylesheet_to_page('project/files.css'); $counter = 0; ?> <div id="files"> <?php if (isset($links) && is_array($links) && count($links)) { ?> <div class="filesList"> <?php foreach ($links as $link) { ?> <?php $counter++; ?> <div class="listedFile <?php echo $counter % 2 ? 'even' : 'odd' ?>"> <div class="fileInfo"> <div class="fileName"><a href="<?php echo $link->asUrl() ?>" title="<?php echo $link->getTitle() ?>" target="_blank"><?php echo $link->getTitle() ?></a></div> <div class="fileDetails"><?php if ($link->getCreatedBy() instanceof User) { ?><span><?php echo lang('created by') ?>:</span> <a href="<?php echo $link->getCreatedBy()->getCardUrl() ?>"><?php echo clean($link->getCreatedBy()->getDisplayName()) ?></a> <?php } ?></div> <?php $options = array(); if ($link->canEdit(logged_user(),active_project())) { $options[] = '<a href="' . $link->getEditUrl() . '">' . lang('edit') . '</a>'; } if ($link->canDelete(logged_user(),active_project())) { $options[] = '<a href="' . $link->getDeleteUrl() . '">' . lang('delete') . '</a>'; } ?> <?php if (count($options)) { ?> <div class="fileOptions"><?php echo implode(' | ', $options) ?></div> <?php } // if ?> </div> </div> <?php } // foreach ?> </div> <?php } else { ?> <p><?php echo lang('no links found') ?></p> <?php } // if ?> </div> <?php trace(__FILE__,'begin'); ?>
dbernar1/Project-Pier-0.8.6
application/plugins/links/views/index.php
PHP
agpl-3.0
1,790
""" Tests for send_email_base_command """ import datetime from unittest import skipUnless import ddt import pytz from django.conf import settings from mock import DEFAULT, Mock, patch from openedx.core.djangoapps.schedules.management.commands import SendEmailBaseCommand from openedx.core.djangoapps.site_configuration.tests.factories import SiteConfigurationFactory, SiteFactory from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms @ddt.ddt @skip_unless_lms @skipUnless('openedx.core.djangoapps.schedules.apps.SchedulesConfig' in settings.INSTALLED_APPS, "Can't test schedules if the app isn't installed") class TestSendEmailBaseCommand(CacheIsolationTestCase): # lint-amnesty, pylint: disable=missing-class-docstring def setUp(self): # lint-amnesty, pylint: disable=super-method-not-called self.command = SendEmailBaseCommand() self.site = SiteFactory() self.site_config = SiteConfigurationFactory.create(site=self.site) def test_handle(self): with patch.object(self.command, 'send_emails') as send_emails: self.command.handle(site_domain_name=self.site.domain, date='2017-09-29') send_emails.assert_called_once_with( self.site, datetime.datetime(2017, 9, 29, tzinfo=pytz.UTC), None ) def test_weeks_option(self): with patch.object(self.command, 'enqueue') as enqueue: self.command.handle(site_domain_name=self.site.domain, date='2017-09-29', weeks=12) assert enqueue.call_count == 12 def test_send_emails(self): with patch.multiple( self.command, offsets=(1, 3, 5), enqueue=DEFAULT, ): arg = Mock(name='arg') kwarg = Mock(name='kwarg') self.command.send_emails(arg, kwarg=kwarg) assert not arg.called assert not kwarg.called for offset in self.command.offsets: self.command.enqueue.assert_any_call(offset, arg, kwarg=kwarg) # lint-amnesty, pylint: disable=no-member
stvstnfrd/edx-platform
openedx/core/djangoapps/schedules/management/commands/tests/test_send_email_base_command.py
Python
agpl-3.0
2,135
/* * Copyright (C) 2000 - 2016 Silverpeas * * 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 (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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/>. */ package org.silverpeas.core.calendar.model; import java.io.Serializable; import org.silverpeas.core.silvertrace.SilverTrace; import org.silverpeas.core.calendar.service.CalendarException; public class Priority implements Serializable, Comparable<Priority> { private static final long serialVersionUID = -5520032042704711631L; public static int[] getAllPriorities() { int[] result = { 0, 1, 2, 3 }; return result; } /** * The minimum allowable priority value. Please note that this refers to the case where no * priority is set. This case happens to be represented by the value 0 which is the lowest integer * value allowable. */ public static final int MINIMUM_PRIORITY = 0; /** * The maximum alloable priority value. Please note that this refers to the highest possible * integer value for priority. When interpreting this value it is seen as the lowest priority * because the value 1 is the highest priority value. */ public static final int MAXIMUM_PRIORITY = 9; private int priority = 2; /** * This is the default constructor. It is used by Castor. You should probably use the constructor * that takes an integer argument in your application code. */ public Priority() { } /** * The purpose of this method is to create a new priority property with the given initial value. * * @param newval The initial value of the priority property * @throws CalendarException */ public Priority(int newval) throws CalendarException { setValue(newval); } /** * The purpose of this method is to set the value of the priority property. * @param newval The new value for the priority property */ public final void setValue(int newval) throws CalendarException { if (newval > MAXIMUM_PRIORITY) { SilverTrace.warn("calendar", "Priority.setValue(int newval)", "calendar_MSG_GREATER_MAXIMUM_PRIORITY", "priority = MAXIMUM_PRIORITY =" + MAXIMUM_PRIORITY); newval = MAXIMUM_PRIORITY; } else if (newval < MINIMUM_PRIORITY) { SilverTrace.warn("calendar", "Priority.setValue(int newval)", "calendar_MSG_LOWER_MINIMUM_PRIORITY", "priority = MINIMUM_PRIORITY =" + MINIMUM_PRIORITY); newval = MINIMUM_PRIORITY; } priority = newval; } public int getValue() { return priority; } @Override public int compareTo(Priority other) { if (other == null) return 1; if (!(other instanceof Priority)) return 0; if ((getValue() == 0) && (other.getValue() != 0)) return -1; if ((getValue() != 0) && (other.getValue() == 0)) return 1; return other.getValue() - getValue(); } }
ebonnet/Silverpeas-Core
core-services/calendar/src/main/java/org/silverpeas/core/calendar/model/Priority.java
Java
agpl-3.0
3,837
#include <sstream> #include "PPEMarkedContent.h" #include "PPTName.h" #include "PPTDictionary.h" // // PPEMarkedContent // /////////////////////////////////////////////////////// PPEMarkedContent::PPEMarkedContent(PPTName *tag, PPTDictionary *property, PPContext *gcontext) : PPElement(gcontext) { _tag = (PPTName *)tag->Copy(); _property = (PPTDictionary *)property->Copy(); } PPEMarkedContent::PPEMarkedContent() { _property = NULL; _tag = NULL; } void PPEMarkedContent::CopyMembersTo(PPBase *obj) { PPElement::CopyMembersTo(obj); PPEMarkedContent *tar_obj = (PPEMarkedContent *)obj; if(_tag) tar_obj->_tag = (PPTName *)_tag->Copy(); if(_property) tar_obj->_property = (PPTDictionary *)_property->Copy(); } void PPEMarkedContent::SetDocument(PPDocument *doc) { if(_property) _property->_document = doc; if(_tag) _tag->_document = doc; } string PPEMarkedContent::MakeCommandString() { string retstr; if (_property) { retstr = _tag->PDFString() + " " + _property->PDFString() + " DP\xa"; } else { retstr = _tag->PDFString() + " MP\xa"; } return retstr; } string PPEMarkedContent::XMLString(int level) { string retstr; ostringstream ostr; ostr << PPTabStr(level) << "<Element type='MarkedContent' tag='" << _tag->_name << "'>" << PP_ENDL; if (_property) { ostr << _property->XMLString(level+1); } ostr << PPTabStr(level) << "</Element>" << PP_ENDL; retstr = ostr.str(); return retstr; }
Neo-Angel/PDFPlus
src/Element/PPEMarkedContent.cpp
C++
agpl-3.0
1,569
(function() { 'use strict'; var DEFAULT_LIST_CONFIG = { 'priority': [ 'priority', 'urgency' ], 'firstLine': [ 'wordcount', 'slugline', 'highlights', 'headline', 'versioncreated' ], 'secondLine': [ 'profile', 'state', 'embargo', 'update', 'takekey', 'takepackage', 'signal', 'broadcast', 'flags', 'updated', 'category', 'provider', 'expiry', 'desk' ] }; /** * Monitoring state - keeps information required to render lists. */ MonitoringState.$inject = ['$q', '$rootScope', 'ingestSources', 'desks', 'highlightsService']; function MonitoringState($q, $rootScope, ingestSources, desks, highlightsService) { this.init = init; this.state = {}; this.setState = setState; this.moveActiveGroup = moveActiveGroup; // reset state on every page change $rootScope.$on('$routeChangeSuccess', reset); var self = this; var ready; /** * Update state * * @param {Object} updates */ function setState(updates) { self.state = angular.extend({}, self.state, updates); } /** * Reset monitoring state */ function reset() { self.state = {}; ready = null; } /** * Init state for react rendering */ function init() { if (!ready) { ready = $q.all({ ingestProvidersById: ingestSources.initialize().then(function() { setState({ingestProvidersById: ingestSources.providersLookup}); }), desksById: desks.initialize().then(function() { setState({desksById: desks.deskLookup}); }), highlightsById: highlightsService.get().then(function(result) { var highlightsById = {}; result._items.forEach(function(item) { highlightsById[item._id] = item; }); setState({highlightsById: highlightsById}); }), // populates cache for mark for highlights activity dropdown deskHighlights: highlightsService.get(desks.getCurrentDeskId()) }); } return ready; } /** * Move active group up/down * * @param {Integer} diff */ function moveActiveGroup(diff) { var groups = self.state.groups; var next = groups.indexOf(self.state.activeGroup) + diff; if (next >= groups.length) { next = 0; } else if (next < 0) { next = groups.length - 1; } setState({activeGroup: groups[next]}); } } angular.module('superdesk.search.react', ['superdesk.highlights', 'superdesk.datetime']) .service('monitoringState', MonitoringState) .directive('sdItemsList', [ '$location', '$timeout', '$injector', '$filter', 'packages', 'asset', 'api', 'search', 'session', 'datetime', 'gettext', 'superdesk', 'workflowService', 'archiveService', 'activityService', 'multi', 'desks', 'familyService', 'Keys', 'dragitem', 'highlightsService', 'monitoringState', 'authoringWorkspace', 'gettextCatalog', '$rootScope', 'config', '$interpolate', function( $location, $timeout, $injector, $filter, packages, asset, api, search, session, datetime, gettext, superdesk, workflowService, archiveService, activityService, multi, desks, familyService, Keys, dragitem, highlightsService, monitoringState, authoringWorkspace, gettextCatalog, $rootScope, config, $interpolate ) { var listConfig = config.list || DEFAULT_LIST_CONFIG; var ItemPriority = function(props) { var priority = props.priority || 3; return React.createElement( 'span', {className: 'priority-label priority-label--' + priority, title: gettext('Priority'), key: 'priority'}, priority ); }; var ItemUrgency = function(props) { var urgency = props.urgency || 3; return React.createElement( 'span', {className: 'urgency-label urgency-label--' + urgency, title: gettextCatalog.getString('Urgency'), key: 'urgency'}, urgency ); }; return { link: function(scope, elem) { elem.attr('tabindex', 0); var menuHolderElem = document.getElementById('react-placeholder'); var closeActionsMenu = function() { ReactDOM.unmountComponentAtNode(menuHolderElem); }; var getViewType = function() { return scope.viewType; }; var groupId = scope.$id; var groups = monitoringState.state.groups || []; monitoringState.setState({ groups: groups.concat(scope.$id), activeGroup: monitoringState.state.activeGroup || groupId }); scope.$watch(function() { return monitoringState.state.activeGroup; }, function(activeGroup) { if (activeGroup === groupId) { elem.focus(); } }); /** * Render element close to target, but append to body * * Used for dropdown menus that would be only partialy visible if rendered * within parent which has overflow: hidden that is required for scrolling * * @param {Object} elem React element * @param {Node} target DOM node */ function renderToBody(elem, target) { // first render it somewhere not visible menuHolderElem.style.zIndex = -1; var node = ReactDOM.findDOMNode(ReactDOM.render(elem, menuHolderElem)); // make sure it's rendered node.style.display = 'block'; var rect = node.getBoundingClientRect(); var width = rect.width; var height = rect.height; var ACTION_MENU_FROM_TOP = 150; // 150 = top-menu + search bar var MENU_MARGIN_HEIGHT = 16; var LEFT_BAR_WIDTH = 48; var BOTTOM_BAR_HEIGHT = 30; var BUFFER = 5; // get target position var targetRect = target.getBoundingClientRect(); // get workspace var workspace = document.getElementById('main-container'); // compute menu position var top = targetRect.top + targetRect.height; var left = targetRect.left + targetRect.width - width; // menu goes off on the right side if (left + width + BUFFER > workspace.clientWidth) { left -= width; left += targetRect.width; } // menu goes off on the left side if (left - LEFT_BAR_WIDTH < 0) { left = targetRect.left; } // menu goes out on the bottom side if (top + height + BOTTOM_BAR_HEIGHT + BUFFER > workspace.clientHeight) { top -= height; top -= targetRect.height; top -= MENU_MARGIN_HEIGHT; top = top < ACTION_MENU_FROM_TOP ? ACTION_MENU_FROM_TOP : top; } node.style.top = top.toFixed() + 'px'; node.style.left = left.toFixed() + 'px'; node.style.position = 'absolute'; menuHolderElem.style.zIndex = 1000; } /** * Test if an item has thumbnail * * @return {Boolean} */ function hasThumbnail(item) { return item.type === 'picture' && item.renditions.thumbnail; } /** * Test if an multi-selection allowed * * @return {Boolean} */ function isCheckAllowed(item) { return !(item.state === 'killed' || (item._type === 'published' && !item.last_published_version)); } /** * Time element */ var TimeElem = function(props) { return React.createElement( 'time', {title: datetime.longFormat(props.date)}, datetime.shortFormat(props.date) ); }; /** * Media Preview - renders item thumbnail */ var MediaPreview = function(props) { var item = props.item; var headline = item.headline || item.slugline || item.type; var preview; if (hasThumbnail(props.item)) { preview = React.createElement( 'img', {src: props.item.renditions.thumbnail.href} ); } return React.createElement( 'div', {className: 'media multi'}, preview ? React.createElement( 'figure', null, preview ) : null, React.createElement( 'span', {className: 'text'}, React.createElement( 'small', {title: headline}, headline.substr(0, 90) ), React.createElement(ItemContainer, {item: item, desk: props.desk}) ), React.createElement(SelectBox, {item: item, onMultiSelect: props.onMultiSelect}) ); }; var SelectBox = React.createClass({ toggle: function(event) { event.stopPropagation(); if (isCheckAllowed(this.props.item)) { var selected = !this.props.item.selected; this.props.onMultiSelect(this.props.item, selected); } }, render: function() { if (this.props.item.selected) { this.props.item.selected = isCheckAllowed(this.props.item); } return React.createElement( 'div', {className: 'selectbox', title: isCheckAllowed(this.props.item) ? null : 'selection not allowed', onClick: this.toggle}, React.createElement( 'span', {className: 'sd-checkbox' + (this.props.item.selected ? ' checked' : '')} ) ); } }); var ItemContainer = function(props) { var item = props.item; var desk = props.desk || null; var label, value; if (item._type !== 'ingest') { if (desk) { label = gettext('desk:'); value = desk.name; } else { if (item._type === 'archive') { label = gettext('location:'); value = gettext('workspace'); } else { if (item._type === 'archived') { label = ''; value = gettext('archived'); } } } } return React.createElement( 'span', {className: 'container', title: value ? label + ' ' + value : null}, React.createElement( 'span', {className: 'location-desk-label'}, label ), value ); }; /** * Media Info - renders item metadata */ var MediaInfo = function(props) { var item = props.item; var meta = []; var source = item.source ? item.source : (props.ingestProvider ? props.ingestProvider.source : ''); if (source) { meta.push( React.createElement('dt', {key: 1}, gettextCatalog.getString('source')), React.createElement('dd', {key: 2, className: 'provider'}, source) ); } meta.push( React.createElement('dt', {key: 3}, gettextCatalog.getString('updated')), React.createElement('dd', {key: 4}, datetime.shortFormat(item.versioncreated)) ); if (item.is_spiked) { meta.push(React.createElement('dt', {key: 5}, gettextCatalog.getString('expires'))); meta.push(React.createElement('dd', {key: 6}, datetime.shortFormat(item.expiry))); } var info = []; var flags = item.flags || {}; info.push(React.createElement( 'h5', {key: 1}, item.headline || item.slugline || item.type )); info.push(React.createElement( 'dl', {key: 2}, meta )); if (flags.marked_for_legal) { info.push(React.createElement( 'div', {key: 3, className: 'state-label legal'}, gettext('Legal') )); } if (item.archived) { info.push(React.createElement( 'div', {className: 'fetched-desk', key: 4}, React.createElement(FetchedDesksInfo, {item: item}) )); } return React.createElement('div', {className: 'media-info'}, info); }; /** * Type icon component */ var TypeIcon = function(props) { if (props.package_type) { return React.createElement('i', {className: 'filetype-icon-takes-pack'}); } else if (props.type === 'composite' && props.highlight) { return React.createElement('i', {className: 'filetype-icon-highlight-pack'}); } else { return React.createElement('i', {className: 'filetype-icon-' + props.type}); } }; var GridTypeIcon = function(props) { return React.createElement( 'span', {className: 'type-icon'}, React.createElement(TypeIcon, {type: props.item.type}) ); }; var ListTypeIcon = React.createClass({ getInitialState: function() { return {hover: false}; }, setHover: function() { this.setState({hover: true}); }, unsetHover: function() { if (this.state.hover) { this.setState({hover: false}); } }, render: function() { var showSelect = this.state.hover || this.props.item.selected; return React.createElement( 'div', {className: 'list-field type-icon', onMouseEnter: this.setHover, onMouseLeave: this.unsetHover}, showSelect ? React.createElement(SelectBox, {item: this.props.item, onMultiSelect: this.props.onMultiSelect}) : React.createElement( TypeIcon, {type: this.props.item.type, package_type: this.props.item.package_type, highlight: this.props.item.highlight} ) ); } }); var ListPriority = function(props) { var css = {className: 'list-field urgency'}; return renderArea('priority', props, css) || React.createElement('div', css); }; var HighlightsList = React.createClass({ removeHighlight: function(highlight) { return function(event) { event.stopPropagation(); highlightsService.markItem(highlight._id, this.props.item); if (getViewType() === 'highlights' && this.props.item.highlights.length === 1) { $rootScope.$broadcast('multi:remove', this.props.item._id); } }.bind(this); }, componentDidMount: function() { this.timeout = null; }, componentWillUnmount: function() { this.stopTimeout(); }, stopTimeout: function() { this.timeout = $timeout.cancel(this.timeout); }, close: function() { this.timeout = $timeout(closeActionsMenu, 2000, false); }, render: function() { var highlights = this.props.highlights; var highlightsById = this.props.highlightsById || {}; var createHighlight = function(id) { var highlight = highlightsById[id]; if (highlight) { return React.createElement( 'li', {key: 'item-highlight-' + highlight._id}, highlight.name, highlightsService.hasMarkItemPrivilege() ? React.createElement( 'button', {className: 'btn btn-mini', onClick: this.removeHighlight(highlight)}, gettext('REMOVE') ):null ); } }.bind(this); var items = [ React.createElement( 'li', {key: 'item-highlight-label'}, React.createElement( 'div', {className: 'menu-label'}, gettext('Marked For') ) ) ]; return React.createElement( 'ul', { className: 'dropdown dropdown-menu highlights-list-menu open', onMouseEnter: this.stopTimeout, onMouseLeave: this.close }, items.concat(highlights.map(createHighlight)) ); } }); var HighlightsInfo = React.createClass({ toggle: function(event) { if (event) { event.stopPropagation(); } closeActionsMenu(); this.renderDropdown(); }, /** * Checks if the given item is in the daterange of the highlights * for every highlight given * * @param {array} highlights * @param {Object} item * @return {Object} */ getHighlightStatuses: function(highlights, item) { var highlightStatuses = {}; var highlightsById = this.props.highlightsById; _.forEach(highlights, function(highlight) { var hours = $filter('hoursFromNow')(item.versioncreated); highlightStatuses[highlight] = highlightsService.isInDateRange(highlightsById[highlight], hours); }); return highlightStatuses; }, getHighlights: function() { var itemHighlights = []; if (isCheckAllowed(this.props.item)) { if (this.props.item.archive_item && this.props.item.archive_item.highlights && this.props.item.archive_item.highlights.length) { itemHighlights = this.props.item.archive_item.highlights; } else { itemHighlights = this.props.item.highlights || []; } } return itemHighlights; }, render: function() { var highlights = this.getHighlights(); var hasActiveHighlight = (function() { var statuses = this.getHighlightStatuses(highlights, this.props.item); if ($location.path() === '/workspace/highlights') { return statuses[$location.search().highlight]; } return highlights.some(function(h) { return statuses[h]; }); }).call(this); return React.createElement( 'div', { className: 'highlights-box', onClick: this.toggle }, highlights.length ? React.createElement( 'div', {className: 'highlights-list dropdown'}, React.createElement( 'button', {className: 'dropdown-toggle'}, React.createElement('i', { className: classNames({ 'icon-star': highlights.length === 1, 'icon-multi-star': highlights.length > 1, 'red': hasActiveHighlight }) }) ) ) : null ); }, renderDropdown: function() { var elem = React.createElement(HighlightsList, { item: this.props.item, highlights: this.getHighlights(), highlightsById: this.props.highlightsById }); var icon = ReactDOM.findDOMNode(this).getElementsByClassName('icon-star')[0] || ReactDOM.findDOMNode(this).getElementsByClassName('icon-multi-star')[0]; renderToBody(elem, icon); } }); var DesksDropdown = React.createClass({ getInitialState: function() { return {open: false}; }, toggle: function(event) { event.stopPropagation(); this.setState({open: !this.state.open}); }, render: function() { var desks = this.props.desks.map(function(desk, index) { return React.createElement( 'li', {key: 'desk' + index}, React.createElement( 'a', {disabled: !desk.isUserDeskMember, onClick: this.props.openDesk(desk)}, desk.desk.name + ' (' + desk.count + ')' ) ); }.bind(this)); return React.createElement( 'dd', {className: 'dropdown dropup more-actions'}, React.createElement( 'button', {className: 'dropdown-toggle', onClick: this.toggle}, React.createElement('i', {className: 'icon-dots'}) ), React.createElement( 'div', {className: 'dropdown-menu'}, React.createElement('ul', {}, desks) ) ); } }); var FetchedDesksInfo = React.createClass({ getInitialState: function() { return {desks: []}; }, componentDidMount: function() { familyService.fetchDesks(this.props.item, false) .then(function(fetchedDesks) { this.setState({desks: fetchedDesks}); }.bind(this)); }, componentDidUpdate: function(prevProps, prevState) { if (prevProps.item !== this.props.item) { familyService.fetchDesks(this.props.item, false) .then(function(fetchedDesks) { this.setState({desks: fetchedDesks}); }.bind(this)); } }, formatDeskName: function(name) { return name.substr(0, 10) + (name.length > 10 ? '...' : ''); }, openDesk: function(desk) { return function(event) { event.stopPropagation(); if (desk.isUserDeskMember) { desks.setCurrentDeskId(desk.desk._id); $location.url('/workspace/monitoring'); if (desk.count === 1) { superdesk.intent('edit', 'item', desk.item); } } }; }, render: function() { var items = []; items.push(React.createElement('dt', {key: 'dt', style: {paddingRight:'5px'}}, gettext('fetched in'))); if (this.state.desks.length) { var desk = this.state.desks[0]; var name = this.formatDeskName(desk.desk.name); items.push(React.createElement('dd', {key: 'dd1'}, desk.isUserDeskMember ? React.createElement('a', {onClick: this.openDesk(desk)}, name) : React.createElement('span', {className: 'container'}, name) )); if (this.state.desks.length > 1) { items.push(React.createElement(DesksDropdown, { key: 'dd2', desks: this.state.desks, openDesk: this.openDesk })); } } return React.createElement('div', {}, React.createElement( 'dl', {}, items ) ); } }); var ListItemInfo = function(props) { return React.createElement( 'div', {className: 'item-info'}, renderArea('firstLine', props, {className: 'line'}), renderArea('secondLine', props, {className: 'line'}) ); }; function renderArea(area, itemProps, props) { var specs = listConfig[area] || []; var contents = specs.map(function(field) { if (fields[field]) { return fields[field](itemProps); } else { console.warn('missing field in list: ' + field); } }).filter(angular.identity); var elemProps = angular.extend({key: area}, props); return contents.length ? React.createElement('div', elemProps, contents) : null; } /** * Fields specified via list config */ var fields = { headline: function(props) { return React.createElement( 'span', {className: 'item-heading', key: 'headline'}, props.item.headline ? props.item.headline.substr(0, 90) : props.item.type ); }, slugline: function(props) { if (props.item.slugline) { return React.createElement( 'span', {className: 'keyword', key: 'slugline'}, props.item.slugline.substr(0, 40) ); } }, wordcount: function(props) { return React.createElement( 'span', {className: 'word-count', key: 'wordcount'}, props.item.word_count ); }, highlights: function(props) { return React.createElement(HighlightsInfo, angular.extend({key: 'highlights'}, props)); }, versioncreated: function(props) { return React.createElement( TimeElem, {date: props.item.versioncreated, key: 'versioncreated'} ); }, profile: function(props) { if (props.item.profile) { return React.createElement( 'div', {className: 'label label--' + props.item.profile, key: 'profile'}, props.item.profile ); } }, state: function(props) { return React.createElement( 'span', { title: $filter('removeLodash')(props.item.state), className: 'state-label state-' + props.item.state, key: 'state' }, $filter('removeLodash')(gettextCatalog.getString(props.item.state)) ); }, embargo: function(props) { if (props.item.embargo) { return React.createElement( 'span', {className: 'state-label state_embargo', title: gettext('embargo'), key: 'embargo'}, gettext('embargo') ); } }, update: function(props) { if (props.item.correction_sequence) { return React.createElement( 'div', {className: 'provider', key: 'update'}, $interpolate(gettext('Update {{ seq }}'))({seq: props.item.correction_sequence}) ); } }, updated: function(props) { var selectUpdate = function(event) { event.stopPropagation(); props.selectUpdate(); }; if (props.item.rewritten_by) { return React.createElement( 'div', {className: 'state-label updated', key: 'updated', onClick: selectUpdate}, gettext('Updated') ); } }, takekey: function(props) { if (props.item.anpa_take_key) { return React.createElement('div', {className: 'takekey', key: 'takekey'}, props.item.anpa_take_key); } }, signal: function(props) { if (props.item.signal) { return React.createElement('span', {className: 'signal', key: 'signal'}, props.item.signal); } }, broadcast: function(props) { var broadcast = props.item.broadcast || {}; if (broadcast.status) { return React.createElement( 'span', {className: 'broadcast-status', title: broadcast.status, key: 'broadcast'}, '!' ); } }, flags: function(props) { var flags = props.item.flags || {}; var elems = [ flags.marked_for_not_publication ? React.createElement( 'div', { className: 'state-label not-for-publication', title: gettext('Not For Publications'), key: 'not-for-publication' }, gettext('Not For Publications')) : null, flags.marked_for_legal ? React.createElement( 'div', { className: 'state-label legal', title: gettext('Legal'), key: 'legal' }, gettext('Legal')) : null, flags.marked_for_sms ? React.createElement( 'div', { className: 'state-label sms', key: 'sms'}, gettext('Sms')) : null ].filter(angular.identity); return elems.length ? React.createElement('div', {key: 'flags'}, elems) : null; }, takepackage: function(props) { var item = props.item; var isTake = _.contains(['text'], item.type) && item.takes && item.takes.sequence > 1; var selectTakesPackage = function(event) { event.stopPropagation(); props.selectTakesPackage(); }; if (isTake) { return React.createElement( 'div', {className: 'state-label takes', onClick: selectTakesPackage, key: 'takepackage'}, gettext('Takes') ); } }, category: function(props) { var anpa = props.item.anpa_category || {}; if (anpa.name) { return React.createElement('div', {className: 'category', key: 'category'}, anpa.name); } }, provider: function(props) { var provider = props.item.source ? props.item.source : (props.ingestProvider ? props.ingestProvider.source : ''); if (provider) { return React.createElement('span', {className: 'provider', key: 'provider'}, provider); } }, expiry: function(props) { if (props.item.is_spiked) { return React.createElement( 'div', {className: 'expires', key: 'expiry'}, gettext('expires') + ' ' + datetime.shortFormat(props.item.expiry) ); } }, desk: function(props) { if (props.item.archived) { return React.createElement(FetchedDesksInfo, {item: props.item, key: 'desk'}); } else { return React.createElement(ItemContainer, {item: props.item, desk: props.desk, key: 'desk'}); } }, priority: function(props) { return props.item.priority ? React.createElement(ItemPriority, angular.extend({key: 'priority'}, props.item)) : null; }, urgency: function(props) { return props.item.urgency ? React.createElement(ItemUrgency, angular.extend({key: 'urgency'}, props.item)) : null; } }; var ActionsMenu = React.createClass({ toggle: function(event) { this.stopEvent(event); closeActionsMenu(); var icon = ReactDOM.findDOMNode(this) .getElementsByClassName('icon-dots-vertical')[0]; renderToBody(this.renderMenu(), icon); }, stopEvent: function(event) { event.stopPropagation(); }, getActions: function() { var item = this.props.item; var type = this.getType(); var intent = {action: 'list', type: type}; var groups = {}; superdesk.findActivities(intent, item).forEach(function(activity) { if (workflowService.isActionAllowed(item, activity.action)) { var group = activity.group || 'default'; groups[group] = groups[group] || []; groups[group].push(activity); } }); return groups; }, getType: function() { return archiveService.getType(this.props.item); }, groups: [ {_id: 'default', label: gettext('Actions')}, {_id: 'packaging', label: gettext('Packaging')}, {_id: 'highlights', label: gettext('Highlights')}, {_id: 'corrections', label: gettext('Corrections')} ], renderMenu: function() { var menu = []; var item = this.props.item; var createAction = function(activity) { return React.createElement(ActionsMenu.Item, { item: item, activity: activity, key: activity._id }); }.bind(this); var actions = this.getActions(); this.groups.map(function(group) { if (actions[group._id]) { menu.push( React.createElement(ActionsMenu.Label, { label: group.label, key: 'group-label-' + group._id }), React.createElement(ActionsMenu.Divider, { key: 'group-divider-' + group._id }) ); menu.push.apply(menu, actions[group._id].map(createAction)); } }); return React.createElement( 'ul', { className: 'dropdown dropdown-menu more-activity-menu open', style: {display: 'block', minWidth: 200} }, menu ); }, render: function() { return React.createElement( 'div', {className: 'item-right toolbox'}, React.createElement( 'div', {className: 'item-actions-menu dropdown-big open'}, React.createElement( 'button', { className: 'more-activity-toggle condensed dropdown-toggle', onClick: this.toggle, onDoubleClick: this.stopEvent }, React.createElement('i', {className: 'icon-dots-vertical'}) ) ) ); } }); ActionsMenu.Label = function(props) { return React.createElement( 'li', null, React.createElement('div', {className: 'menu-label'}, gettextCatalog.getString(props.label)) ); }; ActionsMenu.Divider = function() { return React.createElement('li', {className: 'divider'}); }; ActionsMenu.Item = React.createClass({ run: function(event) { // Stop event propagation so that click on item action // won't select that item for preview/authoring. event.stopPropagation(); scope.$apply(function() { activityService.start(this.props.activity, {data: {item: this.props.item}}); }.bind(this)); closeActionsMenu(); }, getInitialState: function() { return {open: false}; }, open: function() { $timeout.cancel(this.closeTimeout); this.closeTimeout = null; if (!this.state.open) { this.setState({open: true}); } }, close: function() { if (this.state.open && !this.closeTimeout) { this.closeTimeout = $timeout(function() { this.closeTimeout = null; this.setState({open: false}); }.bind(this), 100, false); } }, closeMenu: function(event) { // called by the onclick event of the submenu dropdown to close actions menu. event.stopPropagation(); closeActionsMenu(); }, componentWillUnmount: function() { $timeout.cancel(this.closeTimeout); this.closeTimeout = null; }, render: function() { var activity = this.props.activity; if (activity.dropdown) { return React.createElement( 'li', {onMouseEnter: this.open, onMouseLeave: this.close, onClick: this.closeMenu}, React.createElement( 'div', {className: 'dropdown dropdown-noarrow' + (this.state.open ? ' open' : '')}, React.createElement( 'a', {className: 'dropdown-toggle', title: gettextCatalog.getString(activity.label)}, activity.icon ? React.createElement('i', {className: 'icon-' + activity.icon}, '') : null, gettextCatalog.getString(activity.label), React.createElement('i', {className: 'icon-chevron-right-thin submenu-icon'}) ), this.state.open ? $injector.invoke(activity.dropdown, activity, { item: this.props.item, className: 'dropdown-menu right-submenu upward', translatedLabel: gettextCatalog.getString('No available highlights') }) : null ) ); } else { return React.createElement( 'li', null, React.createElement( 'a', {title: gettextCatalog.getString(activity.label), onClick: this.run}, React.createElement('i', {className: 'icon-' + activity.icon}), React.createElement('span', {style: {display: 'inline'}}, gettextCatalog.getString(activity.label)) ) ); } } }); var ProgressBar = function(props) { return React.createElement('div', {className: 'archiving-progress', style: {width: props.completed + '%'}}); }; var ErrorBox = function(props) { return React.createElement('div', {className: 'error-box'}, React.createElement('p', {className: 'message'}, gettextCatalog.getString('There was an error archiving this item')), React.createElement('div', {className: 'buttons'}) ); }; /** * Item component */ var Item = React.createClass({ shouldComponentUpdate: function(nextProps, nextState) { return nextProps.item !== this.props.item || nextProps.view !== this.props.view || nextProps.flags.selected !== this.props.flags.selected || nextState !== this.state; }, select: function() { this.props.onSelect(this.props.item); }, selectTakesPackage: function() { this.props.onSelect(this.props.item.takes); }, selectUpdate: function() { authoringWorkspace.edit({_id: this.props.item.rewritten_by}, 'view'); }, edit: function(event) { authoringWorkspace.open(this.props.item); }, getInitialState: function() { return {hover: false}; }, setHoverState: function() { this.setState({hover: true}); }, unsetHoverState: function() { this.setState({hover: false}); }, onDragStart: function(event) { dragitem.start(event, this.props.item); }, componentDidUpdate: function() { if (this.props.flags.selected) { var elem = ReactDOM.findDOMNode(this); var list = elem.offsetParent; var factor = this.props.view === 'mgrid' ? 1 : 3; if (elem.offsetTop < list.scrollTop) { // move up if (list.scrollTop - elem.offsetTop <= elem.clientHeight) { // only a bit list.scrollTop -= elem.clientHeight * factor; } else { // we need more, put it on top list.scrollTop = elem.offsetTop; } } if (elem.offsetTop + elem.offsetHeight > list.scrollTop + list.clientHeight) { // move down if (elem.offsetTop + elem.offsetHeight - list.scrollTop - list.clientHeight <= elem.clientHeight) { // only a bit list.scrollTop += elem.clientHeight * factor; } else { // put it on top list.scrollTop = elem.offsetTop; } } } }, render: function() { var item = this.props.item; var contents = [ 'div', { className: classNames( 'media-box', 'media-' + item.type, { locked: item.lock_user && item.lock_session, selected: this.props.flags.selected, archived: item.archived || item.created } ) } ]; if (item._progress) { contents.push(React.createElement(ProgressBar, {completed: item._progress})); } if (this.props.view === 'mgrid') { contents.push( item.archiveError ? React.createElement(ErrorBox) : null, React.createElement(MediaPreview, { item: item, desk: this.props.desk, onMultiSelect: this.props.onMultiSelect }), React.createElement(MediaInfo, {item: item, ingestProvider: this.props.ingestProvider}), React.createElement(GridTypeIcon, {item: item}), item.priority ? React.createElement(ItemPriority, item) : null, item.urgency ? React.createElement(ItemUrgency, item) : null, fields.broadcast({item: item}), this.state.hover ? React.createElement(ActionsMenu, {item: item}) : null ); } else { contents.push( React.createElement('span', {className: 'state-border'}), React.createElement(ListTypeIcon, { item: item, onMultiSelect: this.props.onMultiSelect }), (item.priority || item.urgency) ? React.createElement(ListPriority, {item: item}) : null, React.createElement(ListItemInfo, { item: item, selectTakesPackage: this.selectTakesPackage, selectUpdate: this.selectUpdate, desk: this.props.desk, ingestProvider: this.props.ingestProvider, highlightsById: this.props.highlightsById }), this.state.hover ? React.createElement(ActionsMenu, {item: item}) : null ); } return React.createElement( 'li', { id: item._id, key: item._id, className: classNames('list-item-view', {active: this.props.flags.selected}), onMouseEnter: this.setHoverState, onMouseLeave: this.unsetHoverState, onDragStart: this.onDragStart, onClick: this.select, onDoubleClick: this.edit, draggable: true, tabIndex: '0' }, React.createElement.apply(null, contents) ); } }); /** * Item list component */ var ItemList = React.createClass({ getInitialState: function() { return {itemsList: [], itemsById: {}, selected: null, view: 'mgrid'}; }, multiSelect: function(item, selected) { var itemId = search.generateTrackByIdentifier(item); var itemsById = angular.extend({}, this.state.itemsById); itemsById[itemId] = angular.extend({}, item, {selected: selected}); this.setState({itemsById: itemsById}); scope.$applyAsync(function() { multi.toggle(itemsById[itemId]); }); }, select: function(item) { this.setSelectedItem(item); $timeout.cancel(this.updateTimeout); this.updateTimeout = $timeout(function() { if (item && scope.preview) { scope.$apply(function() { scope.preview(item); }); } }, 200, false); }, edit: function(item) { this.setSelectedItem(item); $timeout.cancel(this.updateTimeout); if (item && scope.edit) { scope.$apply(function() { scope.edit(item); }); } else if (item) { scope.$apply(function() { authoringWorkspace.open(item); }); } }, updateAllItems: function(itemId, changes) { var itemsById = angular.extend({}, this.state.itemsById); _.forOwn(itemsById, function(value, key) { if (_.startsWith(key, itemId)) { itemsById[key] = angular.extend({}, value, changes); } }); this.setState({itemsById: itemsById}); }, findItemByPrefix: function(prefix) { var item; _.forOwn(this.state.itemsById, function(val, key) { if (_.startsWith(key, prefix)) { item = val; } }); return item; }, setSelectedItem: function(item) { this.setState({selected: item ? search.generateTrackByIdentifier(item) : null}); }, getSelectedItem: function() { var selected = this.state.selected; return this.state.itemsById[selected]; }, updateItem: function(itemId, changes) { var item = this.state.itemsById[itemId] || null; if (item) { var itemsById = angular.extend({}, this.state.itemsById); itemsById[itemId] = angular.extend({}, item, changes); this.setState({itemsById: itemsById}); } }, handleKey: function(event) { var diff; switch (event.keyCode) { case Keys.right: case Keys.down: diff = 1; break; case Keys.left: case Keys.up: diff = -1; break; case Keys.enter: if (this.state.selected) { this.edit(this.getSelectedItem()); } event.stopPropagation(); return; case Keys.pageup: case Keys.pagedown: event.preventDefault(); event.stopPropagation(); this.select(); // deselect active item scope.$applyAsync(function() { monitoringState.moveActiveGroup(event.keyCode === Keys.pageup ? -1 : 1); }); return; } if (diff != null) { event.preventDefault(); event.stopPropagation(); if (this.state.selected) { for (var i = 0; i < this.state.itemsList.length; i++) { if (this.state.itemsList[i] === this.state.selected) { var next = Math.min(this.state.itemsList.length - 1, Math.max(0, i + diff)); this.select(this.state.itemsById[this.state.itemsList[next]]); return; } } } else { this.select(this.state.itemsById[this.state.itemsList[0]]); } } }, closeActionsMenu: closeActionsMenu, componentWillUnmount: function() { this.closeActionsMenu(); }, componentWillUpdate: function() { this.closeActionsMenu(); }, render: function render() { var createItem = function createItem(itemId) { var item = this.state.itemsById[itemId]; var task = item.task || {desk: null}; return React.createElement(Item, { key: itemId, item: item, view: this.state.view, flags: {selected: this.state.selected === itemId}, onEdit: this.edit, onSelect: this.select, onMultiSelect: this.multiSelect, ingestProvider: this.props.ingestProvidersById[item.ingest_provider] || null, desk: this.props.desksById[task.desk] || null, highlightsById: this.props.highlightsById }); }.bind(this); var isEmpty = !this.state.itemsList.length; return React.createElement( 'ul', { className: classNames( 'list-view', this.state.view + '-view', {'list-without-items': isEmpty} ), onClick: this.closeActionsMenu, }, isEmpty && !scope.loading ? React.createElement( 'li', {onClick: this.closeActionsMenu}, gettextCatalog.getString('There are currently no items') ) : this.state.itemsList.map(createItem) ); } }); monitoringState.init().then(function() { var itemList = React.createElement(ItemList, monitoringState.state); var listComponent = ReactDOM.render(itemList, elem[0]); /** * Test if item a equals to item b * * @param {Object} a * @param {Object} b * @return {Boolean} */ function isSameVersion(a, b) { return a._etag === b._etag && a._current_version === b._current_version && a._updated === b._updated; } /** * Test if archive_item of a equals to archive_item of b * * @param {Object} a * @param {Object} b * @return {Boolean} */ function isArchiveItemSameVersion(a, b) { if (!a.archive_item && !b.archive_item) { return true; } if (a.archive_item && b.archive_item) { if (b.archive_item.takes) { return false; //take package of the new item might have changed } return (a.archive_item._current_version === b.archive_item._current_version && a.archive_item._updated === b.archive_item._updated); } return false; } scope.$watch('items', function(items) { if (!items) { return; } var itemsList = []; var currentItems = {}; var itemsById = angular.extend({}, listComponent.state.itemsById); items._items.forEach(function(item) { var itemId = search.generateTrackByIdentifier(item); var oldItem = itemsById[itemId] || null; if (!oldItem || !isSameVersion(oldItem, item) || !isArchiveItemSameVersion(oldItem, item)) { itemsById[itemId] = angular.extend({}, oldItem, item); } if (!currentItems[itemId]) { // filter out possible duplicates currentItems[itemId] = true; itemsList.push(itemId); } }); listComponent.setState({ itemsList: itemsList, itemsById: itemsById, view: scope.view }, function() { scope.rendering = scope.loading = false; }); }); scope.$watch('view', function(newValue, oldValue) { if (newValue !== oldValue) { listComponent.setState({view: newValue}); } }); scope.$on('item:lock', function(_e, data) { var itemId = search.getTrackByIdentifier(data.item, data.item_version); listComponent.updateItem(itemId, { lock_user: data.user, lock_session: data.lock_session, lock_time: data.lock_time }); }); scope.$on('item:unlock', function(_e, data) { listComponent.updateAllItems(data.item, { lock_user: null, lock_session: null, lock_time: null }); }); scope.$on('item:highlight', function(_e, data) { var item = listComponent.findItemByPrefix(data.item_id); if (item) { var itemId = search.generateTrackByIdentifier(item); var highlights = item.highlights || []; if (data.marked) { highlights = highlights.concat([data.highlight_id]); } else { highlights = highlights.filter(function(highlight) { return highlight !== data.highlight_id; }); } listComponent.updateItem(itemId, {highlights: highlights}); } }); scope.$on('multi:reset', function(e, data) { var ids = data.ids || []; var shouldUpdate = false; var itemsById = angular.extend({}, listComponent.state.itemsById); _.forOwn(itemsById, function(value, key) { ids.forEach(function(id) { if (_.startsWith(key, id)) { shouldUpdate = true; itemsById[key] = angular.extend({}, value, {selected: null}); } }); }); if (shouldUpdate) { listComponent.setState({itemsById: itemsById}); } }); var updateTimeout; /** * Function for creating small delay, * before activating render function */ function handleScroll($event) { if (scope.rendering) { // ignore $event.preventDefault(); return; } // only scroll the list, not its parent $event.stopPropagation(); listComponent.closeActionsMenu(); $timeout.cancel(updateTimeout); updateTimeout = $timeout(renderIfNeeded, 100, false); } /** * Trigger render in case user scrolls to the very end of list */ function renderIfNeeded() { if (!scope.items) { return; // automatic scroll after removing items } if (isListEnd(elem[0]) && !scope.rendering) { scope.rendering = scope.loading = true; scope.fetchNext(listComponent.state.itemsList.length); } } /** * Check if we reached end of the list elem * * @param {Element} elem * @return {Boolean} */ function isListEnd(elem) { return elem.scrollTop + elem.offsetHeight + 200 >= elem.scrollHeight; } elem.on('keydown', listComponent.handleKey); elem.on('scroll', handleScroll); // remove react elem on destroy scope.$on('$destroy', function() { elem.off(); ReactDOM.unmountComponentAtNode(elem[0]); }); }); } }; }]); })();
vladnicoara/superdesk-client-core
scripts/superdesk-search/react.js
JavaScript
agpl-3.0
81,717
require "rails_helper" RSpec.describe BulkImportWorker, type: :job do let(:subject) { BulkImportWorker } let(:instance) { subject.new } let(:bulk_import) { FactoryBot.create(:bulk_import, progress: "pending", kind: kind) } let(:kind) { nil } let!(:black) { FactoryBot.create(:color, name: "Black") } # Because we use it as a default color let(:sample_csv_lines) do [ %w[manufacturer model year color owner_email serial_number], ["Trek", "Roscoe 8", "2019", "Green", "test@bikeindex.org", "xyz_test"], ["Surly", "Midnight Special", "2018", "White", "test2@bikeindex.org", "example"] ] end let(:sample_csv_impounded_lines) do [ %w[manufacturer model year color serial_number impounded_at impounded_street impounded_city impounded_state impounded_zipcode impounded_country impounded_id], ["Thesis", "OB1", "2020", "Pink", "xyz_test", "2021-02-04", "1409 Martin Luther King Jr Way", "Berkeley", "CA", "94710", "US", "ddd33333"], ["Salsa", "Warbird", "2021", "Purple", "example", Time.current.to_i, "327 17th St", "Oakland", "CA", "94612", ""] ] end # Only handling organization_import and impounded for now, Fuck it let(:csv_lines) { kind == "impounded" ? sample_csv_impounded_lines : sample_csv_lines } let(:csv_string) { csv_lines.map { |r| r.join(",") }.join("\n") } let(:tempfile) do file = Tempfile.new file.write(csv_lines.join("\n")) file.rewind file end describe "perform" do context "bulk import already processed" do let(:bulk_import) { FactoryBot.create(:bulk_import, progress: "finished") } it "returns true" do allow_any_instance_of(BulkImport).to receive(:open_file) { csv_string } expect(instance).to_not receive(:register_bike) instance.perform(bulk_import.id) end end context "bulk import ascend no org" do let(:bulk_import) { FactoryBot.create(:bulk_import_ascend) } it "returns enqueues email, returns true" do Sidekiq::Worker.clear_all bulk_import.reload expect(bulk_import.import_errors?).to be_falsey expect(instance).to_not receive(:register_bike) expect { instance.perform(bulk_import.id) }.to change(UnknownOrganizationForAscendImportWorker.jobs, :count).by 1 bulk_import.reload expect(bulk_import.pending?).to be_truthy expect(bulk_import.import_errors?).to be_truthy expect(UnknownOrganizationForAscendImportWorker.jobs.map { |j| j["args"] }.flatten).to eq([bulk_import.id]) end end context "erroring" do let!(:color) { FactoryBot.create(:color, name: "White") } after { tempfile.close && tempfile.unlink } def bike_matches_target(bike) expect(bike.manufacturer).to eq Manufacturer.other expect(bike.manufacturer_other).to eq "Surly" expect(bike.primary_frame_color).to eq color expect(bike.frame_size).to eq "19in" expect(bike.serial_number).to eq "ZZZZ" expect(bike.owner_email).to eq "test2@bikeindex.org" expect(bike.description).to eq "Midnight Special" end context "valid bike and an invalid bike with substituted header" do let(:target_line_error) { [2, ["Owner email can't be blank"]] } let(:csv_lines) do [ "Product Description,Vendor,Brand,Color,Size,Serial Number,Customer Last Name,Customer First Name,Customer Email", '"Blah","Blah","Surly","","","XXXXX","","",""', '"Midnight Special","","Surly","White","19","ZZZZ","","","test2@bikeindex.org"' ] end it "registers bike, adds row that is an error" do allow_any_instance_of(BulkImport).to receive(:open_file) { File.open(tempfile.path, "r") } expect { instance.perform(bulk_import.id) }.to change(Bike, :count).by 1 bulk_import.reload expect(bulk_import.line_import_errors).to eq([target_line_error]) expect(bulk_import.headers).to eq(%w[description vendor manufacturer color frame_size serial_number customer_last_name customer_first_name owner_email]) expect(bulk_import.import_errors).to eq({line: [target_line_error]}.as_json) expect(bulk_import.bikes.count).to eq 1 expect(BulkImport.line_errors.pluck(:id)).to eq([bulk_import.id]) end end context "invalid file" do let(:csv_lines) do [ "Product Description,Vendor,Brand,Color,Size,Serial Number,Customer Last Name,Customer First Name,Customer Email", '"\"","\'","Surly","","","XXXXX","","","","', '"Midnight Special","","Surly","White","19","ZZZZ","","","test2@bikeindex.org"' ] end it "stores error line, resumes post errored line successfully" do allow_any_instance_of(BulkImport).to receive(:open_file) { File.open(tempfile.path, "r") } # It should throw an error and not create a bike expect { expect { instance.perform(bulk_import.id) }.to raise_error(CSV::MalformedCSVError) }.to change(Bike, :count).by 0 bulk_import.reload expect(bulk_import.progress).to eq "finished" expect(bulk_import.line_import_errors).to be_nil expect(bulk_import.file_import_errors_with_lines).to eq([["Any value after quoted field isn't allowed in line 1.", 1]]) # Note: we don't have auto-resume built in right now. You have to manually go in through the console # and set the progress to be "ongoing", then re-enqueue bulk_import.update_attribute :progress, "ongoing" expect { instance.perform(bulk_import.id) }.to change(Bike, :count).by 1 bulk_import.reload expect(bulk_import.bikes.count).to eq 1 bike_matches_target(bulk_import.bikes.first) # And make sure it hasn't updated the file_import_errors expect(bulk_import.file_import_errors_with_lines).to eq([["Any value after quoted field isn't allowed in line 1.", 1]]) expect(bulk_import.progress).to eq "finished" end end end context "empty import" do let(:csv_lines) { [sample_csv_lines[0].join(","), ""] } it "marks the import empty" do allow_any_instance_of(BulkImport).to receive(:open_file) { File.open(tempfile.path, "r") } expect { instance.perform(bulk_import.id) }.to_not change(Bike, :count) bulk_import.reload expect(bulk_import.no_bikes?).to be_truthy expect(bulk_import.import_errors?).to be_falsey expect(BulkImport.no_bikes.pluck(:id)).to eq([bulk_import.id]) end context "ascend import" do let!(:bulk_import) { FactoryBot.create(:bulk_import_ascend) } let(:organization) { FactoryBot.create(:organization_with_auto_user, ascend_name: "BIKELaneChiC", kind: "bike_shop", pos_kind: "ascend_pos") } it "resolves error, assigns organization and processes" do bulk_import.check_ascend_import_processable! bulk_import.reload expect(bulk_import.import_errors?).to be_truthy # Create organization here expect(organization).to be_present expect(bulk_import.organization).to_not be_present expect { instance.perform(bulk_import.id) }.to_not change(UnknownOrganizationForAscendImportWorker.jobs, :count) bulk_import.reload expect(bulk_import.no_bikes?).to be_truthy expect(bulk_import.import_errors?).to be_falsey expect(BulkImport.no_bikes.pluck(:id)).to eq([bulk_import.id]) expect(bulk_import.organization_id).to eq organization.id expect(bulk_import.creator).to eq organization.auto_user # Only has bikes key - no ascend nil key expect(bulk_import.import_errors.keys).to eq(["bikes"]) end end end context "valid file" do let!(:color_green) { FactoryBot.create(:color, name: "Green") } let!(:color_white) { FactoryBot.create(:color, name: "White") } let!(:surly) { FactoryBot.create(:manufacturer, name: "Surly") } let!(:trek) { FactoryBot.create(:manufacturer, name: "Trek") } let(:file_url) { "https://raw.githubusercontent.com/bikeindex/bike_index/main/public/import_all_optional_fields.csv" } let(:organization) { FactoryBot.create(:organization_with_auto_user) } # We're stubbing the method to use a remote file, don't pass the file in and let it use the factory default let!(:bulk_import) { FactoryBot.create(:bulk_import, progress: "pending", user_id: nil, organization_id: organization.id) } it "creates the bikes, doesn't have any errors" do # In production, we actually use remote files rather than local files. # simulate what that process looks like by loading a remote file in the way we use open_file in BulkImport VCR.use_cassette("bulk_import-perform-success") do allow_any_instance_of(BulkImport).to receive(:open_file) { URI.parse(file_url).open } expect { instance.perform(bulk_import.id) # This test is being flaky! Add debug printout #2101 (actually after, but still...) pp bulk_import.import_errors if bulk_import.reload.blocking_error? }.to change(Bike, :count).by 2 bulk_import.reload expect(bulk_import.progress).to eq "finished" expect(bulk_import.bikes.count).to eq 2 expect(bulk_import.file_import_errors).to_not be_present bike1 = bulk_import.bikes.reorder(:created_at).first expect(bike1.primary_frame_color).to eq color_green expect(bike1.serial_number).to eq "xyz_test" expect(bike1.owner_email).to eq "test@bikeindex.org" expect(bike1.manufacturer).to eq trek expect(bike1.current_ownership.origin).to eq "bulk_import_worker" expect(bike1.current_ownership.status).to eq "status_with_owner" expect(bike1.creator).to eq organization.auto_user expect(bike1.creation_organization).to eq organization expect(bike1.year).to eq 2019 expect(bike1.description).to eq "I love this, it's my favorite" expect(bike1.frame_size).to eq "29in" expect(bike1.frame_size_unit).to eq "in" expect(bike1.public_images.count).to eq 0 expect(bike1.phone).to eq("8887776666") # Previously, was actually geocoding things - but that didn't seem to help people. So just use what was entered expect(bike1.registration_address).to eq({"street" => default_location[:address]}) expect(bike1.registration_address_source).to eq "initial_creation" target_address_hash = default_location.slice(:latitude, :longitude).merge(street: default_location[:address]) expect(bike1.address_hash.reject { |_k, v| v.blank? }.to_h).to eq target_address_hash.as_json expect(bike1.extra_registration_number).to be_nil expect(bike1.owner_name).to be_nil bike2 = bulk_import.bikes.reorder(:created_at).last expect(bike2.primary_frame_color).to eq color_white expect(bike2.serial_number).to eq "example" expect(bike2.owner_email).to eq "test2@bikeindex.org" expect(bike2.manufacturer).to eq surly expect(bike2.current_ownership.origin).to eq "bulk_import_worker" expect(bike2.current_ownership.registration_info).to eq({"user_name" => "Sally"}) expect(bike2.creator).to eq organization.auto_user expect(bike2.creation_organization).to eq organization expect(bike2.year).to_not be_present expect(bike2.public_images.count).to eq 1 expect(bike2.frame_size).to eq "m" expect(bike2.frame_size_unit).to eq "ordinal" expect(bike2.registration_address).to_not be_present expect(bike2.phone).to be_nil expect(bike2.extra_registration_number).to eq "extra serial number" expect(bike2.owner_name).to eq "Sally" end end context "valid file, kind: impounded" do let(:file_url) { "https://raw.githubusercontent.com/bikeindex/bike_index/main/public/import_impounded_all_optional_fields.csv" } let(:impound_configuration) { FactoryBot.create(:impound_configuration) } let(:organization) { impound_configuration.organization } let!(:state) { FactoryBot.create(:state_california) } let(:user) { FactoryBot.create(:organization_member, organization: organization) } # We're stubbing the method to use a remote file, don't pass the file in and let it use the factory default let!(:bulk_import) { FactoryBot.create(:bulk_import, progress: "pending", user_id: user.id, kind: "impounded", organization_id: organization.id) } include_context :geocoder_real let(:bike1_tareget) do { primary_frame_color: color_green, serial_number: "xyz_test", owner_email: "test@bikeindex.org", manufacturer: trek, creator: organization.auto_user, creation_organization_id: organization.id, year: 2019, description: "I love this, it's my favorite", frame_size: "29in", frame_size_unit: "in", registration_address: {}, public_images: [], phone: "8887776666", extra_registration_number: nil, owner_name: nil, status: "status_impounded" } end let(:bike2_target) do { primary_frame_color: color_white, serial_number: "example", owner_email: "test2@bikeindex.org", manufacturer: surly, creator: organization.auto_user, creation_organization_id: organization.id, year: nil, frame_size: "m", frame_size_unit: "ordinal", registration_address: {}, phone: nil, extra_registration_number: "extra serial number", owner_name: "Sally", status: "status_impounded" } end let(:impound_record1_target) do { impounded_description: "It was locked to a handicap railing", display_id: "2020-33333", unregistered_bike: true, street: "1409 Martin Luther King Jr Way", city: "Berkeley", zipcode: "94709", # NOTE: the zipcode that is entered is 94710 state_id: state.id } end let(:impound_record2_target) do { impounded_description: "Appears to be abandoned", display_id: "1", unregistered_bike: true, street: "327 17th St", city: "Oakland", zipcode: "94612", state_id: state.id } end it "creates the bikes and impound records" do VCR.use_cassette("bulk_import-impounded-perform-success", match_requests_on: [:method]) do allow_any_instance_of(BulkImport).to receive(:open_file) { URI.parse(file_url).open } expect { instance.perform(bulk_import.id) # This test is being flaky! Add debug printout #2101 pp bulk_import.import_errors if bulk_import.reload.blocking_error? }.to change(Bike, :count).by 2 bulk_import.reload expect(bulk_import.progress).to eq "finished" expect(bulk_import.bikes.count).to eq 2 expect(bulk_import.file_import_errors).to_not be_present expect(bulk_import.headers).to eq(%w[manufacturer model color owner_email serial_number year description phone secondary_serial owner_name frame_size photo impounded_at impounded_street impounded_city impounded_state impounded_zipcode impounded_country impounded_id impounded_description]) bike1 = bulk_import.bikes.reorder(:created_at).first expect(bike1.current_ownership.origin).to eq "bulk_import_worker" expect(bike1.current_ownership.status).to eq "status_impounded" expect_attrs_to_match_hash(bike1, bike1_tareget) expect(bike1.created_by_notification_or_impounding?).to be_truthy bike1_impound_record = bike1.current_impound_record expect_attrs_to_match_hash(bike1_impound_record, impound_record1_target) expect(bike1_impound_record.impounded_at).to be_within(1.day).of Time.parse("2020-12-30") expect(bike1_impound_record.latitude).to be_within(0.01).of 37.881 expect(bike1.address_hash).to eq bike1_impound_record.address_hash bike2 = bulk_import.bikes.reorder(:created_at).last expect_attrs_to_match_hash(bike2, bike2_target) expect(bike2.public_images.count).to eq 1 expect(bike2.current_ownership.origin).to eq "bulk_import_worker" expect(bike1.current_ownership.status).to eq "status_impounded" expect(bike2.created_by_notification_or_impounding?).to be_truthy bike2_impound_record = bike2.current_impound_record expect_attrs_to_match_hash(bike2_impound_record, impound_record2_target) expect(bike2_impound_record.impounded_at).to be_within(1.day).of Time.parse("2021-01-01") expect(bike2_impound_record.latitude).to be_within(0.01).of 37.8053 expect(bike2.address_hash).to eq bike2_impound_record.address_hash end end end end end context "with assigned bulk import" do before { instance.bulk_import = bulk_import } describe "process_csv" do after { tempfile.close && tempfile.unlink } context "without a header" do let(:csv_lines) { sample_csv_lines.slice(1, 2).map { |l| l.join(",") } } it "adds a file error" do expect(instance).to_not receive(:register_bike) instance.process_csv(File.open(tempfile.path, "r")) bulk_import.reload expect(bulk_import.file_import_errors.to_s).to match(/invalid csv headers/i) expect(bulk_import.progress).to eq "finished" end end context "with an invalid header" do let(:csv_lines) { ([%w[manufacturer email name color]] + sample_csv_lines.slice(1, 2)).map { |l| l.join(",") } } it "adds a file error" do expect(instance).to_not receive(:register_bike) instance.process_csv(File.open(tempfile.path, "r")) bulk_import.reload expect(bulk_import.file_import_errors.to_s).to match(/invalid csv headers/i) expect(bulk_import.progress).to eq "finished" end end context "with failed row" do let(:error_line) { ["Surly", "Midnight Special", "2018", nil, " ", "example"] } let(:csv_lines) { [[sample_csv_lines[0]], [error_line]].map { |l| l.join(",") } } let(:target_line_error) { [2, ["Owner email can't be blank"]] } it "registers a bike and adds a row error" do instance.process_csv(File.open(tempfile.path, "r")) expect(instance.line_errors.count).to eq 1 expect(instance.line_errors.first).to eq target_line_error expect(bulk_import.progress).to eq "ongoing" end end context "with two valid bikes" do let(:csv_lines) { sample_csv_lines.map { |l| l.join(",") } } let(:bparam_line1) { instance.row_to_b_param_hash(sample_csv_lines[0].map(&:to_sym).zip(sample_csv_lines[1]).to_h) } let(:bparam_line2) { instance.row_to_b_param_hash(sample_csv_lines[0].map(&:to_sym).zip(sample_csv_lines[2]).to_h) } it "calls register bike with the valid bikes" do expect(instance).to receive(:register_bike).with(bparam_line1) { Bike.new(id: 1) } expect(instance).to receive(:register_bike).with(bparam_line2) { Bike.new(id: 1) } instance.process_csv(File.open(tempfile.path, "r")) bulk_import.reload expect(bulk_import.import_errors).to_not be_present expect(bulk_import.progress).to eq "ongoing" end end end describe "row_to_b_param_hash" do let(:row) { sample_csv_lines[0].map(&:to_sym).zip(csv_lines[1]).to_h } let(:target) do { owner_email: row[:owner_email], manufacturer_id: "Trek", is_bulk: true, color: "Green", serial_number: row[:serial_number], year: row[:year], frame_model: "Roscoe 8", description: nil, frame_size: nil, phone: nil, address: nil, extra_registration_number: nil, user_name: nil, send_email: true, creation_organization_id: nil } end describe "row_to_b_param_hash" do context "some extra bits" do it "returns the hash we want" do row_hash = row.merge(hidden: true, another_thing: "912913") result = instance.row_to_b_param_hash(row_hash) expect(result.select { |_k, v| v.present? }.keys).to eq([:bulk_import_id, :bike]) expect(result[:bike]).to eq target end end context "with organization" do let(:organization) { FactoryBot.create(:organization) } let!(:bulk_import) { FactoryBot.create(:bulk_import, organization: organization, no_notify: true) } it "registers with organization" do expect(instance.row_to_b_param_hash(row)[:bike]).to eq target.merge(send_email: false, creation_organization_id: organization.id) end end end context "impounded" do let(:row) { sample_csv_impounded_lines[0].map(&:to_sym).zip(csv_lines[1]).to_h } let(:kind) { "impounded" } let(:target) do { owner_email: bulk_import.user.email, manufacturer_id: "Thesis", is_bulk: true, color: "Pink", serial_number: row[:serial_number], year: row[:year], frame_model: "OB1", description: nil, frame_size: nil, phone: nil, address: nil, extra_registration_number: nil, user_name: nil, send_email: true, creation_organization_id: nil } end let(:target_impound) do { impounded_at_with_timezone: "2021-02-04", street: "1409 Martin Luther King Jr Way", city: "Berkeley", state: "CA", zipcode: "94710", country: "US", display_id: "ddd33333", impounded_description: nil, organization_id: bulk_import.organization_id } end it "returns impounded kind" do result = instance.row_to_b_param_hash(row) expect(result.select { |_k, v| v.present? }.keys).to eq([:bulk_import_id, :bike, :impound_record]) expect(result[:bike]).to eq target expect(result[:impound_record]).to eq target_impound end end end describe "register bike" do let!(:manufacturer) { FactoryBot.create(:manufacturer, name: "Surly") } context "valid organization bike" do let(:organization) { FactoryBot.create(:organization_with_auto_user) } let!(:bulk_import) { FactoryBot.create(:bulk_import, organization: organization) } let(:row) { {manufacturer: " Surly", serial_number: "na", color: nil, owner_email: "test2@bikeindex.org", year: "2018", model: "Midnight Special", cycle_type: "tandem"} } def expect_registered_bike(passed_row) expect(organization.auto_user).to_not eq bulk_import.user expect(Bike.count).to eq 0 expect { bike = instance.register_bike(instance.row_to_b_param_hash(passed_row)) # This test is being flaky! Add debug printout #2101 pp bike.errors unless bike.errors.none? }.to change(Bike, :count).by 1 bike = Bike.last expect(bike.owner_email).to eq row[:owner_email] expect(bike.manufacturer).to eq manufacturer expect(bike.serial_number).to eq "unknown" expect(bike.frame_model).to eq "Midnight Special" ownership = bike.current_ownership expect(ownership.bulk?).to be_truthy expect(ownership.origin).to eq "bulk_import_worker" expect(ownership.organization).to eq organization expect(bike.creation_organization).to eq organization expect(bike.creator).to eq organization.auto_user bike end it "registers a bike" do bike = expect_registered_bike(row) expect(bike.primary_frame_color).to eq black expect(bike.paint_id).to be_blank end context "chartreuse color" do let(:color) { "chartreuse" } it "creates a new paint" do expect(Paint.count).to eq 0 bike = expect_registered_bike(row.merge(color: color)) expect(bike.primary_frame_color).to eq black expect(bike.paint_id).to be_present expect(Paint.count).to eq 1 paint = bike.paint expect(paint.manufacturer_id).to be_blank # I don't know where this is set... expect(paint.name).to eq color expect(paint.color_id).to be_blank expect(paint.linked?).to be_falsey end context "with chartreuse paint" do let(:green) { FactoryBot.create(:color, name: "Green") } let!(:paint) { FactoryBot.create(:paint, name: color, color: green) } it "assigns" do expect(Paint.count).to eq 1 bike = expect_registered_bike(row.merge(color: " ChartreuSE ")) expect(bike.primary_frame_color_id).to eq green.id expect(bike.paint_id).to be_present expect(Paint.count).to eq 1 paint = bike.paint expect(paint.manufacturer_id).to be_blank # I don't know where this is set... expect(paint.name).to eq color expect(paint.color_id).to eq green.id expect(paint.linked?).to be_truthy end end end end context "not valid bike" do let(:row) { {manufacturer_id: "\n", serial_number: "na", color: nil} } let(:target_errors) { ["Owner email can't be blank"] } it "returns the invalid bike with errors" do expect { bike = instance.register_bike(instance.row_to_b_param_hash(row)) expect(bike.id).to_not be_present expect(bike.cleaned_error_messages).to eq(target_errors) }.to change(Bike, :count).by 0 end end context "not valid bike" do let(:row) { {manufacturer_id: "\n", serial_number: "", color: nil} } let(:target_errors) { ["Owner email can't be blank"] } it "returns the invalid bike with errors" do bulk_import.kind = "impounded" expect { expect(instance.register_bike(instance.row_to_b_param_hash(row))).to be_blank }.to change(Bike, :count).by 0 end end end describe "rescue_blank_serials" do let(:blank_examples) { ["NA", "N/A", "unkown", "unkown", " ", "none"] } let(:non_blank_examples) { %w[somethingna none8xc9x] } it "rescues blank serials, doesn't rescue non blank serials" do blank_examples.each do |blank| expect(instance.rescue_blank_serial(blank)).to eq("unknown"), "Failure: '#{blank}'" end non_blank_examples.each do |non_blank| expect(instance.rescue_blank_serial(non_blank)).to_not eq("unknown"), "Failure: #{non_blank}" end end end describe "convert_header" do context "headers match" do let(:header_string) { "ManufaCTURER,MODEL, YEAR, owner_email, serial Number, Stuff\n" } let(:target) { %i[manufacturer model year owner_email serial_number stuff] } it "leaves things alone" do expect(instance.convert_headers(header_string)).to eq target expect(instance.bulk_import.import_errors?).to be_falsey end end context "impounded" do let(:kind) { "impounded" } let(:header_string) { "BRAnd, vendor,MODEL,frame_model, frame YEAR,impounded_at, serial, impounded street, impounded-city, Stuff\n" } let(:target) { %i[manufacturer vendor model frame_model year impounded_at serial_number impounded_street impounded_city stuff] } it "returns the symbol if the symbol exists, without overwriting better terms" do expect(instance.convert_headers(header_string)).to eq target expect(instance.bulk_import.import_errors?).to be_falsey end context "crazy characters" do # EPS had a header with a nonbreaking space in it. It was very hard to debug. So - strip out any potential things like that let(:shitty_character) { CGI.unescapeHTML("&#65279;") } let(:header_string) { "#{shitty_character}impounded_id, BRAnd, vendor,MODEL,frame_model, frame YEAR,impounded_at, serial, impounded street, impounded-city, Stuff\n" } it "returns the target" do expect(header_string.first.ord).to eq 65279 expect(instance.convert_headers(header_string)).to eq([:impounded_id] + target) expect(instance.bulk_import.import_errors?).to be_falsey end end end context "conversions" do let(:header_string) { "BRAnd, vendor,MODEL,frame_model, frame YEAR,email, serial, Stuff\n" } let(:target) { %i[manufacturer vendor model frame_model year owner_email serial_number stuff] } it "returns the symbol if the symbol exists, without overwriting better terms" do expect(instance.convert_headers(header_string)).to eq target expect(instance.bulk_import.import_errors?).to be_falsey end context "quote wrapped" do let(:header_string) { '"Product Description","Brand","Color","Size","Serial Number","Customer Last Name","Customer First Name","Customer Email"' } let(:target) { %i[description manufacturer color frame_size serial_number customer_last_name customer_first_name owner_email] } it "leaves things alone" do expect(instance.convert_headers(header_string)).to eq target expect(instance.bulk_import.import_errors?).to be_falsey end end end end end end
bikeindex/bike_index
spec/workers/bulk_import_worker_spec.rb
Ruby
agpl-3.0
30,742
@font-face { font-family: "lato"; font-style: normal; font-stretch: normal; font-weight: 400; src: local("Lato"), url("../fonts/LatoLatin-Regular.woff") format("woff"); } @font-face { font-family: "lato"; font-style: italic; font-stretch: normal; font-weight: 400; src: local("Lato"), url("../fonts/LatoLatin-Italic.woff") format("woff"); } @font-face { font-family: "lato"; font-style: normal; font-stretch: normal; font-weight: 700; src: local("Lato"), url("../fonts/LatoLatin-Bold.woff") format("woff"); } @font-face { font-family: "lato"; font-style: italic; font-stretch: normal; font-weight: 700; src: local("Lato"), url("../fonts/LatoLatin-BoldItalic.woff") format("woff"); } @font-face { font-family: "spectral"; font-style: normal; font-stretch: normal; font-weight: 400; src: local("Spectral"), url("../fonts/Spectral-Regular.woff") format("woff"); } @font-face { font-family: "spectral"; font-style: italic; font-stretch: normal; font-weight: 400; src: local("Spectral"), url("../fonts/Spectral-Italic.woff") format("woff"); } @font-face { font-family: "spectral"; font-style: normal; font-stretch: normal; font-weight: 700; src: local("Spectral"), url("../fonts/Spectral-Bold.woff") format("woff"); } @font-face { font-family: "spectral"; font-style: italic; font-stretch: normal; font-weight: 700; src: local("Spectral"), url("../fonts/Spectral-BoldItalic.woff") format("woff"); } /* stylelint-disable property-no-vendor-prefix */ /* FUNCTIONS */ /* btns */ .btn { margin: 0; padding: 0.5rem 1.5rem; background: #f9fafb; display: inline-block; color: #5b6871; font-size: 1rem; border: none; border-radius: 5px; min-height: 38px; min-width: 15px; line-height: 25px; vertical-align: middle; cursor: pointer; overflow: hidden; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .btn.btn-important { background: #36c; color: #fff; } .btn.btn-important:hover, .btn.btn-important:active { background: #25c; } .btn.btn-attention { background: #f5633e; color: #fff; } .btn.btn-attention:hover, .btn.btn-attention:active { background: #73341f; } .btn:hover { text-decoration: none; } a.btn { min-height: 25px; line-height: 25px; } /*=== Forms */ legend { margin: 2rem 0 1rem 0; padding: 0; display: inline-block; width: auto; font-size: 1rem; clear: both; text-transform: uppercase; letter-spacing: 1px; font-weight: 700; } label { min-height: 25px; padding: 5px 0; cursor: pointer; color: #5b6871; } textarea { width: 360px; max-width: 100%; height: 100px; } input, select, textarea, button { padding: 5px 10px; background: #fff; color: #5b6871; font-family: "lato", "Helvetica", "Arial", sans-serif; font-size: 1rem; border: 1px solid #eff0f2; border-radius: 2px; min-height: 25px; line-height: 25px; vertical-align: middle; } option { padding: 0 0.5em; } input:focus, select:focus, textarea:focus { color: #303136; border-color: #36c; } input:invalid, select:invalid { color: #f5633e; border-color: #f5633e; box-shadow: none; } input:disabled, select:disabled { background: #eff0f2; } input.extend { transition: width 200ms linear; } .form-group { padding: 5px; border-radius: 3px; } .form-group::after { content: ""; display: block; clear: both; } .form-group .group-name { padding: 10px 0; text-align: left; } .form-group .group-controls { min-height: 25px; padding: 5px 0; } .form-group .group-controls .control { line-height: 2em; } .form-group.form-actions { margin: 15px 0 25px; padding: 5px 0; } .form-group.form-actions .btn { margin: 0 0 0 0.5rem; } /*=== Tables */ table { border-collapse: collapse; } tr, th, td { padding: 0.5em; border: 1px solid #d5d8db; } th { background: #f9fafb; } form td, form th { font-weight: normal; text-align: center; } /*=== COMPONENTS */ /*===============*/ /*=== Forms */ /*=== Horizontal-list */ .horizontal-list { margin: 0; padding: 0.1rem 0; } .horizontal-list .item { vertical-align: middle; } .horizontal-list .item:first-child { padding-right: 0.5rem; } /*=== Dropdown */ .dropdown-menu { margin: 0; padding: 0.5rem 0 1rem 0; background: #f9fafb; font-size: 1rem; border: none; border-radius: 3px; box-shadow: 0px 6px 8px 0px rgba(0, 0, 0, 0.35); text-align: right; } .dropdown-menu::after { background: white; width: 10px; height: 10px; content: ""; position: absolute; top: -4px; left: 13px; z-index: -10; transform: rotate(-45deg); } .dropdown-menu .dropdown-header { margin: 1.75rem 2rem 0.5rem 0; font-weight: bold; text-align: right; color: #5b6871; text-transform: uppercase; letter-spacing: 1px; } .dropdown-menu .item { -webkit-transition: all 0.075s ease-in-out; -moz-transition: all 0.075s ease-in-out; -o-transition: all 0.075s ease-in-out; -ms-transition: all 0.075s ease-in-out; transition: all 0.075s ease-in-out; } .dropdown-menu .item a, .dropdown-menu .item span, .dropdown-menu .item .as-link { padding: 0 2rem; color: #303136; font-size: 1rem; line-height: 2.5em; } .dropdown-menu .item:hover { background: #36c; color: #fff; } .dropdown-menu .item:hover a, .dropdown-menu .item:hover button { text-decoration: none; color: #fff; } .dropdown-menu .item[aria-checked=true] a::before { margin: 0 -14px 0 0; font-weight: bold; } .dropdown-menu .input select, .dropdown-menu .input input { margin: 0 auto 5px; padding: 2px 5px; border-radius: 3px; } .dropdown-menu .separator { margin: 0.75rem 0; border-bottom: 1px solid #eff0f2; } .tree .tree-folder .tree-folder-items .dropdown-menu .item { padding: 0; } .tree .tree-folder .tree-folder-items .dropdown-menu .item a, .tree .tree-folder .tree-folder-items .dropdown-menu .item button { color: #303136; } .tree .tree-folder .tree-folder-items .dropdown-menu .item a:hover, .tree .tree-folder .tree-folder-items .dropdown-menu .item button:hover { color: #fff; } .tree .tree-folder .tree-folder-items .dropdown-menu .item:hover { background: #36c; } /*=== Alerts */ .alert { margin: 1rem 0; padding: 1rem; background: #f9fafb; color: #5b6871; font-size: 1rem; border: 1px solid #c5ced3; border-radius: 3px; text-shadow: 0 0 1px #eff0f2; } .alert-head { font-size: 1.15em; } .alert > a { text-decoration: underline; color: inherit; } .alert-warn { background: #fdfde0; color: #73762f; border: 1px solid #73762f33; } .alert-success { background: #cffde7; color: #0c7540; border: 1px solid #0c754033; } .alert-error { background: #fde0d8; color: #73341f; border: 1px solid #73341f33; } /*=== Pagination */ .pagination { background: #eff0f2; color: #303136; font-size: 0.8em; text-align: center; } .pagination .item.pager-current { background: #303136; color: #eff0f2; font-size: 1.5em; font-weight: bold; } .pagination .item a { display: block; color: #303136; font-style: italic; line-height: 3em; text-decoration: none; } .pagination .item a:hover { background: #303136; color: #eff0f2; } .pagination .loading, .pagination a:hover.loading { background: url("loader.gif") center center no-repeat #34495e; font-size: 0; } .content .pagination { margin: 0; padding: 0; } /*=== Boxes */ .box { background: #fff; border: none; border-radius: 3px; box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.25); } .box .box-title { margin: 0; padding: 5px 10px; background: #eff0f2; color: #303136; border-radius: 2px 2px 0 0; } .box .box-title img { margin-left: 0.75rem; } .box .box-title:hover .configure { background: url("icons/cog.svg") no-repeat 4px 4px; display: block; float: right; width: 1.75rem; height: 1.75rem; border-radius: 2px; margin-left: 0.5rem; } .box .box-title:hover .configure .icon { display: none; border-radius: 3px; vertical-align: middle; } .box .box-title:hover .configure:hover { background: url("icons/cog-white.svg") no-repeat 4px 4px #36c; } .box .box-title form input { width: 85%; } .box .box-title form .dropdown { float: left; } .box .box-title form .dropdown a.dropdown-toggle { padding: 0; border-radius: 0; background-image: url(icons/more.svg); background-repeat: no-repeat; background-position: left 8px; } .box .box-title form .dropdown a.dropdown-toggle img { display: none; } .box .box-content .item { padding: 0.5rem 0.75rem; color: #303136; font-size: 1rem; border-bottom: 1px solid #eff0f2; line-height: 1.7em; } .box .box-content .item img { margin-left: 0.75rem; } .box .box-content .item .configure { background: url("icons/cog.svg") no-repeat 4px 4px; display: block; float: right; width: 1.75rem; height: 1.75rem; border-radius: 2px; margin-left: 0.5rem; } .box .box-content .item .configure .icon { display: none; border-radius: 3px; vertical-align: middle; } .box .box-content .item .configure:hover { background: url("icons/cog-white.svg") no-repeat 4px 4px #36c; } .box .box-content .item:last-child { border-bottom: none; } /*=== "Load more" part */ #bigMarkAsRead { text-align: center; text-decoration: none; background: #effcfd; color: #36c; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } #bigMarkAsRead:hover { background: #36c; color: #fff; } #bigMarkAsRead:hover .bigTick { background: url(icons/tick-white.svg) center no-repeat; } #bigMarkAsRead .bigTick { margin: 0.5rem 0; background: url(icons/tick-color.svg) center no-repeat; display: inline-block; width: 64px; height: 64px; text-indent: -9999px; white-space: nowrap; } .formLogin { background: #303136; } .formLogin .header .configure { padding-left: 1rem; } .formLogin .header .configure img { margin-left: 0.5rem; } .formLogin .header .configure a.signin { color: #fff; } .formLogin h1 { color: #fff; } .formLogin form#crypto-form div { margin-bottom: 1rem; } .formLogin form#crypto-form div label { color: #c5ced3; font-size: 1rem; } .formLogin form#crypto-form div input { background: #1d1e22; } .formLogin form#crypto-form div input:focus { background: #f9fafb; color: #303136; } /*=== DIVERS */ /*===========*/ .aside.aside_feed .nav-form input, .aside.aside_feed .nav-form select { width: 140px; } .aside.aside_feed .nav-form .dropdown .dropdown-menu { left: -20px; } .aside.aside_feed .nav-form .dropdown .dropdown-menu::after { left: 33px; } /*=== Tree */ .tree { margin: 10px 0; } .tree#sidebar { scrollbar-color: rgba(255, 255, 0, 0.1) rgba(0, 0, 0, 0.05); scrollbar-color: #fff33 #fff22; } .tree .tree-folder { border-bottom: 1px solid #3f3f3f; } .tree .tree-folder .tree-folder-title { padding: 12px 16px; background: #303136; position: relative; font-size: 0.85rem; letter-spacing: 1px; font-weight: 700; text-transform: uppercase; } .tree .tree-folder .tree-folder-title .title { background: inherit; color: #fff; } .tree .tree-folder .tree-folder-title .title:hover { text-decoration: none; } .tree .tree-folder.active .tree-folder-title { background: #303136; font-weight: bold; } .tree .tree-folder .tree-folder-items { background: #26272a; } .tree .tree-folder .tree-folder-items .item { padding: 0 1rem; line-height: 2.5rem; font-size: 1rem; font-weight: 400; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .tree .tree-folder .tree-folder-items .item.active { background: #36c; } .tree .tree-folder .tree-folder-items .item.active .dropdown li a { color: #303136; } .tree .tree-folder .tree-folder-items .item.active .dropdown li a:hover { color: #fff; } .tree .tree-folder .tree-folder-items .item.active a { color: #fff; } .tree .tree-folder .tree-folder-items .item:hover { background: #17181a; } .tree .tree-folder .tree-folder-items .item a { text-decoration: none; color: #fff; } .tree .tree-folder .tree-folder-items .feed .item-title:not([data-unread="0"])::before { margin: 11px 4px 0 6px; padding: 3px 4px; background: rgba(0, 0, 0, 0.25); display: block; float: right; font-size: 0.75rem; border-radius: 12px; content: attr(data-unread); text-align: center; line-height: 0.75rem; } /*=== Buttons */ .stick { vertical-align: middle; font-size: 0; } .stick input, .stick .btn { border-radius: 0; } .stick .btn:first-child, .stick input:first-child { border-radius: 0 5px 5px 0; } .stick .btn:last-child, .stick input:last-child, .stick .btn + .dropdown > .btn { border-radius: 5px 0 0 5px; } .stick .btn + .btn, .stick .btn + input, .stick .btn + .dropdown > .btn, .stick input + .btn, .stick input + input, .stick input + .dropdown > .btn, .stick .dropdown + .btn, .stick .dropdown + input, .stick .dropdown + .dropdown > .btn { border-right: 1px solid #d5d8db; } .aside { background: #303136; } .aside.aside_feed { padding: 10px 0; text-align: center; background: #303136; } .aside.aside_feed .tree { margin: 10px 0 50px; } /* Sidebar des pages de configuration */ /*=== Navigation */ .nav-list .nav-header, .nav-list .item { height: 2.5em; line-height: 2.5em; font-size: 1rem; } .nav-list .item { background: #303136; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .nav-list .item a { padding: 0 1rem; color: #fff; } .nav-list .item .error a { color: #f5633e; } .nav-list .item:hover { background: #17181a; color: #fff; } .nav-list .item:hover .error a { background: #36c; color: #fff; } .nav-list .item:hover .empty a { background: #f4f762; color: #fff; } .nav-list .item:hover a { color: #fff; text-decoration: none; } .nav-list .item.active { background: #36c; color: #fff; } .nav-list .item.active .error a { background: #36c; color: #fff; } .nav-list .item.active .empty a { background: #f4f762; color: #fff; } .nav-list .item.active a { color: #fff; text-decoration: none; } .nav-list.empty a { color: #f4f762; } .nav-list .disable { text-align: center; background: #f9fafb; color: #a6a7ae; } .nav-list .nav-header { padding: 0 10px; font-weight: bold; color: #5b6871; text-transform: uppercase; letter-spacing: 1px; margin-top: 1rem; } .nav-list .nav-form { padding: 3px; text-align: center; } .nav-list .nav-head { margin: 0; text-align: left; color: #fff; } .nav-list .nav-head a { color: #fff; } .nav-list .nav-head .item { padding: 5px 10px; font-size: 0.9rem; line-height: 1.5rem; } /*=== Aside main page (categories) */ .aside_feed .tree-folder-title > .title:not([data-unread="0"])::after { margin: -0.5rem 0 0 1rem; padding: 0 0.75rem; background: rgba(0, 0, 0, 0.25); border-radius: 12px; position: absolute; left: 0; line-height: 1.5rem; text-align: center; } .feed.item.empty.active { background: #5b6871; } .feed.item.error.active { background: #5b6871; } .feed.item.empty, .feed.item.empty > a { color: #5b6871; } .feed.item.error, .feed.item.error > a { color: #5b6871; } .feed.item.empty.active, .feed.item.error.active, .feed.item.empty.active > a, .feed.item.error.active > a { color: #fff; } .aside_feed .tree-folder-items .dropdown-menu::after { right: 2px; } .aside_feed .tree-folder-items .item .dropdown-target:target ~ .dropdown-toggle > .icon, .aside_feed .tree-folder-items .item:hover .dropdown-toggle > .icon, .aside_feed .tree-folder-items .item.active .dropdown-toggle > .icon { border-radius: 3px; } .aside_feed .stick #btn-add { border-right-color: #303136; } /*=== STRUCTURE */ /*===============*/ /*=== Header */ .header { padding: 0.5rem 1.35rem; background: #303136; display: block; width: auto; table-layout: none; } .header .item { vertical-align: middle; } .header .item.title { width: 280px; font-weight: 400; } .header .item.title h1 a { text-decoration: none; color: #fff; font-size: 1rem; text-transform: uppercase; letter-spacing: 1px; } .header .item.title h1 a img { margin-left: 0.5rem; } .header .item.search input { width: 230px; color: #fff; border: none; border-radius: 0 2px 2px 0; background-color: #26272a; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .header .item.search input:hover { background-color: #17181a; } .header .item.search input:focus { width: 350px; color: #5b6871; background-color: #fff; } .header .item.search .btn { width: 3rem; border-radius: 2px 0 0 2px; background-color: #36c; background-position: center; background-repeat: no-repeat; background-image: url(icons/magnifier.svg); border-right-width: 0; min-height: 35px; } .header .item.search .btn img { display: none; } .header .item.search .btn:hover { background-color: #25c; } .header .item.configure { width: 2rem; position: absolute; left: 1rem; top: 1.25rem; text-align: center; } .header .item.configure .btn { padding: 0 0.5rem; background-color: transparent; background-position: center; background-repeat: no-repeat; background-image: url(icons/cog-white.svg); } .header .item.configure .btn img { display: none; } /*=== Body */ #global { height: calc(100% - 85px); } /*=== Prompt (centered) */ .prompt { text-align: center; } .prompt label { text-align: right; } .prompt form { margin: 10px auto 20px auto; width: 200px; } .prompt input { margin: 5px auto; width: 100%; } .prompt p { margin: 20px 0; } /*=== New article notification */ #new-article { background: #36c; font-size: 1rem; text-align: center; } #new-article:hover { background: #25c; } #new-article > a { line-height: 3em; font-weight: bold; color: #fff; } #new-article > a:hover { text-decoration: none; } /*=== Day indication */ .day { padding: 1rem 1.25rem 0 0; color: #5b6871; font-size: 0.875rem; font-weight: 700; line-height: 3em; letter-spacing: 1px; text-transform: uppercase; } .day .name { padding: 0 1rem 0 1rem; color: #303136; font-size: 0.875rem; position: relative; right: 0; text-transform: uppercase; } /*=== Index menu */ .nav_menu { text-align: center; padding: 5px 0; } .nav_menu .btn { border-right-width: 0; padding: 0.5rem 1rem; background-color: #f9fafb; background-position: center; background-repeat: no-repeat; } .nav_menu .btn:hover { background-color: #eff0f2; } .nav_menu .stick { background: #f9fafb; } .nav_menu .stick .btn { border-right-width: 0; padding: 0.5rem 1rem; background-color: #f9fafb; background-position: center; background-repeat: no-repeat; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .nav_menu .stick .btn:hover { background-color: #d5d8db; } .nav_menu .stick .btn.active { background-color: #36c; } .nav_menu .stick .btn img.icon { display: none; } .nav_menu .stick .btn#toggle-read { background-image: url(icons/read.svg); } .nav_menu .stick .btn#toggle-read.active { background-image: url(icons/read-white.svg); } .nav_menu .stick .btn#toggle-unread { background-image: url(icons/unread.svg); } .nav_menu .stick .btn#toggle-unread.active { background-image: url(icons/unread-white.svg); } .nav_menu .stick .btn#toggle-starred { background-image: url(icons/starred.svg); } .nav_menu .stick .btn#toggle-starred.active { background-image: url(icons/starred-white.svg); } .nav_menu .stick .btn#toggle-non-starred { background-image: url(icons/non-starred.svg); } .nav_menu .stick .btn#toggle-non-starred.active { background-image: url(icons/non-starred-white.svg); } .nav_menu .stick .btn.read_all { padding: 5px 16px; color: #303136; background-color: #f9fafb; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .nav_menu .stick .btn.read_all:hover { background-color: #d5d8db; } .nav_menu .stick .btn.view-normal { background-image: url(icons/view-list.svg); } .nav_menu .stick .btn.view-normal.active { background-image: url(icons/view-list-white.svg); } .nav_menu .stick .btn.view-global { background-image: url(icons/view-global.svg); } .nav_menu .stick .btn.view-global.active { background-image: url(icons/view-global-white.svg); } .nav_menu .stick .btn.view-reader { background-image: url(icons/view-reader.svg); } .nav_menu .stick .btn.view-reader.active { background-image: url(icons/view-reader-white.svg); } .nav_menu .stick .btn.view-rss { background-image: url(icons/rss.svg); } .nav_menu .stick .dropdown a.dropdown-toggle { border-right-width: 0; background-image: url(icons/more.svg); } #dropdown-query ~ .dropdown-menu .dropdown-header .icon { vertical-align: middle; background-color: #a6a7ae; border-radius: 3px; } /*=== Content of feed articles */ .content, .content.thin { padding: 20px 10px; font-size: 1.125rem; line-height: 1.8rem; } .content h1.title a, .content h1 a, .content.thin h1.title a, .content.thin h1 a { color: #303136; font-family: "spectral", serif; font-size: 2rem; } .content h1.title a:hover, .content h1 a:hover, .content.thin h1.title a:hover, .content.thin h1 a:hover { color: #36c; text-decoration: none; } .content .author, .content.thin .author { color: #5b6871; font-size: 1.125rem; } .content p, .content ul, .content.thin p, .content.thin ul { font-size: 1.125rem; line-height: 1.8rem; } .content .content hr, .content.thin .content hr { margin: 30px 10px; background: #d5d8db; height: 1px; border: 0; box-shadow: 0 2px 5px #ccc; } .content pre, .content.thin pre { margin: 10px auto; padding: 10px 20px; overflow: auto; background: #1d1e22; color: #fff; font-size: 0.9rem; border-radius: 3px; } .content pre code, .content.thin pre code { background: transparent; color: #fff; border: none; } .content code, .content.thin code { padding: 2px 5px; background: #f9fafb; border: 1px solid #eff0f2; border-radius: 3px; } .content blockquote, .content.thin blockquote { margin: 0; padding: 5px 20px; background: #f9fafb; display: block; color: #303136; border-top: 1px solid #d5d8db; border-bottom: 1px solid #d5d8db; } .content blockquote p, .content.thin blockquote p { margin: 0; } /*=== Notification and actualize notification */ .notification { padding: 1rem 0; background: #d5d8db; width: 100%; height: 3rem; color: #5b6871; font-size: 1em; border: none; position: fixed; top: auto; bottom: 0; right: 0; left: 0; text-align: center; line-height: 3em; z-index: 10; vertical-align: middle; } .notification .msg { display: inline-block; font-size: 1rem; } .notification.good { background: #10f587; color: #fff; } .notification.bad { background: #f5633e; color: #fff; } .notification a.close { padding: 0 15px; border-radius: 3px 0 0 3px; line-height: 3em; } .notification.good a.close:hover { background: #0c7540; } .notification.bad a.close:hover { background: #73341f; } .notification#actualizeProgress { line-height: 2em; } .notification#actualizeProgress br { display: none; } /*=== Navigation menu (for articles) */ #nav_entries { margin: 0; text-align: center; line-height: 3em; table-layout: fixed; background: #303136; } /*=== Feed articles */ .flux { background: #fff; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .flux:hover { background: #f9fafb; } .flux:hover:not(.current):hover .item.title { background: #f9fafb; } .flux.current { background: #f9fafb; border-right-color: #36c; } .flux.not_read:not(.current) { background: #f2f6f8; } .flux.not_read:not(.current):hover .item.title { background: #f2f6f8; } .flux.not_read .item.title a { color: #36c; } .flux.not_read .item.website a { color: #36c; } .flux.not_read .item.date { color: rgba(51, 102, 204, 0.5); } .flux.favorite { border-right-color: #ffc300; -webkit-transition: all 0.15s ease-in-out; -moz-transition: all 0.15s ease-in-out; -o-transition: all 0.15s ease-in-out; -ms-transition: all 0.15s ease-in-out; transition: all 0.15s ease-in-out; } .flux.favorite:not(.current) { background: #fff6da; } .flux.favorite:not(.current):hover .item.title { background: #fff6da; } .flux .website a { color: #303136; opacity: 0.75; } .flux .website .favicon { padding: 5px; } .flux .item.date { color: rgba(48, 49, 54, 0.5); font-size: 0.85rem; } .flux .bottom { font-size: 1rem; text-align: center; } .flux_header { font-size: 1rem; cursor: pointer; border-top: 1px solid #eff0f2; } .flux_header .title { font-size: 1rem; } /*=== GLOBAL VIEW */ /*================*/ #stream .box.category:not([data-unread="0"]) .box-title .title { font-weight: bold; } #stream .box.category .box-title { padding: 1.5rem; background: none; } #stream .box.category .box-title a.title { color: #5b6871; font-size: 1rem; font-weight: normal; text-decoration: none; text-align: right; text-transform: uppercase; letter-spacing: 1px; } #stream .box.category .box-title a.title:not([data-unread="0"])::after { margin: -0.5rem 0 0 1rem; padding: 0 0.75rem; background: #eff0f2; border-radius: 12px; position: absolute; top: 1.75rem; left: 0; line-height: 1.5rem; text-align: center; } #stream .box.category .box-title a.title:hover { color: #36c; } #stream .box.category .box-content { padding-bottom: 0.5rem; } #stream .box.category .box-content .item.feed { padding: 0.5rem 1.5rem; font-size: 1rem; } #stream .box.category .box-content .item.feed a { color: #303136; font-weight: 400; } #stream .box.category .box-content .item.feed a:hover { color: #36c; text-decoration: none; } #overlay { background: rgba(0, 0, 0, 0.65); } #panel { top: 3rem; left: 3rem; bottom: 3rem; right: 3rem; border-radius: 3px; } /*=== READER VIEW */ /*================*/ #stream.reader .flux { padding: 0 0 50px; background: #eff0f2; color: #303136; border: none; } #stream.reader .flux .author { margin: 0 0 10px; color: #a6a7ae; font-size: 90%; } /*=== Configuration pages */ .post { padding: 1rem 2rem; font-size: 1rem; } .post form { margin: 1rem 0; } .post form .horizontal-list { margin-bottom: 0.5rem; } .post.content { max-width: 550px; } .post h1, .post h2 { color: #303136; font-size: 3rem; margin-top: 1.75rem; font-weight: 300; line-height: 1.2em; } .post a[href="./"] { margin: 0; padding: 0.75rem 1.5rem; background: #f9fafb; display: inline-block; color: #5b6871; font-size: 1rem; border: 1px solid #d5d8db; border-radius: 5px; min-width: 15px; line-height: 25px; vertical-align: middle; cursor: pointer; overflow: hidden; } .post a[href="./"]:hover { background: #36c; color: white; border: 1px solid #36c; text-decoration: none; } #slider { border-right: none; box-shadow: 0px 6px 8px 0px rgba(0, 0, 0, 0.35); } .slide-container .properties { padding: 1rem; background: rgba(0, 0, 0, 0.75); color: white; border: 0; } .slide-container .properties .page-number { left: 1rem; top: 1rem; } /*=== LOGS */ /*=========*/ .loglist { overflow: hidden; border: 1px solid #a6a7ae; } .log { margin: 10px 0; padding: 5px 2%; background: #f9fafb; color: #5b6871; font-size: 0.8rem; overflow: auto; } .log > .date { margin: 0 0 0 10px; padding: 5px 10px; border-radius: 20px; } .log.error > .date { background: #f5633e; color: #fff; } .log.warning > .date { background: #f4f762; } .log.notice > .date { background: #eff0f2; } .log.debug > .date { background: #1d1e22; color: #fff; } /*=== STATISTICS */ /*===============*/ .stat { margin: 10px 0 20px; } .stat th, .stat td, .stat tr { border: none; } .stat > table td, .stat > table th { border-bottom: 1px solid #d5d8db; } .stat > .horizontal-list { margin: 0 0 5px; } .stat > .horizontal-list .item { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .stat > .horizontal-list .item:first-child { width: 270px; } /*=== MOBILE */ /*===========*/ @media (max-width: 840px) { ul.nav .item { width: 100%; } ul.nav .item img { display: none; } ul.nav .item a { box-sizing: border-box; padding: 1rem 2.5rem 1rem 1rem; background: url("../../themes/icons/logout.svg") no-repeat #17181a 97% center; display: inline-block; width: 100%; color: #fff; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } ul.nav .item a:hover, ul.nav .item a:active { background: url("../../themes/icons/logout.svg") no-repeat #f5633e 97% center; text-decoration: none; } .form-group .group-name { text-align: right; } .aside { -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .aside.aside_feed { padding: 0; } .aside .tree .tree-folder .tree-folder-items .item a { padding: 0.5rem 1rem; } .aside .toggle_aside, #panel .close, #close-slider.active { background: #25c; display: block; width: 100%; height: 50px; line-height: 50px; text-align: center; } .header { padding: 0.5rem; } .header .item.title { display: none; } .header .item.search { display: block; } .header .item.search .stick { display: flex; } .header .item.search input { width: 90%; height: 3.5rem; } .header .item.search input:focus { width: 100%; } .header .item.search .btn { min-height: 49px; padding: 0.5rem 2rem; } .header .item.configure { display: none; } .post { padding-right: 1rem; padding-left: 1rem; } .nav_menu .btn { margin: 0; padding: 0.85rem 1.25rem; } .nav_menu .stick { margin: 0.5rem 0.5rem; } .nav_menu .stick .btn { margin: 0; padding: 0.85rem 1.25rem; } .nav_menu .stick .btn.read_all { padding: 0.85rem 1.25rem; } .nav_menu .search { display: none; max-width: 97%; } .nav_menu .search .input { max-width: 97%; width: 90px; } .nav_menu .search .input:focus { width: 400px; } #stream .flux .flux_header { padding: 0.5rem 0; } .day { text-align: center; padding: 1rem 0; } .day .name { padding: 0; display: block; width: 100%; line-height: 1.5rem; margin-bottom: 1rem; } .pagination { margin: 0 0 3.5em; } #nav_entries { line-height: 4.5rem; } .notification { border-radius: 0; } .notification a.close { background: transparent; display: block; right: 0; } .notification a.close:hover { opacity: 0.5; } .notification a.close .icon { display: none; } } /*=== GENERAL */ /*============*/ html, body { background: #eff0f2; height: 100%; font-family: "lato", "Helvetica", "Arial", sans-serif; font-size: 0.875rem; } /*=== Links */ a, button.as-link { outline: none; color: #36c; }
Alkarex/FreshRSS
p/themes/Mapco/mapco.rtl.css
CSS
agpl-3.0
31,222
# coding: utf-8 def configure(app): if app.config.get('DEBUG_TOOLBAR_ENABLED'): try: from flask_debugtoolbar import DebugToolbarExtension DebugToolbarExtension(app) except ImportError: app.logger.info('flask_debugtoolbar is not installed') if app.config.get('OPBEAT'): try: from opbeat.contrib.flask import Opbeat Opbeat( app, logging=app.config.get('OPBEAT', {}).get('LOGGING', False) ) app.logger.info('opbeat configured!!!') except ImportError: app.logger.info('opbeat is not installed') if app.config.get('SENTRY_ENABLED', False): try: from raven.contrib.flask import Sentry app.sentry = Sentry(app) except ImportError: app.logger.info('sentry, raven is not installed')
Spotipo/spotipo
unifispot/ext/development.py
Python
agpl-3.0
902
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert } from 'react-bootstrap'; import { scanFile } from '../actions/fileActions'; import * as types from '../actions/ActionTypes'; class Notification extends React.Component { constructor(props) { super(props); this.state = { show: !(props.notification.trim() === '') }; this.handleDismiss = this.handleDismiss.bind(this); } UNSAFE_componentWillReceiveProps(newProps) { this.setState({ show: !(newProps.notification.trim() === '') }); } handleDismiss() { this.setState({ show: false }); } render() { const { notification } = this.props; const { show } = this.state; if (!show) return <span />; return ( <Alert bsStyle="danger" className="chemscanner-alert-notification" onDismiss={this.handleDismiss} > {notification} </Alert> ); } } Notification.propTypes = { notification: PropTypes.string }; Notification.defaultProps = { notification: '' }; const NotificationContainer = props => <Notification {...props} />; const mapStateToProps = state => ({ notification: state.get('ui').get('notification'), }); const mapDispatchToProps = dispatch => ({ scanFile: (files, getMol) => { dispatch({ type: types.SET_LOADING }); dispatch(scanFile(files, getMol)).then(() => dispatch({ type: types.UNSET_LOADING })); }, }); export default connect( mapStateToProps, mapDispatchToProps )(NotificationContainer);
ComPlat/chemotion_ELN
app/packs/src/components/chemscanner/containers/NotificationContainer.js
JavaScript
agpl-3.0
1,582
#ifndef SERVER_MISC_STRUCTS_H_ #define SERVER_MISC_STRUCTS_H_ #ifndef _TIME_H #include <time.h> #endif #include <string.h> #include <stdint.h> #include "misc/parse.h" #include "misc/spells.h" class sstring; // forward declarations class TObj; class TBeing; class TMonster; class TPerson; class TRoom; class TThing; class Craps; class Descriptor; class TAccount; class affectedData; class saveAffectedData; class roomDirData; class TFuel; class TLight; class TBaseLight; class TDrug; class TDrugContainer; class TFood; class TEgg; class TPen; class TOpal; class TPortal; class TOrganic; class TFFlame; class TGas; class TASubstance; class TTrap; class TKey; class TTool; class TComponent; class TSymbol; class TVial; class TPCorpse; class TMagicItem; class TDrinkCon; class TBaseCup; class TBaseWeapon; class TArrow; class TBow; class TBaseCorpse; class TTable; class TBaseContainer; class TOpenContainer; class TSuitcase; class TBoard; class liqInfoT; class currencyInfoT; class ignoreList; const int MAX_BUF_LENGTH = 240; typedef signed char sbyte; typedef unsigned char ubyte; typedef signed char byte; extern char * mud_str_dup(const char *buf); extern char * mud_str_dup(const sstring &buf); extern char * mud_str_copy(char *dest, const sstring &src, size_t n); class lag_data { public: time_t high; time_t low; time_t total; time_t current; unsigned long count; time_t lagstart[10]; time_t lagtime[10]; unsigned long lagcount[10]; lag_data() : high(0), low(99999), total(0), current(0), count(0) { memset(&lagstart, 0, sizeof(lagstart)); memset(&lagtime, 0, sizeof(lagtime)); memset(&lagcount, 0, sizeof(lagcount)); } }; extern lag_data lag_info; const bool TRUE = true; const bool FALSE = false; const int BIT_POOF_IN = 1; const int BIT_POOF_OUT = 2; const int WAIT_SEC = 4; const int WAIT_ROUND = 4; const unsigned int MAX_STRING_LENGTH = 32000; const int MAX_INPUT_LENGTH = 1024; const int MAX_MESSAGES = 60; const int MAX_ITEMS = 15; const int MESS_ATTACKER = 1; const int MESS_VICTIM = 2; const int MESS_ROOM = 3; const int SECS_PER_REAL_MIN = 60; const int SECS_PER_REAL_HOUR = (60*SECS_PER_REAL_MIN); const int SECS_PER_REAL_DAY = (24*SECS_PER_REAL_HOUR); const int SECS_PER_REAL_YEAR = (365*SECS_PER_REAL_DAY); const int INCHES_PER_FOOT = 12; const int FEET_PER_YARD = 3; const int INCHES_PER_YARD = INCHES_PER_FOOT * FEET_PER_YARD; const int CUBIC_INCHES_PER_FOOT = INCHES_PER_FOOT * INCHES_PER_FOOT * INCHES_PER_FOOT; const int CUBIC_INCHES_PER_YARD = INCHES_PER_YARD * INCHES_PER_YARD * INCHES_PER_YARD; const int MIN_GLOB_TRACK_LEV = 31; /* mininum level for global track */ const int MAX_BAN_HOSTS = 15; // pet information const unsigned int PETTYPE_PET = (1<<0); // 1 const unsigned int PETTYPE_CHARM = (1<<1); // 2 const unsigned int PETTYPE_THRALL = (1<<2); // 4 struct show_room_zone_struct { int blank; int startblank, lastblank; int bottom, top; sstring sb; }; class snoopData { public: TBeing *snooping; // Who am I snooping TBeing *snoop_by; // Who is snooping me snoopData(); snoopData(const snoopData &a); snoopData & operator=(const snoopData &a); ~snoopData(); }; class aliasData { public: char word[12]; // Word for new alias char command[30]; // Command to be aliased aliasData(); aliasData(const aliasData &a); aliasData & operator=(const aliasData &a); ~aliasData(); }; class betData { public: int come; int crap; int slot; int eleven; int twelve; int two; int three; int horn_bet; int field_bet; int hard_eight; int hard_six; int hard_ten; int hard_four; int seven; int one_craps; betData(); betData(const betData &a); betData & operator=(const betData &a); ~betData(); }; class cBetData { public: unsigned int crapsOptions; unsigned int oneRoll; unsigned int roulOptions; cBetData(); cBetData(const cBetData &a); cBetData & operator=(const cBetData &a); ~cBetData(); }; class lastChangeData { public: short hit; short mana; short move; double piety; int money; double exp; int room; double perc; int mudtime; int minute; int fighting; byte full, thirst, pos; short lifeforce; lastChangeData(); lastChangeData(const lastChangeData &a); ~lastChangeData(); }; class objAffData { public: spellNumT type; /* The type of spell that caused this */ sbyte level; /* The level of the affect */ int duration; /* For how long its effects will last */ int renew; /* at what duration it can be reuned */ applyTypeT location; /* Tells which ability to change(APPLY_XXX)*/ long modifier; /* This is added to apropriate ability */ long modifier2; long bitvector; /* Tells which bits to set (AFF_XXX) */ objAffData(); objAffData(const objAffData &a); objAffData & operator=(const objAffData &a); ~objAffData(); void checkForBadness(TObj *); }; class roomDirData { public: const char *description; // What you see when you look at the direction const char *keyword; // keyword for opening and closing doors doorTypeT door_type; // type of door unsigned int condition; // bitvector for door status short lock_difficulty; // how hard to open, -1 = unlockable short weight; // how heavy door is, -1 = no door short trap_info; // Trap flags short trap_dam; // Damage trap will do int key; // Number of object that opens door int to_room; // What room we exit to. -1 means no exit void destroyDoor(dirTypeT, int); void caveinDoor(dirTypeT, int); void wardDoor(dirTypeT, int); doorTypeT doorType() { return door_type; }; int destination() { return to_room; }; const sstring getName() const; const sstring closed() const; roomDirData(); roomDirData(const roomDirData &a); roomDirData & operator=(const roomDirData &a); ~roomDirData(); }; class wizListInfo { public: char *buf1; char *buf2; char *buf3; /* char *buf60; char *buf59; char *buf58; char *buf57; char *buf56; char *buf55; char *buf54; char *buf53; char *buf52; char *buf51; */ wizListInfo(); ~wizListInfo(); }; const int PERMANENT_DURATION = -9; // for affectedData.duration enum joinFlag { joinFlagNone = 0, joinFlagCreateOnly = 1, // fail if this affect is already applied joinFlagUpdateOnly = 2, // fail if this affect isnt already there joinFlagAllowMultiples = 4, // allow multiples of the same affect (by spell) joinFlagOverwriteDur = 8, // overwrite an existing duration with this one joinFlagUpdateDur = 16, // only update duration if this one is higher joinFlagAlwaysRenew = 32, // always allow this affect to be renewed joinFlagAveDur = 64, // average the two durations joinFlagAveMod = 128, // average the two modifiers // composite/default flags joinFlagDefault = joinFlagNone, joinFlagDisease = joinFlagUpdateDur, joinFlagAll = -1, }; class affectedData { public: spellNumT type; sbyte level; int duration; int renew; long modifier; long modifier2; applyTypeT location; uint64_t bitvector; TThing *be; affectedData *next; affectedData(); affectedData(const affectedData &a); affectedData(const saveAffectedData &a); affectedData & operator=(const affectedData &a); ~affectedData(); bool operator !=(affectedData &cmp) { return !(*this == cmp); } bool operator ==(affectedData &cmp) { if (type != cmp.type || location != cmp.location) return false; if (location == APPLY_IMMUNITY || location == APPLY_SPELL) return modifier == cmp.modifier; return true; } long getMod() { return (location == APPLY_IMMUNITY || location == APPLY_SPELL) ? modifier2 : modifier; } void setMod(long v) { if (location == APPLY_IMMUNITY || location == APPLY_SPELL) modifier2 = v; else modifier = v; } bool canBeRenewed() const; bool shouldGenerateText() const; }; // affects size of charFile class saveAffectedData { public: short type; sbyte level; int duration; int renew; long modifier; long modifier2; byte location; uint64_t bitvector; void *unused2; saveAffectedData(); saveAffectedData & operator=(const affectedData &a); }; #if 1 template<class T> inline bool IS_SET(T a, const T b) { return ((a & b) != 0); } template<class T> inline bool IS_SET_ONLY(T a, const T b) { return ((a & b) == b); } template<class T> inline bool IS_SET_DELETE(T a, const T b) { return ((a & b) == b); } template<class T> inline void SET_BIT(T& a, const T& b) { a |= b; } template<class T> inline void REMOVE_BIT(T& a, const T& b) { a &= ~b; } template<class T> inline void ADD_DELETE(T& a, const T& b) { a |= b; } template<class T> inline void REM_DELETE(T& a, const T& b) { a &= ~b; } #else inline bool IS_SET(int a, const int b) { return ((a & b) != 0); } inline bool IS_SET_ONLY(int a, const int b) { return ((a & b) == b); } inline bool IS_SET_DELETE(int a, const int b) { return ((a & b) == b); } inline void SET_BIT(int& a, const int& b) { a |= b; } inline void SET_BIT(unsigned short& a, const unsigned short& b) { a |= b; } inline void SET_BIT(unsigned int& a, const unsigned int& b) { a |= b; } inline void SET_BIT(unsigned long& a, const unsigned long& b) { a |= b; } inline void REMOVE_BIT(int& a, const int& b) { a &= ~b; } inline void REMOVE_BIT(unsigned short& a, const unsigned short& b) { a &= ~b; } inline void REMOVE_BIT(unsigned int& a, const unsigned int& b) { a &= ~b; } inline void REMOVE_BIT(unsigned long& a, const unsigned long& b) { a &= ~b; } inline void ADD_DELETE(int& a, const int& b) { a |= b; } inline void REM_DELETE(int& a, const int& b) { a &= ~b; } #endif inline int GET_BITS(int a, int p, int n) { // return ((a >> (p + 1 - n)) & ~(~0 << n)); } int x, y; x = (a >> (p+1-n)); y = ~(~0 <<n); return x & y; } inline int GET_BITS_CORRECT(int a, int p, int n) { // return ((a >> (p + 1 - n)) & ~(~0 << n)); } int x, y; x = (a >> (p+1-n)); y = ~(~0 <<n); if (n > 7 && x & 1<<(n-1)) // preserve negative values for bytes and up return (x & y) ^ ~y; return x & y; } inline void SET_BITS(int& a, int p, int n, const int y) { // a = ((a & ~(~(~0 << n) << (p+1-n))) | (y << (p+1-n))); } int q,r,s,x; q = (~0 << n); r = (~q << (p+1-n)); s = (a & ~r); x = (y <<(p+1-n)); a = (s | x); return; } inline void SET_BITS_CORRECT(int& a, int p, int n, const int y) { // a = ((a & ~(~(~0 << n) << (p+1-n))) | (y << (p+1-n))); } int q,r,s,x; q = (~0 << n); r = (~q << (p+1-n)); s = (a & ~r); x = (y <<(p+1-n)); // x gets &'d with r to keep from clobbering higher-order bits with a y=-1 a = (s | (x & r)); return; } #endif // MISC_STRUCTS_H_ inclusion sandwich
grimhaven/grimhaven
server/misc/structs.h
C
agpl-3.0
11,239
/** * Created by mark.feder on 10/13/2015. */ (function (mw, $) { "use strict"; mw.KIVQApi = function (embedPlayer) { return this.init(embedPlayer); }; if (!(mw.KIVQApi.prototype = { bindPostfix: '.KIVQApi', init: function (embedPlayer) { var _this = this; this.destroy(); this.embedPlayer = embedPlayer; this.getUserEntryIdAndQuizParams = function(callback){ var getQuizuserEntryIdAndQuizParams = [{ 'service': 'userEntry', 'action': 'list', 'filter:objectType': 'KalturaQuizUserEntryFilter', 'filter:entryIdEqual': _this.embedPlayer.kentryid, 'filter:userIdEqualCurrent':'1', 'filter:orderBy': '-createdAt' }, { 'service': 'quiz_quiz', 'action': 'get', 'entryId': _this.embedPlayer.kentryid }]; _this.getKClient().doRequest(getQuizuserEntryIdAndQuizParams, function (data) { callback(data); }); }; this.getQuestionAnswerCuepoint = function(kQuizUserEntryId,callback){ var getCp = [{ 'service': 'cuepoint_cuepoint', 'action': 'list', 'filter:entryIdEqual': _this.embedPlayer.kentryid, 'filter:objectType': 'KalturaCuePointFilter', 'filter:cuePointTypeEqual': 'quiz.QUIZ_QUESTION', 'filter:orderBy': '+startTime' },{ 'service': 'cuepoint_cuepoint', 'action': 'list', 'filter:objectType': 'KalturaAnswerCuePointFilter', 'filter:entryIdEqual':_this.embedPlayer.kentryid, 'filter:quizUserEntryIdEqual':kQuizUserEntryId, 'filter:cuePointTypeEqual': 'quiz.QUIZ_ANSWER' }]; _this.getKClient().doRequest(getCp, function (data) { callback(data); }); }; this.createQuizUserEntryId = function(callback){ var createQuizuserEntryId = { 'service': 'userEntry', 'action': 'add', 'userEntry:objectType': 'KalturaQuizUserEntry', 'userEntry:entryId': _this.embedPlayer.kentryid }; _this.getKClient().doRequest(createQuizuserEntryId, function (data) { callback(data); }); }; this.addAnswer = function(isAnswered,selectedAnswer,kQuizUserEntryId,questionNr,callback){ var _this = this,answerParams = {}; var quizSetAnswer = { 'service': 'cuepoint_cuepoint', 'cuePoint:objectType': "KalturaAnswerCuePoint", 'cuePoint:answerKey': selectedAnswer, 'cuePoint:quizUserEntryId': kQuizUserEntryId }; if (isAnswered) { answerParams = { 'action': 'update', 'id': $.cpObject.cpArray[questionNr].answerCpId, 'cuePoint:entryId': _this.embedPlayer.kentryid } } else { answerParams = { 'action': 'add', 'cuePoint:entryId': $.cpObject.cpArray[questionNr].cpEntryId, 'cuePoint:parentId': $.cpObject.cpArray[questionNr].cpId, 'cuePoint:startTime': '0' }; } $.extend(quizSetAnswer, answerParams); _this.getKClient().doRequest(quizSetAnswer, function (data) { callback(data); }); }; this.submitQuiz = function (kQuizUserEntryId,callback) { var submitQuizParams = { 'service': 'userEntry', 'action': 'submitQuiz', 'id': kQuizUserEntryId }; _this.getKClient().doRequest(submitQuizParams, function (data) { callback(data); }); }; this.downloadIvqPDF = function (EntryId,callback) { var downloadPdf = { 'service': 'quiz_quiz', 'action': 'getUrl', 'quizOutputType':1, 'entryId': EntryId }; _this.getKClient().doRequest(downloadPdf, function (data) { callback(data); }); }; }, destroy: function () { }, getKClient: function () { var _this = this; if (!this.kClient) { this.kClient = mw.kApiGetPartnerClient(_this.embedPlayer.kwidgetid); } return this.kClient; } })) { } })(window.mw, window.jQuery );
joanpuigsanz/mwEmbed
modules/Quiz/resources/IVQApiCall.js
JavaScript
agpl-3.0
5,376
/** * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'language', 'pt-br', { button: 'Configure o Idioma', remove: 'Remover Idioma' } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/language/lang/pt-br.js
JavaScript
agpl-3.0
284
import json from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.urls import reverse from django.db import models from django.utils.html import strip_tags from opaque_keys.edx.django.models import CourseKeyField from six import text_type class Note(models.Model): """ Stores user Notes for the LMS local Notes service. .. pii: Legacy model for an app that edx.org hasn't used since 2013 .. pii_types: other .. pii_retirement: retained """ user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE) course_id = CourseKeyField(max_length=255, db_index=True) uri = models.CharField(max_length=255, db_index=True) text = models.TextField(default="") quote = models.TextField(default="") range_start = models.CharField(max_length=2048) # xpath string range_start_offset = models.IntegerField() range_end = models.CharField(max_length=2048) # xpath string range_end_offset = models.IntegerField() tags = models.TextField(default="") # comma-separated string created = models.DateTimeField(auto_now_add=True, null=True, db_index=True) updated = models.DateTimeField(auto_now=True, db_index=True) class Meta: app_label = 'notes' def clean(self, json_body): """ Cleans the note object or raises a ValidationError. """ if json_body is None: raise ValidationError('Note must have a body.') body = json.loads(json_body) if not isinstance(body, dict): raise ValidationError('Note body must be a dictionary.') # NOTE: all three of these fields should be considered user input # and may be output back to the user, so we need to sanitize them. # These fields should only contain _plain text_. self.uri = strip_tags(body.get('uri', '')) self.text = strip_tags(body.get('text', '')) self.quote = strip_tags(body.get('quote', '')) ranges = body.get('ranges') if ranges is None or len(ranges) != 1: raise ValidationError('Note must contain exactly one range.') self.range_start = ranges[0]['start'] self.range_start_offset = ranges[0]['startOffset'] self.range_end = ranges[0]['end'] self.range_end_offset = ranges[0]['endOffset'] self.tags = "" tags = [strip_tags(tag) for tag in body.get('tags', [])] if len(tags) > 0: self.tags = ",".join(tags) def get_absolute_url(self): """ Returns the absolute url for the note object. """ kwargs = {'course_id': text_type(self.course_id), 'note_id': str(self.pk)} return reverse('notes_api_note', kwargs=kwargs) def as_dict(self): """ Returns the note object as a dictionary. """ return { 'id': self.pk, 'user_id': self.user.pk, 'uri': self.uri, 'text': self.text, 'quote': self.quote, 'ranges': [{ 'start': self.range_start, 'startOffset': self.range_start_offset, 'end': self.range_end, 'endOffset': self.range_end_offset }], 'tags': self.tags.split(","), 'created': str(self.created), 'updated': str(self.updated) }
jolyonb/edx-platform
lms/djangoapps/notes/models.py
Python
agpl-3.0
3,401
module PdfHelpers def pdf_file_name(record) date = record.try(:pdf_updated_at) || record.updated_at "#{record.model_name.human}-#{record.id}-#{date.strftime '%F'}.pdf" end def render_to_pdf(action = "#{action_name}.html") html = render_to_string(action: action, layout: WickedPdf.config[:layout]) WickedPdf.new.pdf_from_string(html) end def render_pdf_attachment(record) unless record.pdf.exists? raise ActiveRecord::RecordNotFound, 'PDF attachment does not exist' end send_file record.pdf.path, disposition: 'inline', filename: pdf_file_name(record) end def save_with_pdf(record, action = 'show.html') record.pdf = StringIO.new(render_to_pdf(action)) if record.generate_pdf record.save end end
panter/aoz-003
app/controllers/concerns/pdf_helpers.rb
Ruby
agpl-3.0
769
**Description:** Describe in a couple of sentences what this PR adds **JIRA:** Link to JIRA ticket **Merge deadline:** List merge deadline (if any) **Configuration instructions:** List any non-trivial configuration instructions (if any). **Testing instructions:** 1. Open page A 2. Do thing B 3. Expect C to happen 4. If D happened instead - check failed. **Reviewers:** - [ ] tag reviewer - [ ] tag reviewer **Merge checklist:** - [ ] All reviewers approved - [ ] CI build is green - [ ] Documentation updated (not only docstrings) - [ ] Commits are squashed **Post merge:** - [ ] Delete working branch (if not needed anymore) **Author concerns:** List any concerns about this PR - inelegant solutions, hacks, quick-and-dirty implementations, concerns about migrations, etc.
Livit/Livit.Learn.EdX
.github/PULL_REQUEST_TEMPLATE.md
Markdown
agpl-3.0
785
<!DOCTYPE html> <html lang="en" > <head> <title>40123224 cdw11 報告 - CDW11 網頁 (虎尾科大MDE)</title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> /*some stuff for output/input prompts*/ div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid} div.cell.edit_mode{border-radius:4px;border:thin #008000 solid} div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none} div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em} @media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1} div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em} div.prompt:empty{padding-top:0;padding-bottom:0} div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;} div.inner_cell{width:90%;} div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;} div.input_prompt{color:navy;border-top:1px solid transparent;} div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;} div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);} div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;} div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;} div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);} div.output_prompt{color:darkred;} a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;} h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;} /* end stuff for output/input prompts*/ .highlight-ipynb .hll { background-color: #ffffcc } .highlight-ipynb { background: #f8f8f8; } .highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */ .highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */ .highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */ .highlight-ipynb .o { color: #666666 } /* Operator */ .highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */ .highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */ .highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */ .highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */ .highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */ .highlight-ipynb .ge { font-style: italic } /* Generic.Emph */ .highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */ .highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */ .highlight-ipynb .go { color: #888888 } /* Generic.Output */ .highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ .highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */ .highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */ .highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */ .highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ .highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ .highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */ .highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ .highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */ .highlight-ipynb .m { color: #666666 } /* Literal.Number */ .highlight-ipynb .s { color: #BA2121 } /* Literal.String */ .highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */ .highlight-ipynb .nb { color: #008000 } /* Name.Builtin */ .highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */ .highlight-ipynb .no { color: #880000 } /* Name.Constant */ .highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */ .highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */ .highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ .highlight-ipynb .nf { color: #0000FF } /* Name.Function */ .highlight-ipynb .nl { color: #A0A000 } /* Name.Label */ .highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ .highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */ .highlight-ipynb .nv { color: #19177C } /* Name.Variable */ .highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ .highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */ .highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */ .highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */ .highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */ .highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */ .highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */ .highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */ .highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ .highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */ .highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ .highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */ .highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ .highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */ .highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */ .highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */ .highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */ .highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */ .highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */ .highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */ .highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */ .highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */ </style> <style type="text/css"> /* Overrides of notebook CSS for static HTML export */ div.entry-content { overflow: visible; padding: 8px; } .input_area { padding: 0.2em; } a.heading-anchor { white-space: normal; } .rendered_html code { font-size: .8em; } pre.ipynb { color: black; background: #f7f7f7; border: none; box-shadow: none; margin-bottom: 0; padding: 0; margin: 0px; font-size: 13px; } /* remove the prompt div from text cells */ div.text_cell .prompt { display: none; } /* remove horizontal padding from text cells, */ /* so it aligns with outer body text */ div.text_cell_render { padding: 0.5em 0em; } img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none} </style> <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script> <script type="text/javascript"> init_mathjax = function() { if (window.MathJax) { // MathJax loaded MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\(","\\)"] ], displayMath: [ ['$$','$$'], ["\\[","\\]"] ] }, displayAlign: 'left', // Change this to 'center' to center equations. "HTML-CSS": { styles: {'.MathJax_Display': {"margin": 0}} } }); MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } } init_mathjax(); </script> <link rel="canonical" href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40123224-cdw11-bao-gao.html"> <meta name="author" content="40123224" /> <meta name="keywords" content="40123224,cdw11" /> <meta name="description" content="啟動 cdw11 協同專案" /> <meta property="og:site_name" content="CDW11 網頁 (虎尾科大MDE)" /> <meta property="og:type" content="article"/> <meta property="og:title" content="40123224 cdw11 報告"/> <meta property="og:url" content="http://bg11cdw11-40323240.rhcloud.com/static/blog/40123224-cdw11-bao-gao.html"/> <meta property="og:description" content="啟動 cdw11 協同專案"/> <meta property="article:published_time" content="2016-06-19" /> <meta property="article:section" content="bg3" /> <meta property="article:tag" content="40123224" /> <meta property="article:tag" content="cdw11" /> <meta property="article:author" content="40123224" /> <!-- Bootstrap --> <link rel="stylesheet" href="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/css/bootstrap.united.min.css" type="text/css"/> <link href="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/css/pygments/monokai.css" rel="stylesheet"> <link href="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/tipuesearch/tipuesearch.css" rel="stylesheet"> <link rel="stylesheet" href="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/css/style.css" type="text/css"/> <link href="http://bg11cdw11-40323240.rhcloud.com/static/blog/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="CDW11 網頁 (虎尾科大MDE) ATOM Feed"/> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shCore.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJScript.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJava.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPython.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushSql.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushXml.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPhp.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCpp.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCss.js"></script> <script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCSharp.js"></script> <script type='text/javascript'> (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shCore.css"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.getElementsByTagName("head")[0].insertBefore( corecss, document.getElementById("syntaxhighlighteranchor") ); var themecssurl = "http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } //document.getElementById("syntaxhighlighteranchor").appendChild(themecss); document.getElementsByTagName("head")[0].insertBefore( themecss, document.getElementById("syntaxhighlighteranchor") ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['pad-line-numbers'] = false; SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); </script> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/" class="navbar-brand"> CDW11 網頁 (虎尾科大MDE) </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag1.html">Ag1</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag10.html">Ag10</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag1_40223153.html">Ag1_40223153</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag1_402231530.html">Ag1_402231530</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag2.html">Ag2</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag3.html">Ag3</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag4.html">Ag4</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag7.html">Ag7</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag8.html">Ag8</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag9.html">Ag9</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg1.html">Bg1</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg10.html">Bg10</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg101.html">Bg101</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg11.html">Bg11</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg2.html">Bg2</a> </li> <li class="active"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg3.html">Bg3</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg4.html">Bg4</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg5.html">Bg5</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg8.html">Bg8</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg9.html">Bg9</a> </li> <li > <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/g3.html">G3</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><span> <form class="navbar-search" action="http://bg11cdw11-40323240.rhcloud.com/static/blog/search.html"> <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required> </form></span> </li> <li><a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="content"> <article> <header class="page-header"> <h1> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40123224-cdw11-bao-gao.html" rel="bookmark" title="Permalink to 40123224 cdw11 報告"> 40123224 cdw11 報告 </a> </h1> </header> <div class="entry-content"> <div class="panel"> <div class="panel-body"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2016-06-19T17:10:08.544950+08:00"> 週日 19 六月 2016</time> </span> <span class="label label-default">By</span> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/author/40123224.html"><i class="fa fa-user"></i> 40123224</a> <span class="label label-default">Tags</span> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/tag/40123224.html">40123224</a> / <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/tag/cdw11.html">cdw11</a> </footer><!-- /.post-info --> </div> </div> <p>啟動 cdw11 協同專案</p> <p>pelican 網誌位置: <a href="http://cdw11-ag100.rhcloud.com/static/">http://cdw11-ag100.rhcloud.com/static/</a></p> <p>分組程式: <a href="http://cdw11-ag100.rhcloud.com/option">http://cdw11-ag100.rhcloud.com/option</a></p> <p>fileuploadform: <a href="http://cdw11-ag100.rhcloud.com/fileuploadform">http://cdw11-ag100.rhcloud.com/fileuploadform</a></p> <p>imageuploadform: <a href="http://cdw11-ag100.rhcloud.com/imageuploadform">http://cdw11-ag100.rhcloud.com/imageuploadform</a></p> <p>請各組在 CDW11 下課前完成下列3個圖形的零件組合繪圖:</p> <p><img src="http://cdw11-ag100.rhcloud.com/images/cdw11_4a.png" width="100%" /></p> <p><img src="http://cdw11-ag100.rhcloud.com/images/cdw11_badc.png" width="100%" /></p> <p><img src="http://cdw11-ag100.rhcloud.com/images/cdw11_abcd.png" width="100%" /></p> </div> <!-- /.entry-content --> <hr/> <section class="comments" id="comments"> <h2>Comments</h2> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'cadlabmanual'; // required: replace example with your forum shortname var disqus_identifier = '40123224-cdw11-bao-gao'; var disqus_url = 'http://bg11cdw11-40323240.rhcloud.com/static/blog/40123224-cdw11-bao-gao.html'; var disqus_config = function () { this.language = "en"; }; /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> </section> </article> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4> <ul class="list-group" id="recentposts"> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40323240-cdw14-bao-gao.html"> 40323240 cdw14 報告 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40323240-cdw13-bao-gao.html"> 40323240 cdw13 報告 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40323240-cdw11-bao-gao.html"> 40323240 cdw11 報告 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40323250-qi-mo-bao-gao.html"> 40323250 期末報告 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/40323250-cdw13bao-gao.html"> 40323250 cdw13報告 </a> </li> </ul> </li> <li class="list-group-item"><a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a> <ul class="list-group" id="categories"> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag1.html"> <i class="fa fa-folder-open fa-lg"></i> ag1 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag10.html"> <i class="fa fa-folder-open fa-lg"></i> ag10 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag1_40223153.html"> <i class="fa fa-folder-open fa-lg"></i> ag1_40223153 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag1_402231530.html"> <i class="fa fa-folder-open fa-lg"></i> ag1_402231530 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag2.html"> <i class="fa fa-folder-open fa-lg"></i> ag2 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag3.html"> <i class="fa fa-folder-open fa-lg"></i> ag3 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag4.html"> <i class="fa fa-folder-open fa-lg"></i> ag4 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag7.html"> <i class="fa fa-folder-open fa-lg"></i> ag7 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag8.html"> <i class="fa fa-folder-open fa-lg"></i> ag8 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/ag9.html"> <i class="fa fa-folder-open fa-lg"></i> ag9 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg1.html"> <i class="fa fa-folder-open fa-lg"></i> bg1 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg10.html"> <i class="fa fa-folder-open fa-lg"></i> bg10 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg101.html"> <i class="fa fa-folder-open fa-lg"></i> bg101 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg11.html"> <i class="fa fa-folder-open fa-lg"></i> bg11 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg2.html"> <i class="fa fa-folder-open fa-lg"></i> bg2 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg3.html"> <i class="fa fa-folder-open fa-lg"></i> bg3 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg4.html"> <i class="fa fa-folder-open fa-lg"></i> bg4 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg5.html"> <i class="fa fa-folder-open fa-lg"></i> bg5 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg8.html"> <i class="fa fa-folder-open fa-lg"></i> bg8 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/bg9.html"> <i class="fa fa-folder-open fa-lg"></i> bg9 </a> </li> <li class="list-group-item"> <a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/category/g3.html"> <i class="fa fa-folder-open fa-lg"></i> g3 </a> </li> </ul> </li> <li class="list-group-item"><a href="http://bg11cdw11-40323240.rhcloud.com/static/blog/tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a> <ul class="list-group list-inline tagcloud" id="tags"> </ul> </li> <li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4> <ul class="list-group" id="links"> <li class="list-group-item"> <a href="http://getpelican.com/" target="_blank"> Pelican </a> </li> <li class="list-group-item"> <a href="https://github.com/DandyDev/pelican-bootstrap3/" target="_blank"> pelican-bootstrap3 </a> </li> <li class="list-group-item"> <a href="https://github.com/getpelican/pelican-plugins" target="_blank"> pelican-plugins </a> </li> <li class="list-group-item"> <a href="https://github.com/Tipue/Tipue-Search" target="_blank"> Tipue search </a> </li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2016 kmol &middot; Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="http://bg11cdw11-40323240.rhcloud.com/static/blog/theme/js/respond.min.js"></script> <!-- Disqus --> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'cadlabmanual'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); </script> <!-- End Disqus Code --> </body> </html>
40323240/personal-cdw11
static/blog/40123224-cdw11-bao-gao.html
HTML
agpl-3.0
33,568
# frozen_string_literal: true class AboutController < ApplicationController before_action :set_body_classes before_action :set_instance_presenter, only: [:show, :more, :terms] def show if @instance_presenter.contact_account redirect_to short_account_path(@instance_presenter.contact_account) return end serializable_resource = ActiveModelSerializers::SerializableResource.new(InitialStatePresenter.new(initial_state_params), serializer: InitialStateSerializer) @initial_state_json = serializable_resource.to_json end def more render layout: 'public' end def terms render layout: 'public' end private def new_user User.new.tap(&:build_account) end helper_method :new_user def set_instance_presenter @instance_presenter = InstancePresenter.new end def set_body_classes @body_classes = 'with-modals' end def initial_state_params { settings: { known_fediverse: Setting.show_known_fediverse_at_about_page }, token: current_session&.token, } end end
rutan/mastodon
app/controllers/about_controller.rb
Ruby
agpl-3.0
1,060
/* * Copyright 2014, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.k3po.pcap.converter.internal; import junit.framework.TestCase; import org.kaazing.k3po.pcap.converter.internal.packet.Packet; import org.kaazing.k3po.pcap.converter.internal.utils.PacketUtil; import org.kaazing.k3po.pcap.converter.internal.utils.Util; public abstract class AbstractTcpTest extends TestCase { protected static final String CLIENT_IP = "111.111.1.11"; protected static final String SERVER_IP = "222.222.22.222"; protected static final Integer SERVER_PORT = 8080; protected static final Integer CLIENT_PORT = 99999; //client fin protected static final long INITIAL_CLIENT_FIN_SEQNUM = 01L; protected static final long INITIAL_CLIENT_FIN_ACKNUM = 101L; protected static final Packet CLIENT_FIN_PACKET = PacketUtil.getTcpFinPacket(SERVER_IP, CLIENT_IP, SERVER_PORT, CLIENT_PORT, INITIAL_CLIENT_FIN_SEQNUM, INITIAL_CLIENT_FIN_ACKNUM); //server fin protected static final long INITIAL_SERVER_FIN_SEQNUM = 201L; protected static final long INITIAL_SERVER_FIN_ACKNUM = 2101L; protected static final Packet SERVER_FIN_PACKET = PacketUtil.getTcpFinPacket(CLIENT_IP, SERVER_IP, CLIENT_PORT, SERVER_PORT, INITIAL_SERVER_FIN_SEQNUM, INITIAL_SERVER_FIN_ACKNUM); //server ack protected static final long SERVER_RESPONSE_ACK_SEQNUM = 202L; protected static final long SERVER_RESPONSE_ACK_ACKNUM = INITIAL_CLIENT_FIN_SEQNUM + 1L; protected static final Packet SERVER_ACK_PACKET = PacketUtil.getTcpAckPacket(CLIENT_IP, SERVER_IP, CLIENT_PORT, SERVER_PORT, SERVER_RESPONSE_ACK_SEQNUM, SERVER_RESPONSE_ACK_ACKNUM); //client ack protected static final long CLIENT_RESPONSE_ACK_SEQNUM = 02L; protected static final long CLIENT_RESPONSE_ACK_ACKNUM = INITIAL_SERVER_FIN_SEQNUM + 1L; protected static final Packet CLIENT_ACK_PACKET = PacketUtil.getTcpAckPacket(SERVER_IP, CLIENT_IP, SERVER_PORT, CLIENT_PORT, CLIENT_RESPONSE_ACK_SEQNUM, CLIENT_RESPONSE_ACK_ACKNUM); protected final byte[] defaultPayloadByteArray = {0x01, 0x30, 0x30, 0x30, 0x30, (byte)0xFF}; protected final int defaultPayloadLength = defaultPayloadByteArray.length; protected final Packet toClientPayloadPacket = PacketUtil.getTcpPayloadPacket(CLIENT_IP, SERVER_IP, CLIENT_PORT, SERVER_PORT, defaultPayloadByteArray); protected final Packet toServerPayloadPacket = PacketUtil.getTcpPayloadPacket(SERVER_IP, CLIENT_IP, SERVER_PORT, CLIENT_PORT, defaultPayloadByteArray); protected final String payloadScriptWrite = "write [" + Util.getHexFromBytes(defaultPayloadByteArray) + "]"; protected final String payloadScriptRead = "read [" + Util.getHexFromBytes(defaultPayloadByteArray) + "]"; protected final String defaultAsciiPayloadStr = "Hello Robot\n"; protected final byte[] defaultAsciiPayloadByteArray = defaultAsciiPayloadStr.getBytes(); protected final int defaultAsciiPayloadLength = defaultAsciiPayloadByteArray.length; protected final Packet toClientAsciiPayloadPacket = PacketUtil.getTcpPayloadPacket(CLIENT_IP, SERVER_IP, CLIENT_PORT, SERVER_PORT, defaultAsciiPayloadByteArray); protected final Packet toServerAsciiPayloadPacket = PacketUtil.getTcpPayloadPacket(SERVER_IP, CLIENT_IP, SERVER_PORT, CLIENT_PORT, defaultAsciiPayloadByteArray); protected final String asciiPayloadScriptWrite = "write \"" + defaultAsciiPayloadStr.replace("\n", "\\n") + "\""; protected final String asciiPayloadScriptRead = "read \"" + defaultAsciiPayloadStr.replace("\n", "\\n") + "\""; }
irina-mitrea-luxoft/k3po
k3po.pcap.converter/src/test/java/org/kaazing/k3po/pcap/converter/internal/AbstractTcpTest.java
Java
agpl-3.0
4,188
Backbone.SIXHIARA = Backbone.SIXHIARA || {}; Backbone.SIXHIARA.ButtonSaveView = Backbone.View.extend({ events: { "click": "save" }, initialize: function() { this.$el.prop('disabled', true); this.listenTo(this.model, 'aChangeHappens', function(){ this.$el.prop('disabled', false) }, this); }, save: function(){ if(this.model.isValid()){ this.model.save(null, { wait: true, success: function(model, resp, options) { window.location = model.urlShow(); }, error: function(xhr, textStatus, errorThrown) { if (textStatus && textStatus.responseJSON && textStatus.responseJSON.error) { if(Array.isArray(textStatus.responseJSON.error)) { bootbox.alert(textStatus.responseJSON.error.join('\n')); } else{ bootbox.alert(textStatus.responseJSON.error); } } else { bootbox.alert(textStatus.statusText); } } }); } else { bootbox.alert(this.model.validationError.join('\n')); } } });
iCarto/utentes-ui
views/common/ButtonSaveView.js
JavaScript
agpl-3.0
1,314
{% from "macros/_form.html" import render_field, render_label, render_input, render_button with context %} {% set label_width = 'col-sm-2' %} {% set control_width = 'col-sm-6' %} {% macro render_field_default(field, offset='', control_class=control_width, group='') %} {%if offset%}{% set control_class = control_width+' '+offset %}{%endif%} {{ render_field(field, class_={'label': label_width, 'control': control_class, 'group': group} ) }} {% endmacro %} {% set page_title = _("Campaign") %} {% extends "layouts/base_admin.html" %} {% block body %} <h3>{% if edit %}Edit{%else%}New{%endif%} Campaign</h3> <form class="form-horizontal" id="campaign" method="POST" action="" > {{ form.hidden_tag() }} <fieldset class="border"> <legend>Type</legend> {{render_field_default(form.name) }} {# campaign type including nested #} {% with %} {% set field = form.campaign_type %} {% set state = form.campaign_state %} {% set nested_field = form.campaign_subtype %} <div class="form-group campaign_type {% if field.errors %}error{% endif %}"> {{ render_label(field, label_width) }} <div class="control-group {{control_width}}"> {{ field(class_='form-control inline') }} {{ state(class_='form-control inline hide-initial') }} {{ nested_field(class_='form-control inline nested', **{'data-nested-choices': CAMPAIGN_NESTED_CHOICES|json, 'data-nested-selected': nested_field.object_data} ) }} <div class="description"> <span class="glyphicon glyphicon-info-sign info small"></span> <span class="help-inline">{{ descriptions.get(field.id)|safe }}</span> </div> {% if field.errors -%} {% for error in field.errors -%} <span class="help-block error">{{ error|e }}</span> {%- endfor %} {%- endif %} {% if nested_field.errors -%} {% for error in nested_field.errors -%} <span class="help-block error">{{ error|e }}</span> {%- endfor %} {%- endif %} </div> <span class="help-block"></span> </div> {% endwith %} </fieldset> <fieldset class="border"> <legend>Targets</legend> {{ render_field(form.segment_by, class_={'label': label_width, 'control': control_width, 'clear': True}) }} {{ render_field(form.locate_by, class_={'label': label_width, 'control': control_width, 'clear': True}) }} <div class="form-group hide-initial" id="set-targets"> {{render_label(form.target_set, label_width)}} <div class="controls {{control_width}}"> <div class="control-group"> <div class="input-group col-sm-10 left" id="target-search"> <span class="input-group-addon glyphicon glyphicon-search"></span> <div class="search-results open"> <input type="text" class="form-control" name="target-search" placeholder="search"/> </div> <span class="input-group-btn"> <button class="btn btn-default search" type="button">Go</button> </span> </div> <div class="input-group right"> <button class="btn btn-primary add" type="button">Add</button> <div class="description"> <span class="glyphicon glyphicon-info-sign info small"></span> <span class="help-inline">{{ descriptions.get('target_set')|safe }}</span> </div> </div> </div> <!-- target_set entries stored as hidden inputs named target_set-N-FIELD --> <div id="target-set" class="hidden"> {% if form.target_set.data|length %} <input type="hidden" name="target_set_length" value="{{form.target_set|length}}" /> {% endif %} {% for error in form.target_set.errors -%} {# load errors here, for client-side display #} <input type="hidden" name="{{error.target}}-error" value="{{ error.message }}" /> {%- endfor %} {% for t in form.target_set.data %} <input type="hidden" name="target_set-{{loop.index0}}-order" value="{{loop.index0}}" /> <input type="hidden" name="target_set-{{loop.index0}}-title" value="{{t.title}}" /> <input type="hidden" name="target_set-{{loop.index0}}-name" value="{{t.name}}" /> <input type="hidden" name="target_set-{{loop.index0}}-number" value="{{t.number.international}}" /> <input type="hidden" name="target_set-{{loop.index0}}-uid" value="{{t.uid}}" /> {% endfor %} </div> <ol class="target-list list-group sortable hide-initial"></ol> <span class="help-block"></span> </div> </div> {{render_field_default(form.target_ordering) }} {{render_field_default(form.call_limit, offset='col-sm-offset-2') }} {% with %} {% if form.call_maximum.data > 0 %} {% set call_max_display = '' %} {% else %} {% set call_max_display = 'hide-initial' %} {% endif %} {{render_field_default(form.call_maximum, group=call_max_display) }} {% endwith %} </fieldset> <fieldset class="border"> <legend>Phone Numbers</legend> {{render_field_default(form.phone_number_set) }} <div class="col-sm-6 col-sm-offset-2"> <div class="pull-right"><a class="btn btn-default" href="/admin/system" target="_blank">Get More</a> </div> </div> {{render_field_default(form.allow_call_in, offset='col-sm-offset-2') }} </fieldset> <div class="form-group container"> <div class="form-actions"> {% if edit %} <a class="btn btn-warning" href="{{ url_for('campaign.status', campaign_id=campaign_id) }}">Edit Status</a> {%endif%} <div class="pull-right"> {{render_button(form.submit, {'field':'btn-success', 'icon':'arrow-right'}) }} </div> </div> </div> </form> {% endblock %} {% block scripts %} <script type="text/template" id="search-results-dropdown-tmpl"> <ul class="dropdown-menu open"> <li role="presentation" class="dropdown-header"> Search Results <span class="close btn btn-xs">&times;</span> </li> </ul> </script> <script type="text/template" id="search-results-item-tmpl"> <li class="result"> <a data-object='{ "title":"<%= data.title %>", "name":"<%= data.first_name %> <%= data.last_name %>", "number":"<%= data.phone %>", "uid": "<%= data.uid %>" }'> <span class="text"><%= data.title %> <%= data.first_name %> <%= data.last_name %> (<%= data.party %>-<%= data.state %>)</span> <span class="phone"><%= data.phone %></span> </a> </li> </script> <script type="text/template" id="target-item-tmpl"> <span data-field="title" contenteditable placeholder="Title"><%= data.title %></span> <span data-field="name" contenteditable placeholder="Name"><%= data.name %></span> <span data-field="number" contenteditable placeholder="Phone"><%= data.number %></span> <div class="pull-right"> <span class="glyphicon glyphicon-move handle btn btn-xs"></span> <span class="glyphicon glyphicon-remove remove btn btn-xs btn-danger"></span> </div> </script> {% endblock %}
poppingtonic/call-power
call_server/templates/campaign/form.html
HTML
agpl-3.0
8,399
<?php // created: 2015-09-15 18:06:35 $dictionary['AOS_Quotes']['fields']['po_number_c']['inline_edit']='1'; $dictionary['AOS_Quotes']['fields']['po_number_c']['labelValue']='po number'; ?>
chemspace/chemspaceCRM
custom/Extension/modules/AOS_Quotes/Ext/Vardefs/sugarfield_po_number_c.php
PHP
agpl-3.0
192
/** * Axelor Business Solutions * * Copyright (C) 2005-2016 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ package com.axelor.db; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.EntityManager; import javax.persistence.FlushModeType; import javax.persistence.TypedQuery; import com.axelor.db.mapper.Mapper; import com.axelor.db.mapper.Property; import com.axelor.db.mapper.PropertyType; import com.axelor.rpc.Resource; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Provider; /** * The {@code Query} class allows filtering and fetching records quickly. * * <p> * It also provides {@link #update(Map)} and {@link #delete()} method to perform * mass update and delete operation on matched records. * */ public class Query<T extends Model> { private Class<T> beanClass; private String filter; private Object[] params; private Map<String, Object> namedParams; private String orderBy; private JoinHelper joinHelper; private boolean cacheable; private FlushModeType flushMode = FlushModeType.AUTO; private static final String NAME_PATTERN = "((?:[a-zA-Z_]\\w+)(?:(?:\\[\\])?\\.\\w+)*)"; private static final Pattern orderPattern = Pattern.compile( "(\\-)?(?:self\\.)?" + NAME_PATTERN, Pattern.CASE_INSENSITIVE); /** * Create a new instance of {@code Query} with given bean class. * * <p> * Before using the instance, an {@code EntityManager} provider should be * either injected by the {@code Guice} container or should be provided * manually using {@link #setEntityManagerProvider(Provider)} method. * * @param beanClass * model bean class */ public Query(Class<T> beanClass) { this.beanClass = beanClass; this.orderBy = ""; this.joinHelper = new JoinHelper(beanClass); } public static <T extends Model> Query<T> of(Class<T> klass) { return new Query<T>(klass); } protected EntityManager em() { return JPA.em(); } /** * A convenient method to filter the query using JPQL's <i>where</i> clause. * * <p> * The filter string should refer the field names with {@code self.} prefix * and values should not be embedded into the filter string but should be * passed by parameters and {@code ?} placeholder should be used to mark * parameter substitutions. * * Here is an example: * * <pre> * Query&lt;Person&gt; query = Query.of(Person); * query = query.filter(&quot;self.name = ? AND self.age &gt;= ?&quot;, &quot;some&quot;, 20); * * List&lt;Person&gt; matched = query.fetch(); * </pre> * * <p> * This is equivalent to: * * <pre> * SELECT self from Person self WHERE (self.name = ?1) AND (self.age >= ?2) * </pre> * * <p> * The params passed will be added as positional parameters to the JPA query * object before performing {@link #fetch()}. * * @param filter * the filter string * @param params * the parameters * @return the same instance */ public Query<T> filter(String filter, Object... params) { if (this.filter != null) { throw new IllegalStateException("Query is already filtered."); } this.filter = joinHelper.parse(filter); this.params = params; return this; } public Query<T> filter(String filter) { final Object[] params = {}; return filter(filter, params); } /** * Set order by clause for the query. This method can be chained to provide * multiple fields. * * <p> * The {@code spec} is just a field name for {@code ASC} or should be * prefixed with {@code -} for {@code DESC} clause. * * <p> * For example: * * <pre> * Query&lt;Person&gt; query = Query.of(Person); * query = query.filter(&quot;name =&quot;, &quot;some&quot;).filter(&quot;age &gt;=&quot;, 20) * .filter(&quot;lang in&quot;, &quot;en&quot;, &quot;hi&quot;); * * query = query.order(&quot;name&quot;).order(&quot;-age&quot;); * </pre> * * <p> * This is equivalent to: * * <pre> * SELECT p from Person p WHERE (p.name = ?1) AND (p.age >= ?2) AND (lang IN (?3, ?4)) ORDER BY p.name, p.age DESC * </pre> * * @param spec * order spec * @return the same query instance */ public Query<T> order(String spec) { Matcher m = orderPattern.matcher(spec.trim()); if (!m.matches()) { throw new IllegalArgumentException("Invalid order spec: " + spec); } if (orderBy.length() > 0) { orderBy += ", "; } else { orderBy = " ORDER BY "; } String name = this.joinHelper.joinName(m.group(2)); orderBy += name + ("-".equals(m.group(1)) ? " DESC" : ""); return this; } /** * Set the query result cacheable. * * @return the same query instance */ public Query<T> cacheable() { this.cacheable = true; return this; } public Query<T> autoFlush(boolean auto) { this.flushMode = auto ? FlushModeType.AUTO : FlushModeType.COMMIT; return this; } /** * Fetch all the matched records. * * @return list of all the matched records. */ public List<T> fetch() { return fetch(0, 0); } /** * Fetch the matchied records with the given limit. * * @param limit * the limit * @return matched records withing the limit */ public List<T> fetch(int limit) { return fetch(limit, 0); } /** * Fetch the matched records within the given range. * * @param limit * the limit * @param offset * the offset * @return list of matched records within the range */ public List<T> fetch(int limit, int offset) { final TypedQuery<T> query = em().createQuery(selectQuery(), beanClass); if (limit > 0) { query.setMaxResults(limit); } if (offset > 0) { query.setFirstResult(offset); } this.bind(query).opts(cacheable, flushMode); return query.getResultList(); } /** * Fetch the first matched record. * * @return the first matched record. */ public T fetchOne() { try { return fetch(1).get(0); } catch (IndexOutOfBoundsException e) { } return null; } /** * Fetch a matched record at the given offset. * * @param offset * the offset * @return the matched record at given offset */ public T fetchOne(int offset) { try { return fetch(1, offset).get(0); } catch (IndexOutOfBoundsException e) { } return null; } /** * Returns the number of total records matched. * * @return total number */ public long count() { final TypedQuery<Long> query = em().createQuery(countQuery(), Long.class); this.bind(query).opts(cacheable, flushMode); return query.getSingleResult(); } /** * Return a selector to select records with specific fields only. * * @param names field names to select * @return a new instance of {@link Selector} */ public Selector select(String... names) { return new Selector(names); }; /** * Perform mass update on the matched records with the given values. * To avoid unexpected results, clear the session with {@link JPA.clear} * before running the update. * * @param values * the key value map * @return total number of records updated */ public int update(Map<String, Object> values) { final Map<String, Object> params = Maps.newHashMap(); final Map<String, Object> namedParams = Maps.newHashMap(); if (this.namedParams != null) { namedParams.putAll(this.namedParams); } for(String key : values.keySet()) { String name = key.replaceFirst("^self\\.", ""); params.put(name, values.get(key)); namedParams.put(name, values.get(key)); } javax.persistence.Query q = em().createQuery(updateQuery(params)); QueryBinder.of(q).bind(namedParams, this.params); return q.executeUpdate(); } /** * This is similar to {@link #update(Map)} but updates only single field. * * @param field * the field name whose value needs to be changed * @param value * the new value * @return total number of records updated */ public int update(String name, Object value) { Map<String, Object> values = Maps.newHashMap(); values.put(name.replaceFirst("^self\\.", ""), value); return update(values); } /** * Bulk delete all the matched records. <br> * <br> * * This method uses <code>DELETE</code> query and performs * {@link javax.persistence.Query#executeUpdate()}. * * @see #remove() * @return total number of records affected. */ public int delete() { javax.persistence.Query q = em().createQuery(deleteQuery()); this.bind(q); return q.executeUpdate(); } /** * Remove all the matched records. <br> * <br> * * In contrast to the {@link #delete()} method, it performs * {@link EntityManager#remove(Object)} operation by fetching objects in * pages (100 at a time). * * @see #delete() * @return total number of records removed. */ public long remove() { long n = this.count(); while(this.count() > 0) { for(T o : this.fetch(100)) JPA.remove(o); } return n; } protected String selectQuery() { StringBuilder sb = new StringBuilder("SELECT self FROM ") .append(beanClass.getSimpleName()) .append(" self") .append(joinHelper.toString()); if (filter != null && filter.trim().length() > 0) sb.append(" WHERE ").append(filter); sb.append(orderBy); return sb.toString(); } protected String countQuery() { StringBuilder sb = new StringBuilder("SELECT COUNT(self) FROM ") .append(beanClass.getSimpleName()) .append(" self") .append(joinHelper.toString()); if (filter != null && filter.trim().length() > 0) sb.append(" WHERE ").append(filter); return sb.toString(); } protected String updateQuery(Map<String, Object> values) { StringBuilder sb = new StringBuilder("UPDATE ") .append(beanClass.getSimpleName()) .append(" self"); List<String> keys = Lists.newArrayList(); for (String key : values.keySet()) { keys.add(String.format("self.%s = :%s", key, key)); } sb.append(" SET ").append(Joiner.on(", ").join(keys)); if (filter != null && filter.trim().length() > 0) { sb.append(" WHERE self.id IN (") .append(selectQuery().replaceFirst("SELECT self", "SELECT self.id").replaceAll("\\bself", "that")) .append(")"); } return sb.toString(); } protected String deleteQuery() { StringBuilder sb = new StringBuilder("DELETE FROM ") .append(beanClass.getSimpleName()) .append(" self"); if (filter != null && filter.trim().length() > 0) { sb.append(" WHERE self.id IN (") .append(selectQuery().replaceFirst("SELECT self", "SELECT self.id").replaceAll("\\bself", "that")) .append(")"); } return sb.toString(); } protected QueryBinder bind(javax.persistence.Query query) { return QueryBinder.of(query).bind(namedParams, params); } /** * Bind the named parameters of the query with the given values. Named * parameter must me set after query is filtered. * * @param params * mapping for named params. */ public Query<T> bind(Map<String, Object> params) { if (this.filter == null) { throw new IllegalStateException("Query is not filtered yet."); } if (this.namedParams == null) { this.namedParams = Maps.newHashMap(); } if (params != null) { this.namedParams.putAll(params); } return this; } /** * Bind the given named parameter of the query with the given value. * * @param name * the named parameter to bind * @param value * the parameter value * */ public Query<T> bind(String name, Object value) { Map<String, Object> params = Maps.newHashMap(); params.put(name, value); return this.bind(params); } @Override public String toString() { return selectQuery(); } /** * A helper class to select specific field values. The record is returned as * a Map object with the given names as keys. * * <pre> * List&lt;Map&gt; data = Contact.all().filter(&quot;self.age &gt; ?&quot;, 20) * .select(&quot;title.name&quot;, &quot;fullName&quot;, &quot;age&quot;).fetch(80, 0); * </pre> * * This results in following query: * * <pre> * SELECT _title.name, self.fullName JOIN LEFT self.title AS _title WHERE self.age > ? LIMIT 80 * </pre> * * The {@link Selector#fetch(int, int)} method returns a List of Map instead * of the model object. */ public class Selector { private List<String> names = Lists.newArrayList("id", "version"); private List<String> collections = Lists.newArrayList(); private String query; private Mapper mapper = Mapper.of(beanClass); private Selector(String... names) { List<String> selects = Lists.newArrayList(); selects.add("self.id"); selects.add("self.version"); for(String name : names) { Property property = getProperty(name); if (property != null && property.getType() != PropertyType.BINARY) { String alias = joinHelper.joinName(name); if (alias != null) { selects.add(alias); this.names.add(name); } else { collections.add(name); } // select id,version,name field for m2o if (property.isReference() && property.getTargetName() != null) { this.names.add(name + ".id"); this.names.add(name + ".version"); this.names.add(name + "." + property.getTargetName()); selects.add(joinHelper.joinName(name + ".id")); selects.add(joinHelper.joinName(name + ".version")); selects.add(joinHelper.joinName(name + "." + property.getTargetName())); } } } StringBuilder sb = new StringBuilder("SELECT ") .append(" new List(" + Joiner.on(", ").join(selects) + ")") .append(" FROM ") .append(beanClass.getSimpleName()) .append(" self") .append(joinHelper.toString()); if (filter != null && filter.trim().length() > 0) sb.append(" WHERE ").append(filter); sb.append(orderBy); query = sb.toString(); } private Property getProperty(String field) { if (field == null || "".equals(field.trim())) return null; Mapper mapper = this.mapper; Property property = null; Iterator<String> names = Splitter.on(".").split(field).iterator(); while(names.hasNext()) { property = mapper.getProperty(names.next()); if (property == null) return null; if (names.hasNext()) { if (property.getTarget() == null) return null; mapper = Mapper.of(property.getTarget()); } } return property; } @SuppressWarnings("all") public List<List> values(int limit, int offset) { javax.persistence.Query q = em().createQuery(query); if (limit > 0) { q.setMaxResults(limit); } if (offset > 0) { q.setFirstResult(offset); } bind(q).opts(cacheable, flushMode); return q.getResultList(); } @SuppressWarnings("all") public List<Map> fetch(int limit, int offset) { List<List> data = values(limit, offset); List<Map> result = Lists.newArrayList(); for(List items : data) { Map<String, Object> map = Maps.newHashMap(); for(int i = 0 ; i < names.size() ; i++) { Object value = items.get(i); String name = names.get(i); Property property = getProperty(name); // in case of m2o, get the id,version,name tuple if (property != null && property.isReference() && property.getTargetName() != null) { value = getReferenceValue(items, i); i += 3; } else if (value instanceof Model) { value = Resource.toMapCompact(value); } map.put(name, value); } if (collections.size() > 0) { map.putAll(this.fetchCollections(items.get(0))); } result.add(map); } return result; } private Object getReferenceValue(List<?> items, int at) { if (items.get(at) == null) { return null; } Map<String, Object> value = Maps.newHashMap(); String name = names.get(at); String nameField = names.get(at + 3).replace(name + ".", ""); value.put("id", items.get(at+1)); value.put("$version", items.get(at+2)); value.put(nameField, items.get(at+3)); return value; } @SuppressWarnings("all") private Map<String, List> fetchCollections(Object id) { Map<String, List> result = Maps.newHashMap(); Object self = JPA.em().find(beanClass, id); for(String name : collections) { Collection<Model> items = (Collection<Model>) mapper.get(self, name); if (items != null) { List<Object> all = Lists.newArrayList(); for(Model obj : items) { all.add(Resource.toMapCompact(obj)); } result.put(name, all); } } return result; } @Override public String toString() { return query; } } /** * JoinHelper class is used to auto generate <code>LEFT JOIN</code> for * association expressions. * * For example: * * <pre> * Query<Contact> q = Contact.all().filter("self.title.code = ?1 OR self.age > ?2", "mr", 20); * </pre> * * Results in: * * <pre> * SELECT self FROM Contact self LEFT JOIN self.title _title WHERE _title.code = ?1 OR self.age > ?2 * </pre> * * So that all the records are matched even if <code>title</code> field is null. * */ static class JoinHelper { private Class<?> beanClass; private Map<String, String> joins = Maps.newLinkedHashMap(); private static final Pattern pathPattern = Pattern.compile("self\\." + NAME_PATTERN); public JoinHelper(Class<?> beanClass) { this.beanClass = beanClass; } /** * Parse the given filter string and return transformed filter * expression. * * Automatically calculate <code>LEFT JOIN</code> for association path * expressions and the path expressions are replaced with the join * variables. * * @param filter * the filter expression * @return the transformed filter expression */ public String parse(String filter) { String result = ""; Matcher matcher = pathPattern.matcher(filter); int last = 0; while (matcher.find()) { MatchResult matchResult = matcher.toMatchResult(); String alias = joinName(matchResult.group(1)); if (alias == null) { alias = "self." + matchResult.group(1); } result += filter.substring(last, matchResult.start()) + alias; last = matchResult.end(); } if (last < filter.length()) result += filter.substring(last); return result; } /** * Automatically generate <code>LEFT JOIN</code> for the given name * (association path expression) and return the join variable. * * @param name * the path expression or field name * @return join variable if join is created else returns name */ public String joinName(String name) { Mapper mapper = Mapper.of(beanClass); String[] path = name.split("\\."); String prefix = null; String variable = name; if (path.length > 1) { variable = path[path.length - 1]; String joinOn = null; Mapper currentMapper = mapper; for(int i = 0 ; i < path.length - 1 ; i++) { String item = path[i].replace("[]", ""); Property property = currentMapper.getProperty(item); if (property == null) { break; } if (prefix == null) { joinOn = "self." + item; prefix = "_" + item; } else { joinOn = prefix + "." + item; prefix = prefix + "_" + item; } if (!joins.containsKey(joinOn)) { joins.put(joinOn, prefix); } if (property.getTarget() != null) { currentMapper = Mapper.of(property.getTarget()); } if (i == path.length - 2) { property = currentMapper.getProperty(variable); if (property == null) { throw new IllegalArgumentException( String.format("No such field '%s' in object '%s'", variable, currentMapper.getBeanClass().getName())); } if (property != null && property.getTarget() != null) { joinOn = prefix + "." + variable; prefix = prefix + "_" + variable; joins.put(joinOn, prefix); return prefix; } } } } else { Property property = mapper.getProperty(name); if (property != null && property.getTarget() != null) { if (property.isCollection()) { return null; } prefix = "_" + name; joins.put("self." + name, prefix); return prefix; } } if (prefix == null) { prefix = "self"; } return prefix + "." + variable; } @Override public String toString() { if (joins.size() == 0) return ""; List<String> joinItems = Lists.newArrayList(); for(String key : joins.keySet()) { String val = joins.get(key); joinItems.add("LEFT JOIN " + key + " " + val); } return " " + Joiner.on(" ").join(joinItems); } } }
donsunsoft/axelor-development-kit
axelor-core/src/main/java/com/axelor/db/Query.java
Java
agpl-3.0
21,355
# -*- coding: utf-8 -*- """ Basic unit tests for LibraryContentBlock Higher-level tests are in `cms/djangoapps/contentstore/tests/test_libraries.py`. """ import six from bson.objectid import ObjectId from fs.memoryfs import MemoryFS from lxml import etree from mock import Mock, patch from search.search_engine_base import SearchEngine from six.moves import range from web_fragments.fragment import Fragment from xblock.runtime import Runtime as VanillaRuntime from xmodule.library_content_module import ANY_CAPA_TYPE_VALUE, LibraryContentBlock from xmodule.library_tools import LibraryToolsService from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.factories import CourseFactory, LibraryFactory from xmodule.modulestore.tests.utils import MixedSplitTestCase from xmodule.tests import get_test_system from xmodule.validation import StudioValidationMessage from xmodule.x_module import AUTHOR_VIEW from .test_course_module import DummySystem as TestImportSystem dummy_render = lambda block, _: Fragment(block.data) # pylint: disable=invalid-name class LibraryContentTest(MixedSplitTestCase): """ Base class for tests of LibraryContentBlock (library_content_block.py) """ def setUp(self): super(LibraryContentTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.tools = LibraryToolsService(self.store, self.user_id) self.library = LibraryFactory.create(modulestore=self.store) self.lib_blocks = [ self.make_block("html", self.library, data="Hello world from block {}".format(i)) for i in range(1, 5) ] self.course = CourseFactory.create(modulestore=self.store) self.chapter = self.make_block("chapter", self.course) self.sequential = self.make_block("sequential", self.chapter) self.vertical = self.make_block("vertical", self.sequential) self.lc_block = self.make_block( "library_content", self.vertical, max_count=1, source_library_id=six.text_type(self.library.location.library_key) ) def _bind_course_module(self, module): """ Bind a module (part of self.course) so we can access student-specific data. """ module_system = get_test_system(course_id=module.location.course_key) module_system.descriptor_runtime = module.runtime._descriptor_system # pylint: disable=protected-access module_system._services['library_tools'] = self.tools # pylint: disable=protected-access def get_module(descriptor): """Mocks module_system get_module function""" sub_module_system = get_test_system(course_id=module.location.course_key) sub_module_system.get_module = get_module sub_module_system.descriptor_runtime = descriptor._runtime # pylint: disable=protected-access descriptor.bind_for_student(sub_module_system, self.user_id) return descriptor module_system.get_module = get_module module.xmodule_runtime = module_system class TestLibraryContentExportImport(LibraryContentTest): """ Export and import tests for LibraryContentBlock """ maxDiff = None def test_xml_export_import_cycle(self): """ Test the export-import cycle. """ # Children will only set after calling this. self.lc_block.refresh_children() lc_block = self.store.get_item(self.lc_block.location) expected_olx = ( '<library_content display_name="{block.display_name}" max_count="{block.max_count}"' ' source_library_id="{block.source_library_id}" source_library_version="{block.source_library_version}">\n' ' <html url_name="{block.children[0].block_id}"/>\n' ' <html url_name="{block.children[1].block_id}"/>\n' ' <html url_name="{block.children[2].block_id}"/>\n' ' <html url_name="{block.children[3].block_id}"/>\n' '</library_content>\n' ).format( block=lc_block, ) export_fs = MemoryFS() # Set the virtual FS to export the olx to. lc_block.runtime._descriptor_system.export_fs = export_fs # pylint: disable=protected-access # Export the olx. node = etree.Element("unknown_root") lc_block.add_xml_to_node(node) # Read it back with export_fs.open('{dir}/{file_name}.xml'.format( dir=lc_block.scope_ids.usage_id.block_type, file_name=lc_block.scope_ids.usage_id.block_id )) as f: exported_olx = f.read() # And compare. assert exported_olx == expected_olx runtime = TestImportSystem(load_error_modules=True, course_id=lc_block.location.course_key) runtime.resources_fs = export_fs # Now import it. olx_element = etree.fromstring(exported_olx) id_generator = Mock() imported_lc_block = LibraryContentBlock.parse_xml(olx_element, runtime, None, id_generator) # Check the new XBlock has the same properties as the old one. assert imported_lc_block.display_name == lc_block.display_name assert imported_lc_block.source_library_id == lc_block.source_library_id assert imported_lc_block.source_library_version == lc_block.source_library_version assert imported_lc_block.mode == lc_block.mode assert imported_lc_block.max_count == lc_block.max_count assert imported_lc_block.capa_type == lc_block.capa_type assert len(imported_lc_block.children) == 4 assert imported_lc_block.children == lc_block.children class LibraryContentBlockTestMixin(object): """ Basic unit tests for LibraryContentBlock """ problem_types = [ ["multiplechoiceresponse"], ["optionresponse"], ["optionresponse", "coderesponse"], ["coderesponse", "optionresponse"] ] problem_type_lookup = {} def _get_capa_problem_type_xml(self, *args): """ Helper function to create empty CAPA problem definition """ problem = "<problem>" for problem_type in args: problem += "<{problem_type}></{problem_type}>".format(problem_type=problem_type) problem += "</problem>" return problem def _create_capa_problems(self): """ Helper function to create a set of capa problems to test against. Creates four blocks total. """ self.problem_type_lookup = {} for problem_type in self.problem_types: block = self.make_block("problem", self.library, data=self._get_capa_problem_type_xml(*problem_type)) self.problem_type_lookup[block.location] = problem_type def test_lib_content_block(self): """ Test that blocks from a library are copied and added as children """ # Check that the LibraryContent block has no children initially # Normally the children get added when the "source_libraries" setting # is updated, but the way we do it through a factory doesn't do that. assert len(self.lc_block.children) == 0 # Update the LibraryContent module: self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) # Check that all blocks from the library are now children of the block: assert len(self.lc_block.children) == len(self.lib_blocks) def test_children_seen_by_a_user(self): """ Test that each student sees only one block as a child of the LibraryContent block. """ self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) self._bind_course_module(self.lc_block) # Make sure the runtime knows that the block's children vary per-user: assert self.lc_block.has_dynamic_children() assert len(self.lc_block.children) == len(self.lib_blocks) # Check how many children each user will see: assert len(self.lc_block.get_child_descriptors()) == 1 # Check that get_content_titles() doesn't return titles for hidden/unused children assert len(self.lc_block.get_content_titles()) == 1 def test_validation_of_course_libraries(self): """ Test that the validation method of LibraryContent blocks can validate the source_library setting. """ # When source_library_id is blank, the validation summary should say this block needs to be configured: self.lc_block.source_library_id = "" result = self.lc_block.validate() assert not result # Validation fails due to at least one warning/message assert result.summary assert StudioValidationMessage.NOT_CONFIGURED == result.summary.type # When source_library_id references a non-existent library, we should get an error: self.lc_block.source_library_id = "library-v1:BAD+WOLF" result = self.lc_block.validate() assert not result # Validation fails due to at least one warning/message assert result.summary assert StudioValidationMessage.ERROR == result.summary.type assert 'invalid' in result.summary.text # When source_library_id is set but the block needs to be updated, the summary should say so: self.lc_block.source_library_id = six.text_type(self.library.location.library_key) result = self.lc_block.validate() assert not result # Validation fails due to at least one warning/message assert result.summary assert StudioValidationMessage.WARNING == result.summary.type assert 'out of date' in result.summary.text # Now if we update the block, all validation should pass: self.lc_block.refresh_children() assert self.lc_block.validate() def test_validation_of_matching_blocks(self): """ Test that the validation method of LibraryContent blocks can warn the user about problems with other settings (max_count and capa_type). """ # Set max_count to higher value than exists in library self.lc_block.max_count = 50 # In the normal studio editing process, editor_saved() calls refresh_children at this point self.lc_block.refresh_children() result = self.lc_block.validate() assert not result # Validation fails due to at least one warning/message assert result.summary assert StudioValidationMessage.WARNING == result.summary.type assert 'only 4 matching problems' in result.summary.text # Add some capa problems so we can check problem type validation messages self.lc_block.max_count = 1 self._create_capa_problems() self.lc_block.refresh_children() assert self.lc_block.validate() # Existing problem type should pass validation self.lc_block.max_count = 1 self.lc_block.capa_type = 'multiplechoiceresponse' self.lc_block.refresh_children() assert self.lc_block.validate() # ... unless requested more blocks than exists in library self.lc_block.max_count = 10 self.lc_block.capa_type = 'multiplechoiceresponse' self.lc_block.refresh_children() result = self.lc_block.validate() assert not result # Validation fails due to at least one warning/message assert result.summary assert StudioValidationMessage.WARNING == result.summary.type assert 'only 1 matching problem' in result.summary.text # Missing problem type should always fail validation self.lc_block.max_count = 1 self.lc_block.capa_type = 'customresponse' self.lc_block.refresh_children() result = self.lc_block.validate() assert not result # Validation fails due to at least one warning/message assert result.summary assert StudioValidationMessage.WARNING == result.summary.type assert 'no matching problem types' in result.summary.text def test_capa_type_filtering(self): """ Test that the capa type filter is actually filtering children """ self._create_capa_problems() assert len(self.lc_block.children) == 0 # precondition check self.lc_block.capa_type = "multiplechoiceresponse" self.lc_block.refresh_children() assert len(self.lc_block.children) == 1 self.lc_block.capa_type = "optionresponse" self.lc_block.refresh_children() assert len(self.lc_block.children) == 3 self.lc_block.capa_type = "coderesponse" self.lc_block.refresh_children() assert len(self.lc_block.children) == 2 self.lc_block.capa_type = "customresponse" self.lc_block.refresh_children() assert len(self.lc_block.children) == 0 self.lc_block.capa_type = ANY_CAPA_TYPE_VALUE self.lc_block.refresh_children() assert len(self.lc_block.children) == (len(self.lib_blocks) + 4) def test_non_editable_settings(self): """ Test the settings that are marked as "non-editable". """ non_editable_metadata_fields = self.lc_block.non_editable_metadata_fields assert LibraryContentBlock.mode in non_editable_metadata_fields assert LibraryContentBlock.display_name not in non_editable_metadata_fields def test_overlimit_blocks_chosen_randomly(self): """ Tests that blocks to remove from selected children are chosen randomly when len(selected) > max_count. """ blocks_seen = set() total_tries, max_tries = 0, 100 self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) self._bind_course_module(self.lc_block) # Eventually, we should see every child block selected while len(blocks_seen) != len(self.lib_blocks): self._change_count_and_refresh_children(len(self.lib_blocks)) # Now set the number of selections to 1 selected = self._change_count_and_refresh_children(1) blocks_seen.update(selected) total_tries += 1 if total_tries >= max_tries: assert False, "Max tries exceeded before seeing all blocks." break def _change_count_and_refresh_children(self, count): """ Helper method that changes the max_count of self.lc_block, refreshes children, and asserts that the number of selected children equals the count provided. """ self.lc_block.max_count = count selected = self.lc_block.get_child_descriptors() assert len(selected) == count return selected @patch('xmodule.library_tools.SearchEngine.get_search_engine', Mock(return_value=None, autospec=True)) class TestLibraryContentBlockNoSearchIndex(LibraryContentBlockTestMixin, LibraryContentTest): """ Tests for library container when no search index is available. Tests fallback low-level CAPA problem introspection """ pass # pylint:disable=unnecessary-pass search_index_mock = Mock(spec=SearchEngine) # pylint: disable=invalid-name @patch('xmodule.library_tools.SearchEngine.get_search_engine', Mock(return_value=search_index_mock, autospec=True)) class TestLibraryContentBlockWithSearchIndex(LibraryContentBlockTestMixin, LibraryContentTest): """ Tests for library container with mocked search engine response. """ def _get_search_response(self, field_dictionary=None): """ Mocks search response as returned by search engine """ target_type = field_dictionary.get('problem_types') matched_block_locations = [ key for key, problem_types in self.problem_type_lookup.items() if target_type in problem_types ] return { 'results': [ {'data': {'id': str(location)}} for location in matched_block_locations ] } def setUp(self): """ Sets up search engine mock """ super(TestLibraryContentBlockWithSearchIndex, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments search_index_mock.search = Mock(side_effect=self._get_search_response) @patch( 'xmodule.modulestore.split_mongo.caching_descriptor_system.CachingDescriptorSystem.render', VanillaRuntime.render ) @patch('xmodule.html_module.HtmlBlock.author_view', dummy_render, create=True) @patch('xmodule.x_module.DescriptorSystem.applicable_aside_types', lambda self, block: []) class TestLibraryContentRender(LibraryContentTest): """ Rendering unit tests for LibraryContentBlock """ def test_preview_view(self): """ Test preview view rendering """ self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) assert len(self.lc_block.children) == len(self.lib_blocks) self._bind_course_module(self.lc_block) rendered = self.lc_block.render(AUTHOR_VIEW, {'root_xblock': self.lc_block}) assert 'Hello world from block 1' in rendered.content def test_author_view(self): """ Test author view rendering """ self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) assert len(self.lc_block.children) == len(self.lib_blocks) self._bind_course_module(self.lc_block) rendered = self.lc_block.render(AUTHOR_VIEW, {}) assert '' == rendered.content # content should be empty assert 'LibraryContentAuthorView' == rendered.js_init_fn # but some js initialization should happen class TestLibraryContentAnalytics(LibraryContentTest): """ Test analytics features of LibraryContentBlock """ def setUp(self): super(TestLibraryContentAnalytics, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.publisher = Mock() self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) self._bind_course_module(self.lc_block) self.lc_block.xmodule_runtime.publish = self.publisher def _assert_event_was_published(self, event_type): """ Check that a LibraryContentBlock analytics event was published by self.lc_block. """ assert self.publisher.called assert len(self.publisher.call_args[0]) == 3 # pylint:disable=unsubscriptable-object _, event_name, event_data = self.publisher.call_args[0] # pylint:disable=unsubscriptable-object assert event_name == 'edx.librarycontentblock.content.{}'.format(event_type) assert event_data['location'] == six.text_type(self.lc_block.location) return event_data def test_assigned_event(self): """ Test the "assigned" event emitted when a student is assigned specific blocks. """ # In the beginning was the lc_block and it assigned one child to the student: child = self.lc_block.get_child_descriptors()[0] child_lib_location, child_lib_version = self.store.get_block_original_usage(child.location) assert isinstance(child_lib_version, ObjectId) event_data = self._assert_event_was_published("assigned") block_info = { "usage_key": six.text_type(child.location), "original_usage_key": six.text_type(child_lib_location), "original_usage_version": six.text_type(child_lib_version), "descendants": [], } assert event_data ==\ {'location': six.text_type(self.lc_block.location), 'added': [block_info], 'result': [block_info], 'previous_count': 0, 'max_count': 1} self.publisher.reset_mock() # Now increase max_count so that one more child will be added: self.lc_block.max_count = 2 children = self.lc_block.get_child_descriptors() assert len(children) == 2 child, new_child = children if children[0].location == child.location else reversed(children) event_data = self._assert_event_was_published("assigned") assert event_data['added'][0]['usage_key'] == six.text_type(new_child.location) assert len(event_data['result']) == 2 assert event_data['previous_count'] == 1 assert event_data['max_count'] == 2 def test_assigned_event_published(self): """ Same as test_assigned_event but uses the published branch """ self.store.publish(self.course.location, self.user_id) with self.store.branch_setting(ModuleStoreEnum.Branch.published_only): self.lc_block = self.store.get_item(self.lc_block.location) self._bind_course_module(self.lc_block) self.lc_block.xmodule_runtime.publish = self.publisher self.test_assigned_event() def test_assigned_descendants(self): """ Test the "assigned" event emitted includes descendant block information. """ # Replace the blocks in the library with a block that has descendants: with self.store.bulk_operations(self.library.location.library_key): self.library.children = [] main_vertical = self.make_block("vertical", self.library) inner_vertical = self.make_block("vertical", main_vertical) html_block = self.make_block("html", inner_vertical) problem_block = self.make_block("problem", inner_vertical) self.lc_block.refresh_children() # Reload lc_block and set it up for a student: self.lc_block = self.store.get_item(self.lc_block.location) self._bind_course_module(self.lc_block) self.lc_block.xmodule_runtime.publish = self.publisher # Get the keys of each of our blocks, as they appear in the course: course_usage_main_vertical = self.lc_block.children[0] course_usage_inner_vertical = self.store.get_item(course_usage_main_vertical).children[0] inner_vertical_in_course = self.store.get_item(course_usage_inner_vertical) course_usage_html = inner_vertical_in_course.children[0] course_usage_problem = inner_vertical_in_course.children[1] # Trigger a publish event: self.lc_block.get_child_descriptors() event_data = self._assert_event_was_published("assigned") for block_list in (event_data["added"], event_data["result"]): assert len(block_list) == 1 # main_vertical is the only root block added, and is the only result. assert block_list[0]['usage_key'] == six.text_type(course_usage_main_vertical) # Check that "descendants" is a flat, unordered list of all of main_vertical's descendants: descendants_expected = ( (inner_vertical.location, course_usage_inner_vertical), (html_block.location, course_usage_html), (problem_block.location, course_usage_problem), ) descendant_data_expected = {} for lib_key, course_usage_key in descendants_expected: descendant_data_expected[six.text_type(course_usage_key)] = { "usage_key": six.text_type(course_usage_key), "original_usage_key": six.text_type(lib_key), "original_usage_version": six.text_type(self.store.get_block_original_usage(course_usage_key)[1]), } assert len(block_list[0]['descendants']) == len(descendant_data_expected) for descendant in block_list[0]["descendants"]: assert descendant == descendant_data_expected.get(descendant['usage_key']) def test_removed_overlimit(self): """ Test the "removed" event emitted when we un-assign blocks previously assigned to a student. We go from one blocks assigned to none because max_count has been decreased. """ # Decrease max_count to 1, causing the block to be overlimit: self.lc_block.get_child_descriptors() # This line is needed in the test environment or the change has no effect self.publisher.reset_mock() # Clear the "assigned" event that was just published. self.lc_block.max_count = 0 # Check that the event says that one block was removed, leaving no blocks left: children = self.lc_block.get_child_descriptors() assert len(children) == 0 event_data = self._assert_event_was_published("removed") assert len(event_data['removed']) == 1 assert event_data['result'] == [] assert event_data['reason'] == 'overlimit' def test_removed_invalid(self): """ Test the "removed" event emitted when we un-assign blocks previously assigned to a student. We go from two blocks assigned, to one because the others have been deleted from the library. """ # Start by assigning two blocks to the student: self.lc_block.get_child_descriptors() # This line is needed in the test environment or the change has no effect self.lc_block.max_count = 2 initial_blocks_assigned = self.lc_block.get_child_descriptors() assert len(initial_blocks_assigned) == 2 self.publisher.reset_mock() # Clear the "assigned" event that was just published. # Now make sure that one of the assigned blocks will have to be un-assigned. # To cause an "invalid" event, we delete all blocks from the content library # except for one of the two already assigned to the student: keep_block_key = initial_blocks_assigned[0].location keep_block_lib_usage_key, keep_block_lib_version = self.store.get_block_original_usage(keep_block_key) assert keep_block_lib_usage_key is not None deleted_block_key = initial_blocks_assigned[1].location self.library.children = [keep_block_lib_usage_key] self.store.update_item(self.library, self.user_id) self.lc_block.refresh_children() # Check that the event says that one block was removed, leaving one block left: children = self.lc_block.get_child_descriptors() assert len(children) == 1 event_data = self._assert_event_was_published("removed") assert event_data['removed'] ==\ [{'usage_key': six.text_type(deleted_block_key), 'original_usage_key': None, 'original_usage_version': None, 'descendants': []}] assert event_data['result'] ==\ [{'usage_key': six.text_type(keep_block_key), 'original_usage_key': six.text_type(keep_block_lib_usage_key), 'original_usage_version': six.text_type(keep_block_lib_version), 'descendants': []}] assert event_data['reason'] == 'invalid'
stvstnfrd/edx-platform
common/lib/xmodule/xmodule/tests/test_library_content.py
Python
agpl-3.0
26,994
/* Copyright (c) 2000-2013 "independIT Integrative Technologies GmbH", Authors: Ronald Jeninga, Dieter Stubler schedulix Enterprise Job Scheduling System independIT Integrative Technologies GmbH [http://www.independit.de] mailto:contact@independit.de This file is part of schedulix schedulix is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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/>. */ -- Copyright (C) 2001,2002 topIT Informationstechnologie GmbH -- Copyright (C) 2003-2014 independIT Integrative Technologies GmbH CREATE TABLE RESOURCE_REQ_STATES ( ID decimal(20) NOT NULL , RR_ID decimal(20) NOT NULL , RSD_ID decimal(20) NOT NULL , CREATOR_U_ID decimal(20) NOT NULL , CREATE_TS decimal(20) NOT NULL , CHANGER_U_ID decimal(20) NOT NULL , CHANGE_TS decimal(20) NOT NULL , VALID_FROM decimal(20) NOT NULL , VALID_TO decimal(20) NOT NULL ); CREATE INDEX PK_RESOURCE_REQ_STATES ON RESOURCE_REQ_STATES(ID); CREATE VIEW SCI_C_RESOURCE_REQ_STATES AS SELECT ID , RR_ID AS RR_ID , RSD_ID AS RSD_ID , CREATOR_U_ID AS CREATOR_U_ID , timestamptz 'epoch' + cast(to_char(mod(CREATE_TS, 1125899906842624)/1000, '999999999999') as interval) AS CREATE_TS , CHANGER_U_ID AS CHANGER_U_ID , timestamptz 'epoch' + cast(to_char(mod(CHANGE_TS, 1125899906842624)/1000, '999999999999') as interval) AS CHANGE_TS FROM RESOURCE_REQ_STATES WHERE VALID_TO = 9223372036854775807; CREATE VIEW SCI_V_RESOURCE_REQ_STATES AS SELECT ID , RR_ID AS RR_ID , RSD_ID AS RSD_ID , CREATOR_U_ID AS CREATOR_U_ID , timestamptz 'epoch' + cast(to_char(mod(CREATE_TS, 1125899906842624)/1000, '999999999999') as interval) AS CREATE_TS , CHANGER_U_ID AS CHANGER_U_ID , timestamptz 'epoch' + cast(to_char(mod(CHANGE_TS, 1125899906842624)/1000, '999999999999') as interval) AS CHANGE_TS , VALID_FROM , VALID_TO FROM RESOURCE_REQ_STATES;
schedulix/schedulix
sql/pg_gen/RESOURCE_REQ_STATES.sql
SQL
agpl-3.0
2,817
{% extends "base.html" %} {% load i18n %} {% load bootstrap3 %} {% block head_title %}{% if article %}{% trans "Édition de l’article" %}{% else %}{% trans "Nouvel article" %}{% endif %}{% endblock %} {% block bootstrap3_extra_head %} {{ form.media.css }} {% endblock %} {% block body_end %} {{ form.media.js }} {% endblock %} {% block content %} <h1>{% if article %}{% trans "Édition de l’article" %}{% else %}{% trans "Nouvel article" %}{% endif %}</h1> <form method="POST" action="" class="form-horizontal" novalidate> {% csrf_token %} {% bootstrap_form form layout='horizontal' size='small' %} {% buttons %} <button type="submit" class="btn btn-primary pull-right">{% trans "Enregistrer" %}</button> <a class="btn btn-default" href="{% url 'home' %}">{% trans "Annuler" %}</a> {% endbuttons %} </form> {% endblock %}
defivelo/db
apps/article/templates/article/article_form.html
HTML
agpl-3.0
899
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <sstream> #include "exceptions.hh" #include "log.hh" exceptions::truncate_exception::truncate_exception(std::exception_ptr ep) : request_execution_exception(exceptions::exception_code::PROTOCOL_ERROR, sprint("Error during truncate: %s", ep)) {}
kangkot/scylla
exceptions/exceptions.cc
C++
agpl-3.0
1,823
/* * Copyright 2021 Cojen.org * * 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 (at your option) 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/>. */ package org.cojen.tupl; import java.io.Closeable; import java.io.IOException; /** * Support for scanning through all rows in a table. Any exception thrown when acting upon a * scanner automatically closes it. * * <p>RowScanner instances can only be safely used by one thread at a time, and they must be * closed when no longer needed. Instances can be exchanged by threads, as long as a * happens-before relationship is established. Without proper exclusion, multiple threads * interacting with a RowScanner instance may cause database corruption. * * @author Brian S O'Neill * @see Table#newRowScanner Table.newRowScanner * @see RowUpdater * * @author Brian S O'Neill */ public interface RowScanner<R> extends Closeable { /** * Returns a reference to the current row, which is null if the scanner is closed. */ R row(); /** * Step to the next row. * * @return the next row or null if no more rows remain and scanner has been closed */ R step() throws IOException; /** * Step to the next row. * * @param row use this for the next row instead of creating a new one * @return the next row or null if no more rows remain and scanner has been closed * @throws NullPointerException if the given row object is null */ R step(R row) throws IOException; @Override public void close() throws IOException; }
cojen/Tupl
src/main/java/org/cojen/tupl/RowScanner.java
Java
agpl-3.0
2,126
<!DOCTYPE html> <html lang="en"><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <?php include 'include/meta.php'; include 'include/ifmobi.php'; ?> <meta name="Author" content="Anthony Baldwin" /> <title>12Press - Who is an Addict?</title> </head> <body> <?php include 'include/header.php'; include 'include/navbar.php'; ini_set('display_errors', "1"); ini_set('error_reporting', E_ALL ^ E_NOTICE); ?> <div id="main"> <div id="reading"> <h1>Who is an Addict?</h1> <p>Most of us do not have to think twice about this question. We know! Our whole life and thinking was centered in drugs in one form or another—the getting and using and finding ways and means to get more. We lived to use and used to live. Very simply, an addict is a man or woman whose life is controlled by drugs. We are people in the grip of a continuing and progressive illness whose ends are always the same: jails, institutions, and death.</p> <p>&copy; <a href="http://www.na.org">Narcotics Anonymous</a></p> </div> </div> <?php include 'include/footer.php'; ?> </body> </html>
tonybaldwin/12press
who.php
PHP
agpl-3.0
1,084
/* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */ /* cairo - a vector graphics library with display and print output * Copyright � 2006, 2007 Mozilla Corporation * * This library is free software; you can redistribute it and/or * modify it either under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation * (the "LGPL") or, at your option, under the terms of the Mozilla * Public License Version 1.1 (the "MPL"). If you do not alter this * notice, a recipient may use your version of this file under either * the MPL or the LGPL. * * You should have received a copy of the LGPL along with this library * in the file COPYING-LGPL-2.1; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA * You should have received a copy of the MPL along with this library * in the file COPYING-MPL-1.1 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * The Original Code is the cairo graphics library. * The Initial Developer of the Original Code is Mozilla Foundation. * Contributor(s): Vladimir Vukicevic <vladimir@mozilla.com> */ #include "cairoint.h" #pragma hdrstop #if CAIRO_HAS_QUARTZ_SURFACE // { #define _GNU_SOURCE /* required for RTLD_DEFAULT */ #include "cairo-quartz-private.h" //#include "cairo-composite-rectangles-private.h" //#include "cairo-compositor-private.h" //#include "cairo-default-context-private.h" //#include "cairo-error-private.h" //#include "cairo-image-surface-inline.h" //#include "cairo-pattern-private.h" //#include "cairo-surface-backend-private.h" //#include "cairo-surface-clipper-private.h" //#include "cairo-recording-surface-private.h" #include <dlfcn.h> #ifndef RTLD_DEFAULT #define RTLD_DEFAULT ((void *)0) #endif #include <limits.h> #undef QUARTZ_DEBUG #ifdef QUARTZ_DEBUG #define ND(_x) fprintf _x #else #define ND(_x) do {} while(0) #endif #define IS_EMPTY(s) ((s)->extents.width == 0 || (s)->extents.height == 0) /** * SECTION:cairo-quartz * @Title: Quartz Surfaces * @Short_Description: Rendering to Quartz surfaces * @See_Also: #cairo_surface_t * * The Quartz surface is used to render cairo graphics targeting the * Apple OS X Quartz rendering system. **/ /** * CAIRO_HAS_QUARTZ_SURFACE: * * Defined if the Quartz surface backend is available. * This macro can be used to conditionally compile backend-specific code. * * Since: 1.6 **/ #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050 /* This method is private, but it exists. Its params are are exposed * as args to the NS* method, but not as CG. */ enum PrivateCGCompositeMode { kPrivateCGCompositeClear = 0, kPrivateCGCompositeCopy = 1, kPrivateCGCompositeSourceOver = 2, kPrivateCGCompositeSourceIn = 3, kPrivateCGCompositeSourceOut = 4, kPrivateCGCompositeSourceAtop = 5, kPrivateCGCompositeDestinationOver = 6, kPrivateCGCompositeDestinationIn = 7, kPrivateCGCompositeDestinationOut = 8, kPrivateCGCompositeDestinationAtop = 9, kPrivateCGCompositeXOR = 10, kPrivateCGCompositePlusDarker = 11,// (max (0, (1-d) + (1-s))) kPrivateCGCompositePlusLighter = 12,// (min (1, s + d)) }; typedef enum PrivateCGCompositeMode PrivateCGCompositeMode; CG_EXTERN void CGContextSetCompositeOperation(CGContextRef, PrivateCGCompositeMode); #endif /* Some of these are present in earlier versions of the OS than where * they are public; other are not public at all */ /* public since 10.5 */ static void (*CGContextDrawTiledImagePtr)(CGContextRef, CGRect, CGImageRef) = NULL; /* public since 10.6 */ static CGPathRef (* CGContextCopyPathPtr) (CGContextRef) = NULL; static void (* CGContextSetAllowsFontSmoothingPtr) (CGContextRef, bool) = NULL; /* not yet public */ static uint (* CGContextGetTypePtr) (CGContextRef) = NULL; static bool (* CGContextGetAllowsFontSmoothingPtr) (CGContextRef) = NULL; static boolint _cairo_quartz_symbol_lookup_done = FALSE; /* * Utility functions */ #ifdef QUARTZ_DEBUG static void quartz_surface_to_png(cairo_quartz_surface_t * nq, char * dest); static void quartz_image_to_png(CGImageRef, char * dest); #endif static cairo_quartz_surface_t * _cairo_quartz_surface_create_internal(CGContextRef cgContext, cairo_content_t content, uint width, uint height); /* Load all extra symbols */ static void quartz_ensure_symbols(void) { if(LIKELY(_cairo_quartz_symbol_lookup_done)) return; CGContextDrawTiledImagePtr = dlsym(RTLD_DEFAULT, "CGContextDrawTiledImage"); CGContextGetTypePtr = dlsym(RTLD_DEFAULT, "CGContextGetType"); CGContextCopyPathPtr = dlsym(RTLD_DEFAULT, "CGContextCopyPath"); CGContextGetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextGetAllowsFontSmoothing"); CGContextSetAllowsFontSmoothingPtr = dlsym(RTLD_DEFAULT, "CGContextSetAllowsFontSmoothing"); _cairo_quartz_symbol_lookup_done = TRUE; } CGImageRef CairoQuartzCreateCGImage(cairo_format_t format, uint width, uint height, uint stride, void * data, boolint interpolate, CGColorSpaceRef colorSpaceOverride, CGDataProviderReleaseDataCallback releaseCallback, void * releaseInfo) { CGImageRef image = NULL; CGDataProviderRef dataProvider = NULL; CGColorSpaceRef colorSpace = colorSpaceOverride; CGBitmapInfo bitinfo = kCGBitmapByteOrder32Host; int bitsPerComponent, bitsPerPixel; switch(format) { case CAIRO_FORMAT_ARGB32: if(colorSpace == NULL) colorSpace = CGColorSpaceCreateDeviceRGB(); bitinfo |= kCGImageAlphaPremultipliedFirst; bitsPerComponent = 8; bitsPerPixel = 32; break; case CAIRO_FORMAT_RGB24: if(colorSpace == NULL) colorSpace = CGColorSpaceCreateDeviceRGB(); bitinfo |= kCGImageAlphaNoneSkipFirst; bitsPerComponent = 8; bitsPerPixel = 32; break; case CAIRO_FORMAT_A8: bitsPerComponent = 8; bitsPerPixel = 8; break; case CAIRO_FORMAT_A1: #ifdef WORDS_BIGENDIAN bitsPerComponent = 1; bitsPerPixel = 1; break; #endif case CAIRO_FORMAT_RGB30: case CAIRO_FORMAT_RGB16_565: case CAIRO_FORMAT_INVALID: default: return NULL; } dataProvider = CGDataProviderCreateWithData(releaseInfo, data, height * stride, releaseCallback); if(UNLIKELY(!dataProvider)) { // manually release if(releaseCallback) releaseCallback(releaseInfo, data, height * stride); goto FINISH; } if(format == CAIRO_FORMAT_A8 || format == CAIRO_FORMAT_A1) { cairo_quartz_float_t decode[] = {1.0, 0.0}; image = CGImageMaskCreate(width, height, bitsPerComponent, bitsPerPixel, stride, dataProvider, decode, interpolate); } else image = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, stride, colorSpace, bitinfo, dataProvider, NULL, interpolate, kCGRenderingIntentDefault); FINISH: CGDataProviderRelease(dataProvider); if(colorSpace != colorSpaceOverride) CGColorSpaceRelease(colorSpace); return image; } static inline boolint _cairo_quartz_is_cgcontext_bitmap_context(CGContextRef cgc) { if(UNLIKELY(cgc == NULL)) return FALSE; if(LIKELY(CGContextGetTypePtr)) { /* 4 is the type value of a bitmap context */ return CGContextGetTypePtr(cgc) == 4; } /* This will cause a (harmless) warning to be printed if called on a non-bitmap context */ return CGBitmapContextGetBitsPerPixel(cgc) != 0; } /* CoreGraphics limitation with flipped CTM surfaces: height must be less than signed 16-bit max */ #define CG_MAX_HEIGHT SHRT_MAX #define CG_MAX_WIDTH USHRT_MAX /* is the desired size of the surface within bounds? */ boolint _cairo_quartz_verify_surface_size(int width, int height) { /* hmmm, allow width, height == 0 ? */ if(width < 0 || height < 0) return FALSE; if(width > CG_MAX_WIDTH || height > CG_MAX_HEIGHT) return FALSE; return TRUE; } /* * Cairo path -> Quartz path conversion helpers */ /* cairo path -> execute in context */ static cairo_status_t _cairo_path_to_quartz_context_move_to(void * closure, const cairo_point_t * point) { //ND ((stderr, "moveto: %f %f\n", _cairo_fixed_to_double (point->x), _cairo_fixed_to_double (point->y))); double x = _cairo_fixed_to_double(point->x); double y = _cairo_fixed_to_double(point->y); CGContextMoveToPoint(closure, x, y); return CAIRO_STATUS_SUCCESS; } static cairo_status_t _cairo_path_to_quartz_context_line_to(void * closure, const cairo_point_t * point) { //ND ((stderr, "lineto: %f %f\n", _cairo_fixed_to_double (point->x), _cairo_fixed_to_double (point->y))); double x = _cairo_fixed_to_double(point->x); double y = _cairo_fixed_to_double(point->y); CGContextAddLineToPoint(closure, x, y); return CAIRO_STATUS_SUCCESS; } static cairo_status_t _cairo_path_to_quartz_context_curve_to(void * closure, const cairo_point_t * p0, const cairo_point_t * p1, const cairo_point_t * p2) { //ND ((stderr, "curveto: %f,%f %f,%f %f,%f\n", // _cairo_fixed_to_double (p0->x), _cairo_fixed_to_double (p0->y), // _cairo_fixed_to_double (p1->x), _cairo_fixed_to_double (p1->y), // _cairo_fixed_to_double (p2->x), _cairo_fixed_to_double (p2->y))); double x0 = _cairo_fixed_to_double(p0->x); double y0 = _cairo_fixed_to_double(p0->y); double x1 = _cairo_fixed_to_double(p1->x); double y1 = _cairo_fixed_to_double(p1->y); double x2 = _cairo_fixed_to_double(p2->x); double y2 = _cairo_fixed_to_double(p2->y); CGContextAddCurveToPoint(closure, x0, y0, x1, y1, x2, y2); return CAIRO_STATUS_SUCCESS; } static cairo_status_t _cairo_path_to_quartz_context_close_path(void * closure) { //ND ((stderr, "closepath\n")); CGContextClosePath(closure); return CAIRO_STATUS_SUCCESS; } static void _cairo_quartz_cairo_path_to_quartz_context(const cairo_path_fixed_t * path, CGContextRef closure) { cairo_status_t status; CGContextBeginPath(closure); status = _cairo_path_fixed_interpret(path, _cairo_path_to_quartz_context_move_to, _cairo_path_to_quartz_context_line_to, _cairo_path_to_quartz_context_curve_to, _cairo_path_to_quartz_context_close_path, closure); assert(status == CAIRO_STATUS_SUCCESS); } /* * Misc helpers/callbacks */ #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050 static PrivateCGCompositeMode _cairo_quartz_cairo_operator_to_quartz_composite(cairo_operator_t op) { switch(op) { case CAIRO_OPERATOR_CLEAR: return kPrivateCGCompositeClear; case CAIRO_OPERATOR_SOURCE: return kPrivateCGCompositeCopy; case CAIRO_OPERATOR_OVER: return kPrivateCGCompositeSourceOver; case CAIRO_OPERATOR_IN: return kPrivateCGCompositeSourceIn; case CAIRO_OPERATOR_OUT: return kPrivateCGCompositeSourceOut; case CAIRO_OPERATOR_ATOP: return kPrivateCGCompositeSourceAtop; case CAIRO_OPERATOR_DEST_OVER: return kPrivateCGCompositeDestinationOver; case CAIRO_OPERATOR_DEST_IN: return kPrivateCGCompositeDestinationIn; case CAIRO_OPERATOR_DEST_OUT: return kPrivateCGCompositeDestinationOut; case CAIRO_OPERATOR_DEST_ATOP: return kPrivateCGCompositeDestinationAtop; case CAIRO_OPERATOR_XOR: return kPrivateCGCompositeXOR; case CAIRO_OPERATOR_ADD: return kPrivateCGCompositePlusLighter; case CAIRO_OPERATOR_DEST: case CAIRO_OPERATOR_SATURATE: case CAIRO_OPERATOR_MULTIPLY: case CAIRO_OPERATOR_SCREEN: case CAIRO_OPERATOR_OVERLAY: case CAIRO_OPERATOR_DARKEN: case CAIRO_OPERATOR_LIGHTEN: case CAIRO_OPERATOR_COLOR_DODGE: case CAIRO_OPERATOR_COLOR_BURN: case CAIRO_OPERATOR_HARD_LIGHT: case CAIRO_OPERATOR_SOFT_LIGHT: case CAIRO_OPERATOR_DIFFERENCE: case CAIRO_OPERATOR_EXCLUSION: case CAIRO_OPERATOR_HSL_HUE: case CAIRO_OPERATOR_HSL_SATURATION: case CAIRO_OPERATOR_HSL_COLOR: case CAIRO_OPERATOR_HSL_LUMINOSITY: default: ASSERT_NOT_REACHED; } } #endif static CGBlendMode _cairo_quartz_cairo_operator_to_quartz_blend(cairo_operator_t op) { switch(op) { case CAIRO_OPERATOR_MULTIPLY: return kCGBlendModeMultiply; case CAIRO_OPERATOR_SCREEN: return kCGBlendModeScreen; case CAIRO_OPERATOR_OVERLAY: return kCGBlendModeOverlay; case CAIRO_OPERATOR_DARKEN: return kCGBlendModeDarken; case CAIRO_OPERATOR_LIGHTEN: return kCGBlendModeLighten; case CAIRO_OPERATOR_COLOR_DODGE: return kCGBlendModeColorDodge; case CAIRO_OPERATOR_COLOR_BURN: return kCGBlendModeColorBurn; case CAIRO_OPERATOR_HARD_LIGHT: return kCGBlendModeHardLight; case CAIRO_OPERATOR_SOFT_LIGHT: return kCGBlendModeSoftLight; case CAIRO_OPERATOR_DIFFERENCE: return kCGBlendModeDifference; case CAIRO_OPERATOR_EXCLUSION: return kCGBlendModeExclusion; case CAIRO_OPERATOR_HSL_HUE: return kCGBlendModeHue; case CAIRO_OPERATOR_HSL_SATURATION: return kCGBlendModeSaturation; case CAIRO_OPERATOR_HSL_COLOR: return kCGBlendModeColor; case CAIRO_OPERATOR_HSL_LUMINOSITY: return kCGBlendModeLuminosity; #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 case CAIRO_OPERATOR_CLEAR: return kCGBlendModeClear; case CAIRO_OPERATOR_SOURCE: return kCGBlendModeCopy; case CAIRO_OPERATOR_OVER: return kCGBlendModeNormal; case CAIRO_OPERATOR_IN: return kCGBlendModeSourceIn; case CAIRO_OPERATOR_OUT: return kCGBlendModeSourceOut; case CAIRO_OPERATOR_ATOP: return kCGBlendModeSourceAtop; case CAIRO_OPERATOR_DEST_OVER: return kCGBlendModeDestinationOver; case CAIRO_OPERATOR_DEST_IN: return kCGBlendModeDestinationIn; case CAIRO_OPERATOR_DEST_OUT: return kCGBlendModeDestinationOut; case CAIRO_OPERATOR_DEST_ATOP: return kCGBlendModeDestinationAtop; case CAIRO_OPERATOR_XOR: return kCGBlendModeXOR; case CAIRO_OPERATOR_ADD: return kCGBlendModePlusLighter; #else case CAIRO_OPERATOR_CLEAR: case CAIRO_OPERATOR_SOURCE: case CAIRO_OPERATOR_OVER: case CAIRO_OPERATOR_IN: case CAIRO_OPERATOR_OUT: case CAIRO_OPERATOR_ATOP: case CAIRO_OPERATOR_DEST_OVER: case CAIRO_OPERATOR_DEST_IN: case CAIRO_OPERATOR_DEST_OUT: case CAIRO_OPERATOR_DEST_ATOP: case CAIRO_OPERATOR_XOR: case CAIRO_OPERATOR_ADD: #endif case CAIRO_OPERATOR_DEST: case CAIRO_OPERATOR_SATURATE: default: ASSERT_NOT_REACHED; } } static cairo_int_status_t _cairo_cgcontext_set_cairo_operator(CGContextRef context, cairo_operator_t op) { CGBlendMode blendmode; assert(op != CAIRO_OPERATOR_DEST); /* Quartz doesn't support SATURATE at all. COLOR_DODGE and * COLOR_BURN in Quartz follow the ISO32000 definition, but cairo * uses the definition from the Adobe Supplement. Also fallback * on SOFT_LIGHT and HSL_HUE, because their results are * significantly different from those provided by pixman. */ if(op == CAIRO_OPERATOR_SATURATE || op == CAIRO_OPERATOR_SOFT_LIGHT || op == CAIRO_OPERATOR_HSL_HUE || op == CAIRO_OPERATOR_COLOR_DODGE || op == CAIRO_OPERATOR_COLOR_BURN) { return CAIRO_INT_STATUS_UNSUPPORTED; } #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050 if(op <= CAIRO_OPERATOR_ADD) { PrivateCGCompositeMode compmode; compmode = _cairo_quartz_cairo_operator_to_quartz_composite(op); CGContextSetCompositeOperation(context, compmode); return CAIRO_STATUS_SUCCESS; } #endif blendmode = _cairo_quartz_cairo_operator_to_quartz_blend(op); CGContextSetBlendMode(context, blendmode); return CAIRO_STATUS_SUCCESS; } static cairo_int_status_t _cairo_quartz_surface_set_cairo_operator(cairo_quartz_surface_t * surface, cairo_operator_t op) { ND((stderr, "%p _cairo_quartz_surface_set_cairo_operator %d\n", surface, op)); /* When the destination has no color components, we can avoid some * fallbacks, but we have to workaround operators which behave * differently in Quartz. */ if(surface->base.content == CAIRO_CONTENT_ALPHA) { assert(op != CAIRO_OPERATOR_ATOP); /* filtered by surface layer */ if(op == CAIRO_OPERATOR_SOURCE || op == CAIRO_OPERATOR_IN || op == CAIRO_OPERATOR_OUT || op == CAIRO_OPERATOR_DEST_IN || op == CAIRO_OPERATOR_DEST_ATOP || op == CAIRO_OPERATOR_XOR) { return CAIRO_INT_STATUS_UNSUPPORTED; } if(op == CAIRO_OPERATOR_DEST_OVER) op = CAIRO_OPERATOR_OVER; else if(op == CAIRO_OPERATOR_SATURATE) op = CAIRO_OPERATOR_ADD; else if(op == CAIRO_OPERATOR_COLOR_DODGE) op = CAIRO_OPERATOR_OVER; else if(op == CAIRO_OPERATOR_COLOR_BURN) op = CAIRO_OPERATOR_OVER; } return _cairo_cgcontext_set_cairo_operator(surface->cgContext, op); } static inline CGLineCap _cairo_quartz_cairo_line_cap_to_quartz(cairo_line_cap_t ccap) { switch(ccap) { default: ASSERT_NOT_REACHED; case CAIRO_LINE_CAP_BUTT: return kCGLineCapButt; case CAIRO_LINE_CAP_ROUND: return kCGLineCapRound; case CAIRO_LINE_CAP_SQUARE: return kCGLineCapSquare; } } static inline CGLineJoin _cairo_quartz_cairo_line_join_to_quartz(cairo_line_join_t cjoin) { switch(cjoin) { default: ASSERT_NOT_REACHED; case CAIRO_LINE_JOIN_MITER: return kCGLineJoinMiter; case CAIRO_LINE_JOIN_ROUND: return kCGLineJoinRound; case CAIRO_LINE_JOIN_BEVEL: return kCGLineJoinBevel; } } static inline CGInterpolationQuality _cairo_quartz_filter_to_quartz(cairo_filter_t filter) { /* The CGInterpolationQuality enumeration values seem to have the * following meaning: * - kCGInterpolationNone: nearest neighbor * - kCGInterpolationLow: bilinear * - kCGInterpolationHigh: bicubic? Lanczos? */ switch(filter) { case CAIRO_FILTER_NEAREST: case CAIRO_FILTER_FAST: return kCGInterpolationNone; case CAIRO_FILTER_BEST: return kCGInterpolationHigh; case CAIRO_FILTER_GOOD: case CAIRO_FILTER_BILINEAR: return kCGInterpolationLow; case CAIRO_FILTER_GAUSSIAN: return kCGInterpolationDefault; default: ASSERT_NOT_REACHED; return kCGInterpolationDefault; } } static inline void _cairo_quartz_cairo_matrix_to_quartz(const cairo_matrix_t * src, CGAffineTransform * dst) { dst->a = src->xx; dst->b = src->yx; dst->c = src->xy; dst->d = src->yy; dst->tx = src->x0; dst->ty = src->y0; } /* * Source -> Quartz setup and finish functions */ static void ComputeGradientValue(void * info, const cairo_quartz_float_t * in, cairo_quartz_float_t * out) { double fdist = *in; const cairo_gradient_pattern_t * grad = (cairo_gradient_pattern_t*)info; uint i; /* Put fdist back in the 0.0..1.0 range if we're doing * REPEAT/REFLECT */ if(grad->base.extend == CAIRO_EXTEND_REPEAT) { fdist = fdist - floor(fdist); } else if(grad->base.extend == CAIRO_EXTEND_REFLECT) { fdist = fmod(fabs(fdist), 2.0); if(fdist > 1.0) fdist = 2.0 - fdist; } for(i = 0; i < grad->n_stops; i++) if(grad->stops[i].offset > fdist) break; if(i == 0 || i == grad->n_stops) { if(i == grad->n_stops) --i; out[0] = grad->stops[i].color.red; out[1] = grad->stops[i].color.green; out[2] = grad->stops[i].color.blue; out[3] = grad->stops[i].color.alpha; } else { cairo_quartz_float_t ax = grad->stops[i-1].offset; cairo_quartz_float_t bx = grad->stops[i].offset - ax; cairo_quartz_float_t bp = (fdist - ax)/bx; cairo_quartz_float_t ap = 1.0 - bp; out[0] = grad->stops[i-1].color.red * ap + grad->stops[i].color.red * bp; out[1] = grad->stops[i-1].color.green * ap + grad->stops[i].color.green * bp; out[2] = grad->stops[i-1].color.blue * ap + grad->stops[i].color.blue * bp; out[3] = grad->stops[i-1].color.alpha * ap + grad->stops[i].color.alpha * bp; } } static const cairo_quartz_float_t gradient_output_value_ranges[8] = { 0.f, 1.f, 0.f, 1.f, 0.f, 1.f, 0.f, 1.f }; static const CGFunctionCallbacks gradient_callbacks = { 0, ComputeGradientValue, (CGFunctionReleaseInfoCallback)cairo_pattern_destroy }; /* Quartz computes a small number of samples of the gradient color * function. On MacOS X 10.5 it apparently computes only 1024 * samples. */ #define MAX_GRADIENT_RANGE 1024 static CGFunctionRef CairoQuartzCreateGradientFunction(const cairo_gradient_pattern_t * gradient, const cairo_rectangle_int_t * extents, cairo_circle_double_t * start, cairo_circle_double_t * end) { cairo_pattern_t * pat; cairo_quartz_float_t input_value_range[2]; if(gradient->base.extend != CAIRO_EXTEND_NONE) { double bounds_x1, bounds_x2, bounds_y1, bounds_y2; double t[2], tolerance; tolerance = fabs(_cairo_matrix_compute_determinant(&gradient->base.matrix)); tolerance /= _cairo_matrix_transformed_circle_major_axis(&gradient->base.matrix, 1); bounds_x1 = extents->x; bounds_y1 = extents->y; bounds_x2 = extents->x + extents->width; bounds_y2 = extents->y + extents->height; _cairo_matrix_transform_bounding_box(&gradient->base.matrix, &bounds_x1, &bounds_y1, &bounds_x2, &bounds_y2, NULL); _cairo_gradient_pattern_box_to_parameter(gradient, bounds_x1, bounds_y1, bounds_x2, bounds_y2, tolerance, t); if(gradient->base.extend == CAIRO_EXTEND_PAD) { t[0] = MAX(t[0], -0.5); t[1] = MIN(t[1], 1.5); } else if(t[1] - t[0] > MAX_GRADIENT_RANGE) return NULL; /* set the input range for the function -- the function knows how to map values outside of 0.0 .. 1.0 to the correct color */ input_value_range[0] = t[0]; input_value_range[1] = t[1]; } else { input_value_range[0] = 0; input_value_range[1] = 1; } _cairo_gradient_pattern_interpolate(gradient, input_value_range[0], start); _cairo_gradient_pattern_interpolate(gradient, input_value_range[1], end); if(_cairo_pattern_create_copy(&pat, &gradient->base)) return NULL; return CGFunctionCreate(pat, 1, input_value_range, 4, gradient_output_value_ranges, &gradient_callbacks); } /* Obtain a CGImageRef from a #cairo_surface_t * */ typedef struct { cairo_surface_t * surface; cairo_image_surface_t * image_out; void * image_extra; } quartz_source_image_t; static void DataProviderReleaseCallback(void * info, const void * data, size_t size) { quartz_source_image_t * source_img = info; _cairo_surface_release_source_image(source_img->surface, source_img->image_out, source_img->image_extra); SAlloc::F(source_img); } static cairo_status_t _cairo_surface_to_cgimage(cairo_surface_t * source, cairo_rectangle_int_t * extents, cairo_format_t format, cairo_matrix_t * matrix, const cairo_clip_t * clip, CGImageRef * image_out) { cairo_status_t status; quartz_source_image_t * source_img; cairo_image_surface_t * image_surface; if(source->backend && source->backend->type == CAIRO_SURFACE_TYPE_QUARTZ_IMAGE) { cairo_quartz_image_surface_t * surface = (cairo_quartz_image_surface_t*)source; *image_out = CGImageRetain(surface->image); return CAIRO_STATUS_SUCCESS; } if(_cairo_surface_is_quartz(source)) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)source; if(IS_EMPTY(surface)) { *image_out = NULL; return CAIRO_INT_STATUS_NOTHING_TO_DO; } if(_cairo_quartz_is_cgcontext_bitmap_context(surface->cgContext)) { *image_out = CGBitmapContextCreateImage(surface->cgContext); if(*image_out) return CAIRO_STATUS_SUCCESS; } } source_img = _cairo_malloc(sizeof(quartz_source_image_t)); if(UNLIKELY(source_img == NULL)) return _cairo_error(CAIRO_STATUS_NO_MEMORY); source_img->surface = source; if(source->type == CAIRO_SURFACE_TYPE_RECORDING) { image_surface = (cairo_image_surface_t*) cairo_image_surface_create(format, extents->width, extents->height); if(UNLIKELY(image_surface->base.status)) { status = image_surface->base.status; cairo_surface_destroy(&image_surface->base); SAlloc::F(source_img); return status; } status = _cairo_recording_surface_replay_with_clip(source, matrix, &image_surface->base, NULL); if(UNLIKELY(status)) { cairo_surface_destroy(&image_surface->base); SAlloc::F(source_img); return status; } source_img->image_out = image_surface; source_img->image_extra = NULL; cairo_matrix_init_identity(matrix); } else { status = _cairo_surface_acquire_source_image(source_img->surface, &source_img->image_out, &source_img->image_extra); if(UNLIKELY(status)) { SAlloc::F(source_img); return status; } } if(source_img->image_out->width == 0 || source_img->image_out->height == 0) { *image_out = NULL; DataProviderReleaseCallback(source_img, source_img->image_out->data, source_img->image_out->height * source_img->image_out->stride); } else { *image_out = CairoQuartzCreateCGImage(source_img->image_out->format, source_img->image_out->width, source_img->image_out->height, source_img->image_out->stride, source_img->image_out->data, TRUE, NULL, DataProviderReleaseCallback, source_img); /* TODO: differentiate memory error and unsupported surface type */ if(UNLIKELY(*image_out == NULL)) status = CAIRO_INT_STATUS_UNSUPPORTED; } return status; } /* Generic #cairo_pattern_t -> CGPattern function */ typedef struct { CGImageRef image; CGRect imageBounds; boolint do_reflect; } SurfacePatternDrawInfo; static void SurfacePatternDrawFunc(void * ainfo, CGContextRef context) { SurfacePatternDrawInfo * info = (SurfacePatternDrawInfo*)ainfo; CGContextTranslateCTM(context, 0, info->imageBounds.size.height); CGContextScaleCTM(context, 1, -1); CGContextDrawImage(context, info->imageBounds, info->image); if(info->do_reflect) { /* draw 3 more copies of the image, flipped. * DrawImage draws the image according to the current Y-direction into the rectangle given * (imageBounds); at the time of the first DrawImage above, the origin is at the bottom left * of the base image position, and the Y axis is extending upwards. */ /* Make the y axis extend downwards, and draw a flipped image below */ CGContextScaleCTM(context, 1, -1); CGContextDrawImage(context, info->imageBounds, info->image); /* Shift over to the right, and flip vertically (translation is 2x, * since we'll be flipping and thus rendering the rectangle "backwards" */ CGContextTranslateCTM(context, 2 * info->imageBounds.size.width, 0); CGContextScaleCTM(context, -1, 1); CGContextDrawImage(context, info->imageBounds, info->image); /* Then unflip the Y-axis again, and draw the image above the point. */ CGContextScaleCTM(context, 1, -1); CGContextDrawImage(context, info->imageBounds, info->image); } } static void SurfacePatternReleaseInfoFunc(void * ainfo) { SurfacePatternDrawInfo * info = (SurfacePatternDrawInfo*)ainfo; CGImageRelease(info->image); SAlloc::F(info); } static cairo_int_status_t _cairo_quartz_cairo_repeating_surface_pattern_to_quartz(cairo_quartz_surface_t * dest, const cairo_pattern_t * apattern, const cairo_clip_t * clip, CGPatternRef * cgpat) { cairo_surface_pattern_t * spattern; cairo_surface_t * pat_surf; cairo_rectangle_int_t extents; cairo_format_t format = _cairo_format_from_content(dest->base.content); CGImageRef image; CGRect pbounds; CGAffineTransform ptransform, stransform; CGPatternCallbacks cb = { 0, SurfacePatternDrawFunc, SurfacePatternReleaseInfoFunc }; SurfacePatternDrawInfo * info; cairo_quartz_float_t rw, rh; cairo_status_t status; boolint is_bounded; cairo_matrix_t m; /* SURFACE is the only type we'll handle here */ assert(apattern->type == CAIRO_PATTERN_TYPE_SURFACE); spattern = (cairo_surface_pattern_t *)apattern; pat_surf = spattern->surface; if(pat_surf->type != CAIRO_SURFACE_TYPE_RECORDING) { is_bounded = _cairo_surface_get_extents(pat_surf, &extents); assert(is_bounded); } else _cairo_surface_get_extents(&dest->base, &extents); m = spattern->base.matrix; status = _cairo_surface_to_cgimage(pat_surf, &extents, format, &m, clip, &image); if(UNLIKELY(status)) return status; info = _cairo_malloc(sizeof(SurfacePatternDrawInfo)); if(UNLIKELY(!info)) return CAIRO_STATUS_NO_MEMORY; /* XXX -- if we're printing, we may need to call CGImageCreateCopy to make sure * that the data will stick around for this image when the printer gets to it. * Otherwise, the underlying data store may disappear from under us! * * _cairo_surface_to_cgimage will copy when it converts non-Quartz surfaces, * since the Quartz surfaces have a higher chance of sticking around. If the * source is a quartz image surface, then it's set up to retain a ref to the * image surface that it's backed by. */ info->image = image; info->imageBounds = CGRectMake(0, 0, extents.width, extents.height); info->do_reflect = FALSE; pbounds.origin.x = 0; pbounds.origin.y = 0; if(spattern->base.extend == CAIRO_EXTEND_REFLECT) { pbounds.size.width = 2.0 * extents.width; pbounds.size.height = 2.0 * extents.height; info->do_reflect = TRUE; } else { pbounds.size.width = extents.width; pbounds.size.height = extents.height; } rw = pbounds.size.width; rh = pbounds.size.height; cairo_matrix_invert(&m); _cairo_quartz_cairo_matrix_to_quartz(&m, &stransform); /* The pattern matrix is relative to the bottom left, again; the * incoming cairo pattern matrix is relative to the upper left. * So we take the pattern matrix and the original context matrix, * which gives us the correct base translation/y flip. */ ptransform = CGAffineTransformConcat(stransform, dest->cgContextBaseCTM); #ifdef QUARTZ_DEBUG ND((stderr, " pbounds: %f %f %f %f\n", pbounds.origin.x, pbounds.origin.y, pbounds.size.width, pbounds.size.height)); ND((stderr, " pattern xform: t: %f %f xx: %f xy: %f yx: %f yy: %f\n", ptransform.tx, ptransform.ty, ptransform.a, ptransform.b, ptransform.c, ptransform.d)); CGAffineTransform xform = CGContextGetCTM(dest->cgContext); ND((stderr, " context xform: t: %f %f xx: %f xy: %f yx: %f yy: %f\n", xform.tx, xform.ty, xform.a, xform.b, xform.c, xform.d)); #endif *cgpat = CGPatternCreate(info, pbounds, ptransform, rw, rh, kCGPatternTilingConstantSpacing, /* kCGPatternTilingNoDistortion, */ TRUE, &cb); return CAIRO_STATUS_SUCCESS; } /* State used during a drawing operation. */ typedef struct { /* The destination of the mask */ CGContextRef cgMaskContext; /* The destination of the drawing of the source */ CGContextRef cgDrawContext; /* The filter to be used when drawing the source */ CGInterpolationQuality filter; /* Action type */ cairo_quartz_action_t action; /* Destination rect */ CGRect rect; /* Used with DO_SHADING, DO_IMAGE and DO_TILED_IMAGE */ CGAffineTransform transform; /* Used with DO_IMAGE and DO_TILED_IMAGE */ CGImageRef image; /* Used with DO_SHADING */ CGShadingRef shading; /* Temporary destination for unbounded operations */ CGLayerRef layer; CGRect clipRect; } cairo_quartz_drawing_state_t; /* Quartz does not support repeating radients. We handle repeating gradients by manually extending the gradient and repeating color stops. We need to minimize the number of repetitions since Quartz seems to sample our color function across the entire range, even if part of that range is not needed for the visible area of the gradient, and it samples with some fixed resolution, so if the gradient range is too large it samples with very low resolution and the gradient is very coarse. _cairo_quartz_create_gradient_function computes the number of repetitions needed based on the extents. */ static cairo_int_status_t _cairo_quartz_setup_gradient_source(cairo_quartz_drawing_state_t * state, const cairo_gradient_pattern_t * gradient, const cairo_rectangle_int_t * extents) { cairo_matrix_t mat; cairo_circle_double_t start, end; CGFunctionRef gradFunc; CGColorSpaceRef rgb; bool extend = gradient->base.extend != CAIRO_EXTEND_NONE; assert(gradient->n_stops > 0); mat = gradient->base.matrix; cairo_matrix_invert(&mat); _cairo_quartz_cairo_matrix_to_quartz(&mat, &state->transform); gradFunc = CairoQuartzCreateGradientFunction(gradient, extents, &start, &end); if(UNLIKELY(gradFunc == NULL)) return CAIRO_INT_STATUS_UNSUPPORTED; rgb = CGColorSpaceCreateDeviceRGB(); if(gradient->base.type == CAIRO_PATTERN_TYPE_LINEAR) { state->shading = CGShadingCreateAxial(rgb, CGPointMake(start.center.x, start.center.y), CGPointMake(end.center.x, end.center.y), gradFunc, extend, extend); } else { state->shading = CGShadingCreateRadial(rgb, CGPointMake(start.center.x, start.center.y), MAX(start.radius, 0), CGPointMake(end.center.x, end.center.y), MAX(end.radius, 0), gradFunc, extend, extend); } CGColorSpaceRelease(rgb); CGFunctionRelease(gradFunc); state->action = DO_SHADING; return CAIRO_STATUS_SUCCESS; } static cairo_int_status_t _cairo_quartz_setup_state(cairo_quartz_drawing_state_t * state, cairo_composite_rectangles_t * composite) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)composite->surface; cairo_operator_t op = composite->op; const cairo_pattern_t * source = &composite->source_pattern.base; const cairo_clip_t * clip = composite->clip; boolint needs_temp; cairo_status_t status; cairo_format_t format = _cairo_format_from_content(composite->surface->content); state->layer = NULL; state->image = NULL; state->shading = NULL; state->cgDrawContext = NULL; state->cgMaskContext = NULL; status = _cairo_surface_clipper_set_clip(&surface->clipper, clip); if(UNLIKELY(status)) return status; status = _cairo_quartz_surface_set_cairo_operator(surface, op); if(UNLIKELY(status)) return status; /* Save before we change the pattern, colorspace, etc. so that * we can restore and make sure that quartz releases our * pattern (which may be stack allocated) */ CGContextSaveGState(surface->cgContext); state->clipRect = CGContextGetClipBoundingBox(surface->cgContext); state->clipRect = CGRectIntegral(state->clipRect); state->rect = state->clipRect; state->cgMaskContext = surface->cgContext; state->cgDrawContext = state->cgMaskContext; state->filter = _cairo_quartz_filter_to_quartz(source->filter); if(op == CAIRO_OPERATOR_CLEAR) { CGContextSetRGBFillColor(state->cgDrawContext, 0, 0, 0, 1); state->action = DO_DIRECT; return CAIRO_STATUS_SUCCESS; } /* * To implement mask unbounded operations Quartz needs a temporary * surface which will be composited entirely (ignoring the mask). * To implement source unbounded operations Quartz needs a * temporary surface which allows extending the source to a size * covering the whole mask, but there are some optimization * opportunities: * * - CLEAR completely ignores the source, thus we can just use a * solid color fill. * * - SOURCE can be implemented by drawing the source and clearing * outside of the source as long as the two regions have no * intersection. This happens when the source is a pixel-aligned * rectangle. If the source is at least as big as the * intersection between the clip rectangle and the mask * rectangle, no clear operation is needed. */ needs_temp = !_cairo_operator_bounded_by_mask(op); if(needs_temp) { state->layer = CGLayerCreateWithContext(surface->cgContext, state->clipRect.size, NULL); state->cgDrawContext = CGLayerGetContext(state->layer); state->cgMaskContext = state->cgDrawContext; CGContextTranslateCTM(state->cgDrawContext, -state->clipRect.origin.x, -state->clipRect.origin.y); } if(source->type == CAIRO_PATTERN_TYPE_SOLID) { cairo_solid_pattern_t * solid = (cairo_solid_pattern_t*)source; CGContextSetRGBStrokeColor(state->cgDrawContext, solid->color.red, solid->color.green, solid->color.blue, solid->color.alpha); CGContextSetRGBFillColor(state->cgDrawContext, solid->color.red, solid->color.green, solid->color.blue, solid->color.alpha); state->action = DO_DIRECT; return CAIRO_STATUS_SUCCESS; } if(source->type == CAIRO_PATTERN_TYPE_LINEAR || source->type == CAIRO_PATTERN_TYPE_RADIAL) { const cairo_gradient_pattern_t * gpat = (const cairo_gradient_pattern_t*)source; cairo_rectangle_int_t extents; extents = surface->virtual_extents; extents.x -= surface->base.device_transform.x0; extents.y -= surface->base.device_transform.y0; _cairo_rectangle_union(&extents, &surface->extents); return _cairo_quartz_setup_gradient_source(state, gpat, &extents); } if(source->type == CAIRO_PATTERN_TYPE_SURFACE && (source->extend == CAIRO_EXTEND_NONE || (CGContextDrawTiledImagePtr && source->extend == CAIRO_EXTEND_REPEAT))) { const cairo_surface_pattern_t * spat = (const cairo_surface_pattern_t*)source; cairo_surface_t * pat_surf = spat->surface; CGImageRef img; cairo_matrix_t m = spat->base.matrix; cairo_rectangle_int_t extents; CGAffineTransform xform; CGRect srcRect; cairo_fixed_t fw, fh; boolint is_bounded; _cairo_surface_get_extents(composite->surface, &extents); status = _cairo_surface_to_cgimage(pat_surf, &extents, format, &m, clip, &img); if(UNLIKELY(status)) return status; state->image = img; if(state->filter == kCGInterpolationNone && _cairo_matrix_is_translation(&m)) { m.x0 = -ceil(m.x0 - 0.5); m.y0 = -ceil(m.y0 - 0.5); } else { cairo_matrix_invert(&m); } _cairo_quartz_cairo_matrix_to_quartz(&m, &state->transform); if(pat_surf->type != CAIRO_SURFACE_TYPE_RECORDING) { is_bounded = _cairo_surface_get_extents(pat_surf, &extents); assert(is_bounded); } srcRect = CGRectMake(0, 0, extents.width, extents.height); if(source->extend == CAIRO_EXTEND_NONE) { int x, y; if(op == CAIRO_OPERATOR_SOURCE && (pat_surf->content == CAIRO_CONTENT_ALPHA || !_cairo_matrix_is_integer_translation(&m, &x, &y))) { state->layer = CGLayerCreateWithContext(surface->cgContext, state->clipRect.size, NULL); state->cgDrawContext = CGLayerGetContext(state->layer); CGContextTranslateCTM(state->cgDrawContext, -state->clipRect.origin.x, -state->clipRect.origin.y); } CGContextSetRGBFillColor(state->cgDrawContext, 0, 0, 0, 1); state->rect = srcRect; state->action = DO_IMAGE; return CAIRO_STATUS_SUCCESS; } CGContextSetRGBFillColor(state->cgDrawContext, 0, 0, 0, 1); /* Quartz seems to tile images at pixel-aligned regions only -- this * leads to seams if the image doesn't end up scaling to fill the * space exactly. The CGPattern tiling approach doesn't have this * problem. Check if we're going to fill up the space (within some * epsilon), and if not, fall back to the CGPattern type. */ xform = CGAffineTransformConcat(CGContextGetCTM(state->cgDrawContext), state->transform); srcRect = CGRectApplyAffineTransform(srcRect, xform); fw = _cairo_fixed_from_double(srcRect.size.width); fh = _cairo_fixed_from_double(srcRect.size.height); if((fw & CAIRO_FIXED_FRAC_MASK) <= CAIRO_FIXED_EPSILON && (fh & CAIRO_FIXED_FRAC_MASK) <= CAIRO_FIXED_EPSILON) { /* We're good to use DrawTiledImage, but ensure that * the math works out */ srcRect.size.width = round(srcRect.size.width); srcRect.size.height = round(srcRect.size.height); xform = CGAffineTransformInvert(xform); srcRect = CGRectApplyAffineTransform(srcRect, xform); state->rect = srcRect; state->action = DO_TILED_IMAGE; return CAIRO_STATUS_SUCCESS; } /* Fall through to generic SURFACE case */ } if(source->type == CAIRO_PATTERN_TYPE_SURFACE) { cairo_quartz_float_t patternAlpha = 1.0f; CGColorSpaceRef patternSpace; CGPatternRef pattern = NULL; cairo_int_status_t status; status = _cairo_quartz_cairo_repeating_surface_pattern_to_quartz(surface, source, clip, &pattern); if(UNLIKELY(status)) return status; patternSpace = CGColorSpaceCreatePattern(NULL); CGContextSetFillColorSpace(state->cgDrawContext, patternSpace); CGContextSetFillPattern(state->cgDrawContext, pattern, &patternAlpha); CGContextSetStrokeColorSpace(state->cgDrawContext, patternSpace); CGContextSetStrokePattern(state->cgDrawContext, pattern, &patternAlpha); CGColorSpaceRelease(patternSpace); /* Quartz likes to munge the pattern phase (as yet unexplained * why); force it to 0,0 as we've already baked in the correct * pattern translation into the pattern matrix */ CGContextSetPatternPhase(state->cgDrawContext, CGSizeMake(0, 0)); CGPatternRelease(pattern); state->action = DO_DIRECT; return CAIRO_STATUS_SUCCESS; } return CAIRO_INT_STATUS_UNSUPPORTED; } static void _cairo_quartz_teardown_state(cairo_quartz_drawing_state_t * state, cairo_composite_rectangles_t * extents) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)extents->surface; if(state->layer) { CGContextDrawLayerInRect(surface->cgContext, state->clipRect, state->layer); CGLayerRelease(state->layer); } if(state->cgMaskContext) CGContextRestoreGState(surface->cgContext); if(state->image) CGImageRelease(state->image); if(state->shading) CGShadingRelease(state->shading); } static void _cairo_quartz_draw_source(cairo_quartz_drawing_state_t * state, cairo_operator_t op) { CGContextSetShouldAntialias(state->cgDrawContext, state->filter != kCGInterpolationNone); CGContextSetInterpolationQuality(state->cgDrawContext, state->filter); if(state->action == DO_DIRECT) { CGContextFillRect(state->cgDrawContext, state->rect); return; } CGContextConcatCTM(state->cgDrawContext, state->transform); if(state->action == DO_SHADING) { CGContextDrawShading(state->cgDrawContext, state->shading); return; } CGContextTranslateCTM(state->cgDrawContext, 0, state->rect.size.height); CGContextScaleCTM(state->cgDrawContext, 1, -1); if(state->action == DO_IMAGE) { CGContextDrawImage(state->cgDrawContext, state->rect, state->image); if(op == CAIRO_OPERATOR_SOURCE && state->cgDrawContext == state->cgMaskContext) { CGContextBeginPath(state->cgDrawContext); CGContextAddRect(state->cgDrawContext, state->rect); CGContextTranslateCTM(state->cgDrawContext, 0, state->rect.size.height); CGContextScaleCTM(state->cgDrawContext, 1, -1); CGContextConcatCTM(state->cgDrawContext, CGAffineTransformInvert(state->transform)); CGContextAddRect(state->cgDrawContext, state->clipRect); CGContextSetRGBFillColor(state->cgDrawContext, 0, 0, 0, 0); CGContextEOFillPath(state->cgDrawContext); } } else { CGContextDrawTiledImagePtr(state->cgDrawContext, state->rect, state->image); } } static cairo_image_surface_t * _cairo_quartz_surface_map_to_image(void * abstract_surface, const cairo_rectangle_int_t * extents) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)abstract_surface; uint stride, bitinfo, bpp, color_comps; CGColorSpaceRef colorspace; void * imageData; cairo_format_t format; if(surface->imageSurfaceEquiv) return _cairo_surface_map_to_image(surface->imageSurfaceEquiv, extents); if(IS_EMPTY(surface)) return (cairo_image_surface_t*)cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0); if(!_cairo_quartz_is_cgcontext_bitmap_context(surface->cgContext)) return _cairo_image_surface_create_in_error(_cairo_error(CAIRO_STATUS_NO_MEMORY)); bitinfo = CGBitmapContextGetBitmapInfo(surface->cgContext); bpp = CGBitmapContextGetBitsPerPixel(surface->cgContext); // let's hope they don't add YUV under us colorspace = CGBitmapContextGetColorSpace(surface->cgContext); color_comps = CGColorSpaceGetNumberOfComponents(colorspace); /* XXX TODO: We can handle many more data formats by * converting to pixman_format_t */ if(bpp == 32 && color_comps == 3 && (bitinfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaPremultipliedFirst && (bitinfo & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Host) { format = CAIRO_FORMAT_ARGB32; } else if(bpp == 32 && color_comps == 3 && (bitinfo & kCGBitmapAlphaInfoMask) == kCGImageAlphaNoneSkipFirst && (bitinfo & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Host) { format = CAIRO_FORMAT_RGB24; } else if(bpp == 8 && color_comps == 1) { format = CAIRO_FORMAT_A1; } else { return _cairo_image_surface_create_in_error(_cairo_error(CAIRO_STATUS_NO_MEMORY)); } imageData = CGBitmapContextGetData(surface->cgContext); stride = CGBitmapContextGetBytesPerRow(surface->cgContext); return (cairo_image_surface_t*)cairo_image_surface_create_for_data(imageData, format, extents->width, extents->height, stride); } static cairo_int_status_t _cairo_quartz_surface_unmap_image(void * abstract_surface, cairo_image_surface_t * image) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)abstract_surface; if(surface->imageSurfaceEquiv) return _cairo_surface_unmap_image(surface->imageSurfaceEquiv, image); cairo_surface_finish(&image->base); cairo_surface_destroy(&image->base); return CAIRO_STATUS_SUCCESS; } /* * Cairo surface backend implementations */ static cairo_status_t _cairo_quartz_surface_finish(void * abstract_surface) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)abstract_surface; ND((stderr, "_cairo_quartz_surface_finish[%p] cgc: %p\n", surface, surface->cgContext)); if(IS_EMPTY(surface)) return CAIRO_STATUS_SUCCESS; /* Restore our saved gstate that we use to reset clipping */ CGContextRestoreGState(surface->cgContext); _cairo_surface_clipper_reset(&surface->clipper); CGContextRelease(surface->cgContext); surface->cgContext = NULL; if(surface->imageSurfaceEquiv) { cairo_surface_destroy(surface->imageSurfaceEquiv); surface->imageSurfaceEquiv = NULL; } SAlloc::F(surface->imageData); surface->imageData = NULL; return CAIRO_STATUS_SUCCESS; } static cairo_status_t _cairo_quartz_surface_acquire_source_image(void * abstract_surface, cairo_image_surface_t ** image_out, void ** image_extra) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)abstract_surface; //ND ((stderr, "%p _cairo_quartz_surface_acquire_source_image\n", surface)); *image_extra = NULL; *image_out = _cairo_quartz_surface_map_to_image(surface, &surface->extents); if(UNLIKELY(cairo_surface_status(&(*image_out)->base))) { cairo_surface_destroy(&(*image_out)->base); *image_out = NULL; return _cairo_error(CAIRO_STATUS_NO_MEMORY); } return CAIRO_STATUS_SUCCESS; } static void _cairo_quartz_surface_release_source_image(void * abstract_surface, cairo_image_surface_t * image, void * image_extra) { _cairo_quartz_surface_unmap_image(abstract_surface, image); } static cairo_surface_t * _cairo_quartz_surface_create_similar(void * abstract_surface, cairo_content_t content, int width, int height) { cairo_quartz_surface_t * surface, * similar_quartz; cairo_surface_t * similar; cairo_format_t format; if(content == CAIRO_CONTENT_COLOR_ALPHA) format = CAIRO_FORMAT_ARGB32; else if(content == CAIRO_CONTENT_COLOR) format = CAIRO_FORMAT_RGB24; else if(content == CAIRO_CONTENT_ALPHA) format = CAIRO_FORMAT_A8; else return NULL; // verify width and height of surface if(!_cairo_quartz_verify_surface_size(width, height)) { return _cairo_surface_create_in_error(_cairo_error (CAIRO_STATUS_INVALID_SIZE)); } similar = cairo_quartz_surface_create(format, width, height); if(UNLIKELY(similar->status)) return similar; surface = (cairo_quartz_surface_t*)abstract_surface; similar_quartz = (cairo_quartz_surface_t*)similar; similar_quartz->virtual_extents = surface->virtual_extents; return similar; } static boolint _cairo_quartz_surface_get_extents(void * abstract_surface, cairo_rectangle_int_t * extents) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)abstract_surface; *extents = surface->extents; return TRUE; } static cairo_int_status_t _cairo_quartz_cg_paint(const cairo_compositor_t * compositor, cairo_composite_rectangles_t * extents) { cairo_quartz_drawing_state_t state; cairo_int_status_t rv; ND((stderr, "%p _cairo_quartz_surface_paint op %d source->type %d\n", extents->surface, extents->op, extents->source_pattern.base.type)); rv = _cairo_quartz_setup_state(&state, extents); if(UNLIKELY(rv)) goto BAIL; _cairo_quartz_draw_source(&state, extents->op); BAIL: _cairo_quartz_teardown_state(&state, extents); ND((stderr, "-- paint\n")); return rv; } static cairo_int_status_t _cairo_quartz_cg_mask_with_surface(cairo_composite_rectangles_t * extents, cairo_surface_t * mask_surf, const cairo_matrix_t * mask_mat, CGInterpolationQuality filter) { CGRect rect; CGImageRef img; cairo_status_t status; CGAffineTransform mask_matrix; cairo_quartz_drawing_state_t state; cairo_format_t format = _cairo_format_from_content(extents->surface->content); cairo_rectangle_int_t dest_extents; cairo_matrix_t m = *mask_mat; _cairo_surface_get_extents(extents->surface, &dest_extents); status = _cairo_surface_to_cgimage(mask_surf, &dest_extents, format, &m, extents->clip, &img); if(UNLIKELY(status)) return status; status = _cairo_quartz_setup_state(&state, extents); if(UNLIKELY(status)) goto BAIL; rect = CGRectMake(0.0, 0.0, CGImageGetWidth(img), CGImageGetHeight(img)); _cairo_quartz_cairo_matrix_to_quartz(&m, &mask_matrix); /* ClipToMask is essentially drawing an image, so we need to flip the CTM * to get the image to appear oriented the right way */ CGContextConcatCTM(state.cgMaskContext, CGAffineTransformInvert(mask_matrix)); CGContextTranslateCTM(state.cgMaskContext, 0.0, rect.size.height); CGContextScaleCTM(state.cgMaskContext, 1.0, -1.0); state.filter = filter; CGContextSetInterpolationQuality(state.cgMaskContext, filter); CGContextSetShouldAntialias(state.cgMaskContext, filter != kCGInterpolationNone); CGContextClipToMask(state.cgMaskContext, rect, img); CGContextScaleCTM(state.cgMaskContext, 1.0, -1.0); CGContextTranslateCTM(state.cgMaskContext, 0.0, -rect.size.height); CGContextConcatCTM(state.cgMaskContext, mask_matrix); _cairo_quartz_draw_source(&state, extents->op); BAIL: _cairo_quartz_teardown_state(&state, extents); CGImageRelease(img); return status; } static cairo_int_status_t _cairo_quartz_cg_mask_with_solid(cairo_quartz_surface_t * surface, cairo_composite_rectangles_t * extents) { cairo_quartz_drawing_state_t state; double alpha = extents->mask_pattern.solid.color.alpha; cairo_status_t status; status = _cairo_quartz_setup_state(&state, extents); if(UNLIKELY(status)) return status; CGContextSetAlpha(surface->cgContext, alpha); _cairo_quartz_draw_source(&state, extents->op); _cairo_quartz_teardown_state(&state, extents); return CAIRO_STATUS_SUCCESS; } static cairo_int_status_t _cairo_quartz_cg_mask(const cairo_compositor_t * compositor, cairo_composite_rectangles_t * extents) { cairo_quartz_surface_t * surface = (cairo_quartz_surface_t*)extents->surface; const cairo_pattern_t * source = &extents->source_pattern.base; const cairo_pattern_t * mask = &extents->mask_pattern.base; cairo_surface_t * mask_surf; cairo_matrix_t matrix; cairo_status_t status; boolint need_temp; CGInterpolationQuality filter; ND((stderr, "%p _cairo_quartz_surface_mask op %d source->type %d mask->type %d\n", extents->surface, extents->op, extents->source_pattern.base.type, extents->mask_pattern.base.type)); if(mask->type == CAIRO_PATTERN_TYPE_SOLID) return _cairo_quartz_cg_mask_with_solid(surface, extents); need_temp = (mask->type != CAIRO_PATTERN_TYPE_SURFACE || mask->extend != CAIRO_EXTEND_NONE); filter = _cairo_quartz_filter_to_quartz(source->filter); if(!need_temp) { mask_surf = extents->mask_pattern.surface.surface; /* When an opaque surface used as a mask in Quartz, its * luminosity is used as the alpha value, so we con only use * surfaces with alpha without creating a temporary mask. */ need_temp = !(mask_surf->content & CAIRO_CONTENT_ALPHA); } if(!need_temp) { CGInterpolationQuality mask_filter; boolint simple_transform; matrix = mask->matrix; mask_filter = _cairo_quartz_filter_to_quartz(mask->filter); if(mask_filter == kCGInterpolationNone) { simple_transform = _cairo_matrix_is_translation(&matrix); if(simple_transform) { matrix.x0 = ceil(matrix.x0 - 0.5); matrix.y0 = ceil(matrix.y0 - 0.5); } } else { simple_transform = _cairo_matrix_is_integer_translation(&matrix, NULL, NULL); } /* Quartz only allows one interpolation to be set for mask and * source, so we can skip the temp surface only if the source * filtering makes the mask look correct. */ if(source->type == CAIRO_PATTERN_TYPE_SURFACE) need_temp = !(simple_transform || filter == mask_filter); else filter = mask_filter; } if(need_temp) { /* Render the mask to a surface */ mask_surf = _cairo_quartz_surface_create_similar(surface, CAIRO_CONTENT_ALPHA, surface->extents.width, surface->extents.height); status = mask_surf->status; if(UNLIKELY(status)) goto BAIL; /* mask_surf is clear, so use OVER instead of SOURCE to avoid a * temporary layer or fallback to cairo-image. */ status = _cairo_surface_paint(mask_surf, CAIRO_OPERATOR_OVER, mask, NULL); if(UNLIKELY(status)) goto BAIL; cairo_matrix_init_identity(&matrix); } status = _cairo_quartz_cg_mask_with_surface(extents, mask_surf, &matrix, filter); BAIL: if(need_temp) cairo_surface_destroy(mask_surf); return status; } static cairo_int_status_t _cairo_quartz_cg_fill(const cairo_compositor_t * compositor, cairo_composite_rectangles_t * extents, const cairo_path_fixed_t * path, cairo_fill_rule_t fill_rule, double tolerance, cairo_antialias_t antialias) { cairo_quartz_drawing_state_t state; cairo_int_status_t rv = CAIRO_STATUS_SUCCESS; ND((stderr, "%p _cairo_quartz_surface_fill op %d source->type %d\n", extents->surface, extents->op, extents->source_pattern.base.type)); rv = _cairo_quartz_setup_state(&state, extents); if(UNLIKELY(rv)) goto BAIL; CGContextSetShouldAntialias(state.cgMaskContext, (antialias != CAIRO_ANTIALIAS_NONE)); _cairo_quartz_cairo_path_to_quartz_context(path, state.cgMaskContext); if(state.action == DO_DIRECT) { assert(state.cgDrawContext == state.cgMaskContext); if(fill_rule == CAIRO_FILL_RULE_WINDING) CGContextFillPath(state.cgMaskContext); else CGContextEOFillPath(state.cgMaskContext); } else { if(fill_rule == CAIRO_FILL_RULE_WINDING) CGContextClip(state.cgMaskContext); else CGContextEOClip(state.cgMaskContext); _cairo_quartz_draw_source(&state, extents->op); } BAIL: _cairo_quartz_teardown_state(&state, extents); ND((stderr, "-- fill\n")); return rv; } static cairo_int_status_t _cairo_quartz_cg_stroke(const cairo_compositor_t * compositor, cairo_composite_rectangles_t * extents, const cairo_path_fixed_t * path, const cairo_stroke_style_t * style, const cairo_matrix_t * ctm, const cairo_matrix_t * ctm_inverse, double tolerance, cairo_antialias_t antialias) { cairo_quartz_drawing_state_t state; cairo_int_status_t rv = CAIRO_STATUS_SUCCESS; CGAffineTransform strokeTransform, invStrokeTransform; ND((stderr, "%p _cairo_quartz_surface_stroke op %d source->type %d\n", extents->surface, extents->op, extents->source_pattern.base.type)); rv = _cairo_quartz_setup_state(&state, extents); if(UNLIKELY(rv)) goto BAIL; // Turning antialiasing off used to cause misrendering with // single-pixel lines (e.g. 20,10.5 -> 21,10.5 end up being rendered as 2 pixels). // That's been since fixed in at least 10.5, and in the latest 10.4 dot releases. CGContextSetShouldAntialias(state.cgMaskContext, (antialias != CAIRO_ANTIALIAS_NONE)); CGContextSetLineWidth(state.cgMaskContext, style->line_width); CGContextSetLineCap(state.cgMaskContext, _cairo_quartz_cairo_line_cap_to_quartz(style->line_cap)); CGContextSetLineJoin(state.cgMaskContext, _cairo_quartz_cairo_line_join_to_quartz(style->line_join)); CGContextSetMiterLimit(state.cgMaskContext, style->miter_limit); if(style->dash && style->num_dashes) { cairo_quartz_float_t sdash[CAIRO_STACK_ARRAY_LENGTH(cairo_quartz_float_t)]; cairo_quartz_float_t * fdash = sdash; uint max_dashes = style->num_dashes; uint k; if(style->num_dashes%2) max_dashes *= 2; if(max_dashes > ARRAY_LENGTH(sdash)) fdash = _cairo_malloc_ab(max_dashes, sizeof(cairo_quartz_float_t)); if(UNLIKELY(fdash == NULL)) { rv = _cairo_error(CAIRO_STATUS_NO_MEMORY); goto BAIL; } for(k = 0; k < max_dashes; k++) fdash[k] = (cairo_quartz_float_t)style->dash[k % style->num_dashes]; CGContextSetLineDash(state.cgMaskContext, style->dash_offset, fdash, max_dashes); if(fdash != sdash) SAlloc::F(fdash); } else CGContextSetLineDash(state.cgMaskContext, 0, NULL, 0); _cairo_quartz_cairo_path_to_quartz_context(path, state.cgMaskContext); _cairo_quartz_cairo_matrix_to_quartz(ctm, &strokeTransform); CGContextConcatCTM(state.cgMaskContext, strokeTransform); if(state.action == DO_DIRECT) { assert(state.cgDrawContext == state.cgMaskContext); CGContextStrokePath(state.cgMaskContext); } else { CGContextReplacePathWithStrokedPath(state.cgMaskContext); CGContextClip(state.cgMaskContext); _cairo_quartz_cairo_matrix_to_quartz(ctm_inverse, &invStrokeTransform); CGContextConcatCTM(state.cgMaskContext, invStrokeTransform); _cairo_quartz_draw_source(&state, extents->op); } BAIL: _cairo_quartz_teardown_state(&state, extents); ND((stderr, "-- stroke\n")); return rv; } #if CAIRO_HAS_QUARTZ_FONT static cairo_int_status_t _cairo_quartz_cg_glyphs(const cairo_compositor_t * compositor, cairo_composite_rectangles_t * extents, cairo_scaled_font_t * scaled_font, cairo_glyph_t * glyphs, int num_glyphs, boolint overlap) { CGAffineTransform textTransform, invTextTransform; CGGlyph glyphs_static[CAIRO_STACK_ARRAY_LENGTH(CGSize)]; CGSize cg_advances_static[CAIRO_STACK_ARRAY_LENGTH(CGSize)]; CGGlyph * cg_glyphs = &glyphs_static[0]; CGSize * cg_advances = &cg_advances_static[0]; COMPILE_TIME_ASSERT(sizeof(CGGlyph) <= sizeof(CGSize)); cairo_quartz_drawing_state_t state; cairo_int_status_t rv = CAIRO_INT_STATUS_UNSUPPORTED; cairo_quartz_float_t xprev, yprev; int i; CGFontRef cgfref = NULL; boolint didForceFontSmoothing = FALSE; if(cairo_scaled_font_get_type(scaled_font) != CAIRO_FONT_TYPE_QUARTZ) return CAIRO_INT_STATUS_UNSUPPORTED; rv = _cairo_quartz_setup_state(&state, extents); if(UNLIKELY(rv)) goto BAIL; if(state.action == DO_DIRECT) { assert(state.cgDrawContext == state.cgMaskContext); CGContextSetTextDrawingMode(state.cgMaskContext, kCGTextFill); } else { CGContextSetTextDrawingMode(state.cgMaskContext, kCGTextClip); } /* this doesn't addref */ cgfref = _cairo_quartz_scaled_font_get_cg_font_ref(scaled_font); CGContextSetFont(state.cgMaskContext, cgfref); CGContextSetFontSize(state.cgMaskContext, 1.0); switch(scaled_font->options.antialias) { case CAIRO_ANTIALIAS_SUBPIXEL: case CAIRO_ANTIALIAS_BEST: CGContextSetShouldAntialias(state.cgMaskContext, TRUE); CGContextSetShouldSmoothFonts(state.cgMaskContext, TRUE); if(CGContextSetAllowsFontSmoothingPtr && !CGContextGetAllowsFontSmoothingPtr(state.cgMaskContext)) { didForceFontSmoothing = TRUE; CGContextSetAllowsFontSmoothingPtr(state.cgMaskContext, TRUE); } break; case CAIRO_ANTIALIAS_NONE: CGContextSetShouldAntialias(state.cgMaskContext, FALSE); break; case CAIRO_ANTIALIAS_GRAY: case CAIRO_ANTIALIAS_GOOD: case CAIRO_ANTIALIAS_FAST: CGContextSetShouldAntialias(state.cgMaskContext, TRUE); CGContextSetShouldSmoothFonts(state.cgMaskContext, FALSE); break; case CAIRO_ANTIALIAS_DEFAULT: /* Don't do anything */ break; } if(num_glyphs > ARRAY_LENGTH(glyphs_static)) { cg_glyphs = static_cast<CGGlyph *>(_cairo_malloc_ab(num_glyphs, sizeof(CGGlyph) + sizeof(CGSize))); if(UNLIKELY(cg_glyphs == NULL)) { rv = _cairo_error(CAIRO_STATUS_NO_MEMORY); goto BAIL; } cg_advances = (CGSize*)(cg_glyphs + num_glyphs); } /* scale(1,-1) * scaled_font->scale */ textTransform = CGAffineTransformMake(scaled_font->scale.xx, scaled_font->scale.yx, -scaled_font->scale.xy, -scaled_font->scale.yy, 0.0, 0.0); /* scaled_font->scale_inverse * scale(1,-1) */ invTextTransform = CGAffineTransformMake(scaled_font->scale_inverse.xx, -scaled_font->scale_inverse.yx, scaled_font->scale_inverse.xy, -scaled_font->scale_inverse.yy, 0.0, 0.0); CGContextSetTextPosition(state.cgMaskContext, 0.0, 0.0); CGContextSetTextMatrix(state.cgMaskContext, CGAffineTransformIdentity); /* Convert our glyph positions to glyph advances. We need n-1 advances, * since the advance at index 0 is applied after glyph 0. */ xprev = glyphs[0].x; yprev = glyphs[0].y; cg_glyphs[0] = glyphs[0].index; for(i = 1; i < num_glyphs; i++) { cairo_quartz_float_t xf = glyphs[i].x; cairo_quartz_float_t yf = glyphs[i].y; cg_glyphs[i] = glyphs[i].index; cg_advances[i - 1] = CGSizeApplyAffineTransform(CGSizeMake(xf - xprev, yf - yprev), invTextTransform); xprev = xf; yprev = yf; } /* Translate to the first glyph's position before drawing */ CGContextTranslateCTM(state.cgMaskContext, glyphs[0].x, glyphs[0].y); CGContextConcatCTM(state.cgMaskContext, textTransform); CGContextShowGlyphsWithAdvances(state.cgMaskContext, cg_glyphs, cg_advances, num_glyphs); CGContextConcatCTM(state.cgMaskContext, invTextTransform); CGContextTranslateCTM(state.cgMaskContext, -glyphs[0].x, -glyphs[0].y); if(state.action != DO_DIRECT) _cairo_quartz_draw_source(&state, extents->op); BAIL: if(didForceFontSmoothing) CGContextSetAllowsFontSmoothingPtr(state.cgMaskContext, FALSE); _cairo_quartz_teardown_state(&state, extents); if(cg_glyphs != glyphs_static) SAlloc::F(cg_glyphs); return rv; } #endif /* CAIRO_HAS_QUARTZ_FONT */ static const cairo_compositor_t _cairo_quartz_cg_compositor = { &_cairo_fallback_compositor, _cairo_quartz_cg_paint, _cairo_quartz_cg_mask, _cairo_quartz_cg_stroke, _cairo_quartz_cg_fill, #if CAIRO_HAS_QUARTZ_FONT _cairo_quartz_cg_glyphs, #else NULL, #endif }; static cairo_int_status_t _cairo_quartz_surface_paint(void * surface, cairo_operator_t op, const cairo_pattern_t * source, const cairo_clip_t * clip) { return _cairo_compositor_paint(&_cairo_quartz_cg_compositor, surface, op, source, clip); } static cairo_int_status_t _cairo_quartz_surface_mask(void * surface, cairo_operator_t op, const cairo_pattern_t * source, const cairo_pattern_t * mask, const cairo_clip_t * clip) { return _cairo_compositor_mask(&_cairo_quartz_cg_compositor, surface, op, source, mask, clip); } static cairo_int_status_t _cairo_quartz_surface_fill(void * surface, cairo_operator_t op, const cairo_pattern_t * source, const cairo_path_fixed_t * path, cairo_fill_rule_t fill_rule, double tolerance, cairo_antialias_t antialias, const cairo_clip_t * clip) { return _cairo_compositor_fill(&_cairo_quartz_cg_compositor, surface, op, source, path, fill_rule, tolerance, antialias, clip); } static cairo_int_status_t _cairo_quartz_surface_stroke(void * surface, cairo_operator_t op, const cairo_pattern_t * source, const cairo_path_fixed_t * path, const cairo_stroke_style_t * style, const cairo_matrix_t * ctm, const cairo_matrix_t * ctm_inverse, double tolerance, cairo_antialias_t antialias, const cairo_clip_t * clip) { return _cairo_compositor_stroke(&_cairo_quartz_cg_compositor, surface, op, source, path, style, ctm, ctm_inverse, tolerance, antialias, clip); } static cairo_int_status_t _cairo_quartz_surface_glyphs(void * surface, cairo_operator_t op, const cairo_pattern_t * source, cairo_glyph_t * glyphs, int num_glyphs, cairo_scaled_font_t * scaled_font, const cairo_clip_t * clip) { return _cairo_compositor_glyphs(&_cairo_quartz_cg_compositor, surface, op, source, glyphs, num_glyphs, scaled_font, clip); } static cairo_status_t _cairo_quartz_surface_clipper_intersect_clip_path(cairo_surface_clipper_t * clipper, cairo_path_fixed_t * path, cairo_fill_rule_t fill_rule, double tolerance, cairo_antialias_t antialias) { cairo_quartz_surface_t * surface = cairo_container_of(clipper, cairo_quartz_surface_t, clipper); ND((stderr, "%p _cairo_quartz_surface_intersect_clip_path path: %p\n", surface, path)); if(IS_EMPTY(surface)) return CAIRO_STATUS_SUCCESS; if(!path) { /* If we're being asked to reset the clip, we can only do it * by restoring the gstate to our previous saved one, and * saving it again. * * Note that this assumes that ALL quartz surface creation * functions will do a SaveGState first; we do this in create_internal. */ CGContextRestoreGState(surface->cgContext); CGContextSaveGState(surface->cgContext); } else { CGContextSetShouldAntialias(surface->cgContext, (antialias != CAIRO_ANTIALIAS_NONE)); _cairo_quartz_cairo_path_to_quartz_context(path, surface->cgContext); if(fill_rule == CAIRO_FILL_RULE_WINDING) CGContextClip(surface->cgContext); else CGContextEOClip(surface->cgContext); } ND((stderr, "-- intersect_clip_path\n")); return CAIRO_STATUS_SUCCESS; } // XXXtodo implement show_page; need to figure out how to handle begin/end static const struct _cairo_surface_backend cairo_quartz_surface_backend = { CAIRO_SURFACE_TYPE_QUARTZ, _cairo_quartz_surface_finish, _cairo_default_context_create, _cairo_quartz_surface_create_similar, NULL, /* similar image */ _cairo_quartz_surface_map_to_image, _cairo_quartz_surface_unmap_image, _cairo_surface_default_source, _cairo_quartz_surface_acquire_source_image, _cairo_quartz_surface_release_source_image, NULL, /* snapshot */ NULL, /* copy_page */ NULL, /* show_page */ _cairo_quartz_surface_get_extents, NULL, /* get_font_options */ NULL, /* flush */ NULL, /* mark_dirty_rectangle */ _cairo_quartz_surface_paint, _cairo_quartz_surface_mask, _cairo_quartz_surface_stroke, _cairo_quartz_surface_fill, NULL, /* fill-stroke */ _cairo_quartz_surface_glyphs, }; cairo_quartz_surface_t * _cairo_quartz_surface_create_internal(CGContextRef cgContext, cairo_content_t content, uint width, uint height) { cairo_quartz_surface_t * surface; quartz_ensure_symbols(); /* Init the base surface */ surface = _cairo_malloc(sizeof(cairo_quartz_surface_t)); if(UNLIKELY(surface == NULL)) return (cairo_quartz_surface_t*)_cairo_surface_create_in_error(_cairo_error(CAIRO_STATUS_NO_MEMORY)); memzero(surface, sizeof(cairo_quartz_surface_t)); _cairo_surface_init(&surface->base, &cairo_quartz_surface_backend, NULL, /* device */ content, FALSE); /* is_vector */ _cairo_surface_clipper_init(&surface->clipper, _cairo_quartz_surface_clipper_intersect_clip_path); /* Save our extents */ surface->extents.x = surface->extents.y = 0; surface->extents.width = width; surface->extents.height = height; surface->virtual_extents = surface->extents; if(IS_EMPTY(surface)) { surface->cgContext = NULL; surface->cgContextBaseCTM = CGAffineTransformIdentity; surface->imageData = NULL; surface->base.is_clear = TRUE; return surface; } /* Save so we can always get back to a known-good CGContext -- this is * required for proper behaviour of intersect_clip_path(NULL) */ CGContextSaveGState(cgContext); surface->cgContext = cgContext; surface->cgContextBaseCTM = CGContextGetCTM(cgContext); surface->imageData = NULL; surface->imageSurfaceEquiv = NULL; return surface; } /** * cairo_quartz_surface_create_for_cg_context: * @cgContext: the existing CGContext for which to create the surface * @width: width of the surface, in pixels * @height: height of the surface, in pixels * * Creates a Quartz surface that wraps the given CGContext. The * CGContext is assumed to be in the standard Cairo coordinate space * (that is, with the origin at the upper left and the Y axis * increasing downward). If the CGContext is in the Quartz coordinate * space (with the origin at the bottom left), then it should be * flipped before this function is called. The flip can be accomplished * using a translate and a scale; for example: * * <informalexample><programlisting> * CGContextTranslateCTM (cgContext, 0.0, height); * CGContextScaleCTM (cgContext, 1.0, -1.0); * </programlisting></informalexample> * * All Cairo operations are implemented in terms of Quartz operations, * as long as Quartz-compatible elements are used (such as Quartz fonts). * * Return value: the newly created Cairo surface. * * Since: 1.6 **/ cairo_surface_t * cairo_quartz_surface_create_for_cg_context(CGContextRef cgContext, uint width, uint height) { cairo_quartz_surface_t * surf = _cairo_quartz_surface_create_internal(cgContext, CAIRO_CONTENT_COLOR_ALPHA, width, height); if(LIKELY(!surf->base.status)) CGContextRetain(cgContext); return &surf->base; } /** * cairo_quartz_surface_create: * @format: format of pixels in the surface to create * @width: width of the surface, in pixels * @height: height of the surface, in pixels * * Creates a Quartz surface backed by a CGBitmap. The surface is * created using the Device RGB (or Device Gray, for A8) color space. * All Cairo operations, including those that require software * rendering, will succeed on this surface. * * Return value: the newly created surface. * * Since: 1.6 **/ cairo_surface_t * cairo_quartz_surface_create(cairo_format_t format, uint width, uint height) { cairo_quartz_surface_t * surf; CGContextRef cgc; CGColorSpaceRef cgColorspace; CGBitmapInfo bitinfo; void * imageData; int stride; int bitsPerComponent; if(!_cairo_quartz_verify_surface_size(width, height)) return _cairo_surface_create_in_error(_cairo_error(CAIRO_STATUS_INVALID_SIZE)); if(width == 0 || height == 0) { return &_cairo_quartz_surface_create_internal(NULL, _cairo_content_from_format(format), width, height)->base; } if(format == CAIRO_FORMAT_ARGB32 || format == CAIRO_FORMAT_RGB24) { cgColorspace = CGColorSpaceCreateDeviceRGB(); bitinfo = kCGBitmapByteOrder32Host; if(format == CAIRO_FORMAT_ARGB32) bitinfo |= kCGImageAlphaPremultipliedFirst; else bitinfo |= kCGImageAlphaNoneSkipFirst; bitsPerComponent = 8; stride = width * 4; } else if(format == CAIRO_FORMAT_A8) { cgColorspace = NULL; stride = width; bitinfo = kCGImageAlphaOnly; bitsPerComponent = 8; } else if(format == CAIRO_FORMAT_A1) { /* I don't think we can usefully support this, as defined by * cairo_format_t -- these are 1-bit pixels stored in 32-bit * quantities. */ return _cairo_surface_create_in_error(_cairo_error(CAIRO_STATUS_INVALID_FORMAT)); } else { return _cairo_surface_create_in_error(_cairo_error(CAIRO_STATUS_INVALID_FORMAT)); } /* The Apple docs say that for best performance, the stride and the data * pointer should be 16-byte aligned. malloc already aligns to 16-bytes, * so we don't have to anything special on allocation. */ stride = (stride + 15) & ~15; imageData = _cairo_malloc_ab(height, stride); if(UNLIKELY(!imageData)) { CGColorSpaceRelease(cgColorspace); return _cairo_surface_create_in_error(_cairo_error(CAIRO_STATUS_NO_MEMORY)); } /* zero the memory to match the image surface behaviour */ memzero(imageData, height * stride); cgc = CGBitmapContextCreate(imageData, width, height, bitsPerComponent, stride, cgColorspace, bitinfo); CGColorSpaceRelease(cgColorspace); if(!cgc) { SAlloc::F(imageData); return _cairo_surface_create_in_error(_cairo_error(CAIRO_STATUS_NO_MEMORY)); } /* flip the Y axis */ CGContextTranslateCTM(cgc, 0.0, height); CGContextScaleCTM(cgc, 1.0, -1.0); surf = _cairo_quartz_surface_create_internal(cgc, _cairo_content_from_format(format), width, height); if(surf->base.status) { CGContextRelease(cgc); SAlloc::F(imageData); // create_internal will have set an error return &surf->base; } surf->base.is_clear = TRUE; surf->imageData = imageData; surf->imageSurfaceEquiv = cairo_image_surface_create_for_data(imageData, format, width, height, stride); return &surf->base; } /** * cairo_quartz_surface_get_cg_context: * @surface: the Cairo Quartz surface * * Returns the CGContextRef that the given Quartz surface is backed * by. * * A call to cairo_surface_flush() is required before using the * CGContextRef to ensure that all pending drawing operations are * finished and to restore any temporary modification cairo has made * to its state. A call to cairo_surface_mark_dirty() is required * after the state or the content of the CGContextRef has been * modified. * * Return value: the CGContextRef for the given surface. * * Since: 1.6 **/ CGContextRef cairo_quartz_surface_get_cg_context(cairo_surface_t * surface) { if(surface && _cairo_surface_is_quartz(surface)) { cairo_quartz_surface_t * quartz = (cairo_quartz_surface_t*)surface; return quartz->cgContext; } else return NULL; } /** * _cairo_surface_is_quartz: * @surface: a #cairo_surface_t * * Checks if a surface is a #cairo_quartz_surface_t * * Return value: True if the surface is an quartz surface **/ boolint _cairo_surface_is_quartz(const cairo_surface_t * surface) { return surface->backend == &cairo_quartz_surface_backend; } /* Debug stuff */ #ifdef QUARTZ_DEBUG #include <Movies.h> void ExportCGImageToPNGFile(CGImageRef inImageRef, char * dest) { Handle dataRef = NULL; OSType dataRefType; CFStringRef inPath = CFStringCreateWithCString(NULL, dest, kCFStringEncodingASCII); GraphicsExportComponent grex = 0; ulong sizeWritten; ComponentResult result; // create the data reference result = QTNewDataReferenceFromFullPathCFString(inPath, kQTNativeDefaultPathStyle, 0, &dataRef, &dataRefType); if(NULL != dataRef && noErr == result) { // get the PNG exporter result = OpenADefaultComponent(GraphicsExporterComponentType, kQTFileTypePNG, &grex); if(grex) { // tell the exporter where to find its source image result = GraphicsExportSetInputCGImage(grex, inImageRef); if(noErr == result) { // tell the exporter where to save the exporter image result = GraphicsExportSetOutputDataReference(grex, dataRef, dataRefType); if(noErr == result) { // write the PNG file result = GraphicsExportDoExport(grex, &sizeWritten); } } // remember to close the component CloseComponent(grex); } // remember to dispose of the data reference handle DisposeHandle(dataRef); } } void quartz_image_to_png(CGImageRef imgref, char * dest) { static int sctr = 0; char sptr[] = "/Users/vladimir/Desktop/barXXXXX.png"; if(dest == NULL) { slfprintf_stderr("** Writing %p to bar%d\n", imgref, sctr); sprintf(sptr, "/Users/vladimir/Desktop/bar%d.png", sctr); sctr++; dest = sptr; } ExportCGImageToPNGFile(imgref, dest); } void quartz_surface_to_png(cairo_quartz_surface_t * nq, char * dest) { static int sctr = 0; char sptr[] = "/Users/vladimir/Desktop/fooXXXXX.png"; if(nq->base.type != CAIRO_SURFACE_TYPE_QUARTZ) { slfprintf_stderr("** quartz_surface_to_png: surface %p isn't quartz!\n", nq); return; } if(dest == NULL) { slfprintf_stderr("** Writing %p to foo%d\n", nq, sctr); sprintf(sptr, "/Users/vladimir/Desktop/foo%d.png", sctr); sctr++; dest = sptr; } CGImageRef imgref = CGBitmapContextCreateImage(nq->cgContext); if(imgref == NULL) { slfprintf_stderr("quartz surface at %p is not a bitmap context!\n", nq); return; } ExportCGImageToPNGFile(imgref, dest); CGImageRelease(imgref); } #endif /* QUARTZ_DEBUG */ #endif // } 0 CAIRO_HAS_QUARTZ_SURFACE
papyrussolution/OpenPapyrus
Src/OSF/CAIRO-1160/SRC/cairo-quartz-surface.c
C
agpl-3.0
75,645
/* * This file is part of Relaxe. * Copyright (c) 2014 Topi Nieminen * Author: Topi Nieminen <topi.nieminen@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation. * * 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 or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. */ package com.appspot.relaxe.meta; import com.appspot.relaxe.env.IdentifierRules; import com.appspot.relaxe.expr.Identifier; import com.appspot.relaxe.expr.IllegalIdentifierException; import com.appspot.relaxe.meta.DBMetaTestCase; import com.appspot.relaxe.rdbms.Implementation; public abstract class EnvironmentTest<I extends Implementation<I>> extends DBMetaTestCase<I> { // @Override // public void restore() throws IOException, InterruptedException { // // no need to restore // } public void testCreateIdentifier() throws Exception { Implementation<?> env = getEnvironmentContext().getImplementation(); IdentifierRules ir = env.environment().getIdentifierRules(); // PGEnvironment env = newEnv(); final Identifier a = ir.toIdentifier("abc"); assertTrue(a.isOrdinary()); final Identifier b = ir.toIdentifier("Abc"); assertTrue(b.isOrdinary()); final Identifier c = ir.toIdentifier("ABC"); assertTrue(c.isOrdinary()); final Identifier d = ir.toIdentifier("Mary's"); assertFalse("Delimited expected", d.isOrdinary()); } public void testIllegalIdentifier() throws Exception { Implementation<?> env = getEnvironmentContext().getImplementation(); IdentifierRules ir = env.environment().getIdentifierRules(); try { ir.toIdentifier(""); assertThrown(IllegalIdentifierException.class); } catch (IllegalIdentifierException e) { // OK, expected } assertNull(ir.toIdentifier(null)); Identifier id = ir.toIdentifier("1A"); assertFalse(id + " is not not valid as an ordinary", id.isOrdinary()); } }
tjn/relaxe
src/test/java/com/appspot/relaxe/meta/EnvironmentTest.java
Java
agpl-3.0
2,643
perl jopply-sys.pl perl jopply-sys.pl --lanid perl jopply-sys.pl --n=l„rare,cad --lanid=12 perl jopply-sys.pl --nyckelord=l„rare,cad --lanid=12 --epost --verbose perl jopply-sys.pl --n=l„rare,cad --lanid=12 --w perl jopply-sys.pl --n=l„rare,cad --lanid=12 --w --e perl jopply-sys.pl --ann=2621881 perl jopply-sys.pl --help
mobluse/jopply
test/test-sys.bat
Batchfile
agpl-3.0
329
/* Copyright 2014 by Martin Gijsen (www.DeAnalist.nl) * * This file is part of the PowerTools engine. * * The PowerTools engine is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * The PowerTools engine 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 the PowerTools engine. If not, see <http://www.gnu.org/licenses/>. */ package org.powertools.engine; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public final class Arguments { private final Map<String, String> mMap; public Arguments (Map<String, String> map) { this (); mMap.putAll (map); } public Arguments () { mMap = new HashMap<String, String> (); } public void add (String name, String value) { mMap.put (name, value); } public boolean hasArgument (String name) { return mMap.containsKey (name); } public String remove (String name) { if (mMap.containsKey (name)) { return mMap.remove (name); } else { throw new ExecutionException ("field name not found: " + name); } } public String get (String name) { String value = mMap.get (name); if (value == null) { throw new ExecutionException ("no such argument: " + name); } return value; } public List<String> getNames () { return new LinkedList<String> (mMap.keySet ()); } public List<String> selectNames (Filter filter) { List<String> selectedNames = new LinkedList<String> (); for (String name : mMap.keySet ()) { if (filter.isOk (name)) { selectedNames.add (name); } } return selectedNames; } public Set<String> selectValues (Filter filter) { Set<String> selectedValues = new HashSet<String> (); for (String key : mMap.values ()) { if (filter.isOk (key)) { selectedValues.add (key); } } return selectedValues; } public static interface Filter { boolean isOk (String value); } }
MartinGijsen/PowerTools
power-tools-parent/power-tools-engine/src/main/java/org/powertools/engine/Arguments.java
Java
agpl-3.0
2,755
#!/usr/bin/env bash ############################################################################### # geo-infra Scripts and templates to create and manage geoportals # Copyright (c) 2015-2016, sigeom sa # Copyright (c) 2015-2016, Ioda-Net Sàrl # # Contact : contact (at) geoportal (dot) xyz # Repository : https://github.com/ioda-net/geo-infra # # 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 (at your option) 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/>. ############################################################################### HELP['sync-data']="manuel sync-data Synchronise the data." function sync-data { if [[ -d "${DATA_SRC}" ]] && [[ -n "${DATA_DEST}" ]]; then echo rsync --stats -avh -P --no-o --no-g --delete --bwlimit="${BWL}" ${DATA_SRC} ${DATA_DEST} else echo "Source '${DATA_SRC}' or '${DATA_DEST}' is empty. Not synching data." >&2 exit 1 fi } HELP['deploy-portal']="manuel deploy-portal PORTAL Deploy the given portal on production. Don't build anything." function deploy-portal { _prod-repo-release "$1" _update-prod-repos "$1" } function _prod-repo-release { # Takes one argument, the portal name. local portal="$1"; shift; local infra_dir=$(_get-infra-dir "${portal}") local portal_git_repo="${infra_dir}/prod/${portal}" # Get the id of the current commits local current_geo_infra_commit=$(git rev-parse HEAD 2> /dev/null) pushd "${FRONT_DIR}" local current_front_commit=$(git rev-parse HEAD 2> /dev/null) popd # Get the id of the last deployed commit from geo-infra and geo-front pushd "${portal_git_repo}" local previous_tag=$(git tag | sort -nr | head -n 1) local previous_geo_infra_commit=$(_get-previous-commit "- (.+)infra commit:") local previous_front_commit=$(_get-previous-commit "- front commit:") popd # Get the changelog for geo-infra local geo_infra_changelog='' if [[ -n "${previous_geo_infra_commit}" ]]; then geo_infra_changelog=$(_get-geo-infra-changelog) fi # Get the changelog for front & updates from Swisstopo local front_changelog='' local front_update_from_swisstopo='' if [[ -n "${previous_front_commit}" ]]; then front_changelog=$(_get-front-changelog) front_update_from_swisstopo=$(_get-update-from-swisstopo) fi pushd "${portal_git_repo}" _commit-new-front popd } function _get-previous-commit { if [[ -z "${previous_tag}" ]]; then # First push, no changelog echo "" else echo $(git show "${previous_tag}" | grep -E -- "$1" | head -n 1 | awk '{print $4}') fi } function _get-geo-infra-changelog { local range="${previous_geo_infra_commit}..${current_geo_infra_commit}" echo "$(git log "${range}" --oneline | grep -v "Merge branch '.*' into")" } function _get-front-changelog { pushd "${FRONT_DIR}" local range="${previous_front_commit}..${current_front_commit}" echo "$(git log "${range}" --oneline --no-merges)" popd } function _get-update-from-swisstopo { local front_update_from_swisstopo='' pushd "${FRONT_DIR}" local range="${previous_front_commit}..${current_front_commit}" # Get the update list from Swisstopo local changes for merge_commit in $(git log "${range}" --oneline | grep "Merge branch 'master' into" | awk '{print $1}'); do changes=$(git log "${merge_commit}" -1 --pretty=format:"%B" | tail -n +3) front_update_from_swisstopo="${front_update_from_swisstopo}${changes}" done popd echo "${front_update_from_swisstopo}" } function _commit-new-front { _exit-current-dir-not-git-root echo "Commiting modifications" git add -A . &> /dev/null local commit_message="release ${portal} $(date +"%Y-%m-%d-%H-%M-%S") by ${USER} on ${HOSTNAME} from ${SSH_CLIENT} - geo-infra commit: ${current_geo_infra_commit} - front commit: ${current_front_commit} GEO-INFRA CHANGELOG: ${geo_infra_changelog} FRONT CHANGELOG: ${front_changelog} UPDATES FROM SWISSTOPO: ${front_update_from_swisstopo}" # If there's nothing to commit, we stop the function here. if ! git commit -m "${commit_message}" > /dev/null; then echo "Nothing changed on repo $(pwd)." else local tag_message="${USER} ${HOSTNAME} ${SSH_CLIENT}" git tag -a -m "${tag_message}" $(date +"%Y-%m-%d-%H-%M-%S") &> /dev/null echo "Pushing updated repo" git push --quiet git push --tags --quiet fi } function _exit-current-dir-not-git-root { if ! [[ $(git rev-parse --show-toplevel) -ef $(pwd) ]]; then echo "ERROR: $(pwd) is not a git repository. Exiting." >&2 exit 2 fi } function _update-prod-repos { execute-on-prod "export MFP_APP_FOLDER=\"${MFP_APP_FOLDER}\" && \ export CP_CMD=\"${CP_CMD}\" && \ $(declare -f tomcat-copy-conf) && \ cd ${PROD_GIT_REPOS_LOCATION}/$1 && \ echo \"Updating remote repo with new version\" && \ git reset --hard --quiet && \ git clean --force -d --quiet && \ git fetch --quiet && \ git checkout \$(git tag | sort -nr | head -n 1) --quiet && \ echo \"Copy tomcat's configuration\" && \ tomcat-copy-conf 'prod' \"$1\"" } function _work-tree-clean { local git_status_output=$(git status --porcelain --ignore-submodule) if [ -z "${git_status_output}" ] ; then return 0 else return 1 fi } HELP['tomcat-copy-conf']="manuel tomcat-copy-conf TYPE PORTAL Copy the generated MFP configuration files into tomcat's MFP directory. Use the files from TYPE and PORTAL." function tomcat-copy-conf { if type sudo_tomcat_copyconf > /dev/null 2>&1; then sudo_tomcat_copyconf "$2" else if [[ -z "${1:-}" || -z "${2:-}" ]]; then echo "You must specify a portal and a type for tomcat-copy-conf to work" >&2 exit 1 fi local type="$1"; shift local portal="$1"; shift local mfp_portal_dest="${MFP_APP_FOLDER}/${portal}/" if [[ ! -d "${mfp_portal_dest}" ]]; then mkdir -p "${mfp_portal_dest}" fi if [[ "${type}" == "prod" ]]; then if [[ -d "${infra_dir}/${type}/${portal}/print" ]]; then "${CP_CMD}" -av ${type}/${portal}/print/* "${mfp_portal_dest}" > /dev/null else "${CP_CMD}" -av print/* "${mfp_portal_dest}" > /dev/null fi else local infra_dir=$(_get-infra-dir "${portal}") if [[ -d "${infra_dir}/${type}/${portal}/print" ]]; then "${CP_CMD}" -av "${infra_dir}/${type}/${portal}/print"/* "${mfp_portal_dest}" > /dev/null else "${CP_CMD}" -av print/* "${mfp_portal_dest}" > /dev/null fi fi fi } HELP['deploy-global-search-conf']="manuel deploy-global-search-conf Deploy sphinx global configuration." function deploy-global-search-conf { _load-prod-config generate-global-search-conf "prod" pushd "${INFRA_DIR}/prod/search" local message="release search $(date +"%Y-%m-%d-%H-%M-%S")" git add -A . if git ci -am "${message}"; then git tag -a -m "${message}" $(date +"%Y-%m-%d-%H-%M-%S") git push git push --tags fi popd execute-on-prod "cd \"${PROD_GIT_REPOS_LOCATION}/search\" && \ git reset --hard && \ git fetch && \ git checkout \$(git tag | sort -nr | head -n 1) && \ $(declare -f restart-service) && \ $(declare -f reindex) && \ restart-service search && \ reindex" } HELP['reload-apache']="manuel reload-apache " function reload-apache { local prod_cmd="sudo_apache_reload" if type "${prod_cmd}" > /dev/null 2>&1; then "${prod_cmd}" elif sudo /usr/sbin/apachectl -t; then if [[ -e '/usr/lib/systemd/system/httpd.service' ]]; then sudo "${SYSTEMCTL_CMD}" reload httpd.service else sudo "${SYSTEMCTL_CMD}" reload apache2.service fi fi } HELP['deploy-vhost']="manuel deploy-vhost [INFRA_DIR] Deploy the vhost generated in prod/vhost.d to the production server. **This doesn't generate the vhost for prod.** You can specify a specific INFRA_DIR. If INFRA_DIR is not specified, it will loop over all the infra directories it finds in INFRA_DIR." function deploy-vhost { _load-prod-config local infra_dir="${1:-}" local possible_infra_dir local vhost_dir local repos_to_deploy=() local commit_message if [[ -n "${infra_dir}" && -d "${INFRA_DIR}/${infra_dir}/${PROD_VHOST_OUTPUT}" ]]; then repos_to_deploy+=("${INFRA_DIR}/${infra_dir}/${PROD_VHOST_OUTPUT}") elif [[ -d "${INFRA_DIR}/${PROD_VHOST_OUTPUT}" ]]; then repos_to_deploy+=("${INFRA_DIR}/${PROD_VHOST_OUTPUT}") else for possible_infra_dir in $(ls "${INFRA_DIR}"); do if [[ -d "${INFRA_DIR}/${possible_infra_dir}/${PROD_VHOST_OUTPUT}" ]]; then repos_to_deploy+=("${INFRA_DIR}/${possible_infra_dir}/${PROD_VHOST_OUTPUT}") else echo "No vhost to deploy in ${INFRA_DIR}/${possible_infra_dir}" fi done fi # Exit now if no vhosts, exit here: if [[ "${#repos_to_deploy[@]}" -eq 0 ]]; then echo "Found no vhosts to deploy." return fi for vhost_dir in "${repos_to_deploy[@]}"; do pushd "${vhost_dir}" echo "Deploying vhosts for ${vhost_dir}" _exit-current-dir-not-git-root git add -A . commit_message="Update production vhost $(date +"%Y-%m-%d-%H-%M-%S") Added: $(git diff --name-only --diff-filter=A --cached) Modified: $(git diff --name-only --diff-filter=M --cached)" if ! git commit -am "${commit_message}"; then echo "Nothing to commit in $(pwd)" echo "Continuing." continue fi git tag -a -m "Release production vhost $(date +"%Y-%m-%d-%H-%M-%S")" $(date +"%Y-%m-%d-%H-%M-%S") git push git push --tags execute-on-prod "cd \"${PROD_GIT_REPOS_LOCATION}/vhosts.d\" && \ git reset --hard && \ git fetch && \ git checkout \$(git tag | sort -nr | head -n 1) && \ $(declare -f reload-apache) && \ reload-apache" echo "Done" popd done }
ioda-net/geo-infra
tasks/deploy.sh
Shell
agpl-3.0
11,321
/* * TeleStax, Open Source Cloud Communications Copyright 2012. * and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.map.service.mobility.subscriberManagement; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import org.mobicents.protocols.asn.AsnInputStream; import org.mobicents.protocols.asn.AsnOutputStream; import org.mobicents.protocols.asn.Tag; import org.restcomm.protocols.ss7.map.api.primitives.AddressNature; import org.restcomm.protocols.ss7.map.api.primitives.ISDNAddressString; import org.restcomm.protocols.ss7.map.api.primitives.MAPExtensionContainer; import org.restcomm.protocols.ss7.map.api.primitives.NumberingPlan; import org.restcomm.protocols.ss7.map.api.service.supplementary.SSCode; import org.restcomm.protocols.ss7.map.api.service.supplementary.SupplementaryCodeValue; import org.restcomm.protocols.ss7.map.primitives.ISDNAddressStringImpl; import org.restcomm.protocols.ss7.map.primitives.MAPExtensionContainerTest; import org.restcomm.protocols.ss7.map.service.mobility.subscriberManagement.SSCamelDataImpl; import org.restcomm.protocols.ss7.map.service.supplementary.SSCodeImpl; import org.testng.annotations.Test; /** * * @author Lasith Waruna Perera * */ public class SSCamelDataTest { public byte[] getData() { return new byte[] { 48, 52, 48, 3, 4, 1, 96, 4, 4, -111, 34, 50, -11, -96, 39, -96, 32, 48, 10, 6, 3, 42, 3, 4, 11, 12, 13, 14, 15, 48, 5, 6, 3, 42, 3, 6, 48, 11, 6, 3, 42, 3, 5, 21, 22, 23, 24, 25, 26, -95, 3, 31, 32, 33 }; }; @Test(groups = { "functional.decode", "primitives" }) public void testDecode() throws Exception { byte[] data = this.getData(); AsnInputStream asn = new AsnInputStream(data); int tag = asn.readTag(); SSCamelDataImpl prim = new SSCamelDataImpl(); prim.decodeAll(asn); assertEquals(tag, Tag.SEQUENCE); assertEquals(asn.getTagClass(), Tag.CLASS_UNIVERSAL); ArrayList<SSCode> ssEventList = prim.getSsEventList(); assertNotNull(ssEventList); assertEquals(ssEventList.size(), 1); SSCode one = ssEventList.get(0); assertNotNull(one); assertEquals(one.getSupplementaryCodeValue(), SupplementaryCodeValue.allCommunityOfInterestSS); ISDNAddressString gsmSCFAddress = prim.getGsmSCFAddress(); assertTrue(gsmSCFAddress.getAddress().equals("22235")); assertEquals(gsmSCFAddress.getAddressNature(), AddressNature.international_number); assertEquals(gsmSCFAddress.getNumberingPlan(), NumberingPlan.ISDN); assertNotNull(prim.getExtensionContainer()); assertTrue(MAPExtensionContainerTest.CheckTestExtensionContainer(prim.getExtensionContainer())); } @Test(groups = { "functional.encode", "primitives" }) public void testEncode() throws Exception { ArrayList<SSCode> ssEventList = new ArrayList<SSCode>(); ssEventList.add(new SSCodeImpl(SupplementaryCodeValue.allCommunityOfInterestSS.getCode())); ISDNAddressString gsmSCFAddress = new ISDNAddressStringImpl(AddressNature.international_number, NumberingPlan.ISDN, "22235"); MAPExtensionContainer extensionContainer = MAPExtensionContainerTest.GetTestExtensionContainer(); SSCamelDataImpl prim = new SSCamelDataImpl(ssEventList, gsmSCFAddress, extensionContainer); AsnOutputStream asn = new AsnOutputStream(); prim.encodeAll(asn); assertTrue(Arrays.equals(asn.toByteArray(), this.getData())); } }
RestComm/jss7
map/map-impl/src/test/java/org/restcomm/protocols/ss7/map/service/mobility/subscriberManagement/SSCamelDataTest.java
Java
agpl-3.0
4,559
""" Test the views of jurisdiction models """ # Django from django.test import TestCase # Third Party from nose.tools import assert_is_not, eq_ # MuckRock from muckrock.core.test_utils import http_get_response from muckrock.jurisdiction import factories, views class TestExemptionDetailView(TestCase): """The exemption detail view provides information about the exemption at a standalone url.""" def setUp(self): self.view = views.ExemptionDetailView.as_view() def test_ok(self): """The view should return a 200 OK status.""" exemption = factories.ExemptionFactory() url = exemption.get_absolute_url() kwargs = exemption.jurisdiction.get_slugs() kwargs.update({"slug": exemption.slug, "pk": exemption.pk}) response = http_get_response(url, self.view, **kwargs) eq_(response.status_code, 200) def test_unique_for_jurisdiction(self): """Two exemptions may have the same name, as long as they belong to different jurisdictions.""" exemption = factories.ExemptionFactory() url = exemption.get_absolute_url() kwargs = exemption.jurisdiction.get_slugs() kwargs.update({"slug": exemption.slug, "pk": exemption.pk}) another_jurisdiction = factories.StateJurisdictionFactory( parent=exemption.jurisdiction.parent ) assert_is_not(exemption.jurisdiction, another_jurisdiction) factories.ExemptionFactory(jurisdiction=another_jurisdiction) response = http_get_response(url, self.view, **kwargs) eq_(response.status_code, 200) def test_local_exemptions(self): """An exemption at the local level should return 200.""" local = factories.LocalJurisdictionFactory() exemption = factories.ExemptionFactory(jurisdiction=local) url = exemption.get_absolute_url() kwargs = exemption.jurisdiction.get_slugs() kwargs.update({"slug": exemption.slug, "pk": exemption.pk}) response = http_get_response(url, self.view, **kwargs) eq_(response.status_code, 200) def test_state_exemptions(self): """An exemption at the state level should return 200.""" state = factories.StateJurisdictionFactory() exemption = factories.ExemptionFactory(jurisdiction=state) url = exemption.get_absolute_url() kwargs = exemption.jurisdiction.get_slugs() kwargs.update({"slug": exemption.slug, "pk": exemption.pk}) response = http_get_response(url, self.view, **kwargs) eq_(response.status_code, 200) def test_federal_exemptions(self): """An exemption at the federal level should return 200.""" fed = factories.FederalJurisdictionFactory() exemption = factories.ExemptionFactory(jurisdiction=fed) url = exemption.get_absolute_url() kwargs = exemption.jurisdiction.get_slugs() kwargs.update({"slug": exemption.slug, "pk": exemption.pk}) response = http_get_response(url, self.view, **kwargs) eq_(response.status_code, 200)
MuckRock/muckrock
muckrock/jurisdiction/tests/test_views.py
Python
agpl-3.0
3,078
/* CarRideDAO.java * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright Ⓒ 2014-2015 Universiteit Gent * * This file is part of the Degage Web Application * * Corresponding author (see also AUTHORS.txt) * * Kris Coolsaet * Department of Applied Mathematics, Computer Science and Statistics * Ghent University * Krijgslaan 281-S9 * B-9000 GENT Belgium * * The Degage Web Application is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Degage Web Application 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 the Degage Web Application (file LICENSE.txt in the * distribution). If not, see <http://www.gnu.org/licenses/>. */ package be.ugent.degage.db.dao; import be.ugent.degage.db.DataAccessException; import be.ugent.degage.db.models.CarRide; import be.ugent.degage.db.models.ReservationHeader; import java.time.LocalDate; import java.util.List; /** * Created by HannesM on 10/03/14. */ public interface CarRideDAO { public CarRide createCarRide(ReservationHeader reservation, int startMileage, int endMileage, boolean damaged) throws DataAccessException; /** * Returns the trip details of the given ride. Returns null if no trip details are available. */ public CarRide getCarRide(int id) throws DataAccessException; /* No longer used public void updateCarRide(CarRide carRide) throws DataAccessException; */ public void updateCarRideKm(int rideId, int startKm, int endKm) throws DataAccessException; public void endPeriod() throws DataAccessException; public List<CarRide> getBillRidesForLoaner(LocalDate date, int user) throws DataAccessException; public List<CarRide> getBillRidesForCar(LocalDate date, int car) throws DataAccessException; /** * Return the startKm field of the next reservation, or 0 if no next km is filled in */ public int getNextStartKm (int reservationId); /** * Return the endKm field of the previous reservation, or 0 if no previous km is filled in */ public int getPrevEndKm (int reservationId); }
kcoolsae/Degage
db/src/main/java/be/ugent/degage/db/dao/CarRideDAO.java
Java
agpl-3.0
2,555
<?php namespace SPHERE\Application\Api\Setting\UserAccount; use MOC\V\Core\FileSystem\FileSystem; use SPHERE\Application\IModuleInterface; use SPHERE\Application\IServiceInterface; use SPHERE\Application\Setting\User\Account\Account; use SPHERE\Application\Setting\User\Account\Service\Entity\TblUserAccount; use SPHERE\Common\Frontend\IFrontendInterface; use SPHERE\Common\Main; class AccountUserExcel implements IModuleInterface { public static function registerModule() { Main::getDispatcher()->registerRoute(Main::getDispatcher()->createRoute( __NAMESPACE__.'/Download', __NAMESPACE__.'\AccountUserExcel::downloadAccountList' )); } /** * @return IServiceInterface */ public static function useService() { // TODO: Implement useService() method. } /** * @return IFrontendInterface */ public static function useFrontend() { // TODO: Implement useFrontend() method. } /** * @param null $GroupByTime * * @return bool|string */ public function downloadAccountList($GroupByTime = null) { if ($GroupByTime) { $tblUserAccountList = Account::useService()->getUserAccountByTime((new \DateTime($GroupByTime))); if ($tblUserAccountList) { $tblUserAccount = current($tblUserAccountList); $Type = 'Schüler'; $Time = new \DateTime(); $Time = $Time->format('d_m_Y-h_i_s'); if ($tblUserAccount->getType() == TblUserAccount::VALUE_TYPE_STUDENT) { $Type = 'Schüler'; } elseif ($tblUserAccount->getType() == TblUserAccount::VALUE_TYPE_CUSTODY) { $Type = 'Sorgeberechtigte'; } $result = Account::useService()->getExcelData($tblUserAccountList); if ($result) { $fileLocation = Account::useService()->createClassListExcel($result); return FileSystem::getDownload($fileLocation->getRealPath(), "Zugang-Schulsoftware-".$Type."-".$Time.".xlsx")->__toString(); } } } return false; } }
BozzaCoon/SPHERE-Framework
Application/Api/Setting/UserAccount/AccountUserExcel.php
PHP
agpl-3.0
2,242
MWF.xApplication.service = MWF.xApplication.service || {}; MWF.xApplication.service.ServiceManager = MWF.xApplication.service.ServiceManager || {}; MWF.xApplication.service.ServiceManager.options = { "multitask": false, "executable": true };
o2oa/o2oa
o2web/source/x_component_service_ServiceManager/package.js
JavaScript
agpl-3.0
249
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>. """ This class is a base class for nearly all configuration elements like service, hosts or contacts. """ import time import cPickle # for hashing compute # Try to import md5 function try: from hashlib import md5 except ImportError: from md5 import md5 from copy import copy from shinken.graph import Graph from shinken.commandcall import CommandCall from shinken.property import StringProp, ListProp, BoolProp from shinken.brok import Brok from shinken.util import strip_and_uniq from shinken.acknowledge import Acknowledge from shinken.comment import Comment from shinken.complexexpression import ComplexExpressionFactory from shinken.log import logger class Item(object): properties = { 'imported_from': StringProp(default='unknown'), 'use': ListProp(default=''), 'name': StringProp(default=''), # TODO: find why we can't uncomment this line below. #'register': BoolProp(default='1'), } running_properties = { # All errors and warning raised during the configuration parsing # and that will raised real warning/errors during the is_correct 'configuration_warnings': ListProp(default=[]), 'configuration_errors': ListProp(default=[]), 'hash': StringProp(default=''), # We save all template we asked us to load from 'tags': ListProp(default=set(), fill_brok=['full_status']), } macros = { } def __init__(self, params={}): # We have our own id of My Class type :) # use set attr for going into the slots # instead of __dict__ :) cls = self.__class__ self.id = cls.id cls.id += 1 self.customs = {} # for custom variables self.plus = {} # for value with a + self.init_running_properties() # [0] = + -> new key-plus # [0] = _ -> new custom entry in UPPER case for key in params: if len(params[key]) >= 1 and params[key][0] == '+': # Special case: a _MACRO can be a plus. so add to plus # but upper the key for the macro name if key[0] == "_": self.plus[key.upper()] = params[key][1:] # we remove the + else: self.plus[key] = params[key][1:] # we remove the + elif key[0] == "_": custom_name = key.upper() self.customs[custom_name] = params[key] else: setattr(self, key, params[key]) def init_running_properties(self): for prop, entry in self.__class__.running_properties.items(): # Copy is slow, so we check type # Type with __iter__ are list or dict, or tuple. # Item need it's own list, so we copy val = entry.default if hasattr(val, '__iter__'): setattr(self, prop, copy(val)) else: setattr(self, prop, val) # each instance to have his own running prop! def copy(self): """ Return a copy of the item, but give him a new id """ cls = self.__class__ i = cls({}) # Dummy item but with it's own running properties for prop in cls.properties: if hasattr(self, prop): val = getattr(self, prop) setattr(i, prop, val) # Also copy the customs tab i.customs = copy(self.customs) return i def clean(self): """ Clean useless things not requested once item has been fully initialized&configured. Like temporary attributes such as "imported_from", etc.. """ for name in ('imported_from', 'use', 'plus', 'templates',): try: delattr(self, name) except AttributeError: pass def __str__(self): return str(self.__dict__) + '\n' def is_tpl(self): """ Return if the elements is a template """ try: return self.register == '0' except Exception, exp: return False # If a prop is absent and is not required, put the default value def fill_default(self): """ Fill missing properties if they are missing """ cls = self.__class__ for prop, entry in cls.properties.items(): if not hasattr(self, prop) and entry.has_default: setattr(self, prop, entry.default) # We load every useful parameter so no need to access global conf later # Must be called after a change in a global conf parameter def load_global_conf(cls, conf): """ Used to put global values in the sub Class like hosts or services """ # conf have properties, if 'enable_notifications': # { [...] 'class_inherit': [(Host, None), (Service, None), # (Contact, None)]} # get the name and put the value if None, put the Name # (not None) if not (not clear?) for prop, entry in conf.properties.items(): # If we have a class_inherit, and the arbiter really send us it # if 'class_inherit' in entry and hasattr(conf, prop): if hasattr(conf, prop): for (cls_dest, change_name) in entry.class_inherit: if cls_dest == cls: # ok, we've got something to get value = getattr(conf, prop) if change_name is None: setattr(cls, prop, value) else: setattr(cls, change_name, value) # Make this method a classmethod load_global_conf = classmethod(load_global_conf) # Use to make python properties def pythonize(self): cls = self.__class__ for prop, tab in cls.properties.items(): try: new_val = tab.pythonize(getattr(self, prop)) setattr(self, prop, new_val) except AttributeError, exp: #print exp pass # Will be catch at the is_correct moment except KeyError, exp: #print "Missing prop value", exp err = "the property '%s' of '%s' do not have value" % (prop, self.get_name()) self.configuration_errors.append(err) except ValueError, exp: err = "incorrect type for property '%s' of '%s'" % (prop, self.get_name()) self.configuration_errors.append(err) # Compute a hash of this element values. Should be launched # When we got all our values, but not linked with other objects def compute_hash(self): # ID will always changed between runs, so we remove it # for hash compute i = self.id del self.id m = md5() tmp = cPickle.dumps(self, cPickle.HIGHEST_PROTOCOL) m.update(tmp) self.hash = m.digest() # and put again our id self.id = i def get_templates(self): if hasattr(self, 'use') and self.use != '': return self.use.split(',') else: return [] # We fillfull properties with template ones if need def get_property_by_inheritance(self, items, prop): # If I have the prop, I take mine but I check if I must # add a plus property if hasattr(self, prop): value = getattr(self, prop) # Maybe this value is 'null'. If so, we should NOT inherit # and just delete this entry, and hope of course. # Keep "null" values, because in "inheritance chaining" they must # be passed from one level to the next. #if value == 'null': # delattr(self, prop) # return None # Manage the additive inheritance for the property, # if property is in plus, add or replace it # Template should keep the '+' at the beginning of the chain if self.has_plus(prop): value = self.get_plus_and_delete(prop) + ',' + value if self.is_tpl(): value = '+' + value return value # Ok, I do not have prop, Maybe my templates do? # Same story for plus for i in self.templates: value = i.get_property_by_inheritance(items, prop) if value is not None: # If our template give us a '+' value, we should continue to loop still_loop = False if value.startswith('+'): # Templates should keep their + inherited from their parents if not self.is_tpl(): value = value[1:] still_loop = True # Maybe in the previous loop, we set a value, use it too if hasattr(self, prop): # If the current value is strong, it will simplify the problem if value.startswith('+'): # In this case we can remove the + from our current # tpl because our value will be final value = ','.join([getattr(self, prop), value[1:]]) else: # If not, se should keep the + sign of need value = ','.join([getattr(self, prop), value]) # Ok, we can set it setattr(self, prop, value) # If we only got some '+' values, we must still loop # for an end value without it if not still_loop: # And set my own value in the end if need if self.has_plus(prop): value = ','.join([getattr(self, prop), self.get_plus_and_delete(prop)]) # Template should keep their '+' if self.is_tpl() and not value.startswith('+'): value = '+' + value setattr(self, prop, value) return value # Maybe templates only give us + values, so we didn't quit, but we already got a # self.prop value after all template_with_only_plus = hasattr(self, prop) # I do not have endingprop, my templates too... Maybe a plus? # warning: if all my templates gave me '+' values, do not forgot to # add the already set self.prop value if self.has_plus(prop): if template_with_only_plus: value = ','.join([getattr(self, prop), self.get_plus_and_delete(prop)]) else: value = self.get_plus_and_delete(prop) # Template should keep their '+' chain # We must say it's a '+' value, so our son will now that it must # still loop if self.is_tpl() and not value.startswith('+'): value = '+' + value setattr(self, prop, value) return value # Ok so in the end, we give the value we got if we have one, or None # Not even a plus... so None :) return getattr(self, prop, None) # We fillfull properties with template ones if need def get_customs_properties_by_inheritance(self, items): for i in self.templates: tpl_cv = i.get_customs_properties_by_inheritance(items) if tpl_cv is not {}: for prop in tpl_cv: if prop not in self.customs: value = tpl_cv[prop] else: value = self.customs[prop] if self.has_plus(prop): value = self.get_plus_and_delete(prop) + ',' + value self.customs[prop] = value for prop in self.customs: value = self.customs[prop] if self.has_plus(prop): value = self.get_plus_and_delete(prop) + ',' + value self.customs[prop] = value # We can get custom properties in plus, we need to get all # entires and put # them into customs cust_in_plus = self.get_all_plus_and_delete() for prop in cust_in_plus: self.customs[prop] = cust_in_plus[prop] return self.customs def has_plus(self, prop): try: self.plus[prop] except: return False return True def get_all_plus_and_delete(self): res = {} props = self.plus.keys() # we delete entries, so no for ... in ... for prop in props: res[prop] = self.get_plus_and_delete(prop) return res def get_plus_and_delete(self, prop): val = self.plus[prop] del self.plus[prop] return val # Check is required prop are set: # template are always correct def is_correct(self): state = True properties = self.__class__.properties # Raised all previously saw errors like unknown contacts and co if self.configuration_errors != []: state = False for err in self.configuration_errors: logger.error("[item::%s] %s" % (self.get_name(), err)) for prop, entry in properties.items(): if not hasattr(self, prop) and entry.required: logger.warning("[item::%s] %s property is missing" % (self.get_name(), prop)) state = False return state # This function is used by service and hosts # to transform Nagios2 parameters to Nagios3 # ones, like normal_check_interval to # check_interval. There is a old_parameters tab # in Classes that give such modifications to do. def old_properties_names_to_new(self): old_properties = self.__class__.old_properties for old_name, new_name in old_properties.items(): # Ok, if we got old_name and NO new name, # we switch the name if hasattr(self, old_name) and not hasattr(self, new_name): value = getattr(self, old_name) setattr(self, new_name, value) # The arbiter is asking us our raw value before all explode or linking def get_raw_import_values(self): r = {} properties = self.__class__.properties.keys() # Register is not by default in the properties if not 'register' in properties: properties.append('register') for prop in properties: if hasattr(self, prop): v = getattr(self, prop) #print prop, ":", v r[prop] = v return r def add_downtime(self, downtime): self.downtimes.append(downtime) def del_downtime(self, downtime_id): d_to_del = None for dt in self.downtimes: if dt.id == downtime_id: d_to_del = dt dt.can_be_deleted = True if d_to_del is not None: self.downtimes.remove(d_to_del) def add_comment(self, comment): self.comments.append(comment) def del_comment(self, comment_id): c_to_del = None for c in self.comments: if c.id == comment_id: c_to_del = c c.can_be_deleted = True if c_to_del is not None: self.comments.remove(c_to_del) def acknowledge_problem(self, sticky, notify, persistent, author, comment, end_time=0): if self.state != self.ok_up: if notify: self.create_notifications('ACKNOWLEDGEMENT') self.problem_has_been_acknowledged = True if sticky == 2: sticky = True else: sticky = False a = Acknowledge(self, sticky, notify, persistent, author, comment, end_time=end_time) self.acknowledgement = a if self.my_type == 'host': comment_type = 1 else: comment_type = 2 c = Comment(self, persistent, author, comment, comment_type, 4, 0, False, 0) self.add_comment(c) self.broks.append(self.get_update_status_brok()) # Look if we got an ack that is too old with an expire date and should # be delete def check_for_expire_acknowledge(self): if self.acknowledgement and self.acknowledgement.end_time != 0 and self.acknowledgement.end_time < time.time(): self.unacknowledge_problem() # Delete the acknowledgement object and reset the flag # but do not remove the associated comment. def unacknowledge_problem(self): if self.problem_has_been_acknowledged: logger.debug("[item::%s] deleting acknowledge of %s" % (self.get_name(), self.get_dbg_name())) self.problem_has_been_acknowledged = False # Should not be deleted, a None is Good self.acknowledgement = None # del self.acknowledgement # find comments of non-persistent ack-comments and delete them too for c in self.comments: if c.entry_type == 4 and not c.persistent: self.del_comment(c.id) self.broks.append(self.get_update_status_brok()) # Check if we have an acknowledgement and if this is marked as sticky. # This is needed when a non-ok state changes def unacknowledge_problem_if_not_sticky(self): if hasattr(self, 'acknowledgement') and self.acknowledgement is not None: if not self.acknowledgement.sticky: self.unacknowledge_problem() # Will flatten some parameters tagged by the 'conf_send_preparation' # property because they are too "linked" to be send like that (like realms) def prepare_for_conf_sending(self): cls = self.__class__ for prop, entry in cls.properties.items(): # Is this property need preparation for sending? if entry.conf_send_preparation is not None: f = entry.conf_send_preparation if f is not None: val = f(getattr(self, prop)) setattr(self, prop, val) if hasattr(cls, 'running_properties'): for prop, entry in cls.running_properties.items(): # Is this property need preparation for sending? if entry.conf_send_preparation is not None: f = entry.conf_send_preparation if f is not None: val = f(getattr(self, prop)) setattr(self, prop, val) # Get the property for an object, with good value # and brok_transformation if need def get_property_value_for_brok(self, prop, tab): entry = tab[prop] # Get the current value, or the default if need value = getattr(self, prop, entry.default) # Apply brok_transformation if need # Look if we must preprocess the value first pre_op = entry.brok_transformation if pre_op is not None: value = pre_op(self, value) return value # Fill data with info of item by looking at brok_type # in props of properties or running_properties def fill_data_brok_from(self, data, brok_type): cls = self.__class__ # Now config properties for prop, entry in cls.properties.items(): # Is this property intended for broking? if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.properties) # Maybe the class do not have running_properties if hasattr(cls, 'running_properties'): # We've got prop in running_properties too for prop, entry in cls.running_properties.items(): #if 'fill_brok' in cls.running_properties[prop]: if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.running_properties) # Get a brok with initial status def get_initial_status_brok(self): cls = self.__class__ my_type = cls.my_type data = {'id': self.id} self.fill_data_brok_from(data, 'full_status') b = Brok('initial_' + my_type + '_status', data) return b # Get a brok with update item status def get_update_status_brok(self): cls = self.__class__ my_type = cls.my_type data = {'id': self.id} self.fill_data_brok_from(data, 'full_status') b = Brok('update_' + my_type + '_status', data) return b # Get a brok with check_result def get_check_result_brok(self): cls = self.__class__ my_type = cls.my_type data = {} self.fill_data_brok_from(data, 'check_result') b = Brok(my_type + '_check_result', data) return b # Get brok about the new schedule (next_check) def get_next_schedule_brok(self): cls = self.__class__ my_type = cls.my_type data = {} self.fill_data_brok_from(data, 'next_schedule') b = Brok(my_type + '_next_schedule', data) return b # Link one command property to a class (for globals like oc*p_command) def linkify_one_command_with_commands(self, commands, prop): if hasattr(self, prop): command = getattr(self, prop).strip() if command != '': if hasattr(self, 'poller_tag'): cmdCall = CommandCall(commands, command, poller_tag=self.poller_tag) elif hasattr(self, 'reactionner_tag'): cmdCall = CommandCall(commands, command, reactionner_tag=self.reactionner_tag) else: cmdCall = CommandCall(commands, command) setattr(self, prop, cmdCall) else: setattr(self, prop, None) # We look at the 'trigger' prop and we create a trigger for it def explode_trigger_string_into_triggers(self, triggers): src = getattr(self, 'trigger', '') if src: # Change on the fly the characters src = src.replace(r'\n', '\n').replace(r'\t', '\t') t = triggers.create_trigger(src, 'inner-trigger-' + self.__class__.my_type + '' + str(self.id)) if t: # Maybe the trigger factory give me a already existing trigger, # so my name can be dropped self.triggers.append(t.get_name()) # Link with triggers. Can be with a "in source" trigger, or a file name def linkify_with_triggers(self, triggers): # Get our trigger string and trigger names in the same list self.triggers.extend(self.trigger_name) #print "I am linking my triggers", self.get_full_name(), self.triggers new_triggers = [] for tname in self.triggers: t = triggers.find_by_name(tname) if t: new_triggers.append(t) else: self.configuration_errors.append('the %s %s does have a unknown trigger_name "%s"' % (self.__class__.my_type, self.get_full_name(), tname)) self.triggers = new_triggers class Items(object): def __init__(self, items): self.items = {} self.configuration_warnings = [] self.configuration_errors = [] for i in items: self.items[i.id] = i self.templates = {} # We should keep a graph of templates relations self.templates_graph = Graph() def __iter__(self): return self.items.itervalues() def __len__(self): return len(self.items) def __delitem__(self, key): try: del self.items[key] except KeyError: # we don't want it, we do not have it. All is perfect pass def __setitem__(self, key, value): self.items[key] = value def __getitem__(self, key): return self.items[key] def __contains__(self, key): return key in self.items def compute_hash(self): for i in self: i.compute_hash() # We create the reversed list so search will be faster # We also create a twins list with id of twins (not the original # just the others, higher twins) def create_reversed_list(self): self.reversed_list = {} self.twins = [] name_property = self.__class__.name_property for id in self.items: if hasattr(self.items[id], name_property): name = getattr(self.items[id], name_property) if name not in self.reversed_list: self.reversed_list[name] = id else: self.twins.append(id) def find_id_by_name(self, name): if hasattr(self, 'reversed_list'): if name in self.reversed_list: return self.reversed_list[name] else: return None else: # ok, an early ask, with no reversed list from now... name_property = self.__class__.name_property for i in self: if hasattr(i, name_property): i_name = getattr(i, name_property) if i_name == name: return i.id return None def find_by_name(self, name): id = self.find_id_by_name(name) if id is not None: return self.items[id] else: return None # prepare_for_conf_sending to flatten some properties def prepare_for_sending(self): for i in self: i.prepare_for_conf_sending() # It's used to change old Nagios2 names to # Nagios3 ones def old_properties_names_to_new(self): for i in self: i.old_properties_names_to_new() def pythonize(self): for id in self.items: self.items[id].pythonize() def create_tpl_list(self): for id in self.items: i = self.items[id] if i.is_tpl(): self.templates[id] = i def find_tpl_by_name(self, name): for i in self.templates.values(): if hasattr(i, 'name') and i.name == name: return i return None # We will link all templates, and create the template # graph too def linkify_templates(self): # First we create a list of all templates self.create_tpl_list() for i in self: tpls = i.get_templates() new_tpls = [] for tpl in tpls: tpl = tpl.strip() # We save this template in the 'tags' set i.tags.add(tpl) # Then we link it t = self.find_tpl_by_name(tpl) # If it's ok, add the template and update the # template graph too if t is not None: # add the template object to us new_tpls.append(t) else: # not find? not good! err = "the template '%s' defined for '%s' is unknown" % (tpl, i.get_name()) i.configuration_warnings.append(err) i.templates = new_tpls # Now we will create the template graph, so # we look only for templates here. First we should declare our nodes for tpl in self.templates.values(): self.templates_graph.add_node(tpl) # And then really create our edge for tpl in self.templates.values(): for father in tpl.templates: self.templates_graph.add_edge(father, tpl) def is_correct(self): # we are ok at the beginning. Hope we still ok at the end... r = True # Some class do not have twins, because they do not have names # like servicedependencies twins = getattr(self, 'twins', None) if twins is not None: # Ok, look at no twins (it's bad!) for id in twins: i = self.items[id] logger.error("[items] %s.%s is duplicated from %s" %\ (i.__class__.my_type, i.get_name(), getattr(i, 'imported_from', "unknown source"))) r = False # Then look if we have some errors in the conf # Juts print warnings, but raise errors for err in self.configuration_warnings: logger.warning("[items] %s" % err) for err in self.configuration_errors: logger.error("[items] %s" % err) r = False # Then look for individual ok for i in self: # Alias and display_name hook hook prop_name = getattr(self.__class__, 'name_property', None) if prop_name and not hasattr(i, 'alias') and hasattr(i, prop_name): setattr(i, 'alias', getattr(i, prop_name)) if prop_name and getattr(i, 'display_name', '') == '' and hasattr(i, prop_name): setattr(i, 'display_name', getattr(i, prop_name)) # Now other checks if not i.is_correct(): n = getattr(i, 'imported_from', "unknown source") logger.error("[items] In %s is incorrect ; from %s" % (i.get_name(), n)) r = False return r def remove_templates(self): """ Remove useless templates (& properties) of our items ; otherwise we could get errors on config.is_correct() """ tpls = [i for i in self if i.is_tpl()] for i in tpls: del self[i.id] del self.templates del self.templates_graph def clean(self): """ Request to remove the unnecessary attributes/others from our items """ for i in self: i.clean() Item.clean(self) # If a prop is absent and is not required, put the default value def fill_default(self): for i in self: i.fill_default() def __str__(self): s = '' cls = self.__class__ for id in self.items: s = s + str(cls) + ':' + str(id) + str(self.items[id]) + '\n' return s # Inheritance for just a property def apply_partial_inheritance(self, prop): for i in self: i.get_property_by_inheritance(self, prop) if not i.is_tpl(): # If a "null" attribute was inherited, delete it try: if getattr(i, prop) == 'null': delattr(i, prop) except: pass def apply_inheritance(self): # We check for all Class properties if the host has it # if not, it check all host templates for a value cls = self.inner_class for prop in cls.properties: self.apply_partial_inheritance(prop) for i in self: i.get_customs_properties_by_inheritance(self) # We remove twins # Remember: item id respect the order of conf. So if and item # is defined multiple times, # we want to keep the first one. # Services are also managed here but they are specials: # We remove twins services with the same host_name/service_description # Remember: host service are take into account first before hostgroup service # Id of host service are lower than hostgroups one, so they are # in self.twins_services # and we can remove them. def remove_twins(self): for id in self.twins: i = self.items[id] type = i.__class__.my_type logger.warning("[items] %s.%s is already defined '%s'" % (type, i.get_name(), getattr(i, 'imported_from', "unknown source"))) del self[id] # bye bye # do not remove twins, we should look in it, but just void it self.twins = [] #del self.twins #no more need # We've got a contacts property with , separated contacts names # and we want have a list of Contacts def linkify_with_contacts(self, contacts): for i in self: if hasattr(i, 'contacts'): contacts_tab = i.contacts.split(',') contacts_tab = strip_and_uniq(contacts_tab) new_contacts = [] for c_name in contacts_tab: if c_name != '': c = contacts.find_by_name(c_name) if c is not None: new_contacts.append(c) # Else: Add in the errors tab. # will be raised at is_correct else: err = "the contact '%s' defined for '%s' is unknown" % (c_name, i.get_name()) i.configuration_errors.append(err) # Get the list, but first make elements uniq i.contacts = list(set(new_contacts)) # Make link between an object and its escalations def linkify_with_escalations(self, escalations): for i in self: if hasattr(i, 'escalations'): escalations_tab = i.escalations.split(',') escalations_tab = strip_and_uniq(escalations_tab) new_escalations = [] for es_name in [e for e in escalations_tab if e != '']: es = escalations.find_by_name(es_name) if es is not None: new_escalations.append(es) else: # Escalation not find, not good! err = "the escalation '%s' defined for '%s' is unknown" % (es_name, i.get_name()) i.configuration_errors.append(err) i.escalations = new_escalations # Make link between item and it's resultmodulations def linkify_with_resultmodulations(self, resultmodulations): for i in self: if hasattr(i, 'resultmodulations'): resultmodulations_tab = i.resultmodulations.split(',') resultmodulations_tab = strip_and_uniq(resultmodulations_tab) new_resultmodulations = [] for rm_name in resultmodulations_tab: rm = resultmodulations.find_by_name(rm_name) if rm is not None: new_resultmodulations.append(rm) else: err = "the result modulation '%s' defined on the %s '%s' do not exist" % (rm_name, i.__class__.my_type, i.get_name()) i.configuration_errors.append(err) continue i.resultmodulations = new_resultmodulations # Make link between item and it's business_impact_modulations def linkify_with_business_impact_modulations(self, business_impact_modulations): for i in self: if hasattr(i, 'business_impact_modulations'): business_impact_modulations_tab = i.business_impact_modulations.split(',') business_impact_modulations_tab = strip_and_uniq(business_impact_modulations_tab) new_business_impact_modulations = [] for rm_name in business_impact_modulations_tab: rm = business_impact_modulations.find_by_name(rm_name) if rm is not None: new_business_impact_modulations.append(rm) else: err = "the business impact modulation '%s' defined on the %s '%s' do not exist" % (rm_name, i.__class__.my_type, i.get_name()) i.configuration_errors.append(err) continue i.business_impact_modulations = new_business_impact_modulations # If we've got a contact_groups properties, we search for all # theses groups and ask them their contacts, and then add them # all into our contacts property def explode_contact_groups_into_contacts(self, contactgroups): for i in self: if hasattr(i, 'contact_groups'): cgnames = i.contact_groups.split(',') cgnames = strip_and_uniq(cgnames) for cgname in cgnames: cg = contactgroups.find_by_name(cgname) if cg is None: err = "The contact group '%s' defined on the %s '%s' do not exist" % (cgname, i.__class__.my_type, i.get_name()) i.configuration_errors.append(err) continue cnames = contactgroups.get_members_by_name(cgname) # We add contacts into our contacts if cnames != []: if hasattr(i, 'contacts'): i.contacts += ',' + cnames else: i.contacts = cnames # Link a timeperiod property (prop) def linkify_with_timeperiods(self, timeperiods, prop): for i in self: if hasattr(i, prop): tpname = getattr(i, prop).strip() # some default values are '', so set None if tpname == '': setattr(i, prop, None) continue # Ok, get a real name, search for it tp = timeperiods.find_by_name(tpname) # If not found, it's an error if tp is None: err = "The %s of the %s '%s' named '%s' is unknown!" % (prop, i.__class__.my_type, i.get_name(), tpname) i.configuration_errors.append(err) continue # Got a real one, just set it :) setattr(i, prop, tp) # Link one command property def linkify_one_command_with_commands(self, commands, prop): for i in self: if hasattr(i, prop): command = getattr(i, prop).strip() if command != '': if hasattr(i, 'poller_tag'): cmdCall = CommandCall(commands, command, poller_tag=i.poller_tag) elif hasattr(i, 'reactionner_tag'): cmdCall = CommandCall(commands, command, reactionner_tag=i.reactionner_tag) else: cmdCall = CommandCall(commands, command) # TODO: catch None? setattr(i, prop, cmdCall) else: setattr(i, prop, None) # Link a command list (commands with , between) in real CommandCalls def linkify_command_list_with_commands(self, commands, prop): for i in self: if hasattr(i, prop): coms = getattr(i, prop).split(',') coms = strip_and_uniq(coms) com_list = [] for com in coms: if com != '': if hasattr(i, 'poller_tag'): cmdCall = CommandCall(commands, com, poller_tag=i.poller_tag) elif hasattr(i, 'reactionner_tag'): cmdCall = CommandCall(commands, com, reactionner_tag=i.reactionner_tag) else: cmdCall = CommandCall(commands, com) # TODO: catch None? com_list.append(cmdCall) else: # TODO: catch? pass setattr(i, prop, com_list) # Link with triggers. Can be with a "in source" trigger, or a file name def linkify_with_triggers(self, triggers): for i in self: i.linkify_with_triggers(triggers) # We've got a notificationways property with , separated contacts names # and we want have a list of NotificationWay def linkify_with_checkmodulations(self, checkmodulations): for i in self: if not hasattr(i, 'checkmodulations'): continue new_checkmodulations = [] for cw_name in i.checkmodulations: cw = checkmodulations.find_by_name(cw_name) if cw is not None: new_checkmodulations.append(cw) else: err = "The checkmodulations of the %s '%s' named '%s' is unknown!" % (i.__class__.my_type, i.get_name(), cw_name) i.configuration_errors.append(err) # Get the list, but first make elements uniq i.checkmodulations = new_checkmodulations # We've got list of macro modulations as list of names, and # we want real objects def linkify_with_macromodulations(self, macromodulations): for i in self: if not hasattr(i, 'macromodulations'): continue new_macromodulations = [] for cw_name in i.macromodulations: cw = macromodulations.find_by_name(cw_name) if cw is not None: new_macromodulations.append(cw) else: err = "The macromodulations of the %s '%s' named '%s' is unknown!" % (i.__class__.my_type, i.get_name(), cw_name) i.configuration_errors.append(err) # Get the list, but first make elements uniq i.macromodulations = new_macromodulations def evaluate_hostgroup_expression(self, expr, hosts, hostgroups, look_in='hostgroups'): #print "\n"*10, "looking for expression", expr if look_in=='hostgroups': f = ComplexExpressionFactory(look_in, hostgroups, hosts) else: # templates f = ComplexExpressionFactory(look_in, hosts, hosts) expr_tree = f.eval_cor_pattern(expr) #print "RES of ComplexExpressionFactory" #print expr_tree #print "Try to resolve the Tree" set_res = expr_tree.resolve_elements() #print "R2d2 final is", set_res # HOOK DBG return list(set_res) # If we've got a hostgroup_name property, we search for all # theses groups and ask them their hosts, and then add them # all into our host_name property def explode_host_groups_into_hosts(self, hosts, hostgroups): for i in self: hnames_list = [] if hasattr(i, 'hostgroup_name'): hnames_list.extend(self.evaluate_hostgroup_expression(i.hostgroup_name, hosts, hostgroups)) # Maybe there is no host in the groups, and do not have any # host_name too, so tag is as template to do not look at if hnames_list == [] and not hasattr(i, 'host_name'): i.register = '0' if hasattr(i, 'host_name'): hst = i.host_name.split(',') for h in hst: h = h.strip() # If the host start with a !, it's to be removed from # the hostgroup get list if h.startswith('!'): hst_to_remove = h[1:].strip() try: hnames_list.remove(hst_to_remove) # was not in it except ValueError: pass # Else it's an host to add, but maybe it's ALL elif h == '*': for newhost in set(h.host_name for h in hosts.items.values() \ if getattr(h, 'host_name', '') != '' and not h.is_tpl()): hnames_list.append(newhost) #print "DBG in item.explode_host_groups_into_hosts , added '%s' to group '%s'" % (newhost, i) else: hnames_list.append(h) i.host_name = ','.join(list(set(hnames_list))) # Ok, even with all of it, there is still no host, put it as a template if i.host_name == '': i.register = '0' # Take our trigger strings and create true objects with it def explode_trigger_string_into_triggers(self, triggers): for i in self: i.explode_trigger_string_into_triggers(triggers)
wbsavage/shinken
shinken/objects/item.py
Python
agpl-3.0
45,311
# Authors * Andy: <info@andreasseiler.com>
raceface2nd/owngantt
AUTHORS.md
Markdown
agpl-3.0
45
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * 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 (at your option) 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/>. */ package org.kuali.kfs.gl.businessobject; import org.kuali.kfs.sys.KFSKeyConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.core.api.config.property.ConfigurationService; import java.text.MessageFormat; /** * Holds summary information for the Ledger report */ public class LedgerBalanceTypeSummaryTotalLine extends LedgerSummaryTotalLine { private String financialBalanceTypeCode; /** * Constructs a LedgerBalanceTypeSummaryTotalLine * * @param balanceType the balance type summarized by this total line summarizer */ public LedgerBalanceTypeSummaryTotalLine(String balanceType) { this.financialBalanceTypeCode = balanceType; } /** * Gets the balanceType attribute. * * @return Returns the balanceType. */ public String getFinancialBalanceTypeCode() { return financialBalanceTypeCode; } /** * @return the summary for this balance type summary total line */ public String getSummary() { final String message = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(KFSKeyConstants.MESSAGE_REPORT_NIGHTLY_OUT_LEDGER_BALANCE_TYPE_TOTAL); return MessageFormat.format(message, financialBalanceTypeCode); } }
quikkian-ua-devops/will-financials
kfs-core/src/main/java/org/kuali/kfs/gl/businessobject/LedgerBalanceTypeSummaryTotalLine.java
Java
agpl-3.0
2,094
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Db * @subpackage Adapter * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Exception.php 23772 2011-02-28 21:35:29Z ralph $ */ /** * Zend_Db_Adapter_Exception */ require_once 'Zend/Db/Adapter/Exception.php'; /** * Zend_Db_Adapter_Db2_Exception * * @package Zend_Db * @subpackage Adapter * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Db_Adapter_Db2_Exception extends Zend_Db_Adapter_Exception { protected $code = '00000'; protected $message = 'unknown exception'; function __construct($message = 'unknown exception', $code = '00000', Exception $e = null) { parent::__construct($message, $code, $e); } }
WhiteLabelReady/WhiteLabelTransfer
library/Zend/Db/Adapter/Db2/Exception.php
PHP
agpl-3.0
1,455
/** * Node JS intro * * This step covers: * - bootstrap CSS * - rendering a form */ var express = require('express'); // create server var server = express(); server.get('/', function(req, res) { res.render(__dirname + '/views/form.jade'); }); // start server.listen(3000);
hiddentao/nodejs-intro
step12/index.js
JavaScript
agpl-3.0
293
package horizon.geotagger.view; import horizon.geotagger.model.Tag; import java.util.List; import android.graphics.drawable.Drawable; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.OverlayItem; public class TagOverlay extends ItemizedOverlay<OverlayItem> { private final List<Tag> tags; public TagOverlay(Drawable defaultMarker, List<Tag> tags) { super(boundCenterBottom(defaultMarker)); this.tags = tags; populate(); } @Override protected OverlayItem createItem(int i) { Tag tag = tags.get(i); return new OverlayItem(new GeoPoint( (int)(tag.getPlace().getLatitude() * 1E6), (int)(tag.getPlace().getLongitude() * 1E6)), "Tag", "Tag"); } @Override public int size() { return tags.size(); } }
madiarsa/GeoTagger
android-client/src/horizon/geotagger/view/TagOverlay.java
Java
agpl-3.0
810
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ import itertools from datetime import timedelta import ddt from django.core.exceptions import ValidationError from django.test import TestCase, override_settings from django.utils.timezone import now from mock import patch from opaque_keys.edx.locator import CourseLocator from course_modes.helpers import enrollment_mode_display from course_modes.models import CourseMode, Mode, invalidate_course_mode_cache, get_cosmetic_display_price from course_modes.tests.factories import CourseModeFactory from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ( ModuleStoreTestCase, ) @ddt.ddt class CourseModeModelTest(TestCase): """ Tests for the CourseMode model """ NOW = 'now' DATES = { NOW: now(), None: None, } def setUp(self): super(CourseModeModelTest, self).setUp() self.course_key = CourseLocator('Test', 'TestCourse', 'TestCourseRun') CourseMode.objects.all().delete() def tearDown(self): invalidate_course_mode_cache(sender=None) def create_mode( self, mode_slug, mode_name, min_price=0, suggested_prices='', currency='usd', expiration_datetime=None, ): """ Create a new course mode """ return CourseMode.objects.get_or_create( course_id=self.course_key, mode_display_name=mode_name, mode_slug=mode_slug, min_price=min_price, suggested_prices=suggested_prices, currency=currency, _expiration_datetime=expiration_datetime, ) def test_save(self): """ Verify currency is always lowercase. """ cm, __ = self.create_mode('honor', 'honor', 0, '', 'USD') self.assertEqual(cm.currency, 'usd') cm.currency = 'GHS' cm.save() self.assertEqual(cm.currency, 'ghs') def test_modes_for_course_empty(self): """ If we can't find any modes, we should get back the default mode """ # shouldn't be able to find a corresponding course modes = CourseMode.modes_for_course(self.course_key) self.assertEqual([CourseMode.get_default_course_mode()], modes) def test_nodes_for_course_single(self): """ Find the modes for a course with only one mode """ self.create_mode('verified', 'Verified Certificate', 10) modes = CourseMode.modes_for_course(self.course_key) mode = Mode(u'verified', u'Verified Certificate', 10, '', 'usd', None, None, None, None) self.assertEqual([mode], modes) modes_dict = CourseMode.modes_for_course_dict(self.course_key) self.assertEqual(modes_dict['verified'], mode) self.assertEqual(CourseMode.mode_for_course(self.course_key, 'verified'), mode) def test_modes_for_course_multiple(self): """ Finding the modes when there's multiple modes """ mode1 = Mode(u'honor', u'Honor Code Certificate', 0, '', 'usd', None, None, None, None) mode2 = Mode(u'verified', u'Verified Certificate', 10, '', 'usd', None, None, None, None) set_modes = [mode1, mode2] for mode in set_modes: self.create_mode(mode.slug, mode.name, mode.min_price, mode.suggested_prices) modes = CourseMode.modes_for_course(self.course_key) self.assertEqual(modes, set_modes) self.assertEqual(mode1, CourseMode.mode_for_course(self.course_key, u'honor')) self.assertEqual(mode2, CourseMode.mode_for_course(self.course_key, u'verified')) self.assertIsNone(CourseMode.mode_for_course(self.course_key, 'DNE')) def test_min_course_price_for_currency(self): """ Get the min course price for a course according to currency """ # no modes, should get 0 self.assertEqual(0, CourseMode.min_course_price_for_currency(self.course_key, 'usd')) # create some modes mode1 = Mode(u'honor', u'Honor Code Certificate', 10, '', 'usd', None, None, None, None) mode2 = Mode(u'verified', u'Verified Certificate', 20, '', 'usd', None, None, None, None) mode3 = Mode(u'honor', u'Honor Code Certificate', 80, '', 'cny', None, None, None, None) set_modes = [mode1, mode2, mode3] for mode in set_modes: self.create_mode(mode.slug, mode.name, mode.min_price, mode.suggested_prices, mode.currency) self.assertEqual(10, CourseMode.min_course_price_for_currency(self.course_key, 'usd')) self.assertEqual(80, CourseMode.min_course_price_for_currency(self.course_key, 'cny')) def test_modes_for_course_expired(self): expired_mode, _status = self.create_mode('verified', 'Verified Certificate', 10) expired_mode.expiration_datetime = now() + timedelta(days=-1) expired_mode.save() modes = CourseMode.modes_for_course(self.course_key) self.assertEqual([CourseMode.DEFAULT_MODE], modes) mode1 = Mode(u'honor', u'Honor Code Certificate', 0, '', 'usd', None, None, None, None) self.create_mode(mode1.slug, mode1.name, mode1.min_price, mode1.suggested_prices) modes = CourseMode.modes_for_course(self.course_key) self.assertEqual([mode1], modes) expiration_datetime = now() + timedelta(days=1) expired_mode.expiration_datetime = expiration_datetime expired_mode.save() expired_mode_value = Mode( u'verified', u'Verified Certificate', 10, '', 'usd', expiration_datetime, None, None, None ) modes = CourseMode.modes_for_course(self.course_key) self.assertEqual([expired_mode_value, mode1], modes) modes = CourseMode.modes_for_course(CourseLocator('TestOrg', 'TestCourse', 'TestRun')) self.assertEqual([CourseMode.DEFAULT_MODE], modes) def test_verified_mode_for_course(self): self.create_mode('verified', 'Verified Certificate', 10) mode = CourseMode.verified_mode_for_course(self.course_key) self.assertEqual(mode.slug, 'verified') # verify that the professional mode is preferred self.create_mode('professional', 'Professional Education Verified Certificate', 10) mode = CourseMode.verified_mode_for_course(self.course_key) self.assertEqual(mode.slug, 'professional') def test_course_has_payment_options(self): # Has no payment options. honor, _ = self.create_mode('honor', 'Honor') self.assertFalse(CourseMode.has_payment_options(self.course_key)) # Now we do have a payment option. verified, _ = self.create_mode('verified', 'Verified', min_price=5) self.assertTrue(CourseMode.has_payment_options(self.course_key)) # Remove the verified option. verified.delete() self.assertFalse(CourseMode.has_payment_options(self.course_key)) # Finally, give the honor mode payment options honor.suggested_prices = '5, 10, 15' honor.save() self.assertTrue(CourseMode.has_payment_options(self.course_key)) def test_course_has_payment_options_with_no_id_professional(self): # Has payment options. self.create_mode('no-id-professional', 'no-id-professional', min_price=5) self.assertTrue(CourseMode.has_payment_options(self.course_key)) @ddt.data( ([], True), ([("honor", 0), ("audit", 0), ("verified", 100)], True), ([("honor", 100)], False), ([("professional", 100)], False), ([("no-id-professional", 100)], False), ) @ddt.unpack def test_can_auto_enroll(self, modes_and_prices, can_auto_enroll): # Create the modes and min prices for mode_slug, min_price in modes_and_prices: self.create_mode(mode_slug, mode_slug.capitalize(), min_price=min_price) # Verify that we can or cannot auto enroll self.assertEqual(CourseMode.can_auto_enroll(self.course_key), can_auto_enroll) @ddt.data( ([], None), (["honor", "audit", "verified"], "honor"), (["honor", "audit"], "honor"), (["audit", "verified"], "audit"), (["professional"], None), (["no-id-professional"], None), (["credit", "audit", "verified"], "audit"), (["credit"], None), ) @ddt.unpack def test_auto_enroll_mode(self, modes, result): # Verify that the proper auto enroll mode is returned self.assertEqual(CourseMode.auto_enroll_mode(self.course_key, modes), result) def test_all_modes_for_courses(self): now_dt = now() future = now_dt + timedelta(days=1) past = now_dt - timedelta(days=1) # Unexpired, no expiration date CourseModeFactory.create( course_id=self.course_key, mode_display_name="Honor No Expiration", mode_slug="honor_no_expiration", expiration_datetime=None ) # Unexpired, expiration date in future CourseModeFactory.create( course_id=self.course_key, mode_display_name="Honor Not Expired", mode_slug="honor_not_expired", expiration_datetime=future ) # Expired CourseModeFactory.create( course_id=self.course_key, mode_display_name="Verified Expired", mode_slug="verified_expired", expiration_datetime=past ) # We should get all of these back when querying for *all* course modes, # including ones that have expired. other_course_key = CourseLocator(org="not", course="a", run="course") all_modes = CourseMode.all_modes_for_courses([self.course_key, other_course_key]) self.assertEqual(len(all_modes[self.course_key]), 3) self.assertEqual(all_modes[self.course_key][0].name, "Honor No Expiration") self.assertEqual(all_modes[self.course_key][1].name, "Honor Not Expired") self.assertEqual(all_modes[self.course_key][2].name, "Verified Expired") # Check that we get a default mode for when no course mode is available self.assertEqual(len(all_modes[other_course_key]), 1) self.assertEqual(all_modes[other_course_key][0], CourseMode.get_default_course_mode()) @ddt.data('', 'no-id-professional', 'professional', 'verified') def test_course_has_professional_mode(self, mode): # check the professional mode. self.create_mode(mode, 'course mode', 10) modes_dict = CourseMode.modes_for_course_dict(self.course_key) if mode in ['professional', 'no-id-professional']: self.assertTrue(CourseMode.has_professional_mode(modes_dict)) else: self.assertFalse(CourseMode.has_professional_mode(modes_dict)) @ddt.data('no-id-professional', 'professional', 'verified') def test_course_is_professional_mode(self, mode): # check that tuple has professional mode course_mode, __ = self.create_mode(mode, 'course mode', 10) if mode in ['professional', 'no-id-professional']: self.assertTrue(CourseMode.is_professional_mode(course_mode.to_tuple())) else: self.assertFalse(CourseMode.is_professional_mode(course_mode.to_tuple())) def test_course_is_professional_mode_with_invalid_tuple(self): # check that tuple has professional mode with None self.assertFalse(CourseMode.is_professional_mode(None)) @ddt.data( ('no-id-professional', False), ('professional', True), ('verified', True), ('honor', False), ('audit', False) ) @ddt.unpack def test_is_verified_slug(self, mode_slug, is_verified): # check that mode slug is verified or not if is_verified: self.assertTrue(CourseMode.is_verified_slug(mode_slug)) else: self.assertFalse(CourseMode.is_verified_slug(mode_slug)) @ddt.data(*itertools.product( ( CourseMode.HONOR, CourseMode.AUDIT, CourseMode.VERIFIED, CourseMode.PROFESSIONAL, CourseMode.NO_ID_PROFESSIONAL_MODE ), (NOW, None), )) @ddt.unpack def test_invalid_mode_expiration(self, mode_slug, exp_dt_name): exp_dt = self.DATES[exp_dt_name] is_error_expected = CourseMode.is_professional_slug(mode_slug) and exp_dt is not None try: self.create_mode(mode_slug=mode_slug, mode_name=mode_slug.title(), expiration_datetime=exp_dt, min_price=10) self.assertFalse(is_error_expected, "Expected a ValidationError to be thrown.") except ValidationError as exc: self.assertTrue(is_error_expected, "Did not expect a ValidationError to be thrown.") self.assertEqual( exc.messages, [u"Professional education modes are not allowed to have expiration_datetime set."], ) @ddt.data( ("verified", "verify_need_to_verify"), ("verified", "verify_submitted"), ("verified", "verify_approved"), ("verified", 'dummy'), ("verified", None), ('honor', None), ('honor', 'dummy'), ('audit', None), ('professional', None), ('no-id-professional', None), ('no-id-professional', 'dummy') ) @ddt.unpack def test_enrollment_mode_display(self, mode, verification_status): if mode == "verified": self.assertEqual( enrollment_mode_display(mode, verification_status, self.course_key), self._enrollment_display_modes_dicts(verification_status) ) self.assertEqual( enrollment_mode_display(mode, verification_status, self.course_key), self._enrollment_display_modes_dicts(verification_status) ) self.assertEqual( enrollment_mode_display(mode, verification_status, self.course_key), self._enrollment_display_modes_dicts(verification_status) ) elif mode == "honor": self.assertEqual( enrollment_mode_display(mode, verification_status, self.course_key), self._enrollment_display_modes_dicts(mode) ) elif mode == "audit": self.assertEqual( enrollment_mode_display(mode, verification_status, self.course_key), self._enrollment_display_modes_dicts(mode) ) elif mode == "professional": self.assertEqual( enrollment_mode_display(mode, verification_status, self.course_key), self._enrollment_display_modes_dicts(mode) ) @ddt.data( (['honor', 'verified', 'credit'], ['honor', 'verified']), (['professional', 'credit'], ['professional']), ) @ddt.unpack def test_hide_credit_modes(self, available_modes, expected_selectable_modes): # Create the course modes for mode in available_modes: CourseModeFactory.create( course_id=self.course_key, mode_display_name=mode, mode_slug=mode, ) # Check the selectable modes, which should exclude credit selectable_modes = CourseMode.modes_for_course_dict(self.course_key) self.assertItemsEqual(selectable_modes.keys(), expected_selectable_modes) # When we get all unexpired modes, we should see credit as well all_modes = CourseMode.modes_for_course_dict(self.course_key, only_selectable=False) self.assertItemsEqual(all_modes.keys(), available_modes) def _enrollment_display_modes_dicts(self, dict_type): """ Helper function to generate the enrollment display mode dict. """ dict_keys = ['enrollment_title', 'enrollment_value', 'show_image', 'image_alt', 'display_mode'] display_values = { "verify_need_to_verify": ["Your verification is pending", "Verified: Pending Verification", True, 'ID verification pending', 'verified'], "verify_approved": ["You're enrolled as a verified student", "Verified", True, 'ID Verified Ribbon/Badge', 'verified'], "verify_none": ["", "", False, '', 'audit'], "honor": ["You're enrolled as an honor code student", "Honor Code", False, '', 'honor'], "audit": ["", "", False, '', 'audit'], "professional": ["You're enrolled as a professional education student", "Professional Ed", False, '', 'professional'] } if dict_type in ['verify_need_to_verify', 'verify_submitted']: return dict(zip(dict_keys, display_values.get('verify_need_to_verify'))) elif dict_type is None or dict_type == 'dummy': return dict(zip(dict_keys, display_values.get('verify_none'))) else: return dict(zip(dict_keys, display_values.get(dict_type))) def test_expiration_datetime_explicitly_set(self): """ Verify that setting the expiration_date property sets the explicit flag. """ verified_mode, __ = self.create_mode('verified', 'Verified Certificate', 10) now_dt = now() verified_mode.expiration_datetime = now_dt self.assertTrue(verified_mode.expiration_datetime_is_explicit) self.assertEqual(verified_mode.expiration_datetime, now_dt) def test_expiration_datetime_not_explicitly_set(self): """ Verify that setting the _expiration_date property does not set the explicit flag. """ verified_mode, __ = self.create_mode('verified', 'Verified Certificate', 10) now_dt = now() verified_mode._expiration_datetime = now_dt # pylint: disable=protected-access self.assertFalse(verified_mode.expiration_datetime_is_explicit) self.assertEqual(verified_mode.expiration_datetime, now_dt) def test_expiration_datetime_explicitly_set_to_none(self): """ Verify that setting the _expiration_date property does not set the explicit flag. """ verified_mode, __ = self.create_mode('verified', 'Verified Certificate', 10) self.assertFalse(verified_mode.expiration_datetime_is_explicit) verified_mode.expiration_datetime = None self.assertFalse(verified_mode.expiration_datetime_is_explicit) self.assertIsNone(verified_mode.expiration_datetime) @ddt.data( (CourseMode.AUDIT, False), (CourseMode.HONOR, False), (CourseMode.VERIFIED, True), (CourseMode.CREDIT_MODE, True), (CourseMode.PROFESSIONAL, True), (CourseMode.NO_ID_PROFESSIONAL_MODE, True), ) @ddt.unpack def test_eligible_for_cert(self, mode_slug, expected_eligibility): """Verify that non-audit modes are eligible for a cert.""" self.assertEqual(CourseMode.is_eligible_for_certificate(mode_slug), expected_eligibility) @ddt.data( (CourseMode.AUDIT, False), (CourseMode.HONOR, False), (CourseMode.VERIFIED, True), (CourseMode.CREDIT_MODE, False), (CourseMode.PROFESSIONAL, True), (CourseMode.NO_ID_PROFESSIONAL_MODE, False), ) @ddt.unpack def test_verified_min_price(self, mode_slug, is_error_expected): """Verify that verified modes have a price.""" try: self.create_mode(mode_slug=mode_slug, mode_name=mode_slug.title(), min_price=0) except ValidationError: self.assertTrue(is_error_expected, "Did not expect a ValidationError to be thrown.") else: self.assertFalse(is_error_expected, "Expected a ValidationError to be thrown.") class TestDisplayPrices(ModuleStoreTestCase): @override_settings(PAID_COURSE_REGISTRATION_CURRENCY=["USD", "$"]) def test_get_cosmetic_display_price(self): """ Check that get_cosmetic_display_price() returns the correct price given its inputs. """ course = CourseFactory.create() registration_price = 99 course.cosmetic_display_price = 10 with patch('course_modes.models.CourseMode.min_course_price_for_currency', return_value=registration_price): # Since registration_price is set, it overrides the cosmetic_display_price and should be returned self.assertEqual(get_cosmetic_display_price(course), "$99") registration_price = 0 with patch('course_modes.models.CourseMode.min_course_price_for_currency', return_value=registration_price): # Since registration_price is not set, cosmetic_display_price should be returned self.assertEqual(get_cosmetic_display_price(course), "$10") course.cosmetic_display_price = 0 # Since both prices are not set, there is no price, thus "Free" self.assertEqual(get_cosmetic_display_price(course), "Free")
proversity-org/edx-platform
common/djangoapps/course_modes/tests/test_models.py
Python
agpl-3.0
21,323