Private: This was put in place entirely to appease Ruby 1.9.2-p290's more
 strict YAML parsing, which breaks Crack 0.1.8's JSON decoding.

 This will be removed when Crack supports decoding the API's returned
 values.
514065
def decode_json(body)
      if body.to_s =~ /^(?:[\d]+|null|true|false)$/
        MultiJson.decode("[#{body}]").first
      else
        MultiJson.decode body
      end
    end
181522
def solc_parse_output(compiler_output):
    
    # At the moment some solc output like --hashes or -- gas will not output
    # json at all so if used with those arguments the logic here will break.
    # Perhaps solidity will slowly switch to a json only output and this comment
    # can eventually go away and we will not need to add more logic here at
    # all.
    result = yaml.safe_load(compiler_output)['contracts']

    if 'bin' in tuple(result.values())[0]:
        for value in result.values():
            value['bin_hex'] = value['bin']

            # decoding can fail if the compiled contract has unresolved symbols
            try:
                value['bin'] = decode_hex(value['bin_hex'])
            except (TypeError, ValueError):
                pass

    for json_data in ('abi', 'devdoc', 'userdoc'):
        # the values in the output can be configured through the
        # --combined-json flag, check that it's present in the first value and
        # assume all values are consistent
        if json_data not in tuple(result.values())[0]:
            continue

        for value in result.values():
            value[json_data] = yaml.safe_load(value[json_data])

    return result
909900
def output(data = {}, indent = 0)
      case @options['format']
      when 'json'
        puts JSON.pretty_generate(data)
      when 'yaml'
        puts data.to_yaml
      else
        # rubocop:disable Metrics/BlockNesting
        if data.class == Hash
          data.each do |k, v|
            if v.class == Hash || v.class == Array
              puts "#{' ' * indent}#{k.nil? ? 'nil' : k}:"
              output(v, indent + 2)
            else
              puts "#{' ' * indent}#{k.nil? ? 'nil' : k}: #{v.nil? ? 'nil' : v}"
            end
          end
        elsif data.class == Array
          data.each do |d|
            if d.class == Hash || d.class == Array
              output(d, indent + 2)
            else
              puts "#{' ' * indent}#{d.nil? ? 'nil' : d}"
            end
          end
          puts "\nTotal: #{data.size}" if indent < 1
        else
          puts "#{' ' * indent}#{data.nil? ? 'nil' : data}"
        end
        # rubocop:enable Metrics/BlockNesting
      end
    end
311496
def as_json(_options = {})
      hash = {}
      instance_variables.each do |var|
        name = var[1..-1]

        if name =~ /^__/
          # if a variable starts with double underscore, strip one off
          name = name[1..-1]
        elsif name =~ /^_/
          # Hide variables that start with single underscore
          name = nil
        end

        hash[name] = instance_variable_get(var) if name
      end
      hash
    end
817147
def deconstruct_version_string(version)
      match = version.match(/^(\d+)\.(\d+)(?:\.(\d+))?$/)

      # Match should have 4 parts [0] = input string, [1] = major
      # [2] = minor, [3] = patch (possibly blank)
      if match && match.size == 4
        return [match[1].to_i, match[2].to_i, match[3].to_i || 0]
      else
        return nil
      end
    end
198980
def hash_extractor(name, value)
      value.split(',').reduce({}) do |set, tag|
        k, v = tag.split(':')
        if v.nil?
          log_warn("Invalid hash value for #{name}: #{value}")
          return nil
        end

        set.merge(decode(k).downcase.to_sym => decode(v))
      end
    end
567518
def revive_hash hash, o
      o.children.each_slice(2) { |k,v|
        key = accept(k)
        val = accept(v)

        if key == SHOVEL && k.tag != "tag:yaml.org,2002:str"
          case v
          when Nodes::Alias, Nodes::Mapping
            begin
              hash.merge! val
            rescue TypeError
              hash[key] = val
            end
          when Nodes::Sequence
            begin
              h = {}
              val.reverse_each do |value|
                h.merge! value
              end
              hash.merge! h
            rescue TypeError
              hash[key] = val
            end
          else
            hash[key] = val
          end
        else
          # This is where we handle the translated key
          if v.is_a?(Psych::Nodes::Scalar) && !WcaI18n::PLURALIZATION_KEYS.include?(key)
            # For scalar value, the start line registered is the correct line
            # We assume that the '#original_hash: ' comment comes on the line before.
            original_hash = @original_hashes_by_line.delete(v.start_line - 1)
            val = WcaI18n::TranslatedLeaf.new(val, original_hash)
          end
          if pluralization_map?(v)
            # For mappings, the start line registered is the line of the first key/value!
            original_hash = @original_hashes_by_line.delete(v.start_line - 2)
            val = WcaI18n::TranslatedLeaf.new(val, original_hash)
          end
          hash[key] = val
        end
      }
      hash
    end
