Title pretty much sums it up.
I'm trying to display the chess unicode characters in the win10 command prompt and it displays the replacement character (�) instead (copy pasting that gives me the correct character again)
Enforcing UTF-8 encoding.
Setting the CMD Charpage to UTF-8 encoding.
Using the unicode characters instead of codes in my strings.
$icons = {
"Pawn" => "\u2659", # ♙
"Rook" => "\u2656", # ♖
"Knight" => "\u2658", # ♘
"Bishop" => "\u2657", # ♗
"Queen" => "\u2655", # ♕
"King" => "\u2654", # ♔
"Black" => "\u25A0", # ■
"White" => " " #
}
class Graphics
def display_board(b);
system ("cls")
#system ("chcp 65001")
board = b.get_map();
board.each_with_index do |subarr,x|
str = "";
subarr.each_with_index do |value,y|
str += "[" + $icons[value] + "]";
end
puts(str);
end
end
end
Expected result is this :
[♖][♘][♗][♔][♕][♗][♘][♖]
[♙][♙][♙][♙][♙][♙][♙][♙]
[ ][■][ ][■][ ][■][ ][■]
[■][ ][■][ ][■][ ][■][ ]
[ ][■][ ][■][ ][■][ ][■]
[■][ ][■][ ][■][ ][■][ ]
[♙][♙][♙][♙][♙][♙][♙][♙]
[♖][♘][♗][♔][♕][♗][♘][♖]
Actual result :
� for every chess piece.
This doesn't appear to be a ruby problem but rather the default encoding setting for windows and which fonts are used by the command prompt cmd.exe.
Here's how you should be able to get this to work.
Download and install this free monospaced font.
right click windows start button and select Run then type regedit and enter
type in the following path HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont
Right click on the white area under the key entries and select new > string value
in the value data box type Droid Sans Mono
Click OK and then restart Windows.
Right click windows button > run > cmd
Right click the top of the window and select DejaVue Sans Mono font
Test it by typing this ruby -e 'puts "\u2658"'
You should see a font that outputs a knight ♘
For more help see https://www.thewindowsclub.com/add-custom-fonts-to-command-prompt
For other possible fonts which can be used see suggestions on this answer
Related
I was wondering how to print unicode characters, such as Japanese or fun characters like 📦.
I can print hearts with:
hearts = "\u2665"
puts hearts.encode('utf-8')
How can I print more unicode charaters with Ruby in Command Prompt?
My method works with some characters but not all.
Code examples would be greatly appreciated.
You need to enclose the unicode character in { and } if the number of hex digits isn't 4 (credit : /u/Stefan) e.g.:
heart = "\u2665"
package = "\u{1F4E6}"
fire_and_one_hundred = "\u{1F525 1F4AF}"
puts heart
puts package
puts fire_and_one_hundred
Alternatively you could also just put the unicode character directly in your source, which is quite easy at least on macOS with the Emoji & Symbols menu accessed by Ctrl + Command + Space by default (a similar menu can be accessed on Windows 10 by Win + ; ) in most applications including your text editor/Ruby IDE most likely:
heart = "♥"
package = "📦"
fire_and_one_hundred = "🔥💯"
puts heart
puts package
puts fire_and_one_hundred
Output:
♥
📦
🔥💯
How it looks in the macOS terminal:
My script searches a website for songs, but when there are spaces it doesn't search, you have to add underscores. I was wondering if there was a way to replace my spaces with underscores.
Could you please use my current code below to show me how to do it?
set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
open location "http://www.mp3juices.com/search/" & search
end
Note: The solution no longer works as of Big Sur (macOS 11) - it sounds like a bug; do tell us if you have more information.
Try the following:
set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search
end
What you need is URL encoding (i.e., encoding of a string for safe inclusion in a URL), which involves more than just replacing spaces.
The open command-line utility, thankfully, performs this encoding for you, so you can just pass it the string directly; you need do shell script to invoke open, and quoted form of ensures that the string is passed through unmodified (to be URI-encoded by open later).
As you'll see, the kind of URL encoding open performs replaces spaces with %20, not underscores, but that should still work.
mklement0's answer is correct about url encoding but mp3juices uses RESTful URLs (clean URLs). RESTful URLs want's to keep the URL human readable and you won't see/use typical hex values in your url presenting an ASCII number. A snake_case, as you have mentioned (is false), but it is pretty common to use an substitution for whitespaces (%20) (and other characters) in RESTful URLs. However the slug of an RESTful must be converted to RESTful's own RESTful encoding before it can be handled by standard URL encoding.
set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
set search to stringReplace(search, space, "-")
do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search
on stringReplace(theText, searchString, replaceString)
set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, searchString}
set textItems to every text item of theText
set AppleScript's text item delimiters to replaceString
set newText to textItems as string
set AppleScript's text item delimiters to oldTID
return newText
end stringReplace
EDIT: updated the code, unlike the question mentioned that spaces are converted to underscores, mp3juice uses hyphens as substitution for whitespaces.
An update on this, despite the fact that the answer is 3 years old, as I faced the same problem: on recent versions of macOS/OS X/Mac OS X (I think, 10.10 or later), you can use ASOC, the AppleScript/Objective-C bridge:
use framework "Foundation"
urlEncode("my search string with [{?#äöü or whatever characters")
on urlEncode(input)
tell current application's NSString to set rawUrl to stringWithString_(input)
set theEncodedURL to rawUrl's stringByAddingPercentEscapesUsingEncoding:4 -- 4 is NSUTF8StringEncoding
return theEncodedURL as Unicode text
end urlEncode
It should be noted that stringByAddingPercentEscapesUsingEncoding is deprecated, but it will take some time until it’s removed from macOS.
URL encoding in AppleScript
For a general use case (for me at the moment to pass any ASCII url containing chars like #, &, ß, ö to the bit.ly API), I stumbled upon a nice code snippet that instantly added full support to my ShortURL clipboard pasting shortcut. Here's a quote from source:
i was looking for a quick and dirty way to encode some data to pass to a url via POST or GET with applescript and Internet Explorer, there were a few OSAXen which have that ability, but i didn't feel like installing anything, so i wrote this thing (works with standard ascii characters, characters above ascii 127 may run into character set issues see: applescript for converting macroman to windows-1252 encoding)
Notes
Double encoding should be duly noted.
Not tested on non-ASCII URLs.
Tested on OS X 10.8.5.
Code
on urlencode(theText)
set theTextEnc to ""
repeat with eachChar in characters of theText
set useChar to eachChar
set eachCharNum to ASCII number of eachChar
if eachCharNum = 32 then
set useChar to "+"
else if (eachCharNum ≠ 42) and (eachCharNum ≠ 95) and (eachCharNum < 45 or eachCharNum > 46) and (eachCharNum < 48 or eachCharNum > 57) and (eachCharNum < 65 or eachCharNum > 90) and (eachCharNum < 97 or eachCharNum > 122) then
set firstDig to round (eachCharNum / 16) rounding down
set secondDig to eachCharNum mod 16
if firstDig > 9 then
set aNum to firstDig + 55
set firstDig to ASCII character aNum
end if
if secondDig > 9 then
set aNum to secondDig + 55
set secondDig to ASCII character aNum
end if
set numHex to ("%" & (firstDig as string) & (secondDig as string)) as string
set useChar to numHex
end if
set theTextEnc to theTextEnc & useChar as string
end repeat
return theTextEnc
end urlencode
If you need to get the URL as a string (not just feed it into open which does a nifty job of encoding for you) and you're not above using a little Automator, you can throw some JavaScript into your AppleScript:
encodeURIComponent is a built in JavaScript function - it is a complete solution for encoding components of URIs.
For copy/pasters, here are all three scripts in the above Automator chain:
on run {input, parameters}
return text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
end run
function run(input, parameters) {
return encodeURIComponent(input);
}
on run {input, parameters}
display dialog "http://www.mp3juices.com/search/" & input buttons {"okay!"} default button 1
end run
I was hunting around for URL encoding and decoding and came across this helpful link.
Which you can use like so:
set theurl to "https://twitter.com/zackshapiro?format=json"
do shell script "php -r 'echo urlencode(\"" & theurl & "\");'"
# gives me "https%3A%2F%2Ftwitter.com%2Fzackshapiro%3Fformat%3Djson"
set theurl to "https%3A%2F%2Ftwitter.com%2Fzackshapiro%3Fformat%3Djson"
return do shell script "php -r 'echo urldecode(\"" & theurl & "\");'"
# gives me "https://twitter.com/zackshapiro?format=json"
Or as functions:
on encode(str)
do shell script "php -r 'echo urlencode(\"" & str & "\");'"
end encode
on decode(str)
do shell script "php -r 'echo urldecode(\"" & str & "\");'"
end decode
Just so it's said, AppleScriptObjC allows us to use NSString to do the encoding. The script is complicated by the fact that different parts of the URL allow different characters (all of which I've added options for) but in most cases the 'query' option will be used.
See NSCharacterSet's dev page (the section called "Getting Character Sets for URL Encoding") for descriptions of the various URL parts.
use AppleScript version "2.4" -- Yosemite 10.10 or later
use framework "Foundation"
property NSString : class "NSString"
property NSCharacterSet : class "NSCharacterSet"
-- example usage
my percentEncode:"some text" ofType:"query"
on percentEncode:someText ofType:encodeType
set unencodedString to NSString's stringWithString:someText
set allowedCharSet to my charSetForEncodeType:encodeType
set encodedString to unencodedString's stringByAddingPercentEncodingWithAllowedCharacters:allowedCharSet
return encodedString as text
end percentEncode:ofType:
on charSetForEncodeType:encodeType
if encodeType is "path" then
return NSCharacterSet's URLPathAllowedCharacterSet()
else if encodeType is "query" then
return NSCharacterSet's URLQueryAllowedCharacterSet()
else if encodeType is "fragment" then
return NSCharacterSet's URLFragmentAllowedCharacterSet()
else if encodeType is "host" then
return NSCharacterSet's URLHostAllowedCharacterSet()
else if encodeType is "user" then
return NSCharacterSet's URLUserAllowedCharacterSet()
else if encodeType is "password" then
return NSCharacterSet's URLPasswordAllowedCharacterSet()
else
return missing value
end if
end charSetForEncodeType:
The Python Approach:
Find your python3 path (which python3) or if you don't have it, install using brew or miniconda
Now try this:
python_path = /path/to/python3
set search_query to "testy test"
tell application "Google Chrome"
set win to make new window
open location "https://www.google.com/search?q=" & url_encode(q)
end tell
on url_encode(input)
return (do shell script "echo " & input & " | " & python_path & " -c \"import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))\"
")
end url_encode
credits to #Murphy https://stackoverflow.com/a/56321886
tl;dr
what does the first parameters value in com.apple.symbolichotkeys:AppleSymbolicHotKeys represent?
details...
the AppleSymbolicHotKeys structure
the OS X symbolic hotkeys plist file at
~/Library/Preferences/com.apple.symbolichotkeys.plist
stores hotkeys in a dict called as 'AppleSymbolicHotKeys' with entries that look like
<action:int> = Dict {
enabled = <enabled:bool>
value = Dict {
type = <type:string>
parameters = Array {
<param_1:int>
<param_2:int>
<param_3:int>
}
}
}
example:
10 = Dict {
enabled = true
value = Dict {
type = standard
parameters = Array {
56
28
1572864
}
}
}
pro tip: you can take a look with
/usr/libexec/PlistBuddy -c "Print :AppleSymbolicHotKeys" ~/Library/Preferences/com.apple.symbolichotkeys.plist
the values
action:int
this is the id of the action the hotkey will take. there are reasonably complete lists around the net, do some googling 'cause i don't have enough points to post links or whatever.
enabled:bool
whether the hotkey is enabled.
type:string
always seems to be 'standard'.
param_1:int
this is the one i can't get. it doesn't seem necessarily connected to params 2 and 3, though it often changes when the other params are changed. for instance...
i can click Restore Defaults in the System Preferences -> Keyboard -> Shortcuts -> Mission Control view, and it will set "Switch to Desktop 1" to "ctrl + 1". reading the value for that action (number 118), i see that param_1 is set to 65535. if i manually set the key combo to "ctrl + 1" in the UI, i get param_1 set to 49. the values of param_2 and param_3 stay the same throughout.
param_2:int
this seems to be key codes from
/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
for the non-modifier key to be pressed, except for the value 65535, which is very common in param_1, and shows up in param_2 on my local machine for actions 160, 163 and 175.
param_3:int
seems to indicate the modifier key to be depressed, as according to
MODS = {
0=>"No modifier",
131072=>"Shift",
262144=>"Control",
524288=>"Option",
1048576=>"Command",
393216=>"Shift + Control",
655360=>"Shift + Option",
1179648=>"Shift + Command",
786432=>"Control + Option",
1310720=>"Control + Command",
1572864=>"Option + Command",
917504=>"Shift + Control + Option",
1441792=>"Shift + Control + Command",
1703936=>"Shift + Option + Command",
1835008=>"Control + Option + Command",
1966080=>"Shift + Control + Option + Command",
}
where you will notice the numbers representing multiple modifiers are the sum of the modifiers they represent, e.g.
"Shift + Control" = 393216 = 131072 + 262144 = "Shift" + "Control"
so...
any insight would be greatly appreciated, and hope this can serve as a reference for the info i dug up to anyone else approaching the subject.
It is the ascii code of the letter on the key, or -1 (65535) if there is no ascii code. Note that letters are lowercase, so D is 100 (lowercase d).
Sometimes a key that would normally have an ascii code uses 65535 instead. This appears to happen when the control key modifier is used, for example with hot keys for specific spaces.
There is a nice list of keys and values from 2011 here, along with some other good details:
http://hintsforums.macworld.com/showthread.php?t=114785
The numerical values in nrser's answer make more sense when viewed in hexadecimal form:
0x000000 => "No modifier",
0x020000 => "Shift",
0x040000 => "Control",
0x080000 => "Option",
0x100000 => "Command",
The others are simply bit-wise-ORs of the above values, for example:
0x060000 => "Shift + Control",
0x180000 => "Command + Option",
In addition to what's already been said, I've compiled a JSON manifest of all 256 possible modifier bitwise-operated results — including the function keys:
https://gist.github.com/stephancasas/74c4621e2492fb875f0f42778d432973
Is there a way to programmatically get a list of characters a .ttf file supports using Ruby and/or Bash. I am trying to pipe the supported character codes into a text file for later processing.
(I would prefer not to use Font Forge.)
Found a Ruby gem called ttfunk which can be found here.
After a gem install ttfunk, you can get all unicode characters by running the following script:
require 'ttfunk'
file = TTFunk::File.open("path/to/font.ttf")
cmap = file.cmap
chars = {}
unicode_chars = []
cmap.tables.each do |subtable|
next if !subtable.unicode?
chars = chars.merge( subtable.code_map )
end
unicode_chars = chars.keys.map{ |dec| dec.to_s(16) }
puts "\n -- Found #{unicode_chars.length} characters in this font \n\n"
p unicode_chars
Which will output something like:
- Found 2815 characters in this font
["20", "21", "22", "23", ... , "fef8", "fef9", "fefa", "fefb", "fefc", "fffc", "ffff"]
When calling the set method of a text_field in ruby, the text is being entered at a very slow rate in the browser, roughly at 1 character / second.
Environment Information:
Ubuntu 10.10
FireFox 3.6.13
JSSh 0.9
Ruby 1.9.2p136
FireWatir 1.7.1
Kindly advice. Thanks in advance.
It is a known bug: WTR-397
Workaround is to use watir-webdriver or to use value= instead of set. Example:
browser.text_field(how => what).value= "string"
solve slow key type issue on firewatir:
need to edit the file text_field.rb
enter to the folder
#>cd /usr/lib/ruby/gems/1.8/gems/firewatir-1.7.1/lib/firewatir/elements/ make it writeable
#>chmod 777 text_field.rb edit the proc def doKeyPress( value )
put # in front of #o.fireEvent("onKeyDown") and #o.fireEvent("onKeyPress") and #o.fireEvent("onKeyPress")
instead enter fire_key_events
def doKeyPress( value )
begin
max = maxlength
if (max > 0 && value.length > max)
original_value = value
value = original_value[0...max]
element.log " Supplied string is #{suppliedValue.length} chars, which exceeds the max length (#{max}) of the field. Using value: #{value}"
end
rescue
# probably a text area - so it doesnt have a max Length
end
for i in 0..value.length-1
#sleep element.typingspeed # typing speed
c = value[i,1]
#element.log " adding c.chr " + c #.chr.to_s
#o.value = "#{(#o.value.to_s + c)}" #c.chr
fire_key_events #add this
##o.fireEvent("onKeyDown")
##o.fireEvent("onKeyPress")
##o.fireEvent("onKeyUp")
end
now it should work faster