Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to Python3 && adapt to Alfred5 #13

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
I've upgraded scripts to use `Python 3` because macOS 12.3 dropped `Python 2`. And I prefer to use a short version of command like `dec` and `bin` instead of `decimal` and `binary`.

Original README:

# NSC
*Number System Converter -- an [Alfred](http://www.alfredapp.com/) extension*
* * *
Expand Down
11 changes: 6 additions & 5 deletions alp/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ def bundle():

infoPath = os.path.abspath("./info.plist")
if os.path.exists(infoPath):
info = plistlib.readPlist(infoPath)
try:
gBundleID = info["bundleid"]
except KeyError:
raise Exception("Bundle ID not defined or readable from info.plist.")
with open(infoPath, 'rb') as inputFile:
info = plistlib.loads(inputFile.read())
try:
gBundleID = info["bundleid"]
except KeyError:
raise Exception("Bundle ID not defined or readable from info.plist.")
else:
raise Exception("info.plist missing.")

Expand Down
32 changes: 19 additions & 13 deletions alp/item.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-

from xml.etree import ElementTree as ET
import copy
import random
import alp.core as core
import json


class Item(object):
Expand Down Expand Up @@ -55,36 +55,42 @@ def get(self):
return data

def feedback(items):
feedback = ET.Element("items")

def processItem(item):
itemToAdd = ET.SubElement(feedback, "item")
json_item = {}

data = item.get()

for (k, v) in data["attrib"].iteritems():
for (k, v) in data["attrib"].items():
if v is None:
continue
itemToAdd.set(k, v)
json_item[k] = v

for (k, v) in data["content"].iteritems():
for (k, v) in data["content"].items():
if v is None:
continue
if k != "fileIcon" and k != "fileType":
child = ET.SubElement(itemToAdd, k)
child.text = v
json_item[k] = v
if k == "icon":
icon_item = {}
if "fileIcon" in data["content"].keys():
if data["content"]["fileIcon"] == True:
child.set("type", "fileicon")
icon_item["type"] = "fileicon"
if "fileType" in data["content"].keys():
if data["content"]["fileType"] == True:
child.set("type", "filetype")
icon_item["type"] = "filetype"
return json_item

final_items = {}
items_array = []
if isinstance(items, list):
for anItem in items:
processItem(anItem)
final_item = processItem(anItem)
items_array.append(final_item)
else:
processItem(items)
final_item = processItem(items)
items_array.append(final_item)

print ET.tostring(feedback, encoding="utf-8")
final_items["items"] = items_array

print(json.dumps(final_items))
139 changes: 74 additions & 65 deletions convertNumber.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
import sys
import alp
import string
ALPHA = string.digits + string.uppercase + string.lowercase + '+' + '/'
ALPHA = string.digits + string.ascii_letters + '+' + '/'


def base64_encode(num, base, alphabet=ALPHA):
"""Encode a number in Base X
Expand All @@ -29,76 +30,84 @@ def base64_encode(num, base, alphabet=ALPHA):
arr.reverse()
return ''.join(arr)


def base64_decode(string, base, alphabet=ALPHA):
"""Decode a Base X encoded string into the number
"""Decode a Base X encoded string into the number

Arguments:
- `string`: The encoded string
- `base`: base of number
- `alphabet`: The alphabet to use for encoding
"""
strlen = len(string)
num = 0
Arguments:
- `string`: The encoded string
- `base`: base of number
- `alphabet`: The alphabet to use for encoding
"""
strlen = len(string)
num = 0

idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1
idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1

return num
return num


if (len(sys.argv) == 4 and sys.argv[3] != "1"):
# calculate integer first
if (int(sys.argv[2]) <= 36):
# use built in python conversion if possible
decimal = int(sys.argv[1], int(sys.argv[2]))
elif (int(sys.argv[2]) > 36 and int(sys.argv[2]) <= 64):
# otherwise, use base64_decode
decimal = base64_decode(sys.argv[1], int(sys.argv[2]))
else:
# create dictionary to create xml from it
errorDic = dict(title="Ohoh, your number couldn't be converted", subtitle="make sure your base is between 2 and 64", uid="error", valid=False)
e = alp.Item(**errorDic)
alp.feedback(e)
sys.exit()

# create dictionary to create xml from it
decimalDic = dict(title=str(decimal), subtitle="Decimal", uid="decimal", valid=True, arg=str(decimal), icon="icons/decimal.png")
d = alp.Item(**decimalDic)

# calculate new number
if (int(sys.argv[3]) >= 2 and int(sys.argv[3]) <= 64):
conv = base64_encode(decimal, int(sys.argv[3]))
else:
# create dictionary to create xml from it
errorDic = dict(title="Ohoh, your number couldn't be converted", subtitle="make sure your base is between 2 and 64", uid="error", valid=False)
e = alp.Item(**errorDic)
itemsList = [d, e]
alp.feedback(itemsList)
sys.exit()

# create dictionary to create xml from it
convertDic = dict(title=conv, subtitle="Number to base " + str(sys.argv[3]), uid="conv", valid=True, arg=conv)
c = alp.Item(**convertDic)

if (int(sys.argv[2]) >= 36 or int(sys.argv[3]) >= 36):
# create dictionary to create xml from it
infoDic = dict(title="Case-Sensitive", subtitle="Be aware, if base is >= 36 letters are case-sensitive", uid="conv", valid=True, arg=conv)
i = alp.Item(**infoDic)
itemsList = [d, c, i]
else:
itemsList = [d, c]

alp.feedback(itemsList)
# calculate integer first
if (int(sys.argv[2]) <= 36):
# use built in python conversion if possible
decimal = int(sys.argv[1], int(sys.argv[2]))
elif (int(sys.argv[2]) > 36 and int(sys.argv[2]) <= 64):
# otherwise, use base64_decode
decimal = base64_decode(sys.argv[1], int(sys.argv[2]))
else:
# create dictionary to create xml from it
errorDic = dict(title="Ohoh, your number couldn't be converted",
subtitle="make sure your base is between 2 and 64", uid="error", valid=False)
e = alp.Item(**errorDic)
alp.feedback(e)
sys.exit()

# create dictionary to create xml from it
decimalDic = dict(title=str(decimal), subtitle="Decimal", uid="decimal",
valid=True, arg=str(decimal), icon="icons/decimal.png")
d = alp.Item(**decimalDic)

# calculate new number
if (int(sys.argv[3]) >= 2 and int(sys.argv[3]) <= 64):
conv = base64_encode(decimal, int(sys.argv[3]))
else:
# create dictionary to create xml from it
errorDic = dict(title="Ohoh, your number couldn't be converted",
subtitle="make sure your base is between 2 and 64", uid="error", valid=False)
e = alp.Item(**errorDic)
itemsList = [d, e]
alp.feedback(itemsList)
sys.exit()

# create dictionary to create xml from it
convertDic = dict(title=conv, subtitle="Number to base " + str(sys.argv[3]), uid="conv", valid=True, arg=conv)
c = alp.Item(**convertDic)

if (int(sys.argv[2]) >= 36 or int(sys.argv[3]) >= 36):
# create dictionary to create xml from it
infoDic = dict(
title="Case-Sensitive", subtitle="Be aware, if base is >= 36 letters are case-sensitive", uid="conv",
valid=True, arg=conv)
i = alp.Item(**infoDic)
itemsList = [d, c, i]
else:
itemsList = [d, c]

alp.feedback(itemsList)

else:
if (len(sys.argv) != 4):
errorDic = dict(title="Make sure to pass 3 numbers", subtitle="convert `number` `base of original` `base to convert to`", uid="error", valid=False, arg="error")
error = alp.Item(**errorDic)
alp.feedback(error)
elif (int(sys.argv[3]) == 1):
errorDic = dict(title="Base 1 makes no sense", subtitle="", uid="error", valid=False, arg="error")
error = alp.Item(**errorDic)
alp.feedback(error)
if (len(sys.argv) != 4):
errorDic = dict(
title="Make sure to pass 3 numbers", subtitle="convert `number` `base of original` `base to convert to`",
uid="error", valid=False, arg="error")
error = alp.Item(**errorDic)
alp.feedback(error)
elif (int(sys.argv[3]) == 1):
errorDic = dict(title="Base 1 makes no sense", subtitle="", uid="error", valid=False, arg="error")
error = alp.Item(**errorDic)
alp.feedback(error)
16 changes: 8 additions & 8 deletions info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,11 @@
<key>escaping</key>
<integer>0</integer>
<key>keyword</key>
<string>octal</string>
<string>oct</string>
<key>runningsubtext</key>
<string>converting ...</string>
<key>script</key>
<string>python convertOctal.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<string>python3 convertOctal.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<key>subtext</key>
<string>Type any octal number</string>
<key>title</key>
Expand All @@ -151,7 +151,7 @@
<key>runningsubtext</key>
<string>converting ...</string>
<key>script</key>
<string>python convertNumber.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<string>python3 convertNumber.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<key>subtext</key>
<string>convert number to other system</string>
<key>title</key>
Expand All @@ -174,11 +174,11 @@
<key>escaping</key>
<integer>0</integer>
<key>keyword</key>
<string>binary</string>
<string>bin</string>
<key>runningsubtext</key>
<string>converting ...</string>
<key>script</key>
<string>python convertBinary.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<string>python3 convertBinary.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<key>subtext</key>
<string>Type any binary number</string>
<key>title</key>
Expand All @@ -205,7 +205,7 @@
<key>runningsubtext</key>
<string>converting ...</string>
<key>script</key>
<string>python convertHex.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<string>python3 convertHex.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<key>subtext</key>
<string>Type any hexadecimal number</string>
<key>title</key>
Expand Down Expand Up @@ -251,11 +251,11 @@
<key>escaping</key>
<integer>0</integer>
<key>keyword</key>
<string>decimal</string>
<string>dec</string>
<key>runningsubtext</key>
<string>converting ...</string>
<key>script</key>
<string>python convertDecimal.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<string>python3 convertDecimal.py {query} 2&gt;&amp;1 | tee nsc.log</string>
<key>subtext</key>
<string>Type any decimal number</string>
<key>title</key>
Expand Down