when I run the code below,I am getting an error as "index 0 is out of bounds for axis 0 with size 0" - knn

This is my code below
def recomend_book(book_name):
b_id = np.where(books_rating_pivot.index == book_name)[0][0]
_, recommendations = model.kneighbors(books_rating_pivot.iloc[b_id,:].values.reshape(1,-1))
for i in range(len(recommendations)):
if i == 0:
print(f"For book \"{book_name}\" is recommended")
if not i:
print(books_rating_pivot.index[recommendations[i]])
recomend_book('Harry')

Related

lua debug hook causing race condition?

I wanted to report some debug information for a parser I am writing in lua. I am using the debug hook facility for tracking but it seems like there is some form of race condition happening.
Here is my test code:
enters = 0
enters2 = 0
calls = 0
tailcalls = 0
returns = 0
lines = 0
other = 0
exits = 0
local function analyze(arg)
enters = enters + 1
enters2 = enters2 + 1
if arg == "call" then
calls = calls + 1
elseif arg == "tail call" then
tailcalls = tailcalls + 1
elseif arg == "return" then
returns = returns + 1
elseif arg == "line" then
lines = lines + 1
else
other = other + 1
end
exits = exits + 1
end
debug.sethook(analyze, "crl")
-- main code
print("enters = ", enters)
print("enters2 = ", enters2)
print("calls = ", calls)
print("tailcalls = ", tailcalls)
print("returns = ", returns)
print("lines = ", lines)
print("other = ", other)
print("exits = ", exits)
print("sum = ", calls + tailcalls + returns + lines + other)
and here is the result:
enters = 429988
enters2 = 429991
calls = 97433
tailcalls = 7199
returns = 97436
lines = 227931
other = 0
exits = 430009
sum = 430012
Why does none of this add up? I am running lua 5.4.2 on Ubuntu 20.04, no custom c libraries, no further messing with the debug library.
I found the problem...
The calls to the print function when printing the result also trigger the hook, which only affects the results that have not been printed yet.

Issues with an discord.py Mass-Ban Command if the User is Banned

If the User is already banned, the bot shall add 1 to the failed variable... However the failed variable always returns 0 even though a user is banned from the guild
Here's the code:
#commands.command(aliases = ["multiban" , "mass-ban" , "multi-ban"])
#commands.bot_has_permissions(ban_members = True)
#commands.has_permissions(ban_members = True)
async def massban(self , ctx , targets: commands.Greedy[discord.User] , * , grund="Kein Grund angegeben"):
with ctx.channel.typing():
banlist = await ctx.guild.bans()
banned = 0
days = 0
tries = 0
failed = 0
developer = self.client.get_user(705557092802625576)
if developer in targets:
failed += 1
banned -= 1
else:
for x in targets:
tries += 1
if x in banlist:
failed += 1
banned -= 1
else:
try:
await ctx.guild.ban(x , reason = f"{grund}" , delete_message_days = days)
banned += 1
except Exception as e:
failed += 1
print(e)
embed = discord.Embed(color = 0xff2200 , title = "Massban ausgeführt :tools:" ,
description = f"Es wurde versucht, **{tries}** Personen zu bannen. Ergebnisse: \n**{banned}** Nutzer wurde/n gebannt. \n**{failed}** Nutzer konnte/n nicht gebannt werden.")
embed.set_footer(text = f"User-ID: {ctx.author.id}" , icon_url = f"{ctx.message.author.avatar_url}")
embed.set_author(name = f"{ctx.author}" , icon_url = f"{ctx.message.author.avatar_url}")
return await ctx.reply(embed = embed , mention_author = False)
#massban.error
async def massban_error(self , ctx , error):
if isinstance(error , commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention} Berechtigungs-Fehler! [Gebrauchte Berechtigung: ban_members]")
elif isinstance(error , commands.BotMissingPermissions):
await ctx.send(f"{ctx.author.mention} Berechtigungs-Fehler! [Gebrauchte Berechtigung: ban_members]")
elif isinstance(error , commands.UserNotFound):
pass
else:
failed += 1
raise error
The issue might be this line here.
developer = 705557092802625576
if developer in targets:
failed += 1
banned -= 1
You are checking if an int is in a list of discord.User objects which will always return false. You should instead do developer = self.bot.fetch_user(705557092802625576).

