idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
1,600
def handle_mapping_template ( mapping ) if mapping if mapping [ :valueset_path ] && @entry . at_xpath ( mapping [ :valueset_path ] ) @code_list_xpath = mapping [ :valueset_path ] end @value = DataCriteriaMethods . parse_value ( @entry , mapping [ :result_path ] ) if mapping [ :result_path ] end end
Set the value and code_list_xpath using the template mapping held in the ValueSetHelper class
1,601
def handle_derived_specific_occurrences return unless @definition == 'derived' @source_data_criteria = @source_data_criteria . gsub ( "_source" , '' ) if @source_data_criteria @children_criteria << @source_data_criteria if @children_criteria . empty? return if @children_criteria . length != 1 || ( @source_data_criteria . present? && @children_criteria . first != @source_data_criteria ) reference_criteria = @data_criteria_references [ @children_criteria . first ] return if reference_criteria . nil? @is_derived_specific_occurrence_variable = true @subset_operators ||= reference_criteria . subset_operators @derivation_operator ||= reference_criteria . derivation_operator @description = reference_criteria . description @variable = reference_criteria . variable end
Apply some elements from the reference_criteria to the derived specific occurrence
1,602
def create_group_data_criteria ( preconditions , type , value , parent_id , id , standard_category , qds_data_type ) extract_group_data_criteria_tree ( HQMF :: DataCriteria :: UNION , preconditions , type , parent_id ) end
grouping data criteria are used to allow a single reference off of a temporal reference or subset operator grouping data criteria can reference either regular data criteria as children or other grouping data criteria
1,603
def extract_group_data_criteria_tree ( conjunction , preconditions , type , parent_id ) children = [ ] preconditions . each do | precondition | if ( precondition . comparison? ) if ( precondition . reference . id == HQMF :: Document :: MEASURE_PERIOD_ID ) children << measure_period_criteria else children << v2_data_criteria_by_id [ precondition . reference . id ] end else converted_conjunction = convert_grouping_conjunction ( precondition . conjunction_code ) children << extract_group_data_criteria_tree ( converted_conjunction , precondition . preconditions , type , parent_id ) end end if ( children . size > 1 ) build_group_data_criteria ( children , type , parent_id , conjunction ) else children . first end end
pull the children data criteria out of a set of preconditions
1,604
def create_measure_period_v1_data_criteria ( doc , measure_period , v1_data_criteria_by_id ) attributes = doc [ :attributes ] attributes . keys . each { | key | attributes [ key . to_s ] = attributes [ key ] } measure_period_key = attributes [ 'MEASUREMENT_PERIOD' ] [ :id ] measure_start_key = attributes [ 'MEASUREMENT_START_DATE' ] [ :id ] measure_end_key = attributes [ 'MEASUREMENT_END_DATE' ] [ :id ] @measure_period_v1_keys = { measure_start : measure_start_key , measure_end : measure_end_key , measure_period : measure_period_key } type = 'variable' code_list_id , negation_code_list_id , property , status , field_values , effective_time , inline_code_list , children_criteria , derivation_operator , temporal_references , subset_operators = nil measure_period_id = HQMF :: Document :: MEASURE_PERIOD_ID value = measure_period measure_criteria = HQMF :: DataCriteria . new ( measure_period_id , measure_period_id , nil , measure_period_id , code_list_id , children_criteria , derivation_operator , measure_period_id , status , value , field_values , effective_time , inline_code_list , false , nil , temporal_references , subset_operators , nil , nil ) v1_data_criteria_by_id [ measure_period_key ] = measure_criteria v1_data_criteria_by_id [ measure_start_key ] = measure_criteria v1_data_criteria_by_id [ measure_end_key ] = measure_criteria @measure_period_criteria = measure_criteria end
this method creates V1 data criteria for the measurement period . These data criteria can be referenced properly within the restrictions
1,605
def extract_child_criteria @entry . xpath ( "./*/cda:outboundRelationship[@typeCode='COMP']/cda:criteriaReference/cda:id" , HQMF2 :: Document :: NAMESPACES ) . collect do | ref | Reference . new ( ref ) . id end . compact end
Generate a list of child criterias
1,606
def all_subset_operators @entry . xpath ( './*/cda:excerpt' , HQMF2 :: Document :: NAMESPACES ) . collect do | subset_operator | SubsetOperator . new ( subset_operator ) end end
Extracts all subset operators contained in the entry xml
1,607
def check_nil_conjunction_on_child if ( @preconditions . length == 1 && @preconditions . first . conjunction . nil? ) bad_precondition = @preconditions . first if ( bad_precondition . restrictions . empty? && bad_precondition . subset . nil? && bad_precondition . expression . nil? ) @preconditions = @preconditions . first . preconditions else puts "\t PRECONDITION WITHOUT CONJUNCTION: Cannot be fixed" end end end
Preconditions can have nil conjunctions as part of a DATEDIFF we want to remove these and warn
1,608
def specific_occurrence_source_data_criteria ( force_sources = nil ) return [ ] if @source_data_criteria . nil? matching = @source_data_criteria . select { | dc | ! dc . specific_occurrence . nil? } if force_sources existing = matching . map ( & :id ) matching . concat @source_data_criteria . select { | dc | ! existing . include? ( dc . id ) && force_sources . include? ( dc . id ) } end matching end
Get the source data criteria that are specific occurrences
1,609
def attributes_for_code ( code , code_system ) @attributes . find_all { | e | e . send ( :code ) == code && e . send ( :code_obj ) . send ( :system ) == code_system } end
Get specific attributes by code .
1,610
def backfill_patient_characteristics_with_codes ( codes ) [ ] . concat ( self . all_data_criteria ) . concat ( self . source_data_criteria ) . each do | data_criteria | if ( data_criteria . type == :characteristic and ! data_criteria . property . nil? ) if ( codes ) value_set = codes [ data_criteria . code_list_id ] puts "\tno value set for unknown patient characteristic: #{data_criteria.id}" unless value_set else puts "\tno code set to back fill: #{data_criteria.title}" next end if ( data_criteria . property == :gender ) next if value_set . nil? key = value_set . keys [ 0 ] data_criteria . value = HQMF :: Coded . new ( 'CD' , 'Administrative Sex' , value_set [ key ] . first ) else data_criteria . inline_code_list = value_set end elsif ( data_criteria . type == :characteristic ) if ( codes ) value_set = codes [ data_criteria . code_list_id ] if ( value_set ) if ( value_set [ 'LOINC' ] and value_set [ 'LOINC' ] . first == '21112-8' ) data_criteria . definition = 'patient_characteristic_birthdate' end gender_key = ( value_set . keys . select { | set | set == 'Administrative Sex' || set == 'AdministrativeSex' } ) . first if ( gender_key and [ 'M' , 'F' ] . include? value_set [ gender_key ] . first ) data_criteria . definition = 'patient_characteristic_gender' data_criteria . value = HQMF :: Coded . new ( 'CD' , 'Gender' , value_set [ gender_key ] . first ) end end end end end end
patient characteristics data criteria such as GENDER require looking at the codes to determine if the measure is interested in Males or Females . This process is awkward and thus is done as a separate step after the document has been converted .
1,611
def handle_known_template_id ( template_id ) case template_id when VARIABLE_TEMPLATE @derivation_operator = HQMF :: DataCriteria :: INTERSECT if @derivation_operator == HQMF :: DataCriteria :: XPRODUCT @definition ||= 'derived' @variable = true @negation = false when SATISFIES_ANY_TEMPLATE @definition = HQMF :: DataCriteria :: SATISFIES_ANY @negation = false when SATISFIES_ALL_TEMPLATE @definition = HQMF :: DataCriteria :: SATISFIES_ALL @derivation_operator = HQMF :: DataCriteria :: INTERSECT @negation = false else return false end true end
Given a template id modify the variables inside this data criteria to reflect the template
1,612
def extract_information_for_specific_variable reference = @entry . at_xpath ( './*/cda:outboundRelationship/cda:criteriaReference' , HQMF2 :: Document :: NAMESPACES ) if reference ref_id = strip_tokens ( "#{HQMF2::Utilities.attr_val(reference, 'cda:id/@extension')}_#{HQMF2::Utilities.attr_val(reference, 'cda:id/@root')}" ) end reference_criteria = @data_criteria_references [ ref_id ] if ref_id if reference_criteria && reference_criteria . definition == 'derived' reference_criteria = @data_criteria_references [ "GROUP_#{ref_id}" ] end return unless reference_criteria handle_specific_variable_ref ( reference_criteria ) end
Extracts information from a reference for a specific
1,613
def handle_specific_variable_ref ( reference_criteria ) if reference_criteria . children_criteria . empty? @children_criteria = [ reference_criteria . id ] else @field_values = reference_criteria . field_values @temporal_references = reference_criteria . temporal_references @subset_operators = reference_criteria . subset_operators @derivation_operator = reference_criteria . derivation_operator @definition = reference_criteria . definition @description = reference_criteria . description @status = reference_criteria . status @children_criteria = reference_criteria . children_criteria end end
Apply additional information to a specific occurrence s elements from the criteria it references .
1,614
def definition_for_nil_entry reference = @entry . at_xpath ( './*/cda:outboundRelationship/cda:criteriaReference' , HQMF2 :: Document :: NAMESPACES ) ref_id = nil unless reference . nil? ref_id = "#{HQMF2::Utilities.attr_val(reference, 'cda:id/@extension')}_#{HQMF2::Utilities.attr_val(reference, 'cda:id/@root')}" end reference_criteria = @data_criteria_references [ strip_tokens ( ref_id ) ] unless ref_id . nil? if reference_criteria if @children_criteria . blank? @definition = reference_criteria . definition @status = reference_criteria . status if @specific_occurrence @title = reference_criteria . title @description = reference_criteria . description @code_list_id = reference_criteria . code_list_id end else @definition = 'derived' if @specific_occurrence @title = reference_criteria . title @description = reference_criteria . description end end else puts "MISSING_DC_REF: #{ref_id}" unless @variable @definition = 'variable' end end
If there is no entry type extract the entry type from what it references and extract additional information for specific occurrences . If there are no outbound references print an error and mark it as variable .
1,615
def handle_variable ( data_criteria , collapsed_source_data_criteria ) if data_criteria . is_derived_specific_occurrence_variable data_criteria . handle_derived_specific_occurrence_variable extract_source_data_criteria ( data_criteria ) return end tmp_id = data_criteria . id grouper_data_criteria = data_criteria . extract_variable_grouper return unless grouper_data_criteria @data_criteria_references [ data_criteria . id ] = data_criteria @data_criteria_references [ grouper_data_criteria . id ] = grouper_data_criteria sdc = SourceDataCriteriaHelper . strip_non_sc_elements ( grouper_data_criteria ) @source_data_criteria << sdc if collapsed_source_data_criteria [ tmp_id ] data_criteria . instance_variable_set ( :@source_data_criteria , collapsed_source_data_criteria [ tmp_id ] ) else data_criteria_sdc = find ( @source_data_criteria , :id , "#{tmp_id}_source" ) if data_criteria_sdc data_criteria . instance_variable_set ( :@source_data_criteria , data_criteria_sdc . id ) data_criteria_sdc . instance_variable_set ( :@variable , false ) elsif ! [ 'derived' , 'satisfies_any' , 'satisfies_all' ] . include? ( data_criteria . definition ) extract_source_data_criteria ( data_criteria ) end end @data_criteria << grouper_data_criteria end
Create grouper data criteria for encapsulating variable data criteria and update document data criteria list and references map
1,616
def complex_coverage ( data_criteria , check_criteria ) same_value = data_criteria . value . nil? || data_criteria . value . try ( :to_model ) . try ( :to_json ) == check_criteria . value . try ( :to_model ) . try ( :to_json ) same_field_values = same_field_values_check ( data_criteria , check_criteria ) same_negation_values = data_criteria . negation_code_list_id . nil? || data_criteria . negation_code_list_id == check_criteria . negation_code_list_id same_value && same_negation_values && same_field_values end
Check elements that do not already exist ; else if they do check if those elements are the same in a different potentially matching data criteria
1,617
def handle_specific_and_source ( occurrence_identifier , source_data_criteria_extension , source_data_criteria_root , specific_occurrence_const , specific_occurrence ) source_data_criteria = "#{source_data_criteria_extension}_#{source_data_criteria_root}_source" if ! occurrence_identifier . blank? @occurrences_map [ strip_tokens ( source_data_criteria ) ] ||= occurrence_identifier specific_occurrence ||= occurrence_identifier specific_occurrence_const = "#{source_data_criteria}" . upcase else if @is_variable @occurrences_map [ strip_tokens ( source_data_criteria ) ] ||= occurrence_identifier end occurrence = @occurrences_map . try ( :[] , strip_tokens ( source_data_criteria ) ) unless occurrence fail "Could not find occurrence mapping for #{source_data_criteria}, #{source_data_criteria_root}" end specific_occurrence ||= occurrence end specific_occurrence = 'A' unless specific_occurrence specific_occurrence_const = source_data_criteria . upcase unless specific_occurrence_const [ source_data_criteria , source_data_criteria_root , source_data_criteria_extension , specific_occurrence , specific_occurrence_const ] end
Handle setting the specific and source instance variables with a given occurrence identifier
1,618
def basic_setup @status = attr_val ( './*/cda:statusCode/@code' ) @id_xpath = './*/cda:id/@extension' @id = "#{attr_val('./*/cda:id/@extension')}_#{attr_val('./*/cda:id/@root')}" @comments = @entry . xpath ( "./#{CRITERIA_GLOB}/cda:text/cda:xml/cda:qdmUserComments/cda:item/text()" , HQMF2 :: Document :: NAMESPACES ) . map ( & :content ) @code_list_xpath = './*/cda:code' @value_xpath = './*/cda:value' @is_derived_specific_occurrence_variable = false simple_extractions = DataCriteriaBaseExtractions . new ( @entry ) @template_ids = simple_extractions . extract_template_ids @local_variable_name = simple_extractions . extract_local_variable_name @temporal_references = simple_extractions . extract_temporal_references @derivation_operator = simple_extractions . extract_derivation_operator @children_criteria = simple_extractions . extract_child_criteria @subset_operators = simple_extractions . extract_subset_operators @negation , @negation_code_list_id = simple_extractions . extract_negation end
Handles elments that can be extracted directly from the xml . Utilises the BaseExtractions class .
1,619
def duplicate_child_info ( child_ref ) @title ||= child_ref . title @type ||= child_ref . subset_operators @definition ||= child_ref . definition @status ||= child_ref . status @code_list_id ||= child_ref . code_list_id @temporal_references = child_ref . temporal_references if @temporal_references . empty? @subset_operators ||= child_ref . subset_operators @variable ||= child_ref . variable @value ||= child_ref . value end
Duplicates information from a child element to this data criteria if none exits . If the duplication requires that come values should be overwritten do so only in the function calling this .
1,620
def retrieve_field_values_model_for_model field_values = { } @field_values . each_pair do | id , val | field_values [ id ] = val . to_model end @code_list_id ||= code_list_id if %w( transfer_to transfer_from ) . include? @definition field_code_list_id = @code_list_id @code_list_id = nil unless field_code_list_id field_code_list_id = attr_val ( "./#{CRITERIA_GLOB}/cda:outboundRelationship/#{CRITERIA_GLOB}/cda:value/@valueSet" ) end field_values [ @definition . upcase ] = HQMF :: Coded . for_code_list ( field_code_list_id , title ) end return field_values unless field_values . empty? end
Generate the models of the field values
1,621
def retrieve_title_and_description_for_model exact_desc = title . split ( ' ' ) [ 0 ... - 3 ] . join ( ' ' ) exact_desc = title if @definition . start_with? ( 'patient_characteristic' ) && ! title . end_with? ( 'Value Set' ) title_match = title . match ( / \w / ) @title = title_match [ 1 ] if title_match && title_match . length > 1 @description = "#{@description}: #{exact_desc}" end
Generate the title and description used when producing the model
1,622
def save_local ensure_read_only! self . path ||= Doggy . object_root . join ( "#{prefix}-#{id}.json" ) File . open ( @path , 'w' ) { | f | f . write ( JSON . pretty_generate ( to_h ) ) } end
class << self
1,623
def url sch = @options [ :ssl ] ? "https" : "http" hosts = Array ( @options [ :host ] ) @url ||= if hosts . first . include? ( ":" ) URI ( "#{sch}://[#{hosts.first}]:#{port}" ) . to_s else URI ( "#{sch}://#{hosts.first}:#{port}" ) . to_s end end
The URL for this Chef Zero server . If the given host is an IPV6 address it is escaped in brackets according to RFC - 2732 .
1,624
def listen ( hosts , port ) hosts . each do | host | @server . listen ( host , port ) end true rescue Errno :: EADDRINUSE ChefZero :: Log . warn ( "Port #{port} not available" ) @server . listeners . each { | l | l . close } @server . listeners . clear false end
Start a Chef Zero server in a forked process . This method returns the PID to the forked process .
1,625
def stop ( wait = 5 ) if @running @server . shutdown if @server @thread . join ( wait ) if @thread end rescue Timeout :: Error if @thread ChefZero :: Log . error ( "Chef Zero did not stop within #{wait} seconds! Killing..." ) @thread . kill SocketlessServerMap . deregister ( port ) end ensure @server = nil @thread = nil end
Gracefully stop the Chef Zero server .
1,626
def json_response ( response_code , data , options = { } ) options = { pretty : true } . merge ( options ) do_pretty_json = ! ! options . delete ( :pretty ) json = FFI_Yajl :: Encoder . encode ( data , pretty : do_pretty_json ) already_json_response ( response_code , json , options ) end
Serializes data to JSON and returns an Array with the response code HTTP headers and JSON body .
1,627
def already_json_response ( response_code , json_text , options = { } ) version_header = FFI_Yajl :: Encoder . encode ( "min_version" => MIN_API_VERSION . to_s , "max_version" => MAX_API_VERSION . to_s , "request_version" => options [ :request_version ] || DEFAULT_REQUEST_VERSION . to_s , "response_version" => options [ :response_version ] || DEFAULT_RESPONSE_VERSION . to_s ) headers = { "Content-Type" => "application/json" , "X-Ops-Server-API-Version" => version_header , } headers . merge! ( options [ :headers ] ) if options [ :headers ] [ response_code , headers , json_text ] end
Returns an Array with the response code HTTP headers and JSON body .
1,628
def build_uri ( base_uri , rest_path ) if server . options [ :single_org ] if rest_path [ 0 .. 1 ] != [ "organizations" , server . options [ :single_org ] ] raise "Unexpected URL #{rest_path[0..1]} passed to build_uri in single org mode" end return self . class . build_uri ( base_uri , rest_path [ 2 .. - 1 ] ) end self . class . build_uri ( base_uri , rest_path ) end
To be called from inside rest endpoints
1,629
def parse_sasl_params ( sasl_params ) if sasl_params . kind_of? ( Hash ) return sasl_params . inject ( { } ) do | memo , ( k , v ) | memo [ k . to_sym ] = v ; memo end end return nil end
Processes SASL connection params and returns a hash with symbol keys or a nil
1,630
def async_state ( handles ) response = @client . GetOperationStatus ( Hive2 :: Thrift :: TGetOperationStatusReq . new ( operationHandle : prepare_operation_handle ( handles ) ) ) case response . operationState when Hive2 :: Thrift :: TOperationState :: FINISHED_STATE return :finished when Hive2 :: Thrift :: TOperationState :: INITIALIZED_STATE return :initialized when Hive2 :: Thrift :: TOperationState :: RUNNING_STATE return :running when Hive2 :: Thrift :: TOperationState :: CANCELED_STATE return :cancelled when Hive2 :: Thrift :: TOperationState :: CLOSED_STATE return :closed when Hive2 :: Thrift :: TOperationState :: ERROR_STATE return :error when Hive2 :: Thrift :: TOperationState :: UKNOWN_STATE return :unknown when Hive2 :: Thrift :: TOperationState :: PENDING_STATE return :pending when nil raise "No operation state found for handles - has the session been closed?" else return :state_not_in_protocol end end
Map states to symbols
1,631
def async_fetch ( handles , max_rows = 100 ) unless async_is_complete? ( handles ) raise "Can't perform fetch on a query in state: #{async_state(handles)}" end fetch_rows ( prepare_operation_handle ( handles ) , :first , max_rows ) end
Async fetch results from an async execute
1,632
def fetch_rows ( op_handle , orientation = :first , max_rows = 1000 ) fetch_req = prepare_fetch_results ( op_handle , orientation , max_rows ) fetch_results = @client . FetchResults ( fetch_req ) raise_error_if_failed! ( fetch_results ) rows = fetch_results . results . rows TCLIResultSet . new ( rows , TCLISchemaDefinition . new ( get_schema_for ( op_handle ) , rows . first ) ) end
Pull rows from the query result
1,633
def raise_error_if_failed! ( result ) return if result . status . statusCode == 0 error_message = result . status . errorMessage || 'Execution failed!' raise RBHive :: TCLIConnectionError . new ( error_message ) end
Raises an exception if given operation result is a failure
1,634
def parse_options ( args ) config = { } deprecated_args = [ ] flag = / / args . size . times do break if args . empty? peek = args . first next unless peek && ( peek . match ( flag ) || peek . match ( / / ) ) arg = args . shift peek = args . first key = arg if key . match ( / / ) deprecated_args << key unless key . match ( flag ) key , value = key . split ( '=' , 2 ) elsif peek . nil? || peek . match ( flag ) value = true else value = args . shift end value = true if value == 'true' config [ key . sub ( flag , '' ) ] = value if ! deprecated_args . empty? out_string = deprecated_args . map { | a | "--#{a}" } . join ( ' ' ) display ( "Warning: non-unix style params have been deprecated, use #{out_string} instead" ) end end config end
this will clean up when we officially deprecate
1,635
def line_formatter ( array ) if array . any? { | item | item . is_a? ( Array ) } cols = [ ] array . each do | item | if item . is_a? ( Array ) item . each_with_index { | val , idx | cols [ idx ] = [ cols [ idx ] || 0 , ( val || '' ) . length ] . max } end end cols . map { | col | "%-#{col}s" } . join ( " " ) else "%s" end end
produces a printf formatter line for an array of items if an individual line item is an array it will create columns that are lined - up
1,636
def data = ( values = [ ] ) @tag_name = values . first . is_a? ( Cell ) ? :strCache : :strLit values . each do | value | v = value . is_a? ( Cell ) ? value . value : value @pt << @type . new ( :v => v ) end end
creates a new StrVal object
1,637
def relationships r = Relationships . new r << Relationship . new ( cache_definition , PIVOT_TABLE_CACHE_DEFINITION_R , "../#{cache_definition.pn}" ) r end
The relationships for this pivot table .
1,638
def color = ( v ) @color = v if v . is_a? Color self . color . rgb = v if v . is_a? String @color end
Sets the color for the data bars .
1,639
def to_xml_string ( str = "" ) serialized_tag ( 'dataBar' , str ) do value_objects . to_xml_string ( str ) self . color . to_xml_string ( str ) end end
Serialize this object to an xml string
1,640
def serialize ( output , confirm_valid = false ) return false unless ! confirm_valid || self . validate . empty? Relationship . clear_cached_instances Zip :: OutputStream . open ( output ) do | zip | write_parts ( zip ) end true end
Serialize your workbook to disk as an xlsx document .
1,641
def to_stream ( confirm_valid = false ) return false unless ! confirm_valid || self . validate . empty? Relationship . clear_cached_instances zip = write_parts ( Zip :: OutputStream . new ( StringIO . new , true ) ) stream = zip . close_buffer stream . rewind stream end
Serialize your workbook to a StringIO instance
1,642
def write_parts ( zip ) p = parts p . each do | part | unless part [ :doc ] . nil? zip . put_next_entry ( zip_entry_for_part ( part ) ) part [ :doc ] . to_xml_string ( zip ) end unless part [ :path ] . nil? zip . put_next_entry ( zip_entry_for_part ( part ) ) zip . write IO . read ( part [ :path ] ) end end zip end
Writes the package parts to a zip archive .
1,643
def parts parts = [ { :entry => RELS_PN , :doc => relationships , :schema => RELS_XSD } , { :entry => "xl/#{STYLES_PN}" , :doc => workbook . styles , :schema => SML_XSD } , { :entry => CORE_PN , :doc => @core , :schema => CORE_XSD } , { :entry => APP_PN , :doc => @app , :schema => APP_XSD } , { :entry => WORKBOOK_RELS_PN , :doc => workbook . relationships , :schema => RELS_XSD } , { :entry => CONTENT_TYPES_PN , :doc => content_types , :schema => CONTENT_TYPES_XSD } , { :entry => WORKBOOK_PN , :doc => workbook , :schema => SML_XSD } ] workbook . drawings . each do | drawing | parts << { :entry => "xl/#{drawing.rels_pn}" , :doc => drawing . relationships , :schema => RELS_XSD } parts << { :entry => "xl/#{drawing.pn}" , :doc => drawing , :schema => DRAWING_XSD } end workbook . tables . each do | table | parts << { :entry => "xl/#{table.pn}" , :doc => table , :schema => SML_XSD } end workbook . pivot_tables . each do | pivot_table | cache_definition = pivot_table . cache_definition parts << { :entry => "xl/#{pivot_table.rels_pn}" , :doc => pivot_table . relationships , :schema => RELS_XSD } parts << { :entry => "xl/#{pivot_table.pn}" , :doc => pivot_table } parts << { :entry => "xl/#{cache_definition.pn}" , :doc => cache_definition } end workbook . comments . each do | comment | if comment . size > 0 parts << { :entry => "xl/#{comment.pn}" , :doc => comment , :schema => SML_XSD } parts << { :entry => "xl/#{comment.vml_drawing.pn}" , :doc => comment . vml_drawing , :schema => nil } end end workbook . charts . each do | chart | parts << { :entry => "xl/#{chart.pn}" , :doc => chart , :schema => DRAWING_XSD } end workbook . images . each do | image | parts << { :entry => "xl/#{image.pn}" , :path => image . image_src } end if use_shared_strings parts << { :entry => "xl/#{SHARED_STRINGS_PN}" , :doc => workbook . shared_strings , :schema => SML_XSD } end workbook . worksheets . each do | sheet | parts << { :entry => "xl/#{sheet.rels_pn}" , :doc => sheet . relationships , :schema => RELS_XSD } parts << { :entry => "xl/#{sheet.pn}" , :doc => sheet , :schema => SML_XSD } end parts . sort_by { | part | part [ :entry ] } end
The parts of a package
1,644
def validate_single_doc ( schema , doc ) schema = Nokogiri :: XML :: Schema ( File . open ( schema ) ) doc = Nokogiri :: XML ( doc ) errors = [ ] schema . validate ( doc ) . each do | error | errors << error end errors end
Performs xsd validation for a signle document
1,645
def content_types c_types = base_content_types workbook . drawings . each do | drawing | c_types << Axlsx :: Override . new ( :PartName => "/xl/#{drawing.pn}" , :ContentType => DRAWING_CT ) end workbook . charts . each do | chart | c_types << Axlsx :: Override . new ( :PartName => "/xl/#{chart.pn}" , :ContentType => CHART_CT ) end workbook . tables . each do | table | c_types << Axlsx :: Override . new ( :PartName => "/xl/#{table.pn}" , :ContentType => TABLE_CT ) end workbook . pivot_tables . each do | pivot_table | c_types << Axlsx :: Override . new ( :PartName => "/xl/#{pivot_table.pn}" , :ContentType => PIVOT_TABLE_CT ) c_types << Axlsx :: Override . new ( :PartName => "/xl/#{pivot_table.cache_definition.pn}" , :ContentType => PIVOT_TABLE_CACHE_DEFINITION_CT ) end workbook . comments . each do | comment | if comment . size > 0 c_types << Axlsx :: Override . new ( :PartName => "/xl/#{comment.pn}" , :ContentType => COMMENT_CT ) end end if workbook . comments . size > 0 c_types << Axlsx :: Default . new ( :Extension => "vml" , :ContentType => VML_DRAWING_CT ) end workbook . worksheets . each do | sheet | c_types << Axlsx :: Override . new ( :PartName => "/xl/#{sheet.pn}" , :ContentType => WORKSHEET_CT ) end exts = workbook . images . map { | image | image . extname . downcase } exts . uniq . each do | ext | ct = if [ 'jpeg' , 'jpg' ] . include? ( ext ) JPEG_CT elsif ext == 'gif' GIF_CT elsif ext == 'png' PNG_CT end c_types << Axlsx :: Default . new ( :ContentType => ct , :Extension => ext ) end if use_shared_strings c_types << Axlsx :: Override . new ( :PartName => "/xl/#{SHARED_STRINGS_PN}" , :ContentType => SHARED_STRINGS_CT ) end c_types end
Appends override objects for drawings charts and sheets as they exist in your workbook to the default content types .
1,646
def base_content_types c_types = ContentType . new ( ) c_types << Default . new ( :ContentType => RELS_CT , :Extension => RELS_EX ) c_types << Default . new ( :Extension => XML_EX , :ContentType => XML_CT ) c_types << Override . new ( :PartName => "/#{APP_PN}" , :ContentType => APP_CT ) c_types << Override . new ( :PartName => "/#{CORE_PN}" , :ContentType => CORE_CT ) c_types << Override . new ( :PartName => "/xl/#{STYLES_PN}" , :ContentType => STYLES_CT ) c_types << Axlsx :: Override . new ( :PartName => "/#{WORKBOOK_PN}" , :ContentType => WORKBOOK_CT ) c_types . lock c_types end
Creates the minimum content types for generating a valid xlsx document .
1,647
def relationships rels = Axlsx :: Relationships . new rels << Relationship . new ( self , WORKBOOK_R , WORKBOOK_PN ) rels << Relationship . new ( self , CORE_R , CORE_PN ) rels << Relationship . new ( self , APP_R , APP_PN ) rels . lock rels end
Creates the relationships required for a valid xlsx document
1,648
def hyperlink = ( v , options = { } ) options [ :href ] = v if hyperlink . is_a? ( Hyperlink ) options . each do | o | hyperlink . send ( "#{o[0]}=" , o [ 1 ] ) if hyperlink . respond_to? "#{o[0]}=" end else @hyperlink = Hyperlink . new ( self , options ) end hyperlink end
sets or updates a hyperlink for this image .
1,649
def end_at ( x , y = nil ) use_two_cell_anchor unless @anchor . is_a? ( TwoCellAnchor ) @anchor . end_at x , y @anchor . to end
noop if not using a two cell anchor
1,650
def use_one_cell_anchor return if @anchor . is_a? ( OneCellAnchor ) new_anchor = OneCellAnchor . new ( @anchor . drawing , :start_at => [ @anchor . from . col , @anchor . from . row ] ) swap_anchor ( new_anchor ) end
Changes the anchor to a one cell anchor .
1,651
def use_two_cell_anchor return if @anchor . is_a? ( TwoCellAnchor ) new_anchor = TwoCellAnchor . new ( @anchor . drawing , :start_at => [ @anchor . from . col , @anchor . from . row ] ) swap_anchor ( new_anchor ) end
changes the anchor type to a two cell anchor
1,652
def swap_anchor ( new_anchor ) new_anchor . drawing . anchors . delete ( new_anchor ) @anchor . drawing . anchors [ @anchor . drawing . anchors . index ( @anchor ) ] = new_anchor new_anchor . instance_variable_set "@object" , @anchor . object @anchor = new_anchor end
refactoring of swapping code law of demeter be damned!
1,653
def add ( options = { } ) value_objects << Cfvo . new ( :type => options [ :type ] || :min , :val => options [ :val ] || 0 ) colors << Color . new ( :rgb => options [ :color ] || "FF000000" ) { :cfvo => value_objects . last , :color => colors . last } end
creates a new ColorScale object .
1,654
def to_xml_string ( str = '' ) str << '<colorScale>' value_objects . to_xml_string ( str ) colors . each { | color | color . to_xml_string ( str ) } str << '</colorScale>' end
Serialize this color_scale object data to an xml string
1,655
def initialize_default_cfvos ( user_cfvos ) defaults = self . class . default_cfvos user_cfvos . each_with_index do | cfvo , index | if index < defaults . size cfvo = defaults [ index ] . merge ( cfvo ) end add cfvo end while colors . size < defaults . size add defaults [ colors . size - 1 ] end end
There has got to be cleaner way of merging these arrays .
1,656
def add_axis ( name , axis_class ) axis = axis_class . new set_cross_axis ( axis ) axes << [ name , axis ] end
Adds an axis to the collection
1,657
def to_xml_string ( str = '' ) Axlsx :: sanitize ( @shared_xml_string ) str << ( '<?xml version="1.0" encoding="UTF-8"?><sst xmlns="' << XML_NS << '"' ) str << ( ' count="' << @count . to_s << '" uniqueCount="' << unique_count . to_s << '"' ) str << ( ' xml:space="' << xml_space . to_s << '">' << @shared_xml_string << '</sst>' ) end
Creates a new Shared Strings Table agains an array of cells
1,658
def resolve ( cells ) cells . each do | cell | cell_hash = cell . value if index = @unique_cells [ cell_hash ] cell . send :ssti= , index else cell . send :ssti= , @index @shared_xml_string << '<si>' << CellSerializer . run_xml_string ( cell ) << '</si>' @unique_cells [ cell_hash ] = @index @index += 1 end end end
Interate over all of the cells in the array . if our unique cells array does not contain a sharable cell add the cell to our unique cells array and set the ssti attribute on the index of this cell in the shared strings table if a sharable cell already exists in our unique_cells array set the ssti attribute of the cell and move on .
1,659
def to_xml_string ( str = '' ) return if empty? str << '<hyperlinks>' each { | hyperlink | hyperlink . to_xml_string ( str ) } str << '</hyperlinks>' end
seralize the collection of hyperlinks
1,660
def sheet_by_name ( name ) index = @worksheets . index { | sheet | sheet . name == name } @worksheets [ index ] if index end
A quick helper to retrive a worksheet by name
1,661
def insert_worksheet ( index = 0 , options = { } ) worksheet = Worksheet . new ( self , options ) @worksheets . delete_at ( @worksheets . size - 1 ) @worksheets . insert ( index , worksheet ) yield worksheet if block_given? worksheet end
inserts a worksheet into this workbook at the position specified . It the index specified is out of range the worksheet will be added to the end of the worksheets collection
1,662
def relationships r = Relationships . new @worksheets . each do | sheet | r << Relationship . new ( sheet , WORKSHEET_R , WORKSHEET_PN % ( r . size + 1 ) ) end pivot_tables . each_with_index do | pivot_table , index | r << Relationship . new ( pivot_table . cache_definition , PIVOT_TABLE_CACHE_DEFINITION_R , PIVOT_TABLE_CACHE_DEFINITION_PN % ( index + 1 ) ) end r << Relationship . new ( self , STYLES_R , STYLES_PN ) if use_shared_strings r << Relationship . new ( self , SHARED_STRINGS_R , SHARED_STRINGS_PN ) end r end
The workbook relationships . This is managed automatically by the workbook
1,663
def [] ( cell_def ) sheet_name = cell_def . split ( '!' ) [ 0 ] if cell_def . match ( '!' ) worksheet = self . worksheets . select { | s | s . name == sheet_name } . first raise ArgumentError , 'Unknown Sheet' unless sheet_name && worksheet . is_a? ( Worksheet ) worksheet [ cell_def . gsub ( / / , "" ) ] end
returns a range of cells in a worksheet
1,664
def to_xml_string ( str = '' ) add_worksheet ( name : 'Sheet1' ) unless worksheets . size > 0 str << '<?xml version="1.0" encoding="UTF-8"?>' str << ( '<workbook xmlns="' << XML_NS << '" xmlns:r="' << XML_NS_R << '">' ) str << ( '<workbookPr date1904="' << @@date1904 . to_s << '"/>' ) views . to_xml_string ( str ) str << '<sheets>' if is_reversed worksheets . reverse_each { | sheet | sheet . to_sheet_node_xml_string ( str ) } else worksheets . each { | sheet | sheet . to_sheet_node_xml_string ( str ) } end str << '</sheets>' defined_names . to_xml_string ( str ) unless pivot_tables . empty? str << '<pivotCaches>' pivot_tables . each do | pivot_table | str << ( '<pivotCache cacheId="' << pivot_table . cache_definition . cache_id . to_s << '" r:id="' << pivot_table . cache_definition . rId << '"/>' ) end str << '</pivotCaches>' end str << '</workbook>' end
Serialize the workbook
1,665
def set ( margins ) margins . select do | k , v | next unless [ :left , :right , :top , :bottom , :header , :footer ] . include? k send ( "#{k}=" , v ) end end
Set some or all margins at once .
1,666
def coord ( col , row = 0 ) coordinates = parse_coord_args ( col , row ) self . col = coordinates [ 0 ] self . row = coordinates [ 1 ] end
shortcut to set the column row position for this marker
1,667
def parse_coord_args ( x , y = 0 ) if x . is_a? ( String ) x , y = * Axlsx :: name_to_indices ( x ) end if x . is_a? ( Cell ) x , y = * x . pos end if x . is_a? ( Array ) x , y = * x end [ x , y ] end
handles multiple inputs for setting the position of a marker
1,668
def add_comment ( options = { } ) raise ArgumentError , "Comment require an author" unless options [ :author ] raise ArgumentError , "Comment requires text" unless options [ :text ] raise ArgumentError , "Comment requires ref" unless options [ :ref ] self << Comment . new ( self , options ) yield last if block_given? last end
Creates a new Comments object
1,669
def autowidth ( widtharray ) return if value . nil? if styles . cellXfs [ style ] . alignment && styles . cellXfs [ style ] . alignment . wrap_text first = true value . to_s . split ( / \r \n / , - 1 ) . each do | line | if first first = false else widtharray << 0 end widtharray [ - 1 ] += string_width ( line , font_size ) end else widtharray [ - 1 ] += string_width ( value . to_s , font_size ) end widtharray end
Tries to work out the width of the longest line in the run
1,670
def to_xml_string ( str = '' ) valid = RichTextRun :: INLINE_STYLES data = Hash [ self . instance_values . map { | k , v | [ k . to_sym , v ] } ] data = data . select { | key , value | valid . include? ( key ) && ! value . nil? } str << '<r><rPr>' data . keys . each do | key | case key when :font_name str << ( '<rFont val="' << font_name << '"/>' ) when :color str << data [ key ] . to_xml_string else str << ( '<' << key . to_s << ' val="' << xml_value ( data [ key ] ) << '"/>' ) end end clean_value = Axlsx :: trust_input ? @value . to_s : :: CGI . escapeHTML ( Axlsx :: sanitize ( @value . to_s ) ) str << ( '</rPr><t>' << clean_value << '</t></r>' ) end
Serializes the RichTextRun
1,671
def string_width ( string , font_size ) font_scale = font_size / 10.0 string . count ( Worksheet :: THIN_CHARS ) * font_scale end
Returns the width of a string according to the current style This is still not perfect ... - scaling is not linear as font sizes increase
1,672
def font_size return sz if sz font = styles . fonts [ styles . cellXfs [ style ] . fontId ] || styles . fonts [ 0 ] ( font . b || ( defined? ( @b ) && @b ) ) ? ( font . sz * 1.5 ) : font . sz end
we scale the font size if bold style is applied to either the style font or the cell itself . Yes it is a bit of a hack but it is much better than using imagemagick and loading metrics for every character .
1,673
def validate_format_percentage ( name , value ) DataTypeValidator . validate name , Float , value , lambda { | arg | arg >= 0.0 && arg <= 1.0 } end
validates that the value provided is between 0 . 0 and 1 . 0
1,674
def to_xml_string ( node_name = '' , str = '' ) str << "<#{node_name} " str << instance_values . map { | key , value | Axlsx :: camel ( key ) << '="' << value . to_s << '"' } . join ( ' ' ) str << '/>' end
Serialize the contenty type to xml
1,675
def to_xml_string ( str = "" ) return if empty? str << "<dataValidations count='#{size}'>" each { | item | item . to_xml_string ( str ) } str << '</dataValidations>' end
serialize the conditional formattings
1,676
def initialize_value_objects @value_objects = SimpleTypedList . new Cfvo @value_objects . concat [ Cfvo . new ( :type => :percent , :val => 0 ) , Cfvo . new ( :type => :percent , :val => 33 ) , Cfvo . new ( :type => :percent , :val => 67 ) ] @value_objects . lock end
Initalize the simple typed list of value objects I am keeping this private for now as I am not sure what impact changes to the required two cfvo objects will do .
1,677
def to_s data = [ @name . concat ( Array . new ( 32 - @name . size , 0 ) ) , @name_size , @type , @color , @left , @right , @child , @created , @modified , @sector , @size ] . flatten data . pack ( PACKING ) end
Creates a byte string for this storage
1,678
def col_id = ( column_index ) column_index = column_index . col if column_index . is_a? ( Cell ) Axlsx . validate_unsigned_int column_index @col_id = column_index end
Sets the col_id attribute for this filter column .
1,679
def apply ( row , offset ) row . hidden = @filter . apply ( row . cells [ offset + col_id . to_i ] ) end
Apply the filters for this column
1,680
def to_xml_string ( str = '' ) str << '<sheetData>' worksheet . rows . each_with_index do | row , index | row . to_xml_string ( index , str ) end str << '</sheetData>' end
Serialize the sheet data
1,681
def to_xml_string ( str = '' ) return if empty? str << '<definedNames>' each { | defined_name | defined_name . to_xml_string ( str ) } str << '</definedNames>' end
creates the DefinedNames object Serialize to xml
1,682
def add_rule ( rule ) if rule . is_a? Axlsx :: ConditionalFormattingRule @rules << rule elsif rule . is_a? Hash @rules << ConditionalFormattingRule . new ( rule ) end end
Add a ConditionalFormattingRule . If a hash of options is passed in create a rule on the fly .
1,683
def to_xml_string ( str = '' ) str << ( '<conditionalFormatting sqref="' << sqref << '">' ) str << rules . collect { | rule | rule . to_xml_string } . join ( ' ' ) str << '</conditionalFormatting>' end
Serializes the conditional formatting element
1,684
def label_rotation = ( v ) Axlsx :: validate_int ( v ) adjusted = v . to_i * 60000 Axlsx :: validate_angle ( adjusted ) @label_rotation = adjusted end
Specify the degree of label rotation to apply to labels default true
1,685
def title = ( v ) DataTypeValidator . validate "#{self.class}.title" , [ String , Cell ] , v @title ||= Title . new if v . is_a? ( String ) @title . text = v elsif v . is_a? ( Cell ) @title . cell = v end end
The title object for the chart .
1,686
def initialize_page_options ( options ) @page_margins = PageMargins . new options [ :page_margins ] if options [ :page_margins ] @page_setup = PageSetup . new options [ :page_setup ] if options [ :page_setup ] @print_options = PrintOptions . new options [ :print_options ] if options [ :print_options ] @header_footer = HeaderFooter . new options [ :header_footer ] if options [ :header_footer ] @row_breaks = RowBreaks . new @col_breaks = ColBreaks . new end
Initalizes page margin setup and print options
1,687
def add_conditional_formatting ( cells , rules ) cf = ConditionalFormatting . new ( :sqref => cells ) cf . add_rules rules conditional_formattings << cf conditional_formattings end
Add conditional formatting to this worksheet .
1,688
def add_data_validation ( cells , data_validation ) dv = DataValidation . new ( data_validation ) dv . sqref = cells data_validations << dv end
Add data validation to this worksheet .
1,689
def add_chart ( chart_type , options = { } ) chart = worksheet_drawing . add_chart ( chart_type , options ) yield chart if block_given? chart end
Adds a chart to this worksheets drawing . This is the recommended way to create charts for your worksheet . This method wraps the complexity of dealing with ooxml drawing anchors markers graphic frames chart objects and all the other dirty details .
1,690
def column_widths ( * widths ) widths . each_with_index do | value , index | next if value == nil Axlsx :: validate_unsigned_numeric ( value ) unless value == nil find_or_create_column_info ( index ) . width = value end end
This is a helper method that Lets you specify a fixed width for multiple columns in a worksheet in one go . Note that you must call column_widths AFTER adding data otherwise the width will not be set successfully . Setting a fixed column width to nil will revert the behaviour back to calculating the width for you on the next call to add_row .
1,691
def col_style ( index , style , options = { } ) offset = options . delete ( :row_offset ) || 0 cells = @rows [ ( offset .. - 1 ) ] . map { | row | row [ index ] } . flatten . compact cells . each { | cell | cell . style = style } end
Set the style for cells in a specific column
1,692
def row_style ( index , style , options = { } ) offset = options . delete ( :col_offset ) || 0 cells = cols [ ( offset .. - 1 ) ] . map { | column | column [ index ] } . flatten . compact cells . each { | cell | cell . style = style } end
Set the style for cells in a specific row
1,693
def to_sheet_node_xml_string ( str = '' ) add_autofilter_defined_name_to_workbook str << '<sheet ' serialized_attributes str str << ( 'name="' << name << '" ' ) str << ( 'r:id="' << rId << '"></sheet>' ) end
Returns a sheet node serialization for this sheet in the workbook .
1,694
def to_xml_string str = '' add_autofilter_defined_name_to_workbook auto_filter . apply if auto_filter . range str << '<?xml version="1.0" encoding="UTF-8"?>' str << worksheet_node serializable_parts . each do | item | item . to_xml_string ( str ) if item end str << '</worksheet>' end
Serializes the worksheet object to an xml string This intentionally does not use nokogiri for performance reasons
1,695
def relationships r = Relationships . new r + [ tables . relationships , worksheet_comments . relationships , hyperlinks . relationships , worksheet_drawing . relationship , pivot_tables . relationships ] . flatten . compact || [ ] r end
The worksheet relationships . This is managed automatically by the worksheet
1,696
def name_to_cell ( name ) col_index , row_index = * Axlsx :: name_to_indices ( name ) r = rows [ row_index ] r [ col_index ] if r end
returns the column and row index for a named based cell
1,697
def outline_level_rows ( start_index , end_index , level = 1 , collapsed = true ) outline rows , ( start_index .. end_index ) , level , collapsed end
shortcut level to specify the outline level for a series of rows Oulining is what lets you add collapse and expand to a data set .
1,698
def outline_level_columns ( start_index , end_index , level = 1 , collapsed = true ) outline column_info , ( start_index .. end_index ) , level , collapsed end
shortcut level to specify the outline level for a series of columns Oulining is what lets you add collapse and expand to a data set .
1,699
def to_xml_string ( r_index , str = '' ) serialized_tag ( 'row' , str , :r => r_index + 1 ) do tmp = '' each_with_index { | cell , c_index | cell . to_xml_string ( r_index , c_index , tmp ) } str << tmp end end
Serializes the row