Lua - Cipher Logic Error Involving string.gsub, Ciphered Output is Not Input - string

My program seems to be experiencing logical errors. I have looked it over multiple times and even written another program similar to this one (also seems to have the same error). I cannot figure out what is wrong, although I think it may involve my usage of string.gsub...
repeat
local file = io.open("out.txt", "w")
print("would you like to translate Cipher to English or English to Cipher?")
print("enter 1 for translation to English. enter 2 for translation to Cipher")
tchoice=io.read()
if tchoice=="2" then
print(" enter any text to translate it: ")
rawtextin=io.read()
text=string.lower(rawtextin)
text1=string.gsub(text,"a","q")
text2=string.gsub(text1,"b","e")
text3=string.gsub(text2,"c","h")
text4=string.gsub(text3,"d","c")
text5=string.gsub(text4,"e","j")
text6=string.gsub(text5,"f","m")
text7=string.gsub(text6,"g","r")
text8=string.gsub(text7,"h","g")
text9=string.gsub(text8,"i","b")
text10=string.gsub(text9,"j","a")
text11=string.gsub(text10,"k","d")
text12=string.gsub(text11,"l","y")
text13=string.gsub(text12,"m","v")
text14=string.gsub(text13,"n","z")
text15=string.gsub(text14,"o","x")
text16=string.gsub(text15,"p","k")
text17=string.gsub(text16,"q","i")
text18=string.gsub(text17,"r","l")
text19=string.gsub(text18,"s","f")
text20=string.gsub(text19,"t","s")
text21=string.gsub(text20,"u","w")
text22=string.gsub(text21,"v","t")
text23=string.gsub(text22,"w","p")
text24=string.gsub(text23,"x","u")
text25=string.gsub(text24,"y","n")
text26=string.gsub(text25,"z","o")
text27=string.gsub(text26," ","#")
print(text27)
elseif tchoice=="1" then
print("enter text!")
rawtextin=io.read()
text=string.lower(rawtextin)
text1=string.gsub(text,"q","a")
text2=string.gsub(text1,"e","b")
text3=string.gsub(text2,"h","c")
text4=string.gsub(text3,"c","d")
text5=string.gsub(text4,"j","e")
text6=string.gsub(text5,"m","f")
text7=string.gsub(text6,"r","g")
text8=string.gsub(text7,"g","h")
text9=string.gsub(text8,"b","i")
text10=string.gsub(text9,"a","j")
text11=string.gsub(text10,"d","k")
text12=string.gsub(text11,"y","l")
text13=string.gsub(text12,"v","m")
text14=string.gsub(text13,"z","n")
text15=string.gsub(text14,"x","o")
text16=string.gsub(text15,"k","p")
text17=string.gsub(text16,"i","q")
text18=string.gsub(text17,"l","r")
text19=string.gsub(text18,"f","s")
text20=string.gsub(text19,"s","t")
text21=string.gsub(text20,"w","u")
text22=string.gsub(text21,"t","v")
text23=string.gsub(text22,"p","w")
text24=string.gsub(text23,"u","x")
text25=string.gsub(text24,"n","y")
text26=string.gsub(text25,"o","z")
text27=string.gsub(text26,"#"," ")
print(text27)
end
print("writing to out.txt...")
file:write(text27)
file:close()
print("done!")
print("again? type y for yes or anything else for no.")
again=io.read()
until again~="y"
x=io.read()
No errors in the code - What am I missing? I am aware this is not the most efficient way of doing this but I need to figure out what is going wrong before I write a more efficient program using loops and tables.
Sample run (with only significant data included):
in:2
in:hi test
out:gb#safs
in:y
in:1
in:gb#safs
out:hq vjvv

