How to fix incompatible character encodings: UTF-8 and ASCII-8BIT - ruby

The issue is with the 'chap << "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"' line.
chaps = []
ctoc = "toc1\x00"
ctoc << [3, chapters.size].pack("CC")
chapters.each_with_index do |ch, i|
num = i+1
title = ch[:title]
description = ch[:description]
link = ch[:link]
ctoc << "ch#{num}\x00"
chap = "ch#{num}\x00"
chap << [ch[:start]*1000, ch[:end]*1000].pack("NN");
chap << "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
title_tag = [title.encode("utf-16")].pack("a*");
chap << "TIT2"
chap << [title_tag.size+1].pack("N")
chap << "\x00\x00\x01"
chap << title_tag
chaps << chap
end
I have added the following to the top of the file but that didn't fix the issue. Any other ideas to try?
# encoding: utf-8

Related

Create a symlink using ruby

I am trying to create a symlink for the created file but I get an error like File exists - (/etc/nginx/sites-available/sushant.com, /etc/nginx/sites-enabled/sushant.com) (Errno::EEXIST)
Here is my code
require 'fileutils'
open('/etc/hosts') do |f|
matches = []
vhosts = []
f.readlines.each do |lines|
matches << lines if lines =~ /.*.com/
end
matches.each do |val|
val.split.each do |x|
vhosts << x if x =~ /.*.com/
end
end
vhosts.each do |domain|
#put the path to sites-enabled
unless File.file? "/etc/nginx/sites-available/#{domain}"
open("/etc/nginx/sites-available/#{domain}", 'w') do |g|
g << "server { \n"
g << "\tlisten 80 default_server;\n"
g << "\tlisten [::]:80 default_server ipv6only=on;\n"
g << "\troot /usr/share/nginx/html;\n"
g << "\tindex index.html index.htm;\n"
g << "\tserver_name localhost;\n"
g << "\tlocation / {\n"
g << "\t\ttry_files $uri $uri/ =404;\n"
g << "\t}\n"
g << "}\n"
g << "server {\n"
g << "\tpassenger_ruby /path/to/ruby;\n"
g << "\trails_env development;\n"
g << "\tlisten 80;\n"
g << "\tserver_name #{domain};\n"
g << "\troot /usr/share/nginx/html/#{domain}/public;\n"
g << "\tpassenger_enabled on;\n"
g << "}\n"
end
File.symlink "/etc/nginx/sites-available/#{domain}", "/etc/nginx/sites-enabled/#{domain}"
end
end
p vhosts
end
Why is the EEXIST error occurs after I run the script? Am I missing out on something?
I have found out that I should have placed File.symlink "/etc/nginx/sites-available/#{domain}", "/etc/nginx/sites-enabled/#{domain}" first then the action to create the file.

How to get current operating system language?

I am newbie to mfc, and I got struck over how to get the current operating system language (Ex: If it is English operating system I must get it as English and locale can be different. For English OS locale can be Japanese vice versa).
Current locale I am getting it through GetSystemDefaultLangID and the only thing I was left with is I need to get the current operating system language.
Can anyone kindly help me to resolve this issue.
Perhaps you need GetUserDefaultUILanguage. The system's settings and user settings may not be the same.
User Interface Language Management
int wmain()
{
wcout << "GetUserDefaultUILanguage: " << GetUserDefaultUILanguage() << "\n";
wcout << "GetSystemDefaultUILanguage: " << GetSystemDefaultUILanguage() << "\n";
wcout << "\n";
wcout << "GetUserDefaultLangID: " << GetUserDefaultLangID() << "\n";
wcout << "GetSystemDefaultLangID: " << GetSystemDefaultLangID() << "\n";
wcout << "\n";
wcout << "GetUserDefaultLCID: " << GetUserDefaultLCID() << "\n";
wcout << "GetSystemDefaultLCID: " << GetSystemDefaultLCID() << "\n";
wcout << "\n";
wchar_t buf[100];
LCID lcid = GetUserDefaultLCID();
cout << "GetUserDefaultLCID: " << "\n";
if (GetLocaleInfo(lcid, LOCALE_ILANGUAGE, buf, 100)) wcout << buf << "\n";
if (GetLocaleInfo(lcid, LOCALE_SENGLANGUAGE, buf, 100)) wcout << buf << "\n";
if (GetLocaleInfo(lcid, LOCALE_SISO639LANGNAME, buf, 100)) wcout << buf << "\n";
return 0;
}

no implicit conversion of nil into String error