397662
def json mtd, path, _form = []
      form = Hash[_form]
      response = JSON.load resp_with_token mtd, path, form.merge({api_type: "json"})
      if response.is_a?(Hash) && response["json"] && # for example, flairlist.json and {"error": 403} do not have it
         !response["json"]["errors"].empty?
        Module.nesting[1].logger.error "ERROR OCCURED on #{[mtd, path]}"
        fail "unknown how to handle multiple errors" if 1 < response["json"]["errors"].size
        Module.nesting[1].logger.error "error: #{response["json"]["errors"]}"
        error, description = response["json"]["errors"].first
          case error
          when "ALREADY_SUB" ; Module.nesting[1].logger.warn "was rejected by moderator if you didn't see in dups"
          # when "BAD_CAPTCHA" ; update_captcha
          #   json mtd, path, form.merger( {
          #     iden: @iden_and_captcha[0],
          #     captcha: @iden_and_captcha[1],
          #   } ) unless @ignore_captcha
          when "RATELIMIT"
            fail error unless description[/\Ayou are doing that too much\. try again in (\d) minutes\.\z/]
            Module.nesting[1].logger.info "retrying in #{$1.to_i + 1} minutes"
            sleep ($1.to_i + 1) * 60
            return json mtd, path, _form
          else ; fail error
          end
      end
      response
    end
1051279
def parse(schema)
      # Really we'd like to only have data hashes passed into drivers these
      # days, but here we handle a JsonSchema::Schema for now to maintain
      # backward compatibility (this library used to be hyper-schema only).
      if schema.is_a?(JsonSchema::Schema)
        hyper_schema = schema
      else
        hyper_schema = JsonSchema.parse!(schema)
        hyper_schema.expand_references!
      end

      schema = Schema.new
      schema.driver = self
      schema.routes = build_routes(hyper_schema)
      schema
    end
575880
def hash_for_railsbp(error)
        {
          'linter' => error['message'].gsub(/\((.*)\)/, '').strip.parameterize('_').camelize,
          'severity' => 'warning',
          'reason' => error['message'],
          'column' => 0,
          'line' => error['line_number'].to_i
        }
      end
1114481
def parse(self, stream, media_type=None, parser_context=None):
        
        assert yaml, 'YAMLParser requires pyyaml to be installed'

        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)

        try:
            data = stream.read().decode(encoding)
            return yaml.safe_load(data)
        except (ValueError, yaml.parser.ParserError) as exc:
            raise ParseError('YAML parse error - %s' % six.text_type(exc))
9621
def binary_encode_any_high_ascii_in_hash(hash)
      Hash[hash.map { |key, value| [key, binary_encode_any_high_ascii(value)] }]
    end
514802
def from_yaml_file(f):
    
    return from_json(to_json(yaml.load(f, Loader=yaml.Loader)))
1089750
def load_from_source!
    @chunks ||=
      begin
        ## we need to re-read the header because it contains information
        ## that we don't store in the index. actually i think it's just
        ## the mailing list address (if any), so this is kinda overkill.
        ## i could just store that in the index, but i think there might
        ## be other things like that in the future, and i'd rather not
        ## bloat the index.
        ## actually, it's also the differentiation between to/cc/bcc,
        ## so i will keep this.
        rmsg = location.parsed_message
        parse_header rmsg.header
        message_to_chunks rmsg
      rescue SourceError, SocketError, RMail::EncodingUnsupportedError => e
        warn_with_location "problem reading message #{id}"
        debug "could not load message: #{location.inspect}, exception: #{e.inspect}"

        [Chunk::Text.new(error_message.split("\n"))]

      rescue Exception => e

        warn_with_location "problem reading message #{id}"
        debug "could not load message: #{location.inspect}, exception: #{e.inspect}"

        raise e

      end
  end
1166627
def create_hash(response)
      begin
        JSON.parse response
      rescue JSON::ParserError
        response
      rescue StandardError
        response
      end
    end
621655
def as_json(options={})
      options = @options.merge(options)

      if options[:root]
        { options[:root].to_sym => serializable_hash }.merge(meta_hash).merge(data_hash)
      else
        serializable_hash
      end
    end
52058
def parse_sasl_params(sasl_params)
      # Symbilize keys in a hash
      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