local decoded = 'abcdefghijklmnopqrstuvwxyz #'
local encoded = 'qehcjmrgbadyvzxkilfswtpuno# '
local enc, dec = {}, {}
for i = 1, #decoded do
local e, d = encoded:sub(i,i), decoded:sub(i,i)
enc[d] = e
dec[e] = d
end
repeat
local file = io.open("out.txt", "w")
local text27, rawtextin
print("would you like to translate Cipher to English or English to Cipher?")
print("enter 1 for translation to English. enter 2 for translation to Cipher")
local tchoice = io.read()
if tchoice == "2" then
print(" enter any text to translate it: ")
rawtextin = io.read()
text27 = rawtextin:lower():gsub('.',enc)
print(text27)
elseif tchoice == "1" then
print("enter text!")
rawtextin = io.read()
text27 = rawtextin:lower():gsub('.',dec)
print(text27)
end
print("writing to out.txt...")
file:write(text27)
file:close()
print("done!")
print("again? type y for yes or anything else for no.")
local again = io.read()
until again ~= "y"

Related

Smiles bot in Lua: matching text

This is my bot, who copies smilies in game chat.
The smiles it copies are saved in the table called "emoticons". If someone writes ":)", the bot writes ":)" and so on
The code inside the loop is for this: if someone writes, for example, ">:)", you have to make the script copy ">:)" and not just ":)"
CreateFrame, RegisterEvent, SetScript and SendChatMessage are in-game built Lua API
local emoticons = {
":)", "(:", ":))", ">:)", "0:)", ":D", ":]", ":)))", "=]", "?_?", "+.+", ":P", ":3", "^^", "roar", ":V", "D:", ":C", ".D", ".)", "o_o",
"^-^", ":PPP", ":DDD", ":D:D:D", ":DDDD", ":D:D:D:D", ":DDDDD", ":d", ":L", "<O>_<O>", "o/", "+_+", "?_?", "*0*", ":}", ";)", ":))))", "o.o", "<.<''", ":|",
":-)", "^^^^", ":D:D:D:D:D:D", ":D :D :D", "^^^", ":c", ";]", ":9", ">:|", ">.<", ";3", ";P", "T_T", ":3c", ":)))))",
"^^^^^" }
local f = CreateFrame("Frame")
f:RegisterEvent("CHAT_MSG_GUILD")
f:SetScript("OnEvent", function(self, event, text, playerName, _, channelName, playerName2, _, _, channelIndex)
local msg
local n = 0
for x, key in ipairs(emoticons) do
local l = string.len(emoticons[x])
if (string.sub(text, -l) == emoticons[x]) then
if (l > n) then
msg = emoticons[x]
n = l
end
end
end
if (msg) and (playerName ~= UnitName("player")) then
if (event == "CHAT_MSG_GUILD") then SendChatMessage(msg, "GUILD", nil, channelIndex) end
end
end)
Is there any way to improve it? For example, if someone writes
"^^^^^^"
the bot copies
"^^^^^"
which would be the same with one less "^" as it was stored in the table
My goal is that if someone writes, for example, "^^^^^^" and it is not registered in the table, the script will not respond
You're probably better off learning how to use string.gmatch
As an example, let's say you only store one instance of ':D' in your emoticons table. You can iterate through the matches and respond in kind. Here's a small example:
local text = ':D:D:D'
local count = 0
for w in string.gmatch(text, ':D') do
count = count + 1
end
if count > 0 then
local response = ''
for i = 1, count do
response = response .. ':D'
end
print(response) -- prints ':D:D:D'
end
This doesn't handle every case, but hopefully it can help you get started
:D

While making this random password generator, using the python library random_word, the "random word" in the elif statement sometimes returns "None"