I have a ruby script that will create two files by taking and merging values from another file.
#Resources
require 'rubygems'
require 'csv'
col_date = []
col_constant1 = []
col_constant2 = []
col_appYear = []
col_statsDesc = []
col_keyStats =[]
col_weeklyTotal=[]
weekly_total = []
fname = "finalStats.csv" #variable for capture file
finalStatsFile = File.open(fname, "w") #write to capture file
fname2 = "weeklyStats.csv"
weeklyStatsFile = File.open(fname2, "w")
CSV.foreach('compareData.csv', converters: :numeric) do |row|
weekly_total << row[0] - row[1]
weekly_total.each do |data|
data << weekly_total.shift
weeklyStatsFile.puts data
end
end
#retrieve stats from original document
CSV.foreach("autoCapture.csv") {|row| col_date << row[0]}
CSV.foreach("autoCapture.csv") {|row| col_constant1 << row[1]}
CSV.foreach("autoCapture.csv") {|row| col_appYear << row[2]}
CSV.foreach("autoCapture.csv") {|row| col_statsDesc << row[3]}
CSV.foreach("autoCapture.csv") {|row| col_constant2 << row[4]}
CSV.foreach("autoCapture.csv") {|row| col_keyStats << row[5]}
CSV.foreach("weeklyStats.csv") {|row| col_weeklyTotal << row[0]}
col_date.zip(col_constant1, col_appYear, col_statsDesc, col_constant2, col_keyStats, col_weeklyTotal).each do |col_date, col_constant1, col_appYear, col_statsDesc, col_constant2,
col_keyStats, col_weeklyTotal|
finalStatsFile.puts col_date+", "+col_constant1+", "+ col_appYear+", "+col_statsDesc+", "+col_constant2+", "+col_keyStats+", "+col_weeklyTotal
end
In one file I wish to subtract the values in row[1] from the values in row[0] to create a new 'weekly_total' value. I then output this array of values in a file called weeklyStats.csv. This will output a column of values fine.
However, I want to join these values with another set from another file (autoCapture.csv) and when I try to zip them as arrays so that they read across in corresponding rows I get the error:
weeklyStats_csv.rb:42:in `+': no implicit conversion of nil into String (TypeError)
from weeklyStats_csv.rb:42:in `block in <main>'
from weeklyStats_csv.rb:40:in `each'
from weeklyStats_csv.rb:40:in `<main>'
I gather this means that the array zip will not catch an exception if the one of the values is nil and therefore cannot convert to string. The problem is, I have tried converting weekly_total to string and array as I thought that it may be the problem (a mismatch of types) but I just dont where to go from here. Can anyone help?
One of (or more) values in string
finalStatsFile.puts col_date+", "+col_constant1+", "+ col_appYear+", "+col_statsDesc+", "+col_constant2+", "+col_keyStats+", "+col_weeklyTotal
became nil. To fix the output you should explicitly cast them to strings:
finalStatsFile.puts col_date.to_s + ", " +
col_constant1.to_s + ", " +
col_appYear.to_s + ", " +
col_statsDesc.to_s + ", " +
col_constant2.to_s + ", " +
col_keyStats.to_s + ", " +
col_weeklyTotal.to_s
BTW, the whole clause might be rewritten in more rubyish manner:
finalStatsFile.puts [ col_date,
col_constant1,
col_appYear,
col_statsDesc,
col_constant2,
col_keyStats,
col_weeklyTotal ].map(&:to_s).join(', ')

Create JSON of one dimension Ruby

I want to have this:
["(GKA) GOROKA, GOROKA, PAPUA NEW
GUINEA"]
instead of:
[
[
"(GKA)",
"GOROKA",
"GOROKA",
"PAPUA NEW GUINEA"
] ]
I have this code so far:
#aeropuertos = ""
f = File.open("./public/aeropuertos/aeropuertos.cvs", "r")
f.each_line { |line|
fields = line.split(':')
if (fields[2] == "N/A")
#line = "(" << fields[1] << ")" << ",," << fields[3] << "," << fields[4]
else
#line = "(" << fields[1] << ")" << "," << fields[2] << "," << fields[3] << "," << fields[4]
end
#aeropuertos += #line << "\n"
}
return CSV.parse(#aeropuertos).to_json
What should I do?
#aeropuertos = ""
f = File.open("./public/aeropuertos/aeropuertos.cvs", "r")
f.each_line { |line|
fields = line.split(':')
if (fields[2] == "N/A")
#line = "(" << fields[1] << ")" << ",," << fields[3] << "," << fields[4]
else
#line = "(" << fields[1] << ")" << "," << fields[2] << "," << fields[3] << "," << fields[4]
end
#aeropuertos += #line << "\n"
}
res = []
CSV.parse(#aeropuertos).each do |c|
res << c.join(',')
end
return res.to_json
There's no need for the CSV parser. Just create the structure you want as you read each line. That is, instead of making a large string in #aeropuertos and parsing it with a CSV parser, make #aeropuertos an array, and add each #line to the array.
So, instead of this:
#aeropuertos += #line << "\n"
Do this:
#aeropuertos << #line
But be sure to say this at the beginning:
#aeropuertos = []

How to generate xml_builder ruby code from an XML file

I've got an xml file. How could I generate xml_builder ruby code out of that file?
Notice - I'm sort of going backwards here (instead of generating xml, I'm generating ruby code).
Pretty formatting isn't a big deal - I can always run it through a formatter later.
It's sort of impossible, not unlike if you asked "how to generate Ruby script that outputs number 3", for the answer could be:
puts 3
or
puts 2+1
or
puts [1,2,3].count
etc.
So, one answer to your question would be:
xml = File.read('your.xml')
puts "puts <<EOF\n#{xml}\nEOF"
Anyway, if you would just want to generate Builder based script which just generates your XML node-for-node, I guess it would be easiest using XSLT. That's a language constructed exactly for such purposes - transforming XMLs.
Here's what I eventually came up with:
#!/usr/bin/env ruby
require "rexml/document"
filename = ARGV[0]
if filename
f = File.read(filename)
else
raise "Couldn't read file: `#{filename}'"
end
doc = REXML::Document.new(f)
def self.output_hash(attributes={})
count = attributes.size
str = ""
index = 0
attributes.each do |key, value|
if index == 0
str << " "
end
str << "#{key.inspect} => "
str << "#{value.inspect}"
if index + 1 < count
str << ", "
end
index += 1
end
str
end
def self.make_xml_builder(doc, str = "")
doc.each do |element|
if element.respond_to?(:name)
str << "xml.#{element.name}"
str << "#{output_hash(element.attributes)}"
if element.length > 0
str << " do \n"
make_xml_builder(element, str)
str << "end\n"
else
str << "\n"
end
elsif element.class == REXML::Text
string = element.to_s
string.gsub!("\n", "")
string.gsub!("\t", "")
if !string.empty?
str << "xml.text!(#{string.inspect})\n"
end
end
end
str
end
puts make_xml_builder(doc)
After generating that, I then formatted it in Emacs.

Resources