Unbound value for variable in ocaml method. Trying to print first 8 elements of array

I'm trying to write a method which will allow me to print out positions of a chess game for the top 8 positions.
I have a val mutable initial which is an array of 32 entries,each containing chesspiece * chesscolor * chessposition.
The chessposition is defined as:
chess_position = Alive of chessletter * int | Dead;;
Im trying to print out the positions on the first row of the board for now.
I have the following code:
class chess =
object
val mutable initial = ([|Rook,Black,Alive(A,8); (*... *)|])
method print =
for i = 0 to i = 7 do
for j = 0 to j = 32 do
if initial.(j) = (Pawn,White,Alive(A,i)) then tmp1="P" else
if initial.(j) = (Pawn,Black,Alive(A,i)) then tmp1="p" else
if initial.(j) = (Rook,White,Alive(A,i)) then tmp1="R" else
if initial.(j) = (Rook,Black,Alive(A,i)) then tmp1="r" else
if initial.(j) = (Knight,White,Alive(A,i)) then tmp1="N" else
if initial.(j) = (Knight,Black,Alive(A,i)) then tmp1="n" else
if initial.(j) = (Bishop,White,Alive(A,i)) then tmp1="B" else
if initial.(j) = (Bishop,Black,Alive(A,i)) then tmp1="b" else
if initial.(j) = (Queen,White,Alive(A,i)) then tmp1="Q" else
if initial.(j) = (Queen,Black,Alive(A,i)) then tmp1="q" else
if initial.(j) = (King,White,Alive(A,i)) then tmp1="K" else
if initial.(j) = (King,Black,Alive(A,i)) then tmp1="k" else
tmp1=".";
print_string tmp1;
done
done
end
In the case of normal chess starting positions where the row is white,this should print out:
RNBQKBNR
I'm getting an error of unbound value i and i cant understand why.
On a side note,any advice on classes and methods is appreciated since i'm trying to learn this and currently suck at it.
This line:
for i = 0 to i = 7 do
is not legitimate. It parses as this:
for i = 0 to (i = 7) do
The second expression compares i against 7 for equality. But at that point there is no i defined yet. i is only defined in the body of the for loop.
You want to say:
for i = 1 to 7 do

Keeping Score in Swift 3

I honestly can't figure out what I am doing wrong. I have tried every solution I can think of. I am honestly hoping it is something very simple. Anyway, this is my code that I currently have
#IBOutlet var tacScore: UILabel!
#IBOutlet var ticScore: UILabel!
var winCounter = 0
if gameState[combination[0]] == 1 {
winnerLabel.text = "Tac Wins!"
ticScore.text = "Tic:\(winCounter += 1)"
} else {
winnerLabel.text = "Tic Wins!"
ticScore.text = "Tic:\(winCounter += 1)"
}
I don't get an error at all, but when someone wins in my game, the score labels just change too Tic:() and Tac:()
Your code suppose to be like this:
var winCounter = 0
if gameState[combination[0]] == 1 {
winnerLabel.text = "Tac Wins!"
winCounter += 1
tacScore.text = "Tic:\(winCounter)"
}else{
winnerLabel.text = "Tic Wins!"
winCounter += 1
ticScore.text = "Tic:\(winCounter)"
}
The reason here is that the expression will be doing after the string returned to the .text pointer. All you need to do is just count it up first, then update the label.

generating TTT game tree in lua