import numpy as np
from random_word import RandomWords
r = RandomWords()
promptInput = str(input("Do you want to enter your on prompt or randomly generate it, answer
in yes or no : "))
if promptInput == "yes" :
passwordHint = str(input("Enter a prompt for making the password : "))
nums = np.random.randint(1000, 9999)
newHint = passwordHint.capitalize()
nums = str(nums)
password = newHint + nums
print(password)
elif promptInput == "no" :
randomWord = str(r.get_random_word(minLength = 5,maxLength = 7))
nums = np.random.randint(1000, 9999)
newRandomWord = randomWord.capitalize()
nums = str(nums)
password2 = newRandomWord + nums
print(password2)
printing this is mostly returning "None" and then the random numbers,
for example - None8797
else :
print("Enter yes or no only")
This could also be a problem as I previously wanted to test if the
code would work, so I typed out in the elif statement print("none")
It looks like you're using this module:
https://pypi.org/project/Random-Word/
If you take a look at its source code, you'll notice that it fetches random words from an online service at api.wordnik.com. If you're trying to generate secure passwords, this is an absolutely terrible idea.
To make matters worse, the service will only respond when provided with a valid API key. The module has three embedded API keys:
---
API_KEY:
- "d146825 .......... (redacted) .......... 92d3230"
- "1eirq2g .......... (redacted) .......... w02zyj7"
- "c23b746 .......... (redacted) .......... b9b658e"
I tried using one of these, and got the following response:
{"message":"API rate limit exceeded"}
This is probably what's causing the null responses. I suggest you stop using this module immediately and find a better solution.

Using specific elements from a list in different loops for a multiple choice test python 3.x

Basically i'm trying to create a multiple choice test that uses information stored inside of lists to change the questions/ answers by location.
so far I have this
import random
DATASETS = [["You first enter the car", "You start the car","You reverse","You turn",
"Coming to a yellow light","You get cut off","You run over a person","You have to stop short",
"in a high speed chase","in a stolen car","A light is broken","The car next to you breaks down",
"You get a text message","You get a call","Your out of gas","Late for work","Driving angry",
"Someone flips you the bird","Your speedometer stops working","Drinking"],
["Put on seat belt","Check your mirrors","Look over your shoulder","Use your turn signal",
"Slow to a safe stop","Relax and dont get upset","Call 911", "Thank your brakes for working",
"Pull over and give up","Ask to get out","Get it fixed","Offer help","Ignore it","Ignore it",
"Get gas... duh","Drive the speed limit","Don't do it","Smile and wave","Get it fixed","Don't do it"],
[''] * 20,
['B','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A'],
[''] * 20]
def main():
questions(0)
answers(1)
def questions(pos):
for words in range(len(DATASETS[0])):
DATASETS[2][words] = input("\n" + str(words + 1) + ".)What is the proper procedure when %s" %DATASETS[0][words] +
'\nA.)'+random.choice(DATASETS[1]) + '\nB.)%s' %DATASETS[1][words] + '\nC.)'
+random.choice(DATASETS[1]) + '\nD.)'+random.choice(DATASETS[1])+
"\nChoose your answer carefully: ")
def answers(pos):
for words in range(len(DATASETS[0])):
DATASETS[4] = list(x is y for x, y in zip(DATASETS[2], DATASETS[3]))
print(DATASETS)
I apologize if the code is crude to some... i'm in my first year of classes and this is my first bout of programming.
list 3 is my key for the right answer's, I want my code in questions() to change the position of the correct answer so that it correlates to the key provided....
I've tried for loops, if statements and while loops but just cant get it to do what I envision. Any help is greatly appreciated
tmp = "\n" + str(words + 1) + ".)What is the proper procedure when %s" %DATASETS[0][words] + '\nA.)'
if DATASETS[3][words] == 'A': #if the answer key is A
tmp = tmp + DATASETS[1][words] #append the first choice as correct choice
else:
tmp = tmp + random.choice(DATASETS[1]) #if not, randomise the choice
Do similar if-else for 'B', 'C', and 'D'
Once your question is formulated, then you can use it:
DATASETS[2][words] = input(tmp)
This is a bit long but I am not sure if any shorter way exists.

How to make Discord bot send image with the name of number chosen by user? (Python 3.5.x)

I'm still learning python and programming and i've got myself into a problem that i can't solve. I want to make a command that would make a bot send an image that its name corresponds to number what user wrote (e.g. user wrote "!image_nr 22" and bot sends 22.jpg). I've only made code that sends random image from folder but I cant get into chosen. Here's my latest code for this problem:
elif message.content.startswith("!obrazeknr"): #missing an argument or something, idk what to make here
obrazDirectoryChc = "C:/Users/Lewando54/Downloads/Localisation/English/" + liczba + ".jpg"
await client.send_file(message.channel, obrazDirectoryChc, content=obrazName[1])
You could try inside this elif statement:
msg = message.content[12:] #skips the command word and the '!' and the " "
msg = msg.split() #split the message into an array at the spaces.
#msg = ["!image_nr","22"]
if msg[0] == "!image_nr" and msg[1].isnumeric():
obrazDirectoryChc = "C:/Users/Lewando54/Downloads/Localisation/English/" +
liczba + ".jpg"
await client.send_file(message.channel, obrazDirectoryChc,
content=obrazName[int(msg[1]])
now it should send the user requested photo.
e.g. !obrazeknr image_nr 22
Hope this helps. Sorry for the long wait; I just saw this today.
Might be a better idea, for next time, posting on https://programming.stackoverflow.com could give you more help.
It works. I've slightly modified it and it works. Thx for idea :D
elif message.content.startswith('!obrazeknr'):
msg1 = message.content #skips the command word and the '!' and the " "
msg1 = msg1.split() #split the message into an array at the spaces.
#msg = ["!obrazeknr","22"]
if msg1[0] == "!obrazeknr" and msg1[1].isnumeric() == True:
await client.send_file(message.channel, "C:/Users/Lewando54/Downloads/Localisation/English/" + str(int(msg1[1])) + ".jpg")

How to convert cmudict-0.7b or cmudict-0.7b.dict in to FST format to use it with phonetisaurus?

I am looking for a simple procedure to generate FST (finite state transducer) from cmudict-0.7b or cmudict-0.7b.dict, which will be used with phonetisaurus.
I tried following set of commands (phonetisaurus Aligner, Google NGramLibrary and phonetisaurus arpa2wfst) and able to generate FST but it didn't work. I am not sure where I did a mistake or miss any step. I guess very first command ie phonetisaurus-align, is not correct.
phonetisaurus-align --input=cmudict.dict --ofile=cmudict/cmudict.corpus --seq1_del=false
ngramsymbols < cmudict/cmudict.corpus > cmudict/cmudict.syms
/usr/local/bin/farcompilestrings --symbols=cmudict/cmudict.syms --keep_symbols=1 cmudict/cmudict.corpus > cmudict/cmudict.far
ngramcount --order=8 cmudict/cmudict.far > cmudict/cmudict.cnts
ngrammake --v=2 --bins=3 --method=kneser_ney cmudict/cmudict.cnts > cmudict/cmudict.mod
ngramprint --ARPA cmudict/cmudict.mod > cmudict/cmudict.arpa
phonetisaurus-arpa2wfst-omega --lm=cmudict/cmudict.arpa > cmudict/cmudict.fst
I tried fst with phonetisaurus-g2p as follows:
phonetisaurus-g2p --model=cmudict/cmudict.fst --nbest=3 --input=HELLO --words
But it didn't return anything....
Appreciate any help on this matter.
It is very important to keep dictionary in the right format. Phonetisaurus is very sensitive about that, it requires word and phonemes to be tab separated, spaces would not work then. It also does not allow pronunciation variant numbers CMUSphinx uses like (2) or (3). You need to cleanup dictionary with simple python script for example before feeding it into phonetisaurus. Here is the one I use:
#!/usr/bin/python
import sys
if len(sys.argv) != 3:
print "Split the list on train and test sets"
print
print "Usage: traintest.py file split_count"
exit()
infile = open(sys.argv[1], "r")
outtrain = open(sys.argv[1] + ".train", "w")
outtest = open(sys.argv[1] + ".test", "w")
cnt = 0
split_count = int(sys.argv[2])
for line in infile:
items = line.split()
if items[0][-1] == ')':
items[0] = items[0][:-3]
if items[0].find("_") > 0:
continue
line = items[0] + '\t' + " ".join(items[1:]) + '\n'
if cnt % split_count == 3:
outtest.write(line)
else:
outtrain.write(line)
cnt = cnt + 1

Resources