I am attempting to write a tic-tac-toe game in lua, and plan on using the minimax algorithm to decide non-human moves. The first step in this involves generating a tree of all possible board states from a single input state. I am trying to recursively do this, but cannot seem to figure out how. (I think) I understand conceptually how this should be done, but am having trouble implementing it in lua.
I am trying to structure my tree in the following manner. Each node is a list with two fields.
{ config = {}, children = {} }
Config is a list of integers (0,1,2) that represent empty, X, and O and defines a TTT board state. Children is a list nodes which are all possible board states one move away from the current node.
Here is my function that I currently have to build the game tree
function tree_builder(board, player)
supertemp = {}
for i in ipairs(board.config) do
--iterate through the current board state.
--for each empty location create a new node
--representing a possible board state
if board.config[i] == 0 then
temp = {config = {}, children = {}}
for j in ipairs(board.config) do
temp.config[j] = board.config[j]
end
temp.config[i] = player
temp.children = tree_builder(temp, opposite(player))
supertemp[i] = temp
end
end
return supertemp
end
The function is called in the following manner:
start_board = {config = {1,0,0,0}, children = {} }
start_board.children = tree_builder(start_board, 1)
When I comment out the recursive element of the function (the line "temp.children = builder(temp, opposite(player))") and only generate the first level of children. the output is correct. When called via code that is conceptually identical to (I am using love2D so formatting is different):
for i in pairs(start_board.children) do
print (start_board.children[i].config)
The three children are:
1,1,0,0
1,0,1,0
1,0,0,1
However, once I add the recursive element, the following is output for the same three children
1,1,2,1
1,1,2,1
1,1,2,1
I have been searching online for help and most of what I have found is conceptual in nature or involves implementation in different languages. I believe I have implemented the recursive element wrongly, but cannot wrap my head around the reasons why.
Don't understand what opposite(player) means in temp.children = tree_builder(temp, opposite(player)).
Notice that a recursion need an end condition.
This is my solution under your structure:
local COL = 3
local ROW = 3
local function printBoard( b )
local output = ""
local i = 1
for _,v in ipairs(b.config) do
output = output .. v .. ( (i % COL == 0) and '\n' or ',' )
i = i + 1
end
print( output )
end
local function shallowCopy( t )
local t2 = {}
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
local MAX_STEP = COL * ROW
local ING = 0
local P1 = 1
local P2 = 2
local TIE = 3
local STATUS = { [P1] = "P1 Win", [P2] = "P2 Win", [TIE] = "Tied" }
local start_board = { config = {P1,0,0,0,0,0,0,0,0}, children = {} }
local function checkIfOver( board, step )
local config = board.config
local over = false
--check rows
for i=0,ROW-1 do
over = true
for j=1,COL do
if 0 == config[i*COL+1] or config[i*COL+j] ~= config[i*COL+1] then
over = false
end
end
if over then
return config[i*COL+1]
end
end
--check cols
for i=1,COL do
over = true
for j=0,ROW-1 do
if 0 == config[i] or config[i] ~= config[i+COL*j] then
over = false
end
end
if over then
return config[i]
end
end
--check diagonals
if config[1] ~= 0 and config[1] == config[5] and config[5] == config[9] then
return config[1]
end
if config[3] ~=0 and config[3] == config[5] and config[5] == config[7] then
return config[3]
end
if step >= MAX_STEP then
return TIE
else
return ING
end
end
local function treeBuilder( board, step )
--check the game is over
local over = checkIfOver( board, step )
if over ~= ING then
printBoard( board )
print( STATUS[over], '\n---------\n' )
return
end
local child
local childCfg
for i,v in ipairs(board.config) do
if 0 == v then
child = { config = {}, children = {} }
childCfg = shallowCopy( board.config )
childCfg[i] = (step % 2 == 0) and P1 or P2
child.config = childCfg
table.insert( board.children, child )
treeBuilder( child, step + 1 )
end
end
end
treeBuilder( start_board, 1 )

Resources