code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
__version__ = "0.1.1"
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/_version.py | _version.py |
from setuptools import setup
setup(name="SevenWonEnv", version="0.0.1", install_requires=["gymnasium==0.27.1", "numpy"])
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/setup.py | setup.py |
from gymnasium.envs.registration import register
register(
id="SevenWonderEnv-v0",
entry_point="SevenWonEnv.envs:SevenWonderEnv",
)
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/__init__.py | __init__.py |
import gymnasium as gym
import sys
import copy
from gymnasium import error, spaces, utils
from gymnasium.utils import seeding
import numpy as np
import json
import random
from operator import itemgetter
from SevenWonEnv.envs.mainGameEnv.mainHelper import filterPlayer, buildCard, rotateHand
from SevenWonEnv.envs.mainGameEnv.PlayerClass import Player
from SevenWonEnv.envs.mainGameEnv.WonderClass import Wonder
from SevenWonEnv.envs.mainGameEnv.resourceClass import Resource
from SevenWonEnv.envs.mainGameEnv.Personality import (
Personality,
RandomAI,
RuleBasedAI,
Human,
DQNAI,
)
from SevenWonEnv.envs.mainGameEnv.stageClass import Stage
EnvAmount = 0
class SevenWonderEnv(gym.Env):
#Private helper methods
def __loadWonder(self):
fileOper = open("mainGameEnv/Card/wonders_list.json", "rt")
wonderList = json.load(fileOper)
wonderList = wonderList["wonders"]
wonderName = list(wonderList.keys())
fileOper.close()
return wonderList, wonderName
def __actionToCode(self, cardCode, actionCode):
return cardCode * 4 + actionCode
def __codeToAction(self, action):
cardCode = int(action / 4)
actionCode = action % 4
# convert cardCode and actionCode to ones that can be used in step
card = self.dictCard[cardCode]
playlist = self.dictPlay[actionCode]
return card, playlist
def __initActionSpace(self):
counter = 0
fileOper = open("mainGameEnv/Card/card_list.json", "rt")
cardList = json.load(fileOper)
for age in cardList:
for playerNum in cardList[age]:
for color in cardList[age][playerNum]:
for card in cardList[age][playerNum][color]:
if not card["name"] in self.dictCard.values():
self.dictCard[counter] = card["name"]
counter += 1
for key, value in self.dictCard.items():
self.dictCardToCode[value] = key
# for (key,value) in self.dictCardToCode.items():
# print(key,value)
fileOper.close()
# [playStatus,wonder,side,stage] for each card.
self.dictPlay[0] = [0, None, None, None] # playStatus 0 = play with paying cost
self.dictPlay[1] = [
1,
None,
None,
None,
] # playStatus 1 = play with effect freeStructure
self.dictPlay[2] = [
-1,
None,
None,
None,
] # playStatus -1 = discard the card for 3 coins
self.dictPlay[3] = [2, None, None, None] # upgrade wonders
fileOper.close()
metadata = {"render.modes": ["human"]}
def __addPlayer(self, personality):
assignNumber = self.player - self.unAssignedPersonality + 1
self.playerList[assignNumber].assignPersonality(personality)
self.unAssignedPersonality -= 1
print("Player {} is ".format(assignNumber), personality)
def __initGameNPerson(self, player):
self.unAssignedPersonality = player
fileOper = open("mainGameEnv/Card/card_list.json", "rt")
cardList = json.load(fileOper)
cardAge = []
for i in range(1, 4):
cardAge.append(self.getCardAge("age_" + str(i), player, cardList))
fileOper.close()
wonderList, wonderName = self.__loadWonder()
random.shuffle(wonderName)
wonderSelected = wonderName[0:player]
playerList = {}
for i in range(1, player + 1):
newPlayer = Player(i, player, Human)
side = "A" if random.randrange(2) % 2 == 0 else "B"
wonderCurName = wonderSelected[i - 1]
wonderCur = wonderList[wonderCurName]
initialResource = Resource(wonderCur["initial"]["type"], wonderCur["initial"]["amount"])
newWonders = Wonder(wonderCurName, side, initialResource, **wonderList[wonderCurName][side])
newPlayer.assignWonders(newWonders)
playerList[i] = newPlayer
for i in range(1, player + 1):
curPlayer = playerList[i]
playerList[i].assignLeftRight(playerList[curPlayer.left], playerList[curPlayer.right])
print("SETUP COMPLETE")
return cardAge, playerList
def __stateGenerator(self, playerNum):
state = []
for resourceAmount in self.playerList[playerNum].resource.values():
state.append(resourceAmount)
for colorAmount in self.playerList[playerNum].color.values():
state.append(colorAmount)
for eastPrice in self.playerList[playerNum].eastTradePrices.values():
state.append(eastPrice - 1)
for westPrice in self.playerList[playerNum].westTradePrices.values():
state.append(westPrice - 1)
state.append(self.playerList[playerNum].coin)
for resourceAmount in self.playerList[playerNum].left.resource.values():
state.append(resourceAmount)
for colorAmount in self.playerList[playerNum].left.color.values():
state.append(colorAmount)
for resourceAmount in self.playerList[playerNum].right.resource.values():
state.append(resourceAmount)
for colorAmount in self.playerList[playerNum].right.color.values():
state.append(colorAmount)
state.append(self.age - 1)
return state
def printPersonality(self):
for i in range(1, self.player + 1):
print(self.playerList[i].personality)
def __stepActionDict(self):
actionDict = {}
for i in range(1, self.player + 1):
card, action = self.playerList[i].playCard(self.age)
actionDict[i] = self.__actionToCode(card, action)
return actionDict
def __illegalAction(self, action, playerNum):
cardName, actionList = self.__codeToAction(action)
card = self.playerList[playerNum].findCardFromHand(cardName)
info = {}
done = False
reward = 0
if card is None:
return True # Card not on hand
if self.specialAction != 0: # extraTurn from card effect
if self.specialAction == 1: # buildDiscarded
if actionList[0] != 0:
return True # illegal action. A card must be played, not used for wonders or discarded.
elif self.specialAction == 2: # playSeventhCard. Still have to pay (if needed)
if actionList[0] == 2 and self.playerList[playerNum].wonders.stage + 1 >= len(
self.playerList[playerNum].wonders.step
):
return True # illegal action. Can't upgrade wonders if it's already maxed
if actionList[0] == 2 and self.playerList[playerNum].wonders.stage + 1 >= len(
self.playerList[playerNum].wonders.step
):
return True # illegal action. Can't upgrade wonders if it's already maxed
return False
def __rewardCalculation(self, action, playerNum):
cardName, actionList = self.__codeToAction(action)
player = self.playerList[playerNum]
card = player.findCardFromHand(cardName)
info = {}
done = False
reward = 0
if self.__illegalAction(action, playerNum):
state = self.__stateGenerator(playerNum)
vecState = np.array(state).reshape((70,))
return vecState, -10000, done, info
left, right = player.playable(card)
if self.specialAction != 0: # extraTurn from card effect
if self.specialAction == 1: # buildDiscarded
left, right = (0, 0)
selectedCard = [card, left, right, actionList[0]]
cardGet, action = player.playChosenCard(selectedCard)
player.assignHand(copy.deepcopy(self.tempCardList))
self.specialAction = 0
player.endTurnEffect = None
# specialAction=2 : playSeventhCard. Still have to pay (if needed)
else:
if actionList[0] != 2: # discard/play
selectedCard = [card, left, right, actionList[0]]
else: # use for upgrade
selectedCard = [
player.wonders.step[player.wonders.stage + 1],
left,
right,
0,
card,
]
cardGet, action = player.playChosenCard(selectedCard)
self.specialAction = 0
state = self.__stateGenerator(playerNum)
vecState = np.array(state).reshape((70,))
if self.turn == 6 and "extraPlay" not in info.keys():
for j in range(len(self.playerList)):
self.discarded.append(self.playerList[j + 1].hand[0])
# print(self.playerList[j + 1].hand)
if player.endAgeEffect == "playSeventhCard":
info["extraPlay"] = "playSeventhCard"
self.specialAction = 2
if self.age == 3 and "extraPlay" not in info.keys():
endScore = []
for i in range(len(self.playerList)):
endScore.append((i + 1, self.playerList[i + 1].endGameCal()))
endScore = sorted(endScore, key=itemgetter(1), reverse=True)
# for (key, value) in endScore:
# print("Player {} score {}".format(key, value))
for i in range(len(endScore)):
key = endScore[i][0]
# print(key)
if key == playerNum: # endScore[i] is DQN, not RBAI
if i == 0:
reward = 1.5
elif i == 1:
reward = 0.5
elif i == 2:
reward = -0.5
elif i == 3:
reward = -1.5
done = True
elif not "extraPlay" in info.keys(): # end Age
self.age += 1
self.turn = 0
for i in range(len(self.playerList)):
self.playerList[i + 1].assignHand(self.cardShuffled[self.age - 1][i])
if any("freeStructure" in effect for effect in self.playerList[i + 1].endAgeEffect):
self.playerList[i + 1].freeStructure = True
return vecState, reward, done, info
else:
self.turn += 1
if actionList[0] != 2: # discard/play
if actionList[0] == 1: # play with effect = no cost
player.freeStructure = False
left, right = (0, 0)
selectedCard = [card, left, right, actionList[0]]
else:
selectedCard = [
player.wonders.step[player.wonders.stage + 1],
left,
right,
0,
card,
]
cardGet, action = player.playChosenCard(selectedCard)
if action == -1:
self.discarded.append(card)
state = self.__stateGenerator(playerNum)
vecState = np.array(state).reshape((70,))
return vecState, reward, done, info
#Public methods
def __init__(self, player):
"""
Initialize the environment with given amount of player
Args:
player: amount of player
"""
global EnvAmount
super(SevenWonderEnv, self).__init__()
self.player = player
self.dictPlay = {}
self.dictCard = {}
self.dictCardToCode = {}
self.personalityList = []
self.__initActionSpace()
path = "GameLog/gameLog" + str(EnvAmount) + ".txt"
EnvAmount = EnvAmount + 1
# sys.stdout = open(path, 'w')
# action space
# 75 unique cards to play * (play(2, use effect FREESTRUCTURE and NOT use effect) + discard(1) + upgradeWonder(1) = 4 action per card) = 300 total actions
# action = 4*cardCode + actionCode
self.action_space = spaces.Discrete(300)
# observation space
# resourceAmountOwn(11) + colorAmountOwn(7)+ownEastTradingCost(7)+ownWestTradingCost(7)+ coin (1) resourceAmountLeft(11)+colorAmountLeft(7)
# +resourceAmountRight(11)+colorAmountRight(7)+AgeNumber(1)
# =observation_space of 70
obserSpaceSize = (
([5] * 10 + [20] + [10] * 7 + [2] * 7 + [2] * 7 + [100])
+ ([5] * 10 + [20] + [10] * 7)
+ ([5] * 10 + [20] + [10] * 7)
+ [3]
)
self.observation_space = spaces.MultiDiscrete(obserSpaceSize)
self.discarded = []
self.cardAge = None
self.playerList = None
self.age = 1
self.turn = 0
self.cardShuffled = []
self.specialAction = 0
self.tempCardList = []
self.unAssignedPersonality = 0
self.cardAge, self.playerList = self.__initGameNPerson(self.player)
for ageNum in range(1, 4):
cardThisAge = self.cardAge[ageNum - 1]
random.shuffle(cardThisAge)
self.cardShuffled.append([cardThisAge[i : i + 7] for i in range(0, len(cardThisAge), 7)])
for i in range(len(self.cardShuffled[0])):
self.playerList[i + 1].assignHand(self.cardShuffled[0][i])
print("Setup complete")
def setPersonality(self, personalityList):
"""
Set the personality for each player.
Args:
personalityList: List[Personality]
"""
self.personalityList = personalityList
for personality in personalityList:
if self.unAssignedPersonality == 0:
sys.exit("Program Stopped : Add too many players' personality")
self.__addPlayer(personality)
def getCardAge(self, age, player, cardList):
jsonAge = filterPlayer(cardList[age], player)
cardAge = []
for color in jsonAge:
for card in jsonAge[color]:
card = buildCard(card["name"], color, card["payResource"], card["getResource"])
cardAge.append(card)
return cardAge
def step(self, action):
"""
Proceed one turn of the game.
Args:
action: 0 by default.
Returns:
List[tuple] containing (new_state, reward, done, info)
"""
if self.unAssignedPersonality != 0:
sys.exit("Program Stopped : Some Players do not have personality.")
rewardAll = []
for j in range(0, len(self.playerList)):
card, action = self.playerList[j + 1].playCard(self.age)
print("Card, action", card, action)
actionCode = self.__actionToCode(self.dictCardToCode[card.name], action)
vecState, reward, done, info = self.__rewardCalculation(actionCode, j + 1)
rewardAll.append((vecState, reward, done, info))
if action == -1: # card discarded
self.discarded.append(card)
print("PLAYER {} discard {}".format(j + 1, card.name))
elif action == 2:
print("PLAYER {} upgrade wonders to stage {}".format(j + 1, self.playerList[j + 1].wonders.stage))
else:
print("PLAYER {} play {}".format(j + 1, card.name))
rotateHand(self.playerList, self.age)
for j in range(len(self.playerList)):
player = self.playerList[j + 1]
if player.endTurnEffect == "buildDiscarded":
if not self.discarded:
continue
# print("DISCARDED")
# for dis in self.discarded:
# print(dis.name)
if j == 0:
info["extraPlay"] = "buildDiscarded"
self.specialAction = 1
self.tempCardList = copy.deepcopy(player.hand)
player.hand = self.discarded
else:
card, action = player.playFromEffect(self.discarded, player.endTurnEffect, self.age)
removeCard = None
for disCard in self.discarded:
if disCard.name == card.name:
removeCard = disCard
break
self.discarded.remove(removeCard)
# print("BEFORE AGE" + str(self.age) + "TURN" + str(self.turn))
# for playerNum in self.playerList:
# playerCur = self.playerList[playerNum]
# print("Player " + str(playerCur.player))
# print("Card")
# for card in playerCur.hand:
# print(card.name)
if self.turn == 6 and not "extraPlay" in info.keys():
for j in range(len(self.playerList)):
self.discarded.append(self.playerList[j + 1].hand[0])
# print(self.playerList[j + 1].hand)
if self.playerList[1].endAgeEffect == "playSeventhCard":
info["extraPlay"] = "playSeventhCard"
self.specialAction = 2
if self.age == 3 and not "extraPlay" in info.keys():
endScore = []
for i in range(len(self.playerList)):
endScore.append((i + 1, self.playerList[i + 1].endGameCal()))
endScore = sorted(endScore, key=itemgetter(1), reverse=True)
for key, value in endScore:
print("Player {} score {}".format(key, value))
for i in range(len(endScore)):
key = endScore[i][0]
print(key)
if key == 1: # endScore[i] is DQN, not RBAI
if i == 0:
reward = 1.5
elif i == 1:
reward = 0.5
elif i == 2:
reward = -0.5
elif i == 3:
reward = -1.5
done = True
elif "extraPlay" not in info.keys(): # end Age
self.age += 1
self.turn = 0
for i in range(len(self.playerList)):
self.playerList[i + 1].assignHand(self.cardShuffled[self.age - 1][i])
if any("freeStructure" in effect for effect in self.playerList[i + 1].endAgeEffect):
self.playerList[i + 1].freeStructure = True
# print("AFTER AGE" + str(self.age) + "TURN" + str(self.turn))
# for playerNum in self.playerList:
# playerCur = self.playerList[playerNum]
# print("Player " + str(playerCur.player))
# print("Card")
# for card in playerCur.hand:
# print(card.name)
# print("special " + str(self.specialAction))
return rewardAll
def legalAction(self, playerNum):
"""
Given the player number, return all legal actions as a list of action code
Args:
playerNum: The position of player (1-n)
Returns:
List[actionCode]
"""
player = self.playerList[playerNum]
actionCode = range(4)
posAct = []
for card in player.hand:
if self.specialAction == 1: # play from discard
posAct.append(self.__actionToCode(self.dictCardToCode[card.name], 0))
continue
for action in actionCode:
if action == 2: # discard is always available
posAct.append(self.__actionToCode(self.dictCardToCode[card.name], action))
if action == 0: # pay normally
left, right = player.playable(card)
if left != -1 and right != -1:
posAct.append(self.__actionToCode(self.dictCardToCode[card.name], action))
if action == 1: # pay with effect freeStructure
if player.freeStructure:
posAct.append(self.__actionToCode(self.dictCardToCode[card.name], action))
if action == 3:
steps = player.wonders.step
existedStage = player.wonders.stage + 1
# print(type(steps[existedStage]))
if existedStage < len(steps):
left, right = player.playable(steps[existedStage])
if left != -1 and right != -1:
posAct.append(self.__actionToCode(self.dictCardToCode[card.name], action))
return posAct
def reset(self, seed=None, options=None):
"""
Reset the environment after each episode
Args:
seed: Seed ID for randomization
options: Default to None
Returns:
List[State]
"""
self.age = 1
self.turn = 0
self.cardShuffled = []
self.discarded = []
self.cardAge, self.playerList = self.__initGameNPerson(self.player)
self.setPersonality(self.personalityList)
for ageNum in range(1, 4):
cardThisAge = self.cardAge[ageNum - 1]
random.shuffle(cardThisAge)
self.cardShuffled.append([cardThisAge[i : i + 7] for i in range(0, len(cardThisAge), 7)])
for i in range(len(self.cardShuffled[0])):
self.playerList[i + 1].assignHand(self.cardShuffled[0][i])
state = self.__stateGenerator(1)
vecState = np.array(state).reshape((70,))
# (vecState.shape)
return vecState
def render(self, mode="human"):
pass
def close(self):
pass
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/SevenWonderEnv.py | SevenWonderEnv.py |
from SevenWonEnv.envs.SevenWonderEnv import SevenWonderEnv
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/__init__.py | __init__.py |
import random
from sys import stdin
from copy import deepcopy
from SevenWonEnv.envs.mainGameEnv.stageClass import Stage
from SevenWonEnv.envs.mainGameEnv.cardClass import Card
class Personality:
def __init__(self):
pass
def make_choice(self, player, age, options):
pass
class DQNAI(Personality): # placeholder
def __init__(self):
super().__init__()
def make_choice(self, player, age, options):
pass
class RuleBasedAI(Personality):
def __init__(self):
super().__init__()
def make_choice(self, player, age, options):
# return random.choice(range(len(options)))
for choicesIndex in range(len(options)):
if isinstance(options[choicesIndex][0], Stage): # If stage is free, buy it. 50% to buy if it's not free.
if options[choicesIndex][1] + options[choicesIndex][2] == 0 or random.randint(0, 1) % 2 == 0:
return choicesIndex
else:
continue
# options[choicesIndex[3]] is play code. If it's -1, it means discarded. 0 is play with paying, 1 is play with effect.
if age < 3:
posChoice = []
nonDiscard = []
for choicesIndex in range(len(options)):
if options[choicesIndex][3] != -1:
nonDiscard.append(choicesIndex)
nonDiscarded = [option for option in options if option[3] != -1]
if not nonDiscarded: # have only choice by discarding
return random.choice(range(len(options)))
for choicesIndex in range(
len(options)
): # Select Card that gives more than 1 resource. If there are multiple cards, select one randomly
if type(options[choicesIndex][0]).__name__ == "Card":
if options[choicesIndex][0].getResource["type"] == "mixed" and options[choicesIndex][3] != -1:
posChoice.append(choicesIndex)
if posChoice:
return random.choice(posChoice)
for choicesIndex in range(
len(options)
): # Select Card that can be selected between resource. If there are multiple cards, select one randomly
if isinstance(options[choicesIndex][0], Card):
if options[choicesIndex][0].getResource["type"] == "choose" and options[choicesIndex][3] != -1:
posChoice.append(choicesIndex)
if posChoice:
return random.choice(posChoice)
zeroRes = {key: value for (key, value) in player.resource.items() if value == 0 and key != "shield"}
for choicesIndex in range(
len(options)
): # Select resource that does not have yet (0 resource) except military. If there are multiple cards, select one randomly
if isinstance(options[choicesIndex][0], Card):
for res in zeroRes.keys():
if options[choicesIndex][0].getResource["type"] == res and options[choicesIndex][3] != -1:
posChoice.append(choicesIndex)
if posChoice:
return random.choice(posChoice)
if not (
player.resource["shield"] > player.left.resource["shield"]
or player.resource["shield"] > player.right.resource["shield"]
):
for choicesIndex in range(
len(options)
): # Select military IF it makes player surpass neighbors in shield. If there are multiple cards, select one randomly
if isinstance(options[choicesIndex][0], Card):
if options[choicesIndex][0].getResource["type"] == "shield" and options[choicesIndex][3] != -1:
shieldPts = options[choicesIndex][0].getResource["amount"]
if (
player.resource["shield"] + shieldPts > player.left.resource["shield"]
or player.resource["shield"] + shieldPts > player.right.resource["shield"]
):
posChoice.append(choicesIndex)
if posChoice:
return random.choice(posChoice)
for choicesIndex in range(len(options)): # Select science card. If there are multiple cards, select one.
if isinstance(options[choicesIndex][0], Card):
if options[choicesIndex][0].color == "green" and options[choicesIndex][3] != -1:
posChoice.append(choicesIndex)
if posChoice:
return random.choice(posChoice)
for choicesIndex in range(len(options)): # Select VP (civil) card. If there are multiple cards, select one.
if isinstance(options[choicesIndex][0], Card):
if options[choicesIndex][0].getResource["type"] == "VP" and options[choicesIndex][3] != -1:
if not posChoice:
posChoice.append(choicesIndex)
elif (
options[posChoice[0]][0].getResource["amount"]
< options[choicesIndex][0].getResource["amount"]
):
posChoice = [choicesIndex]
if posChoice:
return random.choice(posChoice)
# play random non-discarded choice
return random.choice(nonDiscard)
else: # age 3. Simulate all plays, greedy by most points.
basePoints = player.endGameCal()
gainPoints = -1
selected = []
for choicesIndex in range(len(options)):
afterPlayer = deepcopy(player)
afterPlayer.hand = deepcopy(player.hand)
# print("HAND")
# print(len(afterPlayer.hand))
# print(choicesIndex)
# print(options[choicesIndex])
afterPlayer.playChosenCardFake(options[choicesIndex])
addPoints = afterPlayer.endGameCal() - basePoints
if addPoints < 0:
print("WRONG")
if addPoints > gainPoints:
selected = [choicesIndex]
gainPoints = addPoints
elif addPoints == gainPoints:
selected.append(choicesIndex)
if selected:
return random.choice(selected)
else:
return random.choice(range(len(options)))
class Human(Personality):
def __init__(self):
super().__init__()
def make_choice(self, player, age, options):
return int(stdin.readline())
class RandomAI(Personality):
def __init__(self):
super().__init__()
def make_choice(self, player, age, options):
return random.choice(range(len(options)))
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/Personality.py | Personality.py |
class Card:
def __init__(self, name, color, payResource, getResource):
self.name = name
self.color = color
self.payResource = payResource
self.getResource = getResource
def printCard(self):
print("name:" + self.name)
print(self.payResource)
print(self.getResource)
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/cardClass.py | cardClass.py |
class Stage:
def __init__(self, number, payResource, getResource):
self.stage = number
self.payResource = payResource
self.getResource = getResource
def printStage(self):
print("step:" + str(self.stage))
print(self.payResource)
print(self.getResource)
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/stageClass.py | stageClass.py |
class Resource:
def __init__(self, resource, amount):
self.resource = resource
self.amount = amount
def printResource(self):
print(self.__dict__)
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/resourceClass.py | resourceClass.py |
import json
import random
from operator import itemgetter
from SevenWonEnv.envs.mainGameEnv.mainHelper import (
filterPlayer,
buildCard,
rotateHand,
battle,
)
from SevenWonEnv.envs.mainGameEnv.PlayerClass import Player
from SevenWonEnv.envs.mainGameEnv.WonderClass import Wonder
from SevenWonEnv.envs.mainGameEnv.resourceClass import Resource
from SevenWonEnv.envs.mainGameEnv.Personality import RuleBasedAI
from SevenWonEnv.envs.mainGameEnv.stageClass import Stage
import sys
def init(player):
fileOper = open("Card/card_list.json", "rt")
cardList = json.load(fileOper)
cardAge = []
for i in range(1, 4):
cardAge.append(getCardAge("age_" + str(i), player, cardList))
fileOper = open("Card/wonders_list.json", "rt")
wonderList = json.load(fileOper)
wonderList = wonderList["wonders"]
wonderName = list(wonderList.keys())
random.shuffle(wonderName)
wonderSelected = wonderName[0:player]
# print(wonderSelected)
# print(wonderList['Rhodes'])
playerList = {}
for i in range(1, player + 1):
newPlayer = Player(i, player, RuleBasedAI)
side = "A" if random.randrange(2) % 2 == 0 else "B"
wonderCurName = wonderSelected[i - 1]
wonderCur = wonderList[wonderCurName]
initialResource = Resource(wonderCur["initial"]["type"], wonderCur["initial"]["amount"])
# print(type(wonderList[wonderCurName][side]))
newWonders = Wonder(wonderCurName, side, initialResource, **wonderList[wonderCurName][side])
newPlayer.assignWonders(newWonders)
playerList[i] = newPlayer
for i in range(1, player + 1):
curPlayer = playerList[i]
playerList[i].assignLeftRight(playerList[curPlayer.left], playerList[curPlayer.right])
print("SETUP COMPLETE")
return cardAge, playerList
def getCardAge(age, player, cardList):
jsonAge = filterPlayer(cardList[age], player)
cardAge = []
for color in jsonAge:
for card in jsonAge[color]:
card = buildCard(card["name"], color, card["payResource"], card["getResource"])
cardAge.append(card)
return cardAge
if __name__ == "__main__":
discarded = []
logger = open("loggers.txt", "w+")
player = input("How many players?")
player = int(player)
path = "../gameLog.txt"
sys.stdout = open(path, "w")
cardAge, playerList = init(player)
for player in playerList.keys():
print("Player {} with wonders {}".format(player, playerList[player].wonders.name))
for age in range(1, 4):
cardThisAge = cardAge[age - 1]
random.shuffle(cardThisAge)
cardShuffled = [cardThisAge[i : i + 7] for i in range(0, len(cardThisAge), 7)]
for i in range(len(cardShuffled)):
if any("freeStructure" in effect for effect in playerList[i + 1].endAgeEffect):
playerList[i + 1].freeStructure = True
playerList[i + 1].assignHand(cardShuffled[i])
for i in range(0, 6):
for j in range(len(playerList)):
# print("j" + str(j))
card, action = playerList[j + 1].playCard(age)
if action == -1: # card discarded
discarded.append(card)
print("PLAYER {} discard {}".format(j + 1, card.name))
elif isinstance(card, Stage):
print("PLAYER {} play step {}".format(j + 1, card.stage))
else:
print("PLAYER {} play {}".format(j + 1, card.name))
rotateHand(playerList, age)
for j in range(len(playerList)):
print("PLAYER {} resource".format(j + 1), end=" ")
for res in playerList[j + 1].resource:
print(res, playerList[j + 1].resource[res], end=" ")
print()
for j in range(len(playerList)):
player = playerList[j + 1]
if player.endTurnEffect == "buildDiscarded":
card, action = player.playFromEffect(discarded, player.endTurnEffect, age=age)
discarded = [disCard for disCard in discarded if disCard.name != card.name]
print("REMAINING HANDS")
for j in range(len(playerList)):
discarded.append(playerList[j + 1].hand[0])
print(playerList[j + 1].hand)
print("AGE" + str(age))
for j in range(len(playerList)):
playerList[j + 1].printPlayer()
# military conflict
for j in range(1, 1 + len(playerList)):
battle(playerList[j], playerList[j % len(playerList) + 1], age)
# end game period
endScore = []
for i in range(len(playerList)):
endScore.append((i + 1, playerList[i + 1].endGameCal()))
endScore = sorted(endScore, key=itemgetter(1), reverse=True)
print("SCOREBOARD")
for i in endScore:
print("Player {} with score {}".format(i[0], i[1]))
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/main.py | main.py |
from SevenWonEnv.envs.mainGameEnv.stageClass import Stage
class Wonder:
def __init__(self, name, side, beginResource, **kwargs):
self.name = name
self.side = side
self.stage = 0
self.step = {}
self.beginResource = beginResource
steps = kwargs
# print(len(steps))
for level in steps:
# print("build level : {}".format(level))
levelNum = int(level[6])
self.step[levelNum] = Stage(levelNum, kwargs[level]["payResource"], kwargs[level]["getResource"])
def printWonder(self):
print(self.__dict__)
self.beginResource.printResource()
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/WonderClass.py | WonderClass.py |
from SevenWonEnv.envs.mainGameEnv.resourceClass import Resource
from SevenWonEnv.envs.mainGameEnv.cardClass import Card
from SevenWonEnv.envs.mainGameEnv.stageClass import Stage
from SevenWonEnv.envs.mainGameEnv import mainHelper
import operator
class ResourceBFS:
def __init__(self, accuArr, remainArr):
self.accuArr = accuArr
self.remainArr = remainArr
class Player:
def __init__(self, playerNumber, totalPlayer, person):
self.player = playerNumber
self.card = []
self.choosecard = []
self.chooseStage = []
self.coin = 3
self.warVP = 0
self.warLoseVP = 0
self.color = dict.fromkeys(["brown", "grey", "blue", "yellow", "red", "green", "purple"], 0)
self.eastTradePrices = dict.fromkeys(["wood", "clay", "ore", "stone", "papyrus", "glass", "loom"], 2)
self.westTradePrices = self.eastTradePrices.copy()
self.resource = dict.fromkeys(
[
"wood",
"clay",
"ore",
"stone",
"papyrus",
"glass",
"loom",
"compass",
"wheel",
"tablet",
"shield",
],
0,
)
self.VP = 0
self.wonders = None
self.left = (playerNumber - 2) % totalPlayer + 1
self.right = playerNumber % totalPlayer + 1
self.hand = []
self.lastPlayColor = None
self.lastPlayEffect = None
self.endAgeEffect = []
self.endGameEffect = []
self.personality = person
self.freeStructure = False
self.endTurnEffect = None
def assignPersonality(self, personality):
self.personality = personality
def assignWonders(self, wonder):
self.wonders = wonder
beginRes = wonder.beginResource
self.resource[beginRes.resource] += beginRes.amount
def assignLeftRight(self, leftPlayer, rightPlayer):
self.left = leftPlayer
self.right = rightPlayer
def printPlayer(self):
print(self.__dict__)
self.wonders.printWonder()
for card in self.card:
print(card.name, end=" ")
def assignHand(self, hand):
self.hand = hand
def cardExist(self, name):
for singleCard in self.card:
if singleCard.name == name:
return True
return False
def resourceExist(self, resourceType): # Use in case of neighbor Player
if self.resource[resourceType] > 0:
return True
for card in self.choosecard:
for choose in card.getResource["resource"]:
if choose["type"] == resourceType:
return True
return False
def checkLeftRight(self, amount, resourceType):
leftPrice = self.westTradePrices[resourceType]
rightPrice = self.eastTradePrices[resourceType]
minPrice = 10000000
side = "M"
if self.coin >= leftPrice * amount and self.left.resourceExist(resourceType):
minPrice = leftPrice * amount
side = "L"
if self.coin >= rightPrice * amount and self.right.resourceExist(resourceType):
if minPrice > rightPrice * amount:
minPrice = rightPrice * amount
side = "R"
if side == "M":
return -1, side
return minPrice, side
def addiResComp(self, targetArr, curResArr):
# print("BEFORE")
# for i in targetArr:
# i.printResource()
for res in curResArr:
name = res.resource
# print("Name" + name)
for tar in targetArr:
if name == tar.resource:
tar.amount -= res.amount
targetArr = [i for i in targetArr if i.amount > 0]
# print("AFTER")
# for i in targetArr:
# i.printResource()
return targetArr
def BFS(self, targetArray, resourceArray):
queue = []
minLeft = 10000000
minRight = 10000000
queue.append(ResourceBFS([], resourceArray))
while queue:
left = 0
right = 0
price = -1
side = "M"
# print(queue[0])
qFront = queue[0]
curRes = qFront.accuArr
# print(curRes)
remainRes = qFront.remainArr
# print("REMAINRES")
# print(remainRes)
remainArr = self.addiResComp(targetArray[:], curRes[:])
for remain in remainArr:
price, side = self.checkLeftRight(remain.amount, remain.resource)
if price == -1:
break
if side == "L":
left += price
elif side == "R":
right += price
if price != -1 and left + right < minLeft + minRight:
minLeft = left
minRight = right
queue.pop(0)
if remainRes:
resChooseCard = remainRes[0]
for res in resChooseCard.getResource["resource"]:
# print("RES")
# print(res)
selectRes = mainHelper.resBuild(res)
newResAccu = curRes[:]
newResAccu.append(selectRes)
# print('NewResAccu : {}'.format(newResAccu))
newRemRes = remainRes[1:]
if newRemRes is None:
newRemRes = []
queue.append(ResourceBFS(newResAccu, newRemRes))
return minLeft, minRight
def playable(self, card):
# if isinstance(card,Stage):
# print("IN STAGE")
# print(card.payResource)
# print("--------------")
# print(card.payResource)
payRes = card.payResource
if payRes["type"] == "choose":
if self.cardExist(payRes["resource"][0]["name"]):
return 0, 0
else:
payRes = payRes["resource"][1]
# print("NEW PAYRES-----")
# print(payRes)
if payRes["type"] == "none":
return 0, 0
elif payRes["type"] == "coin":
if self.coin >= payRes["amount"]:
return 0, 0
else:
return -1, -1
else:
missResource = {}
if payRes["type"] == "mixed":
for res in payRes["resource"]:
if self.resource[res["type"]] < res["amount"]:
missResource[res["type"]] = res["amount"] - self.resource[res["type"]]
else:
res = payRes
if self.resource[res["type"]] < res["amount"]:
missResource[res["type"]] = res["amount"] - self.resource[res["type"]]
if len(missResource) == 0:
return 0, 0
missResource = dict(sorted(missResource.items(), key=operator.itemgetter(1), reverse=True))
# print("oldMissResource")
# print(missResource)
missArr = []
for name, amount in missResource.items():
missArr.append(Resource(name, amount))
left, right = self.BFS(missArr, self.choosecard + self.chooseStage)
if self.coin >= left + right:
return left, right
else:
return -1, -1
def findCardFromHand(self, cardName):
for card in self.hand:
if card.name == cardName:
return card
return None
def activateEffect(self, effect):
if effect == "freeStructure":
self.freeStructure = True
self.endAgeEffect.append(effect)
elif effect == "playSeventhCard":
self.endAgeEffect.append(effect)
elif effect == "buildDiscarded":
self.endTurnEffect = effect
elif effect == "sideTradingRaws":
self.activateEffect("eastTradingRaws")
self.activateEffect("westTradingRaws")
elif effect == "eastTradingRaws":
self.eastTradePrices["wood"] = 1
self.eastTradePrices["clay"] = 1
self.eastTradePrices["ore"] = 1
self.eastTradePrices["stone"] = 1
elif effect == "westTradingRaws":
self.westTradePrices["wood"] = 1
self.westTradePrices["clay"] = 1
self.westTradePrices["ore"] = 1
self.westTradePrices["stone"] = 1
elif effect == "sideManuPosts":
self.eastTradePrices["papyrus"] = 1
self.eastTradePrices["glass"] = 1
self.eastTradePrices["loom"] = 1
self.westTradePrices["papyrus"] = 1
self.westTradePrices["glass"] = 1
self.westTradePrices["loom"] = 1
elif effect == "threeBrownOneCoin":
self.coin += self.left.color["brown"] + self.color["brown"] + self.right.color["brown"]
elif effect == "brownOneCoinOneVP":
self.coin += self.color["brown"]
self.endGameEffect.append(effect)
elif effect == "yellowOneCoinOneVP":
self.coin += self.color["yellow"]
self.endGameEffect.append(effect)
elif effect == "stageThreeCoinOneVP":
self.coin += self.wonders.stage * 3
self.endGameEffect.append(effect)
elif effect == "greyTwoCoinTwoVP":
self.coin += self.color["grey"] * 2
self.endGameEffect.append(effect)
else: # effect == "sideBrownOneVP","sideGreyTwoVP","sideYellowOneVP","sideGreenOneVP","sideRedOneVP",
# "sideDefeatOneVP","brownGreyPurpleOneVP", "brownOneCoinOneVP", "yellowOneCoinOneVP", "stageThreeCoinOneVP",
# "greyTwoCoinTwoVP","copyPurpleNeighbor"
self.endGameEffect.append(effect)
def VPFromSide(self, col, mult):
return (self.left.color[col] + self.right.color[col]) * mult
def VPFromEffect(self, effect):
if effect == "sideBrownOneVP":
return self.VPFromSide("brown", 1)
elif effect == "sideGreyTwoVP":
return self.VPFromSide("grey", 2)
elif effect == "sideYellowOneVP":
return self.VPFromSide("yellow", 1)
elif effect == "sideGreenOneVP":
return self.VPFromSide("green", 1)
elif effect == "sideRedOneVP":
return self.VPFromSide("red", 1)
elif effect == "sideDefeatOneVP":
return self.left.warLoseVP + self.right.warLoseVP
elif effect == "brownGreyPurpleOneVP":
return self.color["brown"] + self.color["grey"] + self.color["purple"]
elif effect == "brownOneCoinOneVP":
return self.color["brown"]
elif effect == "yellowOneCoinOneVP":
return self.color["yellow"]
elif effect == "stageThreeCoinOneVP":
return self.wonders.stage
elif effect == "greyTwoCoinTwoVP":
return self.color["grey"] * 2
else:
return 0
def scienceVP(self, chooseScience):
maxScience = 0
compass = self.resource["compass"]
wheel = self.resource["wheel"]
tablet = self.resource["tablet"]
if chooseScience == 0:
return compass**2 + wheel**2 + tablet**2 + min(compass, wheel, tablet) * 7
for addCom in range(0, chooseScience):
for addWheel in range(0, chooseScience - addCom):
addTab = chooseScience - addCom - addWheel
compass = addCom + self.resource["compass"]
wheel = addWheel + self.resource["wheel"]
tablet = addTab + self.resource["tablet"]
points = compass**2 + wheel**2 + tablet**2 + min(compass, wheel, tablet) * 7
if points > maxScience:
maxScience = points
return maxScience
def endGameCal(self):
extraPoint = 0
# print("Player" + str(self.player))
# print("Before" + str(self.VP))
# military
extraPoint += self.warVP - self.warLoseVP
# print("War : " + str(self.warVP - self.warLoseVP))
# coin : 3coins -> 1VP
extraPoint += int(self.coin / 3)
# print("Coin : " + str(int(self.coin/3)))
# wonders VP are automatically added when wonders are played
# effect cards activation
copyPurple = False
for effect in self.endGameEffect:
if effect == "copyPurpleNeighbor":
copyPurple = True
else:
extraPoint += self.VPFromEffect(effect)
maxCopy = 0
scienceNeighbor = False
if copyPurple:
purple = []
for card in self.left.card:
if card.color == "purple":
purple.append(card)
for card in self.right.card:
if card.color == "purple":
purple.append(card)
maxPt = 0
for card in purple:
if card.name == "scientists guild":
scienceNeighbor = True
else:
if maxPt < self.VPFromEffect(card.getResource["effect"]):
maxPt = self.VPFromEffect(card.getResource["effect"])
maxCopy = maxPt
# science points
chooseScience = 0
for card in self.choosecard:
if card.getResource["type"] == "choose" and card.getResource["resource"][0]["type"] == "compass":
chooseScience += 1
for i in range(0, self.wonders.stage):
if (
self.wonders.step[i + 1].getResource["type"] == "choose"
and self.wonders.step[i + 1].getResource["resource"][0]["type"] == "compass"
):
chooseScience += 1
maxScience = self.scienceVP(chooseScience)
if scienceNeighbor:
copyScience = self.scienceVP(chooseScience + 1)
if maxScience + maxCopy < copyScience:
maxScience = copyScience
# print("Science : " + str(maxScience))
extraPoint += maxScience
return self.VP + extraPoint
def deleteCardFromHand(self, card):
if any(cardExist for cardExist in self.hand if cardExist.name == card.name):
self.hand.remove(card)
return 1
else:
return -1
def addedCardSys(self, cardGetResource, selectedCard):
if cardGetResource["type"] == "choose":
if isinstance(selectedCard, Stage):
self.chooseStage.append(selectedCard)
else:
self.choosecard.append(selectedCard)
elif cardGetResource["type"] == "VP":
self.VP += cardGetResource["amount"]
elif cardGetResource["type"] == "coin":
self.coin += cardGetResource["amount"]
elif cardGetResource["type"] != "effect":
self.resource[cardGetResource["type"]] += cardGetResource["amount"]
else:
self.activateEffect(cardGetResource["effect"])
self.lastPlayEffect = cardGetResource["effect"]
return
def playChosenCard(self, selectedCard):
self.lastPlayEffect = None
leftPrice = selectedCard[1]
rightPrice = selectedCard[2]
action = selectedCard[3]
stage = None
if len(selectedCard) == 5:
stage = selectedCard[4]
selectedCard = selectedCard[0]
if action == -1:
# print("SELECT")
# if isinstance(selectedCard,Card):
# print(selectedCard.name)
# else:
# print(selectedCard.stage)
status = self.deleteCardFromHand(selectedCard)
if not status:
print("ERROR STATUS")
self.coin += 3
return selectedCard, action
elif action == 1:
self.freeStructure = False
if isinstance(selectedCard, Card):
# print(selectedCard.name)
status = self.deleteCardFromHand(selectedCard)
self.card.append(selectedCard)
self.color[selectedCard.color] += 1
self.lastPlayColor = selectedCard.color
elif action == 2:
status = self.deleteCardFromHand(selectedCard)
self.wonders.stage += 1
# print(self.wonders.name)
# print(self.wonders.step[self.wonders.stage].printCard())
if selectedCard.getResource["type"] == "mixed":
for resource in selectedCard.getResource["resource"]:
if resource["type"] == "mixed":
for innerRes in resource["resource"]:
self.addedCardSys(innerRes, selectedCard)
else:
# print(resource["type"])
self.addedCardSys(resource, selectedCard)
elif selectedCard.getResource["type"] == "choose":
if isinstance(stage, Stage):
self.chooseStage.append(stage)
else:
self.choosecard.append(selectedCard)
else:
self.addedCardSys(selectedCard.getResource, selectedCard)
return selectedCard, action
def playChosenCardFake(self, selectedCard):
self.lastPlayEffect = None
leftPrice = selectedCard[1]
rightPrice = selectedCard[2]
action = selectedCard[3]
stage = None
if len(selectedCard) == 5:
stage = selectedCard[4]
selectedCard = selectedCard[0]
if action == -1:
# print("SELECT")
# if isinstance(selectedCard,Card):
# print(selectedCard.name)
# else:
# print(selectedCard.stage)
# self.deleteCardFromHand(selectedCard)
self.coin += 3
return selectedCard, action
elif action == 1:
self.freeStructure = False
if isinstance(selectedCard, Card):
# print(selectedCard.name)
# self.deleteCardFromHand(selectedCard)
self.card.append(selectedCard)
self.color[selectedCard.color] += 1
self.lastPlayColor = selectedCard.color
elif action == 2:
# self.deleteCardFromHand(stageCard)
self.wonders.stage += 1
# print(self.wonders.name)
# print(self.wonders.step[self.wonders.stage].printCard())
if selectedCard.getResource["type"] == "mixed":
for resource in selectedCard.getResource["resource"]:
if resource["type"] == "mixed":
for innerRes in resource["resource"]:
self.addedCardSys(innerRes, selectedCard)
else:
# print(resource["type"])
self.addedCardSys(resource, selectedCard)
elif selectedCard.getResource["type"] == "choose":
if isinstance(selectedCard, Stage):
self.chooseStage.append(stage)
else:
self.choosecard.append(selectedCard)
else:
self.addedCardSys(selectedCard.getResource, selectedCard)
return selectedCard, action
def playFromEffect(self, cardList, effect, age): # playSeventhCard or buildDiscarded
if effect == "playSeventhCard":
card = cardList[0]
choices = []
choices.append([card, 0, 0, -1])
left, right = self.playable(card)
if left != -1 and right != -1:
choices.append([card, left, right, 0])
steps = self.wonders.step
# print("LEN STEPS : {}".format(len(steps)))
existedStage = self.wonders.stage + 1
# print(type(steps[existedStage]))
if existedStage < len(steps):
left, right = self.playable(steps[existedStage])
if left != -1 and right != -1:
for card in self.hand:
choices.append([card, left, right, 2, steps[existedStage]])
# print("APPENDED STAGES")
persona = self.personality
selectedCard = choices[persona.make_choice(self=persona, player=self, age=age, options=choices)]
return self.playChosenCard(selectedCard)
elif effect == "buildDiscarded":
choices = []
for card in cardList:
choices.append([card, 0, 0, 0])
persona = self.personality
selectedCard = choices[persona.make_choice(self=persona, player=self, age=age, options=choices)]
self.hand.append(selectedCard[0])
return self.playChosenCard(selectedCard)
else:
print("something wrong")
exit(-1)
def playCard(self, age):
self.lastPlayEffect = None
self.endTurnEffect = None
choices = []
for card in self.hand:
choices.append([card, 0, 0, -1]) # -1 for discard card
for card in self.hand:
left, right = self.playable(card)
if left != -1 and right != -1:
choices.append([card, left, right, 0]) # card,leftPrice,rightPrice,0 for not using free effect
if self.freeStructure == True:
for card in self.hand:
choices.append([card, 0, 0, 1]) # card,leftPrice,rightPrice,1 for using free effect
steps = self.wonders.step
existedStage = self.wonders.stage + 1
if existedStage < len(steps):
left, right = self.playable(steps[existedStage])
if left != -1 and right != -1:
for card in self.hand:
choices.append([card, left, right, 2, steps[existedStage]]) # Append Stage
persona = self.personality
selectedCard = choices[persona.make_choice(self=persona, player=self, age=age, options=choices)]
print("SELECT", selectedCard)
return self.playChosenCard(selectedCard)
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/PlayerClass.py | PlayerClass.py |
from SevenWonEnv.envs.mainGameEnv.cardClass import Card
from SevenWonEnv.envs.mainGameEnv.resourceClass import Resource
import random
def resBuild(cardJSON):
# print("Construct resource from {} type with {} amount".format(cardJSON['type'],cardJSON['amount']))
return Resource(cardJSON["type"], cardJSON["amount"])
def filterPlayer(jsonCard, playerNum):
jsonString = {}
start = 3
while start <= playerNum:
name = str(start) + "players"
# print(jsonCard[name])
# print(jsonCard[name].keys())
for color in jsonCard[name].keys():
if color == "purple":
random.shuffle(jsonCard[name][color])
jsonCard[name][color] = jsonCard[name][color][0 : playerNum + 2]
if color not in jsonString:
jsonString[color] = []
jsonString[color] += jsonCard[name][color]
start += 1
return jsonString
def buildCard(name, color, payResource, getResource):
return Card(name, color, payResource, getResource)
def rotateHand(playerList, age):
# print(playerList)
handList = []
for i in range(1, len(playerList) + 1):
handList.append(playerList[i].hand)
if age % 2 == 1:
handList = handList[-1:] + handList[:-1]
else:
handList = handList[1:] + handList[:1]
for i in range(1, len(playerList) + 1):
playerList[i].assignHand(handList[i - 1])
def battle(player1, player2, age):
winPts = 2 * age - 1
winner = None
loser = None
if player1.resource["shield"] > player2.resource["shield"]:
winner = player1
loser = player2
elif player1.resource["shield"] < player2.resource["shield"]:
winner = player2
loser = player1
if winner is not None:
winner.warVP += winPts
loser.warVP -= 1
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/mainGameEnv/mainHelper.py | mainHelper.py |
from SevenWonEnv.envs.mainGameEnv.mainHelper import (
filterPlayer,
buildCard,
rotateHand,
battle,
)
from SevenWonEnv.envs.mainGameEnv.PlayerClass import Player
from SevenWonEnv.envs.mainGameEnv.WonderClass import Wonder
from SevenWonEnv.envs.mainGameEnv.resourceClass import Resource
from SevenWonEnv.envs.mainGameEnv.Personality import (
Personality,
RandomAI,
RuleBasedAI,
Human,
DQNAI,
)
from SevenWonEnv.envs.mainGameEnv.stageClass import Stage
from SevenWonEnv.envs.mainGameEnv.cardClass import Card
from SevenWonEnv.envs.SevenWonderEnv import SevenWonderEnv
import gymnasium as gym
import unittest
from unittest import mock
# Unit Testing
class Test(unittest.TestCase):
def test_AddNoPlayer(self):
with mock.patch.object(SevenWonderEnv, "__init__", lambda sel, player: None):
env = SevenWonderEnv(player=4)
env.unAssignedPersonality = 4
with self.assertRaises(SystemExit) as cm:
env.step(0)
exc = cm.exception
assert exc.code == "Program Stopped : Some Players do not have personality."
def test_AddTooManyPlayer(self):
with mock.patch.object(SevenWonderEnv, "__init__", lambda sel, player: None):
env = SevenWonderEnv(player=4)
env.unAssignedPersonality = 0
env.player = 4
env.playerList = []
with self.assertRaises(SystemExit) as cm:
env.setPersonality([Human])
exc = cm.exception
assert exc.code == "Program Stopped : Add too many players' personality"
def test_GetCardAge(self):
with mock.patch.object(SevenWonderEnv, "__init__", lambda sel, player: None):
env = SevenWonderEnv(player=3)
cardList = {
"age_1": {
"3players": {
"brown": [
{
"name": "lumber yard",
"payResource": {"type": "none"},
"getResource": {"type": "wood", "amount": 1},
}
]
}
}
}
result = env.getCardAge("age_1", 3, cardList)
assert result[0].name == "lumber yard"
assert result[0].color == "brown"
assert result[0].getResource == {"type": "wood", "amount": 1}
assert result[0].payResource == {"type": "none"}
def testBattle(self):
with mock.patch.object(Player, "__init__", lambda se, playNum, totNum, person: None):
p1 = Player(0, 4, Human)
p2 = Player(0, 4, Human)
p1.resource = {}
p2.resource = {}
p1.resource["shield"] = 0
p2.resource["shield"] = 1
p1.warVP = 0
p2.warVP = 0
battle(p1, p2, age=1)
assert p1.warVP == -1
assert p2.warVP == 1
p1.warVP = 0
p2.warVP = 0
battle(p1, p2, age=2)
assert p1.warVP == -1
assert p2.warVP == 3
p1.resource["shield"] = 1
battle(p1, p2, age=3)
assert p1.warVP == -1
assert p2.warVP == 3
def testAssignWonders(self):
with mock.patch.object(Wonder, "__init__", lambda se, name, side, begin: None):
won = Wonder("Rhodes", "A", Resource("wood", 2))
won.beginResource = Resource("wood", 2)
player = Player(1, 4, Human)
player.assignWonders(won)
assert player.resource["wood"] == 2
# Integration Testing
def testInitGameWithAI(self):
env = SevenWonderEnv(player=4)
env.setPersonality([RuleBasedAI, RuleBasedAI, RuleBasedAI, RuleBasedAI])
assert env.player == 4
assert env.unAssignedPersonality == 0
for i in range(1, 5):
assert len(env.playerList[i].hand) == 7
def testStepGameWithAI(self):
env = SevenWonderEnv(player=4)
env.setPersonality([RuleBasedAI, RuleBasedAI, RuleBasedAI, RuleBasedAI])
assert env.player == 4
assert env.unAssignedPersonality == 0
for i in range(1, 5):
assert len(env.playerList[i].hand) == 7
rewardAll = env.step(0)
assert len(rewardAll) == 4
assert len(rewardAll[0]) == 4
state = env.reset()
assert len(state) == 70
if __name__ == "__main__":
unittest.main()
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/SevenWondersEnv/SevenWonEnv/envs/Test/allTests.py | allTests.py |
Search.setIndex({"docnames": ["index"], "filenames": ["index.rst"], "titles": ["Welcome to 7Wonder-RL-Lib\u2019s documentation!"], "terms": {"index": 0, "modul": 0, "search": 0, "page": 0, "master": [], "file": [], "creat": [], "sphinx": [], "quickstart": [], "wed": [], "mai": [], "10": [], "21": [], "53": [], "31": [], "2023": [], "you": [], "can": 0, "adapt": [], "thi": 0, "complet": [], "your": 0, "like": [], "should": 0, "least": [], "contain": 0, "root": [], "toctre": [], "direct": [], "maxdepth": [], "2": 0, "caption": [], "content": [], "class": 0, "sevenwonenv": 0, "env": 0, "sevenwonderenv": 0, "player": 0, "close": 0, "after": 0, "user": 0, "ha": 0, "finish": 0, "us": 0, "environ": 0, "code": 0, "necessari": 0, "clean": 0, "up": 0, "i": 0, "critic": 0, "render": 0, "window": 0, "databas": 0, "http": 0, "connect": 0, "legalact": 0, "playernum": 0, "given": 0, "number": 0, "return": 0, "all": 0, "legal": 0, "action": 0, "list": 0, "param": [], "int": [], "mode": 0, "human": 0, "comput": 0, "frame": 0, "specifi": 0, "render_mod": 0, "dure": 0, "initi": 0, "The": 0, "metadata": 0, "possibl": 0, "wai": 0, "implement": 0, "In": 0, "addit": 0, "version": 0, "most": 0, "achiev": 0, "through": 0, "gymnasium": 0, "make": 0, "which": 0, "automat": 0, "appli": 0, "wrapper": 0, "collect": 0, "note": 0, "As": 0, "known": 0, "__init__": 0, "object": 0, "state": 0, "initialis": 0, "By": 0, "convent": 0, "none": 0, "default": 0, "continu": 0, "current": 0, "displai": 0, "termin": 0, "usual": 0, "consumpt": 0, "occur": 0, "step": 0, "doesn": 0, "t": 0, "need": 0, "call": 0, "rgb_arrai": 0, "singl": 0, "repres": 0, "A": 0, "np": 0, "ndarrai": 0, "shape": 0, "x": 0, "y": 0, "3": 0, "rgb": 0, "valu": 0, "an": 0, "pixel": 0, "imag": 0, "ansi": 0, "string": 0, "str": 0, "stringio": 0, "style": 0, "text": 0, "represent": 0, "each": 0, "time": 0, "includ": 0, "newlin": 0, "escap": 0, "sequenc": 0, "e": 0, "g": 0, "color": 0, "rgb_array_list": 0, "ansi_list": 0, "base": 0, "ar": 0, "except": 0, "rendercollect": 0, "pop": 0, "reset": 0, "sure": 0, "kei": 0, "support": 0, "chang": 0, "0": 0, "25": 0, "function": 0, "wa": 0, "longer": 0, "accept": 0, "paramet": 0, "rather": 0, "cartpol": 0, "v1": 0, "seed": 0, "option": 0, "episod": 0, "setperson": 0, "personalitylist": 0, "set": 0, "person": 0, "proce": 0, "one": 0, "turn": 0, "game": 0, "tupl": 0, "posit": 0, "1": 0, "n": 0, "arg": 0, "actioncod": 0, "id": 0, "random": 0, "new_stat": 0, "reward": 0, "done": 0, "info": 0, "librari": 0, "provid": 0, "test": 0, "reinforc": 0, "learn": 0, "7": 0, "wonder": 0, "There": 0, "multipl": 0, "ai": 0, "howev": 0, "now": 0, "mostli": 0, "cover": 0, "onli": 0, "tradit": 0, "board": 0, "go": 0, "chess": 0, "etc": 0, "52": 0, "card": 0, "poker": 0, "rummi": 0, "where": 0, "do": 0, "realli": 0, "have": 0, "interact": 0, "other": 0, "euro": 0, "good": 0, "algorithm": 0, "mani": 0, "aspect": 0, "explor": 0, "trade": 0, "deal": 0, "imperfect": 0, "inform": 0, "stochast": 0, "element": 0, "introduc": 0, "mention": 0, "abov": 0, "out": 0, "new": 0, "basic": 0, "system": 0, "allow": 0, "custom": 0, "space": 0, "To": 0, "gym": 0, "run": 0, "pip": [], "sevenwondersenv": 0, "exampl": 0, "how": 0, "declar": 0, "below": 0, "import": 0, "from": 0, "maingameenv": 0, "4": 0, "randomai": 0, "rulebasedai": 0, "dqnai": 0, "append": 0, "rang": 0, "statelist": 0, "variabl": 0, "consist": 0, "depend": 0, "add": 0, "model": 0, "py": 0, "main": 0, "init": 0, "make_choic": 0, "For": 0, "take": 0, "choic": 0, "randomli": 0, "choos": 0, "def": 0, "self": 0, "super": 0, "ag": 0, "len": 0, "develop": 0, "build": 0}, "objects": {"SevenWonEnv.envs": [[0, 0, 0, "-", "SevenWonderEnv"]], "SevenWonEnv.envs.SevenWonderEnv": [[0, 1, 1, "", "SevenWonderEnv"]], "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv": [[0, 2, 1, "", "close"], [0, 2, 1, "", "legalAction"], [0, 2, 1, "", "render"], [0, 2, 1, "", "reset"], [0, 2, 1, "", "setPersonality"], [0, 2, 1, "", "step"]]}, "objtypes": {"0": "py:module", "1": "py:class", "2": "py:method"}, "objnames": {"0": ["py", "module", "Python module"], "1": ["py", "class", "Python class"], "2": ["py", "method", "Python method"]}, "titleterms": {"welcom": 0, "7wonder": 0, "rl": 0, "lib": 0, "": 0, "document": 0, "indic": 0, "tabl": 0, "readm": 0, "file": 0, "overview": 0, "instal": 0, "usag": 0}, "envversion": {"sphinx.domains.c": 2, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 8, "sphinx.domains.index": 1, "sphinx.domains.javascript": 2, "sphinx.domains.math": 2, "sphinx.domains.python": 3, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx": 57}, "alltitles": {"Welcome to 7Wonder-RL-Lib\u2019s documentation!": [[0, "welcome-to-7wonder-rl-lib-s-documentation"]], "Readme File": [[0, "readme-file"]], "7Wonder-RL-Lib": [[0, "wonder-rl-lib"]], "Overview": [[0, "overview"]], "Installation": [[0, "installation"]], "Usage": [[0, "usage"]], "Documentation": [[0, "module-SevenWonEnv.envs.SevenWonderEnv"]], "Indices and tables": [[0, "indices-and-tables"]]}, "indexentries": {"sevenwonenv.envs.sevenwonderenv": [[0, "module-SevenWonEnv.envs.SevenWonderEnv"]], "sevenwonderenv (class in sevenwonenv.envs.sevenwonderenv)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv"]], "close() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.close"]], "legalaction() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.legalAction"]], "module": [[0, "module-SevenWonEnv.envs.SevenWonderEnv"]], "render() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.render"]], "reset() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.reset"]], "setpersonality() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.setPersonality"]], "step() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.step"]]}}) | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/searchindex.js | searchindex.js |
Welcome to 7Wonder-RL-Lib's documentation!
==========================================
Readme File
===========
.. include:: ../README.md
:parser: myst_parser.sphinx_
Documentation
----------------
.. automodule:: SevenWonEnv.envs.SevenWonderEnv
:members:
.. toctree::
:maxdepth: 2
:caption: Contents:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/index.rst | index.rst |
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = '7Wonder-RL-Lib'
copyright = '2023, Phudis Dawieang'
author = 'Phudis Dawieang'
release = '0.1.0'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = ['myst_parser','sphinx.ext.autodoc', 'sphinx.ext.coverage']
source_suffix = {'.rst': 'restructuredtext', '.md': 'markdown'}
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
import recommonmark
from recommonmark.transform import AutoStructify
# At the bottom of conf.py
def setup(app):
app.add_config_value('recommonmark_config', {
'url_resolver': lambda url: github_doc_root + url,
'auto_toc_tree_section': 'Contents',
}, True)
app.add_transform(AutoStructify) | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/conf.py | conf.py |
Search.setIndex({"docnames": ["index"], "filenames": ["index.rst"], "titles": ["Welcome to 7Wonder-RL-Lib\u2019s documentation!"], "terms": {"index": 0, "modul": 0, "search": 0, "page": 0, "master": [], "file": [], "creat": [], "sphinx": [], "quickstart": [], "wed": [], "mai": [], "10": [], "21": [], "53": [], "31": [], "2023": [], "you": [], "can": 0, "adapt": [], "thi": 0, "complet": [], "your": 0, "like": [], "should": 0, "least": [], "contain": 0, "root": [], "toctre": [], "direct": [], "maxdepth": [], "2": 0, "caption": [], "content": [], "class": 0, "sevenwonenv": 0, "env": 0, "sevenwonderenv": 0, "player": 0, "close": 0, "after": 0, "user": 0, "ha": 0, "finish": 0, "us": 0, "environ": 0, "code": 0, "necessari": 0, "clean": 0, "up": 0, "i": 0, "critic": 0, "render": 0, "window": 0, "databas": 0, "http": 0, "connect": 0, "legalact": 0, "playernum": 0, "given": 0, "number": 0, "return": 0, "all": 0, "legal": 0, "action": 0, "list": 0, "param": [], "int": [], "mode": 0, "human": 0, "comput": 0, "frame": 0, "specifi": 0, "render_mod": 0, "dure": 0, "initi": 0, "The": 0, "metadata": 0, "possibl": 0, "wai": 0, "implement": 0, "In": 0, "addit": 0, "version": 0, "most": 0, "achiev": 0, "through": 0, "gymnasium": 0, "make": 0, "which": 0, "automat": 0, "appli": 0, "wrapper": 0, "collect": 0, "note": 0, "As": 0, "known": 0, "__init__": 0, "object": 0, "state": 0, "initialis": 0, "By": 0, "convent": 0, "none": 0, "default": 0, "continu": 0, "current": 0, "displai": 0, "termin": 0, "usual": 0, "consumpt": 0, "occur": 0, "step": 0, "doesn": 0, "t": 0, "need": 0, "call": 0, "rgb_arrai": 0, "singl": 0, "repres": 0, "A": 0, "np": 0, "ndarrai": 0, "shape": 0, "x": 0, "y": 0, "3": 0, "rgb": 0, "valu": 0, "an": 0, "pixel": 0, "imag": 0, "ansi": 0, "string": 0, "str": 0, "stringio": 0, "style": 0, "text": 0, "represent": 0, "each": 0, "time": 0, "includ": 0, "newlin": 0, "escap": 0, "sequenc": 0, "e": 0, "g": 0, "color": 0, "rgb_array_list": 0, "ansi_list": 0, "base": 0, "ar": 0, "except": 0, "rendercollect": 0, "pop": 0, "reset": 0, "sure": 0, "kei": 0, "support": 0, "chang": 0, "0": 0, "25": 0, "function": 0, "wa": 0, "longer": 0, "accept": 0, "paramet": 0, "rather": 0, "cartpol": 0, "v1": 0, "seed": 0, "option": 0, "episod": 0, "setperson": 0, "personalitylist": 0, "set": 0, "person": 0, "proce": 0, "one": 0, "turn": 0, "game": 0, "tupl": 0, "posit": 0, "1": 0, "n": 0, "arg": 0, "actioncod": 0, "id": 0, "random": 0, "new_stat": 0, "reward": 0, "done": 0, "info": 0, "librari": 0, "provid": 0, "test": 0, "reinforc": 0, "learn": 0, "7": 0, "wonder": 0, "There": 0, "multipl": 0, "ai": 0, "howev": 0, "now": 0, "mostli": 0, "cover": 0, "onli": 0, "tradit": 0, "board": 0, "go": 0, "chess": 0, "etc": 0, "52": 0, "card": 0, "poker": 0, "rummi": 0, "where": 0, "do": 0, "realli": 0, "have": 0, "interact": 0, "other": 0, "euro": 0, "good": 0, "algorithm": 0, "mani": 0, "aspect": 0, "explor": 0, "trade": 0, "deal": 0, "imperfect": 0, "inform": 0, "stochast": 0, "element": 0, "introduc": 0, "mention": 0, "abov": 0, "out": 0, "new": 0, "basic": 0, "system": 0, "allow": 0, "custom": 0, "space": 0, "To": 0, "gym": 0, "run": 0, "pip": [], "sevenwondersenv": 0, "exampl": 0, "how": 0, "declar": 0, "below": 0, "import": 0, "from": 0, "maingameenv": 0, "4": 0, "randomai": 0, "rulebasedai": 0, "dqnai": 0, "append": 0, "rang": 0, "statelist": 0, "variabl": 0, "consist": 0, "depend": 0, "add": 0, "model": 0, "py": 0, "main": 0, "init": 0, "make_choic": 0, "For": 0, "take": 0, "choic": 0, "randomli": 0, "choos": 0, "def": 0, "self": 0, "super": 0, "ag": 0, "len": 0, "develop": 0, "build": 0}, "objects": {"SevenWonEnv.envs": [[0, 0, 0, "-", "SevenWonderEnv"]], "SevenWonEnv.envs.SevenWonderEnv": [[0, 1, 1, "", "SevenWonderEnv"]], "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv": [[0, 2, 1, "", "close"], [0, 2, 1, "", "legalAction"], [0, 2, 1, "", "render"], [0, 2, 1, "", "reset"], [0, 2, 1, "", "setPersonality"], [0, 2, 1, "", "step"]]}, "objtypes": {"0": "py:module", "1": "py:class", "2": "py:method"}, "objnames": {"0": ["py", "module", "Python module"], "1": ["py", "class", "Python class"], "2": ["py", "method", "Python method"]}, "titleterms": {"welcom": 0, "7wonder": 0, "rl": 0, "lib": 0, "": 0, "document": 0, "indic": 0, "tabl": 0, "readm": 0, "file": 0, "overview": 0, "instal": 0, "usag": 0}, "envversion": {"sphinx.domains.c": 2, "sphinx.domains.changeset": 1, "sphinx.domains.citation": 1, "sphinx.domains.cpp": 8, "sphinx.domains.index": 1, "sphinx.domains.javascript": 2, "sphinx.domains.math": 2, "sphinx.domains.python": 3, "sphinx.domains.rst": 2, "sphinx.domains.std": 2, "sphinx": 57}, "alltitles": {"Welcome to 7Wonder-RL-Lib\u2019s documentation!": [[0, "welcome-to-7wonder-rl-lib-s-documentation"]], "Readme File": [[0, "readme-file"]], "7Wonder-RL-Lib": [[0, "wonder-rl-lib"]], "Overview": [[0, "overview"]], "Installation": [[0, "installation"]], "Usage": [[0, "usage"]], "Documentation": [[0, "module-SevenWonEnv.envs.SevenWonderEnv"]], "Indices and tables": [[0, "indices-and-tables"]]}, "indexentries": {"sevenwonenv.envs.sevenwonderenv": [[0, "module-SevenWonEnv.envs.SevenWonderEnv"]], "sevenwonderenv (class in sevenwonenv.envs.sevenwonderenv)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv"]], "close() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.close"]], "legalaction() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.legalAction"]], "module": [[0, "module-SevenWonEnv.envs.SevenWonderEnv"]], "render() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.render"]], "reset() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.reset"]], "setpersonality() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.setPersonality"]], "step() (sevenwonenv.envs.sevenwonderenv.sevenwonderenv method)": [[0, "SevenWonEnv.envs.SevenWonderEnv.SevenWonderEnv.step"]]}}) | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/searchindex.js | searchindex.js |
var DOCUMENTATION_OPTIONS = {
URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
VERSION: '0.1.0',
LANGUAGE: 'en',
COLLAPSE_INDEX: false,
BUILDER: 'html',
FILE_SUFFIX: '.html',
LINK_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt',
NAVIGATION_WITH_KEYS: false,
SHOW_SEARCH_SUMMARY: true,
ENABLE_SEARCH_SHORTCUTS: true,
}; | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/documentation_options.js | documentation_options.js |
/*
* doctools.js
* ~~~~~~~~~~~
*
* Base JavaScript utilities for all Sphinx HTML documentation.
*
* :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
"use strict";
const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([
"TEXTAREA",
"INPUT",
"SELECT",
"BUTTON",
]);
const _ready = (callback) => {
if (document.readyState !== "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
};
/**
* Small JavaScript module for the documentation.
*/
const Documentation = {
init: () => {
Documentation.initDomainIndexTable();
Documentation.initOnKeyListeners();
},
/**
* i18n support
*/
TRANSLATIONS: {},
PLURAL_EXPR: (n) => (n === 1 ? 0 : 1),
LOCALE: "unknown",
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext: (string) => {
const translated = Documentation.TRANSLATIONS[string];
switch (typeof translated) {
case "undefined":
return string; // no translation
case "string":
return translated; // translation exists
default:
return translated[0]; // (singular, plural) translation tuple exists
}
},
ngettext: (singular, plural, n) => {
const translated = Documentation.TRANSLATIONS[singular];
if (typeof translated !== "undefined")
return translated[Documentation.PLURAL_EXPR(n)];
return n === 1 ? singular : plural;
},
addTranslations: (catalog) => {
Object.assign(Documentation.TRANSLATIONS, catalog.messages);
Documentation.PLURAL_EXPR = new Function(
"n",
`return (${catalog.plural_expr})`
);
Documentation.LOCALE = catalog.locale;
},
/**
* helper function to focus on search bar
*/
focusSearchBar: () => {
document.querySelectorAll("input[name=q]")[0]?.focus();
},
/**
* Initialise the domain index toggle buttons
*/
initDomainIndexTable: () => {
const toggler = (el) => {
const idNumber = el.id.substr(7);
const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`);
if (el.src.substr(-9) === "minus.png") {
el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`;
toggledRows.forEach((el) => (el.style.display = "none"));
} else {
el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`;
toggledRows.forEach((el) => (el.style.display = ""));
}
};
const togglerElements = document.querySelectorAll("img.toggler");
togglerElements.forEach((el) =>
el.addEventListener("click", (event) => toggler(event.currentTarget))
);
togglerElements.forEach((el) => (el.style.display = ""));
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler);
},
initOnKeyListeners: () => {
// only install a listener if it is really needed
if (
!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS &&
!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS
)
return;
document.addEventListener("keydown", (event) => {
// bail for input elements
if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return;
// bail with special keys
if (event.altKey || event.ctrlKey || event.metaKey) return;
if (!event.shiftKey) {
switch (event.key) {
case "ArrowLeft":
if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break;
const prevLink = document.querySelector('link[rel="prev"]');
if (prevLink && prevLink.href) {
window.location.href = prevLink.href;
event.preventDefault();
}
break;
case "ArrowRight":
if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break;
const nextLink = document.querySelector('link[rel="next"]');
if (nextLink && nextLink.href) {
window.location.href = nextLink.href;
event.preventDefault();
}
break;
}
}
// some keyboard layouts may need Shift to get /
switch (event.key) {
case "/":
if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break;
Documentation.focusSearchBar();
event.preventDefault();
}
});
},
};
// quick alias for translations
const _ = Documentation.gettext;
_ready(Documentation.init);
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/doctools.js | doctools.js |
/*
* language_data.js
* ~~~~~~~~~~~~~~~~
*
* This script contains the language-specific data used by searchtools.js,
* namely the list of stopwords, stemmer, scorer and splitter.
*
* :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
var stopwords = ["a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "near", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"];
/* Non-minified version is copied as a separate JS file, is available */
/**
* Porter Stemmer
*/
var Stemmer = function() {
var step2list = {
ational: 'ate',
tional: 'tion',
enci: 'ence',
anci: 'ance',
izer: 'ize',
bli: 'ble',
alli: 'al',
entli: 'ent',
eli: 'e',
ousli: 'ous',
ization: 'ize',
ation: 'ate',
ator: 'ate',
alism: 'al',
iveness: 'ive',
fulness: 'ful',
ousness: 'ous',
aliti: 'al',
iviti: 'ive',
biliti: 'ble',
logi: 'log'
};
var step3list = {
icate: 'ic',
ative: '',
alize: 'al',
iciti: 'ic',
ical: 'ic',
ful: '',
ness: ''
};
var c = "[^aeiou]"; // consonant
var v = "[aeiouy]"; // vowel
var C = c + "[^aeiouy]*"; // consonant sequence
var V = v + "[aeiou]*"; // vowel sequence
var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
var s_v = "^(" + C + ")?" + v; // vowel in stem
this.stemWord = function (w) {
var stem;
var suffix;
var firstch;
var origword = w;
if (w.length < 3)
return w;
var re;
var re2;
var re3;
var re4;
firstch = w.substr(0,1);
if (firstch == "y")
w = firstch.toUpperCase() + w.substr(1);
// Step 1a
re = /^(.+?)(ss|i)es$/;
re2 = /^(.+?)([^s])s$/;
if (re.test(w))
w = w.replace(re,"$1$2");
else if (re2.test(w))
w = w.replace(re2,"$1$2");
// Step 1b
re = /^(.+?)eed$/;
re2 = /^(.+?)(ed|ing)$/;
if (re.test(w)) {
var fp = re.exec(w);
re = new RegExp(mgr0);
if (re.test(fp[1])) {
re = /.$/;
w = w.replace(re,"");
}
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
re2 = new RegExp(s_v);
if (re2.test(stem)) {
w = stem;
re2 = /(at|bl|iz)$/;
re3 = new RegExp("([^aeiouylsz])\\1$");
re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re2.test(w))
w = w + "e";
else if (re3.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
else if (re4.test(w))
w = w + "e";
}
}
// Step 1c
re = /^(.+?)y$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(s_v);
if (re.test(stem))
w = stem + "i";
}
// Step 2
re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step2list[suffix];
}
// Step 3
re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step3list[suffix];
}
// Step 4
re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
re2 = /^(.+?)(s|t)(ion)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
if (re.test(stem))
w = stem;
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1] + fp[2];
re2 = new RegExp(mgr1);
if (re2.test(stem))
w = stem;
}
// Step 5
re = /^(.+?)e$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
re2 = new RegExp(meq1);
re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
w = stem;
}
re = /ll$/;
re2 = new RegExp(mgr1);
if (re.test(w) && re2.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
// and turn initial Y back to y
if (firstch == "y")
w = firstch.toLowerCase() + w.substr(1);
return w;
}
}
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/language_data.js | language_data.js |
/* Highlighting utilities for Sphinx HTML documentation. */
"use strict";
const SPHINX_HIGHLIGHT_ENABLED = true
/**
* highlight a given string on a node by wrapping it in
* span elements with the given class name.
*/
const _highlight = (node, addItems, text, className) => {
if (node.nodeType === Node.TEXT_NODE) {
const val = node.nodeValue;
const parent = node.parentNode;
const pos = val.toLowerCase().indexOf(text);
if (
pos >= 0 &&
!parent.classList.contains(className) &&
!parent.classList.contains("nohighlight")
) {
let span;
const closestNode = parent.closest("body, svg, foreignObject");
const isInSVG = closestNode && closestNode.matches("svg");
if (isInSVG) {
span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
} else {
span = document.createElement("span");
span.classList.add(className);
}
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
parent.insertBefore(
span,
parent.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling
)
);
node.nodeValue = val.substr(0, pos);
if (isInSVG) {
const rect = document.createElementNS(
"http://www.w3.org/2000/svg",
"rect"
);
const bbox = parent.getBBox();
rect.x.baseVal.value = bbox.x;
rect.y.baseVal.value = bbox.y;
rect.width.baseVal.value = bbox.width;
rect.height.baseVal.value = bbox.height;
rect.setAttribute("class", className);
addItems.push({ parent: parent, target: rect });
}
}
} else if (node.matches && !node.matches("button, select, textarea")) {
node.childNodes.forEach((el) => _highlight(el, addItems, text, className));
}
};
const _highlightText = (thisNode, text, className) => {
let addItems = [];
_highlight(thisNode, addItems, text, className);
addItems.forEach((obj) =>
obj.parent.insertAdjacentElement("beforebegin", obj.target)
);
};
/**
* Small JavaScript module for the documentation.
*/
const SphinxHighlight = {
/**
* highlight the search words provided in localstorage in the text
*/
highlightSearchWords: () => {
if (!SPHINX_HIGHLIGHT_ENABLED) return; // bail if no highlight
// get and clear terms from localstorage
const url = new URL(window.location);
const highlight =
localStorage.getItem("sphinx_highlight_terms")
|| url.searchParams.get("highlight")
|| "";
localStorage.removeItem("sphinx_highlight_terms")
url.searchParams.delete("highlight");
window.history.replaceState({}, "", url);
// get individual terms from highlight string
const terms = highlight.toLowerCase().split(/\s+/).filter(x => x);
if (terms.length === 0) return; // nothing to do
// There should never be more than one element matching "div.body"
const divBody = document.querySelectorAll("div.body");
const body = divBody.length ? divBody[0] : document.querySelector("body");
window.setTimeout(() => {
terms.forEach((term) => _highlightText(body, term, "highlighted"));
}, 10);
const searchBox = document.getElementById("searchbox");
if (searchBox === null) return;
searchBox.appendChild(
document
.createRange()
.createContextualFragment(
'<p class="highlight-link">' +
'<a href="javascript:SphinxHighlight.hideSearchWords()">' +
_("Hide Search Matches") +
"</a></p>"
)
);
},
/**
* helper function to hide the search marks again
*/
hideSearchWords: () => {
document
.querySelectorAll("#searchbox .highlight-link")
.forEach((el) => el.remove());
document
.querySelectorAll("span.highlighted")
.forEach((el) => el.classList.remove("highlighted"));
localStorage.removeItem("sphinx_highlight_terms")
},
initEscapeListener: () => {
// only install a listener if it is really needed
if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) return;
document.addEventListener("keydown", (event) => {
// bail for input elements
if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return;
// bail with special keys
if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
if (DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS && (event.key === "Escape")) {
SphinxHighlight.hideSearchWords();
event.preventDefault();
}
});
},
};
_ready(SphinxHighlight.highlightSearchWords);
_ready(SphinxHighlight.initEscapeListener);
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/sphinx_highlight.js | sphinx_highlight.js |
/*
* searchtools.js
* ~~~~~~~~~~~~~~~~
*
* Sphinx JavaScript utilities for the full-text search.
*
* :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
"use strict";
/**
* Simple result scoring code.
*/
if (typeof Scorer === "undefined") {
var Scorer = {
// Implement the following function to further tweak the score for each result
// The function takes a result array [docname, title, anchor, descr, score, filename]
// and returns the new score.
/*
score: result => {
const [docname, title, anchor, descr, score, filename] = result
return score
},
*/
// query matches the full name of an object
objNameMatch: 11,
// or matches in the last dotted part of the object name
objPartialMatch: 6,
// Additive scores depending on the priority of the object
objPrio: {
0: 15, // used to be importantResults
1: 5, // used to be objectResults
2: -5, // used to be unimportantResults
},
// Used when the priority is not in the mapping.
objPrioDefault: 0,
// query found in title
title: 15,
partialTitle: 7,
// query found in terms
term: 5,
partialTerm: 2,
};
}
const _removeChildren = (element) => {
while (element && element.lastChild) element.removeChild(element.lastChild);
};
/**
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
*/
const _escapeRegExp = (string) =>
string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
const _displayItem = (item, searchTerms) => {
const docBuilder = DOCUMENTATION_OPTIONS.BUILDER;
const docUrlRoot = DOCUMENTATION_OPTIONS.URL_ROOT;
const docFileSuffix = DOCUMENTATION_OPTIONS.FILE_SUFFIX;
const docLinkSuffix = DOCUMENTATION_OPTIONS.LINK_SUFFIX;
const showSearchSummary = DOCUMENTATION_OPTIONS.SHOW_SEARCH_SUMMARY;
const [docName, title, anchor, descr, score, _filename] = item;
let listItem = document.createElement("li");
let requestUrl;
let linkUrl;
if (docBuilder === "dirhtml") {
// dirhtml builder
let dirname = docName + "/";
if (dirname.match(/\/index\/$/))
dirname = dirname.substring(0, dirname.length - 6);
else if (dirname === "index/") dirname = "";
requestUrl = docUrlRoot + dirname;
linkUrl = requestUrl;
} else {
// normal html builders
requestUrl = docUrlRoot + docName + docFileSuffix;
linkUrl = docName + docLinkSuffix;
}
let linkEl = listItem.appendChild(document.createElement("a"));
linkEl.href = linkUrl + anchor;
linkEl.dataset.score = score;
linkEl.innerHTML = title;
if (descr)
listItem.appendChild(document.createElement("span")).innerHTML =
" (" + descr + ")";
else if (showSearchSummary)
fetch(requestUrl)
.then((responseData) => responseData.text())
.then((data) => {
if (data)
listItem.appendChild(
Search.makeSearchSummary(data, searchTerms)
);
});
Search.output.appendChild(listItem);
};
const _finishSearch = (resultCount) => {
Search.stopPulse();
Search.title.innerText = _("Search Results");
if (!resultCount)
Search.status.innerText = Documentation.gettext(
"Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories."
);
else
Search.status.innerText = _(
`Search finished, found ${resultCount} page(s) matching the search query.`
);
};
const _displayNextItem = (
results,
resultCount,
searchTerms
) => {
// results left, load the summary and display it
// this is intended to be dynamic (don't sub resultsCount)
if (results.length) {
_displayItem(results.pop(), searchTerms);
setTimeout(
() => _displayNextItem(results, resultCount, searchTerms),
5
);
}
// search finished, update title and status message
else _finishSearch(resultCount);
};
/**
* Default splitQuery function. Can be overridden in ``sphinx.search`` with a
* custom function per language.
*
* The regular expression works by splitting the string on consecutive characters
* that are not Unicode letters, numbers, underscores, or emoji characters.
* This is the same as ``\W+`` in Python, preserving the surrogate pair area.
*/
if (typeof splitQuery === "undefined") {
var splitQuery = (query) => query
.split(/[^\p{Letter}\p{Number}_\p{Emoji_Presentation}]+/gu)
.filter(term => term) // remove remaining empty strings
}
/**
* Search Module
*/
const Search = {
_index: null,
_queued_query: null,
_pulse_status: -1,
htmlToText: (htmlString) => {
const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html');
htmlElement.querySelectorAll(".headerlink").forEach((el) => { el.remove() });
const docContent = htmlElement.querySelector('[role="main"]');
if (docContent !== undefined) return docContent.textContent;
console.warn(
"Content block not found. Sphinx search tries to obtain it via '[role=main]'. Could you check your theme or template."
);
return "";
},
init: () => {
const query = new URLSearchParams(window.location.search).get("q");
document
.querySelectorAll('input[name="q"]')
.forEach((el) => (el.value = query));
if (query) Search.performSearch(query);
},
loadIndex: (url) =>
(document.body.appendChild(document.createElement("script")).src = url),
setIndex: (index) => {
Search._index = index;
if (Search._queued_query !== null) {
const query = Search._queued_query;
Search._queued_query = null;
Search.query(query);
}
},
hasIndex: () => Search._index !== null,
deferQuery: (query) => (Search._queued_query = query),
stopPulse: () => (Search._pulse_status = -1),
startPulse: () => {
if (Search._pulse_status >= 0) return;
const pulse = () => {
Search._pulse_status = (Search._pulse_status + 1) % 4;
Search.dots.innerText = ".".repeat(Search._pulse_status);
if (Search._pulse_status >= 0) window.setTimeout(pulse, 500);
};
pulse();
},
/**
* perform a search for something (or wait until index is loaded)
*/
performSearch: (query) => {
// create the required interface elements
const searchText = document.createElement("h2");
searchText.textContent = _("Searching");
const searchSummary = document.createElement("p");
searchSummary.classList.add("search-summary");
searchSummary.innerText = "";
const searchList = document.createElement("ul");
searchList.classList.add("search");
const out = document.getElementById("search-results");
Search.title = out.appendChild(searchText);
Search.dots = Search.title.appendChild(document.createElement("span"));
Search.status = out.appendChild(searchSummary);
Search.output = out.appendChild(searchList);
const searchProgress = document.getElementById("search-progress");
// Some themes don't use the search progress node
if (searchProgress) {
searchProgress.innerText = _("Preparing search...");
}
Search.startPulse();
// index already loaded, the browser was quick!
if (Search.hasIndex()) Search.query(query);
else Search.deferQuery(query);
},
/**
* execute search (requires search index to be loaded)
*/
query: (query) => {
const filenames = Search._index.filenames;
const docNames = Search._index.docnames;
const titles = Search._index.titles;
const allTitles = Search._index.alltitles;
const indexEntries = Search._index.indexentries;
// stem the search terms and add them to the correct list
const stemmer = new Stemmer();
const searchTerms = new Set();
const excludedTerms = new Set();
const highlightTerms = new Set();
const objectTerms = new Set(splitQuery(query.toLowerCase().trim()));
splitQuery(query.trim()).forEach((queryTerm) => {
const queryTermLower = queryTerm.toLowerCase();
// maybe skip this "word"
// stopwords array is from language_data.js
if (
stopwords.indexOf(queryTermLower) !== -1 ||
queryTerm.match(/^\d+$/)
)
return;
// stem the word
let word = stemmer.stemWord(queryTermLower);
// select the correct list
if (word[0] === "-") excludedTerms.add(word.substr(1));
else {
searchTerms.add(word);
highlightTerms.add(queryTermLower);
}
});
if (SPHINX_HIGHLIGHT_ENABLED) { // set in sphinx_highlight.js
localStorage.setItem("sphinx_highlight_terms", [...highlightTerms].join(" "))
}
// console.debug("SEARCH: searching for:");
// console.info("required: ", [...searchTerms]);
// console.info("excluded: ", [...excludedTerms]);
// array of [docname, title, anchor, descr, score, filename]
let results = [];
_removeChildren(document.getElementById("search-progress"));
const queryLower = query.toLowerCase();
for (const [title, foundTitles] of Object.entries(allTitles)) {
if (title.toLowerCase().includes(queryLower) && (queryLower.length >= title.length/2)) {
for (const [file, id] of foundTitles) {
let score = Math.round(100 * queryLower.length / title.length)
results.push([
docNames[file],
titles[file] !== title ? `${titles[file]} > ${title}` : title,
id !== null ? "#" + id : "",
null,
score,
filenames[file],
]);
}
}
}
// search for explicit entries in index directives
for (const [entry, foundEntries] of Object.entries(indexEntries)) {
if (entry.includes(queryLower) && (queryLower.length >= entry.length/2)) {
for (const [file, id] of foundEntries) {
let score = Math.round(100 * queryLower.length / entry.length)
results.push([
docNames[file],
titles[file],
id ? "#" + id : "",
null,
score,
filenames[file],
]);
}
}
}
// lookup as object
objectTerms.forEach((term) =>
results.push(...Search.performObjectSearch(term, objectTerms))
);
// lookup as search terms in fulltext
results.push(...Search.performTermsSearch(searchTerms, excludedTerms));
// let the scorer override scores with a custom scoring function
if (Scorer.score) results.forEach((item) => (item[4] = Scorer.score(item)));
// now sort the results by score (in opposite order of appearance, since the
// display function below uses pop() to retrieve items) and then
// alphabetically
results.sort((a, b) => {
const leftScore = a[4];
const rightScore = b[4];
if (leftScore === rightScore) {
// same score: sort alphabetically
const leftTitle = a[1].toLowerCase();
const rightTitle = b[1].toLowerCase();
if (leftTitle === rightTitle) return 0;
return leftTitle > rightTitle ? -1 : 1; // inverted is intentional
}
return leftScore > rightScore ? 1 : -1;
});
// remove duplicate search results
// note the reversing of results, so that in the case of duplicates, the highest-scoring entry is kept
let seen = new Set();
results = results.reverse().reduce((acc, result) => {
let resultStr = result.slice(0, 4).concat([result[5]]).map(v => String(v)).join(',');
if (!seen.has(resultStr)) {
acc.push(result);
seen.add(resultStr);
}
return acc;
}, []);
results = results.reverse();
// for debugging
//Search.lastresults = results.slice(); // a copy
// console.info("search results:", Search.lastresults);
// print the results
_displayNextItem(results, results.length, searchTerms);
},
/**
* search for object names
*/
performObjectSearch: (object, objectTerms) => {
const filenames = Search._index.filenames;
const docNames = Search._index.docnames;
const objects = Search._index.objects;
const objNames = Search._index.objnames;
const titles = Search._index.titles;
const results = [];
const objectSearchCallback = (prefix, match) => {
const name = match[4]
const fullname = (prefix ? prefix + "." : "") + name;
const fullnameLower = fullname.toLowerCase();
if (fullnameLower.indexOf(object) < 0) return;
let score = 0;
const parts = fullnameLower.split(".");
// check for different match types: exact matches of full name or
// "last name" (i.e. last dotted part)
if (fullnameLower === object || parts.slice(-1)[0] === object)
score += Scorer.objNameMatch;
else if (parts.slice(-1)[0].indexOf(object) > -1)
score += Scorer.objPartialMatch; // matches in last name
const objName = objNames[match[1]][2];
const title = titles[match[0]];
// If more than one term searched for, we require other words to be
// found in the name/title/description
const otherTerms = new Set(objectTerms);
otherTerms.delete(object);
if (otherTerms.size > 0) {
const haystack = `${prefix} ${name} ${objName} ${title}`.toLowerCase();
if (
[...otherTerms].some((otherTerm) => haystack.indexOf(otherTerm) < 0)
)
return;
}
let anchor = match[3];
if (anchor === "") anchor = fullname;
else if (anchor === "-") anchor = objNames[match[1]][1] + "-" + fullname;
const descr = objName + _(", in ") + title;
// add custom score for some objects according to scorer
if (Scorer.objPrio.hasOwnProperty(match[2]))
score += Scorer.objPrio[match[2]];
else score += Scorer.objPrioDefault;
results.push([
docNames[match[0]],
fullname,
"#" + anchor,
descr,
score,
filenames[match[0]],
]);
};
Object.keys(objects).forEach((prefix) =>
objects[prefix].forEach((array) =>
objectSearchCallback(prefix, array)
)
);
return results;
},
/**
* search for full-text terms in the index
*/
performTermsSearch: (searchTerms, excludedTerms) => {
// prepare search
const terms = Search._index.terms;
const titleTerms = Search._index.titleterms;
const filenames = Search._index.filenames;
const docNames = Search._index.docnames;
const titles = Search._index.titles;
const scoreMap = new Map();
const fileMap = new Map();
// perform the search on the required terms
searchTerms.forEach((word) => {
const files = [];
const arr = [
{ files: terms[word], score: Scorer.term },
{ files: titleTerms[word], score: Scorer.title },
];
// add support for partial matches
if (word.length > 2) {
const escapedWord = _escapeRegExp(word);
Object.keys(terms).forEach((term) => {
if (term.match(escapedWord) && !terms[word])
arr.push({ files: terms[term], score: Scorer.partialTerm });
});
Object.keys(titleTerms).forEach((term) => {
if (term.match(escapedWord) && !titleTerms[word])
arr.push({ files: titleTerms[word], score: Scorer.partialTitle });
});
}
// no match but word was a required one
if (arr.every((record) => record.files === undefined)) return;
// found search word in contents
arr.forEach((record) => {
if (record.files === undefined) return;
let recordFiles = record.files;
if (recordFiles.length === undefined) recordFiles = [recordFiles];
files.push(...recordFiles);
// set score for the word in each file
recordFiles.forEach((file) => {
if (!scoreMap.has(file)) scoreMap.set(file, {});
scoreMap.get(file)[word] = record.score;
});
});
// create the mapping
files.forEach((file) => {
if (fileMap.has(file) && fileMap.get(file).indexOf(word) === -1)
fileMap.get(file).push(word);
else fileMap.set(file, [word]);
});
});
// now check if the files don't contain excluded terms
const results = [];
for (const [file, wordList] of fileMap) {
// check if all requirements are matched
// as search terms with length < 3 are discarded
const filteredTermCount = [...searchTerms].filter(
(term) => term.length > 2
).length;
if (
wordList.length !== searchTerms.size &&
wordList.length !== filteredTermCount
)
continue;
// ensure that none of the excluded terms is in the search result
if (
[...excludedTerms].some(
(term) =>
terms[term] === file ||
titleTerms[term] === file ||
(terms[term] || []).includes(file) ||
(titleTerms[term] || []).includes(file)
)
)
break;
// select one (max) score for the file.
const score = Math.max(...wordList.map((w) => scoreMap.get(file)[w]));
// add result to the result list
results.push([
docNames[file],
titles[file],
"",
null,
score,
filenames[file],
]);
}
return results;
},
/**
* helper function to return a node containing the
* search summary for a given text. keywords is a list
* of stemmed words.
*/
makeSearchSummary: (htmlText, keywords) => {
const text = Search.htmlToText(htmlText);
if (text === "") return null;
const textLower = text.toLowerCase();
const actualStartPosition = [...keywords]
.map((k) => textLower.indexOf(k.toLowerCase()))
.filter((i) => i > -1)
.slice(-1)[0];
const startWithContext = Math.max(actualStartPosition - 120, 0);
const top = startWithContext === 0 ? "" : "...";
const tail = startWithContext + 240 < text.length ? "..." : "";
let summary = document.createElement("p");
summary.classList.add("context");
summary.textContent = top + text.substr(startWithContext, 240).trim() + tail;
return summary;
},
};
_ready(Search.init);
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/searchtools.js | searchtools.js |
!function(n){var e={};function t(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return n[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=e,t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:i})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(i,o,function(e){return n[e]}.bind(null,o));return i},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){t(1),n.exports=t(3)},function(n,e,t){(function(){var e="undefined"!=typeof window?window.jQuery:t(2);n.exports.ThemeNav={navBar:null,win:null,winScroll:!1,winResize:!1,linkScroll:!1,winPosition:0,winHeight:null,docHeight:null,isRunning:!1,enable:function(n){var t=this;void 0===n&&(n=!0),t.isRunning||(t.isRunning=!0,e((function(e){t.init(e),t.reset(),t.win.on("hashchange",t.reset),n&&t.win.on("scroll",(function(){t.linkScroll||t.winScroll||(t.winScroll=!0,requestAnimationFrame((function(){t.onScroll()})))})),t.win.on("resize",(function(){t.winResize||(t.winResize=!0,requestAnimationFrame((function(){t.onResize()})))})),t.onResize()})))},enableSticky:function(){this.enable(!0)},init:function(n){n(document);var e=this;this.navBar=n("div.wy-side-scroll:first"),this.win=n(window),n(document).on("click","[data-toggle='wy-nav-top']",(function(){n("[data-toggle='wy-nav-shift']").toggleClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift")})).on("click",".wy-menu-vertical .current ul li a",(function(){var t=n(this);n("[data-toggle='wy-nav-shift']").removeClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift"),e.toggleCurrent(t),e.hashChange()})).on("click","[data-toggle='rst-current-version']",(function(){n("[data-toggle='rst-versions']").toggleClass("shift-up")})),n("table.docutils:not(.field-list,.footnote,.citation)").wrap("<div class='wy-table-responsive'></div>"),n("table.docutils.footnote").wrap("<div class='wy-table-responsive footnote'></div>"),n("table.docutils.citation").wrap("<div class='wy-table-responsive citation'></div>"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n('<button class="toctree-expand" title="Open/close menu"></button>'),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}if(t.length>0){$(".wy-menu-vertical .current").removeClass("current").attr("aria-expanded","false"),t.addClass("current").attr("aria-expanded","true"),t.closest("li.toctree-l1").parent().addClass("current").attr("aria-expanded","true");for(let n=1;n<=10;n++)t.closest("li.toctree-l"+n).addClass("current").attr("aria-expanded","true");t[0].scrollIntoView()}}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current").attr("aria-expanded","false"),e.siblings().find("li.current").removeClass("current").attr("aria-expanded","false");var t=e.find("> ul li");t.length&&(t.removeClass("current").attr("aria-expanded","false"),e.toggleClass("current").attr("aria-expanded",(function(n,e){return"true"==e?"false":"true"})))}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(e,t){var i=(new Date).getTime(),o=Math.max(0,16-(i-n)),r=window.setTimeout((function(){e(i+o)}),o);return n=i+o,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(n){clearTimeout(n)})}()}).call(window)},function(n,e){n.exports=jQuery},function(n,e,t){}]); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/js/theme.js | theme.js |
!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=4)}({4:function(e,t,r){}}); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/js/badge_only.js | badge_only.js |
/**
* @preserve HTML5 Shiv 3.7.3-pre | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=y.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=y.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),y.elements=c+" "+a,j(b)}function f(a){var b=x[a[v]];return b||(b={},w++,a[v]=w,x[w]=b),b}function g(a,c,d){if(c||(c=b),q)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():u.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||t.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),q)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return y.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(y,b.frag)}function j(a){a||(a=b);var d=f(a);return!y.shivCSS||p||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),q||i(a,d),a}function k(a){for(var b,c=a.getElementsByTagName("*"),e=c.length,f=RegExp("^(?:"+d().join("|")+")$","i"),g=[];e--;)b=c[e],f.test(b.nodeName)&&g.push(b.applyElement(l(b)));return g}function l(a){for(var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(A+":"+a.nodeName);d--;)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function m(a){for(var b,c=a.split("{"),e=c.length,f=RegExp("(^|[\\s,>+~])("+d().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),g="$1"+A+"\\:$2";e--;)b=c[e]=c[e].split("}"),b[b.length-1]=b[b.length-1].replace(f,g),c[e]=b.join("}");return c.join("{")}function n(a){for(var b=a.length;b--;)a[b].removeNode()}function o(a){function b(){clearTimeout(g._removeSheetTimer),d&&d.removeNode(!0),d=null}var d,e,g=f(a),h=a.namespaces,i=a.parentWindow;return!B||a.printShived?a:("undefined"==typeof h[A]&&h.add(A),i.attachEvent("onbeforeprint",function(){b();for(var f,g,h,i=a.styleSheets,j=[],l=i.length,n=Array(l);l--;)n[l]=i[l];for(;h=n.pop();)if(!h.disabled&&z.test(h.media)){try{f=h.imports,g=f.length}catch(o){g=0}for(l=0;g>l;l++)n.push(f[l]);try{j.push(h.cssText)}catch(o){}}j=m(j.reverse().join("")),e=k(a),d=c(a,j)}),i.attachEvent("onafterprint",function(){n(e),clearTimeout(g._removeSheetTimer),g._removeSheetTimer=setTimeout(b,500)}),a.printShived=!0,a)}var p,q,r="3.7.3",s=a.html5||{},t=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,u=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,v="_html5shiv",w=0,x={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",p="hidden"in a,q=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){p=!0,q=!0}}();var y={elements:s.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:r,shivCSS:s.shivCSS!==!1,supportsUnknownElements:q,shivMethods:s.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=y,j(b);var z=/^$|\b(?:all|print)\b/,A="html5shiv",B=!q&&function(){var c=b.documentElement;return!("undefined"==typeof b.namespaces||"undefined"==typeof b.parentWindow||"undefined"==typeof c.applyElement||"undefined"==typeof c.removeNode||"undefined"==typeof a.attachEvent)}();y.type+=" print",y.shivPrint=o,o(b),"object"==typeof module&&module.exports&&(module.exports=y)}("undefined"!=typeof window?window:this,document); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/js/html5shiv-printshiv.min.js | html5shiv-printshiv.min.js |
/**
* @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3-pre",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_build/html/_static/js/html5shiv.min.js | html5shiv.min.js |
var DOCUMENTATION_OPTIONS = {
URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
VERSION: '0.1.0',
LANGUAGE: 'en',
COLLAPSE_INDEX: false,
BUILDER: 'html',
FILE_SUFFIX: '.html',
LINK_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt',
NAVIGATION_WITH_KEYS: false,
SHOW_SEARCH_SUMMARY: true,
ENABLE_SEARCH_SHORTCUTS: true,
}; | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/documentation_options.js | documentation_options.js |
/*
* doctools.js
* ~~~~~~~~~~~
*
* Base JavaScript utilities for all Sphinx HTML documentation.
*
* :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
"use strict";
const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([
"TEXTAREA",
"INPUT",
"SELECT",
"BUTTON",
]);
const _ready = (callback) => {
if (document.readyState !== "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
};
/**
* Small JavaScript module for the documentation.
*/
const Documentation = {
init: () => {
Documentation.initDomainIndexTable();
Documentation.initOnKeyListeners();
},
/**
* i18n support
*/
TRANSLATIONS: {},
PLURAL_EXPR: (n) => (n === 1 ? 0 : 1),
LOCALE: "unknown",
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext: (string) => {
const translated = Documentation.TRANSLATIONS[string];
switch (typeof translated) {
case "undefined":
return string; // no translation
case "string":
return translated; // translation exists
default:
return translated[0]; // (singular, plural) translation tuple exists
}
},
ngettext: (singular, plural, n) => {
const translated = Documentation.TRANSLATIONS[singular];
if (typeof translated !== "undefined")
return translated[Documentation.PLURAL_EXPR(n)];
return n === 1 ? singular : plural;
},
addTranslations: (catalog) => {
Object.assign(Documentation.TRANSLATIONS, catalog.messages);
Documentation.PLURAL_EXPR = new Function(
"n",
`return (${catalog.plural_expr})`
);
Documentation.LOCALE = catalog.locale;
},
/**
* helper function to focus on search bar
*/
focusSearchBar: () => {
document.querySelectorAll("input[name=q]")[0]?.focus();
},
/**
* Initialise the domain index toggle buttons
*/
initDomainIndexTable: () => {
const toggler = (el) => {
const idNumber = el.id.substr(7);
const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`);
if (el.src.substr(-9) === "minus.png") {
el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`;
toggledRows.forEach((el) => (el.style.display = "none"));
} else {
el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`;
toggledRows.forEach((el) => (el.style.display = ""));
}
};
const togglerElements = document.querySelectorAll("img.toggler");
togglerElements.forEach((el) =>
el.addEventListener("click", (event) => toggler(event.currentTarget))
);
togglerElements.forEach((el) => (el.style.display = ""));
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler);
},
initOnKeyListeners: () => {
// only install a listener if it is really needed
if (
!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS &&
!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS
)
return;
document.addEventListener("keydown", (event) => {
// bail for input elements
if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return;
// bail with special keys
if (event.altKey || event.ctrlKey || event.metaKey) return;
if (!event.shiftKey) {
switch (event.key) {
case "ArrowLeft":
if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break;
const prevLink = document.querySelector('link[rel="prev"]');
if (prevLink && prevLink.href) {
window.location.href = prevLink.href;
event.preventDefault();
}
break;
case "ArrowRight":
if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break;
const nextLink = document.querySelector('link[rel="next"]');
if (nextLink && nextLink.href) {
window.location.href = nextLink.href;
event.preventDefault();
}
break;
}
}
// some keyboard layouts may need Shift to get /
switch (event.key) {
case "/":
if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break;
Documentation.focusSearchBar();
event.preventDefault();
}
});
},
};
// quick alias for translations
const _ = Documentation.gettext;
_ready(Documentation.init);
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/doctools.js | doctools.js |
/*
* language_data.js
* ~~~~~~~~~~~~~~~~
*
* This script contains the language-specific data used by searchtools.js,
* namely the list of stopwords, stemmer, scorer and splitter.
*
* :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
var stopwords = ["a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "near", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"];
/* Non-minified version is copied as a separate JS file, is available */
/**
* Porter Stemmer
*/
var Stemmer = function() {
var step2list = {
ational: 'ate',
tional: 'tion',
enci: 'ence',
anci: 'ance',
izer: 'ize',
bli: 'ble',
alli: 'al',
entli: 'ent',
eli: 'e',
ousli: 'ous',
ization: 'ize',
ation: 'ate',
ator: 'ate',
alism: 'al',
iveness: 'ive',
fulness: 'ful',
ousness: 'ous',
aliti: 'al',
iviti: 'ive',
biliti: 'ble',
logi: 'log'
};
var step3list = {
icate: 'ic',
ative: '',
alize: 'al',
iciti: 'ic',
ical: 'ic',
ful: '',
ness: ''
};
var c = "[^aeiou]"; // consonant
var v = "[aeiouy]"; // vowel
var C = c + "[^aeiouy]*"; // consonant sequence
var V = v + "[aeiou]*"; // vowel sequence
var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
var s_v = "^(" + C + ")?" + v; // vowel in stem
this.stemWord = function (w) {
var stem;
var suffix;
var firstch;
var origword = w;
if (w.length < 3)
return w;
var re;
var re2;
var re3;
var re4;
firstch = w.substr(0,1);
if (firstch == "y")
w = firstch.toUpperCase() + w.substr(1);
// Step 1a
re = /^(.+?)(ss|i)es$/;
re2 = /^(.+?)([^s])s$/;
if (re.test(w))
w = w.replace(re,"$1$2");
else if (re2.test(w))
w = w.replace(re2,"$1$2");
// Step 1b
re = /^(.+?)eed$/;
re2 = /^(.+?)(ed|ing)$/;
if (re.test(w)) {
var fp = re.exec(w);
re = new RegExp(mgr0);
if (re.test(fp[1])) {
re = /.$/;
w = w.replace(re,"");
}
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
re2 = new RegExp(s_v);
if (re2.test(stem)) {
w = stem;
re2 = /(at|bl|iz)$/;
re3 = new RegExp("([^aeiouylsz])\\1$");
re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re2.test(w))
w = w + "e";
else if (re3.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
else if (re4.test(w))
w = w + "e";
}
}
// Step 1c
re = /^(.+?)y$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(s_v);
if (re.test(stem))
w = stem + "i";
}
// Step 2
re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step2list[suffix];
}
// Step 3
re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
re = new RegExp(mgr0);
if (re.test(stem))
w = stem + step3list[suffix];
}
// Step 4
re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
re2 = /^(.+?)(s|t)(ion)$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
if (re.test(stem))
w = stem;
}
else if (re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1] + fp[2];
re2 = new RegExp(mgr1);
if (re2.test(stem))
w = stem;
}
// Step 5
re = /^(.+?)e$/;
if (re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
re = new RegExp(mgr1);
re2 = new RegExp(meq1);
re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
w = stem;
}
re = /ll$/;
re2 = new RegExp(mgr1);
if (re.test(w) && re2.test(w)) {
re = /.$/;
w = w.replace(re,"");
}
// and turn initial Y back to y
if (firstch == "y")
w = firstch.toLowerCase() + w.substr(1);
return w;
}
}
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/language_data.js | language_data.js |
/* Highlighting utilities for Sphinx HTML documentation. */
"use strict";
const SPHINX_HIGHLIGHT_ENABLED = true
/**
* highlight a given string on a node by wrapping it in
* span elements with the given class name.
*/
const _highlight = (node, addItems, text, className) => {
if (node.nodeType === Node.TEXT_NODE) {
const val = node.nodeValue;
const parent = node.parentNode;
const pos = val.toLowerCase().indexOf(text);
if (
pos >= 0 &&
!parent.classList.contains(className) &&
!parent.classList.contains("nohighlight")
) {
let span;
const closestNode = parent.closest("body, svg, foreignObject");
const isInSVG = closestNode && closestNode.matches("svg");
if (isInSVG) {
span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
} else {
span = document.createElement("span");
span.classList.add(className);
}
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
parent.insertBefore(
span,
parent.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling
)
);
node.nodeValue = val.substr(0, pos);
if (isInSVG) {
const rect = document.createElementNS(
"http://www.w3.org/2000/svg",
"rect"
);
const bbox = parent.getBBox();
rect.x.baseVal.value = bbox.x;
rect.y.baseVal.value = bbox.y;
rect.width.baseVal.value = bbox.width;
rect.height.baseVal.value = bbox.height;
rect.setAttribute("class", className);
addItems.push({ parent: parent, target: rect });
}
}
} else if (node.matches && !node.matches("button, select, textarea")) {
node.childNodes.forEach((el) => _highlight(el, addItems, text, className));
}
};
const _highlightText = (thisNode, text, className) => {
let addItems = [];
_highlight(thisNode, addItems, text, className);
addItems.forEach((obj) =>
obj.parent.insertAdjacentElement("beforebegin", obj.target)
);
};
/**
* Small JavaScript module for the documentation.
*/
const SphinxHighlight = {
/**
* highlight the search words provided in localstorage in the text
*/
highlightSearchWords: () => {
if (!SPHINX_HIGHLIGHT_ENABLED) return; // bail if no highlight
// get and clear terms from localstorage
const url = new URL(window.location);
const highlight =
localStorage.getItem("sphinx_highlight_terms")
|| url.searchParams.get("highlight")
|| "";
localStorage.removeItem("sphinx_highlight_terms")
url.searchParams.delete("highlight");
window.history.replaceState({}, "", url);
// get individual terms from highlight string
const terms = highlight.toLowerCase().split(/\s+/).filter(x => x);
if (terms.length === 0) return; // nothing to do
// There should never be more than one element matching "div.body"
const divBody = document.querySelectorAll("div.body");
const body = divBody.length ? divBody[0] : document.querySelector("body");
window.setTimeout(() => {
terms.forEach((term) => _highlightText(body, term, "highlighted"));
}, 10);
const searchBox = document.getElementById("searchbox");
if (searchBox === null) return;
searchBox.appendChild(
document
.createRange()
.createContextualFragment(
'<p class="highlight-link">' +
'<a href="javascript:SphinxHighlight.hideSearchWords()">' +
_("Hide Search Matches") +
"</a></p>"
)
);
},
/**
* helper function to hide the search marks again
*/
hideSearchWords: () => {
document
.querySelectorAll("#searchbox .highlight-link")
.forEach((el) => el.remove());
document
.querySelectorAll("span.highlighted")
.forEach((el) => el.classList.remove("highlighted"));
localStorage.removeItem("sphinx_highlight_terms")
},
initEscapeListener: () => {
// only install a listener if it is really needed
if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) return;
document.addEventListener("keydown", (event) => {
// bail for input elements
if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return;
// bail with special keys
if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return;
if (DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS && (event.key === "Escape")) {
SphinxHighlight.hideSearchWords();
event.preventDefault();
}
});
},
};
_ready(SphinxHighlight.highlightSearchWords);
_ready(SphinxHighlight.initEscapeListener);
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/sphinx_highlight.js | sphinx_highlight.js |
/*
* searchtools.js
* ~~~~~~~~~~~~~~~~
*
* Sphinx JavaScript utilities for the full-text search.
*
* :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
"use strict";
/**
* Simple result scoring code.
*/
if (typeof Scorer === "undefined") {
var Scorer = {
// Implement the following function to further tweak the score for each result
// The function takes a result array [docname, title, anchor, descr, score, filename]
// and returns the new score.
/*
score: result => {
const [docname, title, anchor, descr, score, filename] = result
return score
},
*/
// query matches the full name of an object
objNameMatch: 11,
// or matches in the last dotted part of the object name
objPartialMatch: 6,
// Additive scores depending on the priority of the object
objPrio: {
0: 15, // used to be importantResults
1: 5, // used to be objectResults
2: -5, // used to be unimportantResults
},
// Used when the priority is not in the mapping.
objPrioDefault: 0,
// query found in title
title: 15,
partialTitle: 7,
// query found in terms
term: 5,
partialTerm: 2,
};
}
const _removeChildren = (element) => {
while (element && element.lastChild) element.removeChild(element.lastChild);
};
/**
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
*/
const _escapeRegExp = (string) =>
string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
const _displayItem = (item, searchTerms) => {
const docBuilder = DOCUMENTATION_OPTIONS.BUILDER;
const docUrlRoot = DOCUMENTATION_OPTIONS.URL_ROOT;
const docFileSuffix = DOCUMENTATION_OPTIONS.FILE_SUFFIX;
const docLinkSuffix = DOCUMENTATION_OPTIONS.LINK_SUFFIX;
const showSearchSummary = DOCUMENTATION_OPTIONS.SHOW_SEARCH_SUMMARY;
const [docName, title, anchor, descr, score, _filename] = item;
let listItem = document.createElement("li");
let requestUrl;
let linkUrl;
if (docBuilder === "dirhtml") {
// dirhtml builder
let dirname = docName + "/";
if (dirname.match(/\/index\/$/))
dirname = dirname.substring(0, dirname.length - 6);
else if (dirname === "index/") dirname = "";
requestUrl = docUrlRoot + dirname;
linkUrl = requestUrl;
} else {
// normal html builders
requestUrl = docUrlRoot + docName + docFileSuffix;
linkUrl = docName + docLinkSuffix;
}
let linkEl = listItem.appendChild(document.createElement("a"));
linkEl.href = linkUrl + anchor;
linkEl.dataset.score = score;
linkEl.innerHTML = title;
if (descr)
listItem.appendChild(document.createElement("span")).innerHTML =
" (" + descr + ")";
else if (showSearchSummary)
fetch(requestUrl)
.then((responseData) => responseData.text())
.then((data) => {
if (data)
listItem.appendChild(
Search.makeSearchSummary(data, searchTerms)
);
});
Search.output.appendChild(listItem);
};
const _finishSearch = (resultCount) => {
Search.stopPulse();
Search.title.innerText = _("Search Results");
if (!resultCount)
Search.status.innerText = Documentation.gettext(
"Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories."
);
else
Search.status.innerText = _(
`Search finished, found ${resultCount} page(s) matching the search query.`
);
};
const _displayNextItem = (
results,
resultCount,
searchTerms
) => {
// results left, load the summary and display it
// this is intended to be dynamic (don't sub resultsCount)
if (results.length) {
_displayItem(results.pop(), searchTerms);
setTimeout(
() => _displayNextItem(results, resultCount, searchTerms),
5
);
}
// search finished, update title and status message
else _finishSearch(resultCount);
};
/**
* Default splitQuery function. Can be overridden in ``sphinx.search`` with a
* custom function per language.
*
* The regular expression works by splitting the string on consecutive characters
* that are not Unicode letters, numbers, underscores, or emoji characters.
* This is the same as ``\W+`` in Python, preserving the surrogate pair area.
*/
if (typeof splitQuery === "undefined") {
var splitQuery = (query) => query
.split(/[^\p{Letter}\p{Number}_\p{Emoji_Presentation}]+/gu)
.filter(term => term) // remove remaining empty strings
}
/**
* Search Module
*/
const Search = {
_index: null,
_queued_query: null,
_pulse_status: -1,
htmlToText: (htmlString) => {
const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html');
htmlElement.querySelectorAll(".headerlink").forEach((el) => { el.remove() });
const docContent = htmlElement.querySelector('[role="main"]');
if (docContent !== undefined) return docContent.textContent;
console.warn(
"Content block not found. Sphinx search tries to obtain it via '[role=main]'. Could you check your theme or template."
);
return "";
},
init: () => {
const query = new URLSearchParams(window.location.search).get("q");
document
.querySelectorAll('input[name="q"]')
.forEach((el) => (el.value = query));
if (query) Search.performSearch(query);
},
loadIndex: (url) =>
(document.body.appendChild(document.createElement("script")).src = url),
setIndex: (index) => {
Search._index = index;
if (Search._queued_query !== null) {
const query = Search._queued_query;
Search._queued_query = null;
Search.query(query);
}
},
hasIndex: () => Search._index !== null,
deferQuery: (query) => (Search._queued_query = query),
stopPulse: () => (Search._pulse_status = -1),
startPulse: () => {
if (Search._pulse_status >= 0) return;
const pulse = () => {
Search._pulse_status = (Search._pulse_status + 1) % 4;
Search.dots.innerText = ".".repeat(Search._pulse_status);
if (Search._pulse_status >= 0) window.setTimeout(pulse, 500);
};
pulse();
},
/**
* perform a search for something (or wait until index is loaded)
*/
performSearch: (query) => {
// create the required interface elements
const searchText = document.createElement("h2");
searchText.textContent = _("Searching");
const searchSummary = document.createElement("p");
searchSummary.classList.add("search-summary");
searchSummary.innerText = "";
const searchList = document.createElement("ul");
searchList.classList.add("search");
const out = document.getElementById("search-results");
Search.title = out.appendChild(searchText);
Search.dots = Search.title.appendChild(document.createElement("span"));
Search.status = out.appendChild(searchSummary);
Search.output = out.appendChild(searchList);
const searchProgress = document.getElementById("search-progress");
// Some themes don't use the search progress node
if (searchProgress) {
searchProgress.innerText = _("Preparing search...");
}
Search.startPulse();
// index already loaded, the browser was quick!
if (Search.hasIndex()) Search.query(query);
else Search.deferQuery(query);
},
/**
* execute search (requires search index to be loaded)
*/
query: (query) => {
const filenames = Search._index.filenames;
const docNames = Search._index.docnames;
const titles = Search._index.titles;
const allTitles = Search._index.alltitles;
const indexEntries = Search._index.indexentries;
// stem the search terms and add them to the correct list
const stemmer = new Stemmer();
const searchTerms = new Set();
const excludedTerms = new Set();
const highlightTerms = new Set();
const objectTerms = new Set(splitQuery(query.toLowerCase().trim()));
splitQuery(query.trim()).forEach((queryTerm) => {
const queryTermLower = queryTerm.toLowerCase();
// maybe skip this "word"
// stopwords array is from language_data.js
if (
stopwords.indexOf(queryTermLower) !== -1 ||
queryTerm.match(/^\d+$/)
)
return;
// stem the word
let word = stemmer.stemWord(queryTermLower);
// select the correct list
if (word[0] === "-") excludedTerms.add(word.substr(1));
else {
searchTerms.add(word);
highlightTerms.add(queryTermLower);
}
});
if (SPHINX_HIGHLIGHT_ENABLED) { // set in sphinx_highlight.js
localStorage.setItem("sphinx_highlight_terms", [...highlightTerms].join(" "))
}
// console.debug("SEARCH: searching for:");
// console.info("required: ", [...searchTerms]);
// console.info("excluded: ", [...excludedTerms]);
// array of [docname, title, anchor, descr, score, filename]
let results = [];
_removeChildren(document.getElementById("search-progress"));
const queryLower = query.toLowerCase();
for (const [title, foundTitles] of Object.entries(allTitles)) {
if (title.toLowerCase().includes(queryLower) && (queryLower.length >= title.length/2)) {
for (const [file, id] of foundTitles) {
let score = Math.round(100 * queryLower.length / title.length)
results.push([
docNames[file],
titles[file] !== title ? `${titles[file]} > ${title}` : title,
id !== null ? "#" + id : "",
null,
score,
filenames[file],
]);
}
}
}
// search for explicit entries in index directives
for (const [entry, foundEntries] of Object.entries(indexEntries)) {
if (entry.includes(queryLower) && (queryLower.length >= entry.length/2)) {
for (const [file, id] of foundEntries) {
let score = Math.round(100 * queryLower.length / entry.length)
results.push([
docNames[file],
titles[file],
id ? "#" + id : "",
null,
score,
filenames[file],
]);
}
}
}
// lookup as object
objectTerms.forEach((term) =>
results.push(...Search.performObjectSearch(term, objectTerms))
);
// lookup as search terms in fulltext
results.push(...Search.performTermsSearch(searchTerms, excludedTerms));
// let the scorer override scores with a custom scoring function
if (Scorer.score) results.forEach((item) => (item[4] = Scorer.score(item)));
// now sort the results by score (in opposite order of appearance, since the
// display function below uses pop() to retrieve items) and then
// alphabetically
results.sort((a, b) => {
const leftScore = a[4];
const rightScore = b[4];
if (leftScore === rightScore) {
// same score: sort alphabetically
const leftTitle = a[1].toLowerCase();
const rightTitle = b[1].toLowerCase();
if (leftTitle === rightTitle) return 0;
return leftTitle > rightTitle ? -1 : 1; // inverted is intentional
}
return leftScore > rightScore ? 1 : -1;
});
// remove duplicate search results
// note the reversing of results, so that in the case of duplicates, the highest-scoring entry is kept
let seen = new Set();
results = results.reverse().reduce((acc, result) => {
let resultStr = result.slice(0, 4).concat([result[5]]).map(v => String(v)).join(',');
if (!seen.has(resultStr)) {
acc.push(result);
seen.add(resultStr);
}
return acc;
}, []);
results = results.reverse();
// for debugging
//Search.lastresults = results.slice(); // a copy
// console.info("search results:", Search.lastresults);
// print the results
_displayNextItem(results, results.length, searchTerms);
},
/**
* search for object names
*/
performObjectSearch: (object, objectTerms) => {
const filenames = Search._index.filenames;
const docNames = Search._index.docnames;
const objects = Search._index.objects;
const objNames = Search._index.objnames;
const titles = Search._index.titles;
const results = [];
const objectSearchCallback = (prefix, match) => {
const name = match[4]
const fullname = (prefix ? prefix + "." : "") + name;
const fullnameLower = fullname.toLowerCase();
if (fullnameLower.indexOf(object) < 0) return;
let score = 0;
const parts = fullnameLower.split(".");
// check for different match types: exact matches of full name or
// "last name" (i.e. last dotted part)
if (fullnameLower === object || parts.slice(-1)[0] === object)
score += Scorer.objNameMatch;
else if (parts.slice(-1)[0].indexOf(object) > -1)
score += Scorer.objPartialMatch; // matches in last name
const objName = objNames[match[1]][2];
const title = titles[match[0]];
// If more than one term searched for, we require other words to be
// found in the name/title/description
const otherTerms = new Set(objectTerms);
otherTerms.delete(object);
if (otherTerms.size > 0) {
const haystack = `${prefix} ${name} ${objName} ${title}`.toLowerCase();
if (
[...otherTerms].some((otherTerm) => haystack.indexOf(otherTerm) < 0)
)
return;
}
let anchor = match[3];
if (anchor === "") anchor = fullname;
else if (anchor === "-") anchor = objNames[match[1]][1] + "-" + fullname;
const descr = objName + _(", in ") + title;
// add custom score for some objects according to scorer
if (Scorer.objPrio.hasOwnProperty(match[2]))
score += Scorer.objPrio[match[2]];
else score += Scorer.objPrioDefault;
results.push([
docNames[match[0]],
fullname,
"#" + anchor,
descr,
score,
filenames[match[0]],
]);
};
Object.keys(objects).forEach((prefix) =>
objects[prefix].forEach((array) =>
objectSearchCallback(prefix, array)
)
);
return results;
},
/**
* search for full-text terms in the index
*/
performTermsSearch: (searchTerms, excludedTerms) => {
// prepare search
const terms = Search._index.terms;
const titleTerms = Search._index.titleterms;
const filenames = Search._index.filenames;
const docNames = Search._index.docnames;
const titles = Search._index.titles;
const scoreMap = new Map();
const fileMap = new Map();
// perform the search on the required terms
searchTerms.forEach((word) => {
const files = [];
const arr = [
{ files: terms[word], score: Scorer.term },
{ files: titleTerms[word], score: Scorer.title },
];
// add support for partial matches
if (word.length > 2) {
const escapedWord = _escapeRegExp(word);
Object.keys(terms).forEach((term) => {
if (term.match(escapedWord) && !terms[word])
arr.push({ files: terms[term], score: Scorer.partialTerm });
});
Object.keys(titleTerms).forEach((term) => {
if (term.match(escapedWord) && !titleTerms[word])
arr.push({ files: titleTerms[word], score: Scorer.partialTitle });
});
}
// no match but word was a required one
if (arr.every((record) => record.files === undefined)) return;
// found search word in contents
arr.forEach((record) => {
if (record.files === undefined) return;
let recordFiles = record.files;
if (recordFiles.length === undefined) recordFiles = [recordFiles];
files.push(...recordFiles);
// set score for the word in each file
recordFiles.forEach((file) => {
if (!scoreMap.has(file)) scoreMap.set(file, {});
scoreMap.get(file)[word] = record.score;
});
});
// create the mapping
files.forEach((file) => {
if (fileMap.has(file) && fileMap.get(file).indexOf(word) === -1)
fileMap.get(file).push(word);
else fileMap.set(file, [word]);
});
});
// now check if the files don't contain excluded terms
const results = [];
for (const [file, wordList] of fileMap) {
// check if all requirements are matched
// as search terms with length < 3 are discarded
const filteredTermCount = [...searchTerms].filter(
(term) => term.length > 2
).length;
if (
wordList.length !== searchTerms.size &&
wordList.length !== filteredTermCount
)
continue;
// ensure that none of the excluded terms is in the search result
if (
[...excludedTerms].some(
(term) =>
terms[term] === file ||
titleTerms[term] === file ||
(terms[term] || []).includes(file) ||
(titleTerms[term] || []).includes(file)
)
)
break;
// select one (max) score for the file.
const score = Math.max(...wordList.map((w) => scoreMap.get(file)[w]));
// add result to the result list
results.push([
docNames[file],
titles[file],
"",
null,
score,
filenames[file],
]);
}
return results;
},
/**
* helper function to return a node containing the
* search summary for a given text. keywords is a list
* of stemmed words.
*/
makeSearchSummary: (htmlText, keywords) => {
const text = Search.htmlToText(htmlText);
if (text === "") return null;
const textLower = text.toLowerCase();
const actualStartPosition = [...keywords]
.map((k) => textLower.indexOf(k.toLowerCase()))
.filter((i) => i > -1)
.slice(-1)[0];
const startWithContext = Math.max(actualStartPosition - 120, 0);
const top = startWithContext === 0 ? "" : "...";
const tail = startWithContext + 240 < text.length ? "..." : "";
let summary = document.createElement("p");
summary.classList.add("context");
summary.textContent = top + text.substr(startWithContext, 240).trim() + tail;
return summary;
},
};
_ready(Search.init);
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/searchtools.js | searchtools.js |
!function(n){var e={};function t(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return n[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=e,t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:i})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(i,o,function(e){return n[e]}.bind(null,o));return i},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){t(1),n.exports=t(3)},function(n,e,t){(function(){var e="undefined"!=typeof window?window.jQuery:t(2);n.exports.ThemeNav={navBar:null,win:null,winScroll:!1,winResize:!1,linkScroll:!1,winPosition:0,winHeight:null,docHeight:null,isRunning:!1,enable:function(n){var t=this;void 0===n&&(n=!0),t.isRunning||(t.isRunning=!0,e((function(e){t.init(e),t.reset(),t.win.on("hashchange",t.reset),n&&t.win.on("scroll",(function(){t.linkScroll||t.winScroll||(t.winScroll=!0,requestAnimationFrame((function(){t.onScroll()})))})),t.win.on("resize",(function(){t.winResize||(t.winResize=!0,requestAnimationFrame((function(){t.onResize()})))})),t.onResize()})))},enableSticky:function(){this.enable(!0)},init:function(n){n(document);var e=this;this.navBar=n("div.wy-side-scroll:first"),this.win=n(window),n(document).on("click","[data-toggle='wy-nav-top']",(function(){n("[data-toggle='wy-nav-shift']").toggleClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift")})).on("click",".wy-menu-vertical .current ul li a",(function(){var t=n(this);n("[data-toggle='wy-nav-shift']").removeClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift"),e.toggleCurrent(t),e.hashChange()})).on("click","[data-toggle='rst-current-version']",(function(){n("[data-toggle='rst-versions']").toggleClass("shift-up")})),n("table.docutils:not(.field-list,.footnote,.citation)").wrap("<div class='wy-table-responsive'></div>"),n("table.docutils.footnote").wrap("<div class='wy-table-responsive footnote'></div>"),n("table.docutils.citation").wrap("<div class='wy-table-responsive citation'></div>"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n('<button class="toctree-expand" title="Open/close menu"></button>'),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}if(t.length>0){$(".wy-menu-vertical .current").removeClass("current").attr("aria-expanded","false"),t.addClass("current").attr("aria-expanded","true"),t.closest("li.toctree-l1").parent().addClass("current").attr("aria-expanded","true");for(let n=1;n<=10;n++)t.closest("li.toctree-l"+n).addClass("current").attr("aria-expanded","true");t[0].scrollIntoView()}}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current").attr("aria-expanded","false"),e.siblings().find("li.current").removeClass("current").attr("aria-expanded","false");var t=e.find("> ul li");t.length&&(t.removeClass("current").attr("aria-expanded","false"),e.toggleClass("current").attr("aria-expanded",(function(n,e){return"true"==e?"false":"true"})))}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(e,t){var i=(new Date).getTime(),o=Math.max(0,16-(i-n)),r=window.setTimeout((function(){e(i+o)}),o);return n=i+o,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(n){clearTimeout(n)})}()}).call(window)},function(n,e){n.exports=jQuery},function(n,e,t){}]); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/js/theme.js | theme.js |
!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=4)}({4:function(e,t,r){}}); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/js/badge_only.js | badge_only.js |
/**
* @preserve HTML5 Shiv 3.7.3-pre | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=y.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=y.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),y.elements=c+" "+a,j(b)}function f(a){var b=x[a[v]];return b||(b={},w++,a[v]=w,x[w]=b),b}function g(a,c,d){if(c||(c=b),q)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():u.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||t.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),q)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return y.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(y,b.frag)}function j(a){a||(a=b);var d=f(a);return!y.shivCSS||p||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),q||i(a,d),a}function k(a){for(var b,c=a.getElementsByTagName("*"),e=c.length,f=RegExp("^(?:"+d().join("|")+")$","i"),g=[];e--;)b=c[e],f.test(b.nodeName)&&g.push(b.applyElement(l(b)));return g}function l(a){for(var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(A+":"+a.nodeName);d--;)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function m(a){for(var b,c=a.split("{"),e=c.length,f=RegExp("(^|[\\s,>+~])("+d().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),g="$1"+A+"\\:$2";e--;)b=c[e]=c[e].split("}"),b[b.length-1]=b[b.length-1].replace(f,g),c[e]=b.join("}");return c.join("{")}function n(a){for(var b=a.length;b--;)a[b].removeNode()}function o(a){function b(){clearTimeout(g._removeSheetTimer),d&&d.removeNode(!0),d=null}var d,e,g=f(a),h=a.namespaces,i=a.parentWindow;return!B||a.printShived?a:("undefined"==typeof h[A]&&h.add(A),i.attachEvent("onbeforeprint",function(){b();for(var f,g,h,i=a.styleSheets,j=[],l=i.length,n=Array(l);l--;)n[l]=i[l];for(;h=n.pop();)if(!h.disabled&&z.test(h.media)){try{f=h.imports,g=f.length}catch(o){g=0}for(l=0;g>l;l++)n.push(f[l]);try{j.push(h.cssText)}catch(o){}}j=m(j.reverse().join("")),e=k(a),d=c(a,j)}),i.attachEvent("onafterprint",function(){n(e),clearTimeout(g._removeSheetTimer),g._removeSheetTimer=setTimeout(b,500)}),a.printShived=!0,a)}var p,q,r="3.7.3",s=a.html5||{},t=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,u=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,v="_html5shiv",w=0,x={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",p="hidden"in a,q=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){p=!0,q=!0}}();var y={elements:s.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:r,shivCSS:s.shivCSS!==!1,supportsUnknownElements:q,shivMethods:s.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=y,j(b);var z=/^$|\b(?:all|print)\b/,A="html5shiv",B=!q&&function(){var c=b.documentElement;return!("undefined"==typeof b.namespaces||"undefined"==typeof b.parentWindow||"undefined"==typeof c.applyElement||"undefined"==typeof c.removeNode||"undefined"==typeof a.attachEvent)}();y.type+=" print",y.shivPrint=o,o(b),"object"==typeof module&&module.exports&&(module.exports=y)}("undefined"!=typeof window?window:this,document); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/js/html5shiv-printshiv.min.js | html5shiv-printshiv.min.js |
/**
* @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
!function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3-pre",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); | 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/docs/_static/js/html5shiv.min.js | html5shiv.min.js |
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/.github/ISSUE_TEMPLATE/bug_report.md | bug_report.md |
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| 7Wonder-RL-Lib | /7Wonder-RL-Lib-0.1.1.tar.gz/7Wonder-RL-Lib-0.1.1/.github/ISSUE_TEMPLATE/feature_request.md | feature_request.md |
def ko(a,b):
return a+b
def dabash(a,b):
return a/b
def kam(a,b):
return a-b
def karat(a,b):
return a*b | 7asiba | /7asiba-0.1-py3-none-any.whl/pypi/__init__.py | __init__.py |
from distutils.core import setup
setup(
name='7d_demand_bundles',
packages=['7d_demand_bundles'],
version='0.0.0',
description='My first Python library',
author='Rafael Zanuto Bianchi',
license='MIT',
setup_requires=['nb_black==1.0.7', 'numpy==1.20.0',
'openpyxl==3.0.90','pandas==1.3.3',
'PuLP==2.5.0']
)
| 7d-demand-bundles | /7d_demand_bundles-0.0.0.tar.gz/7d_demand_bundles-0.0.0/setup.py | setup.py |
# 7i96
7i96 Configuration Tool
Scope
Read in the ini configuration file for changes.
Create a complete configuration from scratch.
Depends on python3-pyqt5
sudo apt-get install python3-pqt5
Open the sample ini file then make changes as needed then build
You can create a configuration then run it with the Axis GUI and use
Machine > Calibration to tune each axis. Save the values to the ini file and
next time you run the 7i96 Configuration Tool it will read the values from the
ini file.
| 7i96 | /7i96-0.0.2.tar.gz/7i96-0.0.2/README.md | README.md |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="7i96",
version="0.0.2",
author="John Thornton",
author_email="bjt128@gmail.com",
description="LinuxCNC 2.8 Mesa 7i96 Configuration Tool",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/jethornton/7i96",
packages=setuptools.find_packages(),
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
"Operating System :: OS Independent",
),
)
| 7i96 | /7i96-0.0.2.tar.gz/7i96-0.0.2/setup.py | setup.py |
Some deploy packages for ocr.
| 7lk_ocr_deploy | /7lk_ocr_deploy-0.1.69.tar.gz/7lk_ocr_deploy-0.1.69/README.txt | README.txt |
# -*- coding: utf-8 -*-
import codecs
import os
import sys
from setuptools import find_packages
from distutils.core import setup, Extension
try:
from setuptools import setup
except:
from distutils.core import setup
def read(fname):
"""
定义一个read方法,用来读取目录下的长描述
我们一般是将README文件中的内容读取出来作为长描述,这个会在PyPI中你这个包的页面上展现出来,
你也可以不用这个方法,自己手动写内容即可,
PyPI上支持.rst格式的文件。暂不支持.md格式的文件,<BR>.rst文件PyPI会自动把它转为HTML形式显示在你包的信息页面上。
"""
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
NAME = "7lk_ocr_deploy"
"""
名字,一般放你包的名字即可
"""
PACKAGES = ["libsvm", ]
"""
包含的包,可以多个,这是一个列表
"""
DESCRIPTION = "Some deploy packages for ocr."
LONG_DESCRIPTION = read("README.txt")
KEYWORDS = "test python package"
AUTHOR = "cjyfff"
AUTHOR_EMAIL = "youremail@email.com"
URL = "http://blog.useasp.net/"
VERSION = "0.1.69"
LICENSE = "MIT"
svm = Extension('libsvm', sources=['libsvm-source/svm.cpp'], library_dirs=['/usr/local/lib'],)
svm_predict = Extension('svm-predict', sources=['libsvm-source/svm-predict.c'])
svm_scale = Extension('svm-scale', sources=['libsvm-source/svm-scale.c'])
svm_train = Extension('svm-train', sources=['libsvm-source/svm-train.c'])
INSTALL_REQUIRES = ['Django==1.8', 'numpy==1.10.1', 'Pillow==3.0.0', 'PyYAML==3.11',
'django_nose>=1.4.1', 'nose>=1.3.7', 'pylint>=1.4.4', 'pylint-django>=0.6.1',
'celery==3.1.19', 'django-celery==3.1.17', 'redis==2.10.5', 'Whoosh==2.7.0',
'jieba==0.37', 'requests==2.9.0',
]
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
],
keywords=KEYWORDS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
url=URL,
license=LICENSE,
packages=PACKAGES,
include_package_data=True,
zip_safe=True,
ext_modules=[svm, svm_predict, svm_scale, svm_train],
install_requires=INSTALL_REQUIRES,
)
| 7lk_ocr_deploy | /7lk_ocr_deploy-0.1.69.tar.gz/7lk_ocr_deploy-0.1.69/setup.py | setup.py |
#!/usr/bin/env python
from ctypes import *
from ctypes.util import find_library
from os import path
import sys
__all__ = ['libsvm', 'svm_problem', 'svm_parameter',
'toPyModel', 'gen_svm_nodearray', 'print_null', 'svm_node', 'C_SVC',
'EPSILON_SVR', 'LINEAR', 'NU_SVC', 'NU_SVR', 'ONE_CLASS',
'POLY', 'PRECOMPUTED', 'PRINT_STRING_FUN', 'RBF',
'SIGMOID', 'c_double', 'svm_model']
try:
dirname = path.dirname(path.abspath(__file__))
if sys.platform == 'win32':
libsvm = CDLL(path.join(dirname, r'..\windows\libsvm.dll'))
else:
libsvm = CDLL(path.join(dirname, '../libsvm.so'))
except:
# For unix the prefix 'lib' is not considered.
if find_library('svm'):
libsvm = CDLL(find_library('svm'))
elif find_library('libsvm'):
libsvm = CDLL(find_library('libsvm'))
else:
raise Exception('LIBSVM library not found.')
C_SVC = 0
NU_SVC = 1
ONE_CLASS = 2
EPSILON_SVR = 3
NU_SVR = 4
LINEAR = 0
POLY = 1
RBF = 2
SIGMOID = 3
PRECOMPUTED = 4
PRINT_STRING_FUN = CFUNCTYPE(None, c_char_p)
def print_null(s):
return
def genFields(names, types):
return list(zip(names, types))
def fillprototype(f, restype, argtypes):
f.restype = restype
f.argtypes = argtypes
class svm_node(Structure):
_names = ["index", "value"]
_types = [c_int, c_double]
_fields_ = genFields(_names, _types)
def __str__(self):
return '%d:%g' % (self.index, self.value)
def gen_svm_nodearray(xi, feature_max=None, isKernel=None):
if isinstance(xi, dict):
index_range = xi.keys()
elif isinstance(xi, (list, tuple)):
if not isKernel:
xi = [0] + xi # idx should start from 1
index_range = range(len(xi))
else:
raise TypeError('xi should be a dictionary, list or tuple')
if feature_max:
assert(isinstance(feature_max, int))
index_range = filter(lambda j: j <= feature_max, index_range)
if not isKernel:
index_range = filter(lambda j:xi[j] != 0, index_range)
index_range = sorted(index_range)
ret = (svm_node * (len(index_range)+1))()
ret[-1].index = -1
for idx, j in enumerate(index_range):
ret[idx].index = j
ret[idx].value = xi[j]
max_idx = 0
if index_range:
max_idx = index_range[-1]
return ret, max_idx
class svm_problem(Structure):
_names = ["l", "y", "x"]
_types = [c_int, POINTER(c_double), POINTER(POINTER(svm_node))]
_fields_ = genFields(_names, _types)
def __init__(self, y, x, isKernel=None):
if len(y) != len(x):
raise ValueError("len(y) != len(x)")
self.l = l = len(y)
max_idx = 0
x_space = self.x_space = []
for i, xi in enumerate(x):
tmp_xi, tmp_idx = gen_svm_nodearray(xi,isKernel=isKernel)
x_space += [tmp_xi]
max_idx = max(max_idx, tmp_idx)
self.n = max_idx
self.y = (c_double * l)()
for i, yi in enumerate(y): self.y[i] = yi
self.x = (POINTER(svm_node) * l)()
for i, xi in enumerate(self.x_space): self.x[i] = xi
class svm_parameter(Structure):
_names = ["svm_type", "kernel_type", "degree", "gamma", "coef0",
"cache_size", "eps", "C", "nr_weight", "weight_label", "weight",
"nu", "p", "shrinking", "probability"]
_types = [c_int, c_int, c_int, c_double, c_double,
c_double, c_double, c_double, c_int, POINTER(c_int), POINTER(c_double),
c_double, c_double, c_int, c_int]
_fields_ = genFields(_names, _types)
def __init__(self, options = None):
if options == None:
options = ''
self.parse_options(options)
def __str__(self):
s = ''
attrs = svm_parameter._names + list(self.__dict__.keys())
values = map(lambda attr: getattr(self, attr), attrs)
for attr, val in zip(attrs, values):
s += (' %s: %s\n' % (attr, val))
s = s.strip()
return s
def set_to_default_values(self):
self.svm_type = C_SVC;
self.kernel_type = RBF
self.degree = 3
self.gamma = 0
self.coef0 = 0
self.nu = 0.5
self.cache_size = 100
self.C = 1
self.eps = 0.001
self.p = 0.1
self.shrinking = 1
self.probability = 0
self.nr_weight = 0
self.weight_label = (c_int*0)()
self.weight = (c_double*0)()
self.cross_validation = False
self.nr_fold = 0
self.print_func = cast(None, PRINT_STRING_FUN)
def parse_options(self, options):
if isinstance(options, list):
argv = options
elif isinstance(options, str):
argv = options.split()
else:
raise TypeError("arg 1 should be a list or a str.")
self.set_to_default_values()
self.print_func = cast(None, PRINT_STRING_FUN)
weight_label = []
weight = []
i = 0
while i < len(argv):
if argv[i] == "-s":
i = i + 1
self.svm_type = int(argv[i])
elif argv[i] == "-t":
i = i + 1
self.kernel_type = int(argv[i])
elif argv[i] == "-d":
i = i + 1
self.degree = int(argv[i])
elif argv[i] == "-g":
i = i + 1
self.gamma = float(argv[i])
elif argv[i] == "-r":
i = i + 1
self.coef0 = float(argv[i])
elif argv[i] == "-n":
i = i + 1
self.nu = float(argv[i])
elif argv[i] == "-m":
i = i + 1
self.cache_size = float(argv[i])
elif argv[i] == "-c":
i = i + 1
self.C = float(argv[i])
elif argv[i] == "-e":
i = i + 1
self.eps = float(argv[i])
elif argv[i] == "-p":
i = i + 1
self.p = float(argv[i])
elif argv[i] == "-h":
i = i + 1
self.shrinking = int(argv[i])
elif argv[i] == "-b":
i = i + 1
self.probability = int(argv[i])
elif argv[i] == "-q":
self.print_func = PRINT_STRING_FUN(print_null)
elif argv[i] == "-v":
i = i + 1
self.cross_validation = 1
self.nr_fold = int(argv[i])
if self.nr_fold < 2:
raise ValueError("n-fold cross validation: n must >= 2")
elif argv[i].startswith("-w"):
i = i + 1
self.nr_weight += 1
nr_weight = self.nr_weight
weight_label += [int(argv[i-1][2:])]
weight += [float(argv[i])]
else:
raise ValueError("Wrong options")
i += 1
libsvm.svm_set_print_string_function(self.print_func)
self.weight_label = (c_int*self.nr_weight)()
self.weight = (c_double*self.nr_weight)()
for i in range(self.nr_weight):
self.weight[i] = weight[i]
self.weight_label[i] = weight_label[i]
class svm_model(Structure):
_names = ['param', 'nr_class', 'l', 'SV', 'sv_coef', 'rho',
'probA', 'probB', 'sv_indices', 'label', 'nSV', 'free_sv']
_types = [svm_parameter, c_int, c_int, POINTER(POINTER(svm_node)),
POINTER(POINTER(c_double)), POINTER(c_double),
POINTER(c_double), POINTER(c_double), POINTER(c_int),
POINTER(c_int), POINTER(c_int), c_int]
_fields_ = genFields(_names, _types)
def __init__(self):
self.__createfrom__ = 'python'
def __del__(self):
# free memory created by C to avoid memory leak
if hasattr(self, '__createfrom__') and self.__createfrom__ == 'C':
libsvm.svm_free_and_destroy_model(pointer(self))
def get_svm_type(self):
return libsvm.svm_get_svm_type(self)
def get_nr_class(self):
return libsvm.svm_get_nr_class(self)
def get_svr_probability(self):
return libsvm.svm_get_svr_probability(self)
def get_labels(self):
nr_class = self.get_nr_class()
labels = (c_int * nr_class)()
libsvm.svm_get_labels(self, labels)
return labels[:nr_class]
def get_sv_indices(self):
total_sv = self.get_nr_sv()
sv_indices = (c_int * total_sv)()
libsvm.svm_get_sv_indices(self, sv_indices)
return sv_indices[:total_sv]
def get_nr_sv(self):
return libsvm.svm_get_nr_sv(self)
def is_probability_model(self):
return (libsvm.svm_check_probability_model(self) == 1)
def get_sv_coef(self):
return [tuple(self.sv_coef[j][i] for j in xrange(self.nr_class - 1))
for i in xrange(self.l)]
def get_SV(self):
result = []
for sparse_sv in self.SV[:self.l]:
row = dict()
i = 0
while True:
row[sparse_sv[i].index] = sparse_sv[i].value
if sparse_sv[i].index == -1:
break
i += 1
result.append(row)
return result
def toPyModel(model_ptr):
"""
toPyModel(model_ptr) -> svm_model
Convert a ctypes POINTER(svm_model) to a Python svm_model
"""
if bool(model_ptr) == False:
raise ValueError("Null pointer")
m = model_ptr.contents
m.__createfrom__ = 'C'
return m
fillprototype(libsvm.svm_train, POINTER(svm_model), [POINTER(svm_problem), POINTER(svm_parameter)])
fillprototype(libsvm.svm_cross_validation, None, [POINTER(svm_problem), POINTER(svm_parameter), c_int, POINTER(c_double)])
fillprototype(libsvm.svm_save_model, c_int, [c_char_p, POINTER(svm_model)])
fillprototype(libsvm.svm_load_model, POINTER(svm_model), [c_char_p])
fillprototype(libsvm.svm_get_svm_type, c_int, [POINTER(svm_model)])
fillprototype(libsvm.svm_get_nr_class, c_int, [POINTER(svm_model)])
fillprototype(libsvm.svm_get_labels, None, [POINTER(svm_model), POINTER(c_int)])
fillprototype(libsvm.svm_get_sv_indices, None, [POINTER(svm_model), POINTER(c_int)])
fillprototype(libsvm.svm_get_nr_sv, c_int, [POINTER(svm_model)])
fillprototype(libsvm.svm_get_svr_probability, c_double, [POINTER(svm_model)])
fillprototype(libsvm.svm_predict_values, c_double, [POINTER(svm_model), POINTER(svm_node), POINTER(c_double)])
fillprototype(libsvm.svm_predict, c_double, [POINTER(svm_model), POINTER(svm_node)])
fillprototype(libsvm.svm_predict_probability, c_double, [POINTER(svm_model), POINTER(svm_node), POINTER(c_double)])
fillprototype(libsvm.svm_free_model_content, None, [POINTER(svm_model)])
fillprototype(libsvm.svm_free_and_destroy_model, None, [POINTER(POINTER(svm_model))])
fillprototype(libsvm.svm_destroy_param, None, [POINTER(svm_parameter)])
fillprototype(libsvm.svm_check_parameter, c_char_p, [POINTER(svm_problem), POINTER(svm_parameter)])
fillprototype(libsvm.svm_check_probability_model, c_int, [POINTER(svm_model)])
fillprototype(libsvm.svm_set_print_string_function, None, [PRINT_STRING_FUN])
| 7lk_ocr_deploy | /7lk_ocr_deploy-0.1.69.tar.gz/7lk_ocr_deploy-0.1.69/libsvm/svm.py | svm.py |
#!/usr/bin/env python
import os
import sys
from svm import *
from svm import __all__ as svm_all
__all__ = ['evaluations', 'svm_load_model', 'svm_predict', 'svm_read_problem',
'svm_save_model', 'svm_train'] + svm_all
sys.path = [os.path.dirname(os.path.abspath(__file__))] + sys.path
def svm_read_problem(data_file_name):
"""
svm_read_problem(data_file_name) -> [y, x]
Read LIBSVM-format data from data_file_name and return labels y
and data instances x.
"""
prob_y = []
prob_x = []
for line in open(data_file_name):
line = line.split(None, 1)
# In case an instance with all zero features
if len(line) == 1: line += ['']
label, features = line
xi = {}
for e in features.split():
ind, val = e.split(":")
xi[int(ind)] = float(val)
prob_y += [float(label)]
prob_x += [xi]
return (prob_y, prob_x)
def svm_load_model(model_file_name):
"""
svm_load_model(model_file_name) -> model
Load a LIBSVM model from model_file_name and return.
"""
model = libsvm.svm_load_model(model_file_name.encode())
if not model:
print("can't open model file %s" % model_file_name)
return None
model = toPyModel(model)
return model
def svm_save_model(model_file_name, model):
"""
svm_save_model(model_file_name, model) -> None
Save a LIBSVM model to the file model_file_name.
"""
libsvm.svm_save_model(model_file_name.encode(), model)
def evaluations(ty, pv):
"""
evaluations(ty, pv) -> (ACC, MSE, SCC)
Calculate accuracy, mean squared error and squared correlation coefficient
using the true values (ty) and predicted values (pv).
"""
if len(ty) != len(pv):
raise ValueError("len(ty) must equal to len(pv)")
total_correct = total_error = 0
sumv = sumy = sumvv = sumyy = sumvy = 0
for v, y in zip(pv, ty):
if y == v:
total_correct += 1
total_error += (v-y)*(v-y)
sumv += v
sumy += y
sumvv += v*v
sumyy += y*y
sumvy += v*y
l = len(ty)
ACC = 100.0*total_correct/l
MSE = total_error/l
try:
SCC = ((l*sumvy-sumv*sumy)*(l*sumvy-sumv*sumy))/((l*sumvv-sumv*sumv)*(l*sumyy-sumy*sumy))
except:
SCC = float('nan')
return (ACC, MSE, SCC)
def svm_train(arg1, arg2=None, arg3=None):
"""
svm_train(y, x [, options]) -> model | ACC | MSE
svm_train(prob [, options]) -> model | ACC | MSE
svm_train(prob, param) -> model | ACC| MSE
Train an SVM model from data (y, x) or an svm_problem prob using
'options' or an svm_parameter param.
If '-v' is specified in 'options' (i.e., cross validation)
either accuracy (ACC) or mean-squared error (MSE) is returned.
options:
-s svm_type : set type of SVM (default 0)
0 -- C-SVC (multi-class classification)
1 -- nu-SVC (multi-class classification)
2 -- one-class SVM
3 -- epsilon-SVR (regression)
4 -- nu-SVR (regression)
-t kernel_type : set type of kernel function (default 2)
0 -- linear: u'*v
1 -- polynomial: (gamma*u'*v + coef0)^degree
2 -- radial basis function: exp(-gamma*|u-v|^2)
3 -- sigmoid: tanh(gamma*u'*v + coef0)
4 -- precomputed kernel (kernel values in training_set_file)
-d degree : set degree in kernel function (default 3)
-g gamma : set gamma in kernel function (default 1/num_features)
-r coef0 : set coef0 in kernel function (default 0)
-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
-m cachesize : set cache memory size in MB (default 100)
-e epsilon : set tolerance of termination criterion (default 0.001)
-h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)
-b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
-wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)
-v n: n-fold cross validation mode
-q : quiet mode (no outputs)
"""
prob, param = None, None
if isinstance(arg1, (list, tuple)):
assert isinstance(arg2, (list, tuple))
y, x, options = arg1, arg2, arg3
param = svm_parameter(options)
prob = svm_problem(y, x, isKernel=(param.kernel_type == PRECOMPUTED))
elif isinstance(arg1, svm_problem):
prob = arg1
if isinstance(arg2, svm_parameter):
param = arg2
else:
param = svm_parameter(arg2)
if prob == None or param == None:
raise TypeError("Wrong types for the arguments")
if param.kernel_type == PRECOMPUTED:
for xi in prob.x_space:
idx, val = xi[0].index, xi[0].value
if xi[0].index != 0:
raise ValueError('Wrong input format: first column must be 0:sample_serial_number')
if val <= 0 or val > prob.n:
raise ValueError('Wrong input format: sample_serial_number out of range')
if param.gamma == 0 and prob.n > 0:
param.gamma = 1.0 / prob.n
libsvm.svm_set_print_string_function(param.print_func)
err_msg = libsvm.svm_check_parameter(prob, param)
if err_msg:
raise ValueError('Error: %s' % err_msg)
if param.cross_validation:
l, nr_fold = prob.l, param.nr_fold
target = (c_double * l)()
libsvm.svm_cross_validation(prob, param, nr_fold, target)
ACC, MSE, SCC = evaluations(prob.y[:l], target[:l])
if param.svm_type in [EPSILON_SVR, NU_SVR]:
print("Cross Validation Mean squared error = %g" % MSE)
print("Cross Validation Squared correlation coefficient = %g" % SCC)
return MSE
else:
print("Cross Validation Accuracy = %g%%" % ACC)
return ACC
else:
m = libsvm.svm_train(prob, param)
m = toPyModel(m)
# If prob is destroyed, data including SVs pointed by m can remain.
m.x_space = prob.x_space
return m
def svm_predict(y, x, m, options=""):
"""
svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
Predict data (y, x) with the SVM model m.
options:
-b probability_estimates: whether to predict probability estimates,
0 or 1 (default 0); for one-class SVM only 0 is supported.
-q : quiet mode (no outputs).
The return tuple contains
p_labels: a list of predicted labels
p_acc: a tuple including accuracy (for classification), mean-squared
error, and squared correlation coefficient (for regression).
p_vals: a list of decision values or probability estimates (if '-b 1'
is specified). If k is the number of classes, for decision values,
each element includes results of predicting k(k-1)/2 binary-class
SVMs. For probabilities, each element contains k values indicating
the probability that the testing instance is in each class.
Note that the order of classes here is the same as 'model.label'
field in the model structure.
"""
def info(s):
print(s)
predict_probability = 0
argv = options.split()
i = 0
while i < len(argv):
if argv[i] == '-b':
i += 1
predict_probability = int(argv[i])
elif argv[i] == '-q':
info = print_null
else:
raise ValueError("Wrong options")
i+=1
svm_type = m.get_svm_type()
is_prob_model = m.is_probability_model()
nr_class = m.get_nr_class()
pred_labels = []
pred_values = []
if predict_probability:
if not is_prob_model:
raise ValueError("Model does not support probabiliy estimates")
if svm_type in [NU_SVR, EPSILON_SVR]:
info("Prob. model for test data: target value = predicted value + z,\n"
"z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g" % m.get_svr_probability());
nr_class = 0
prob_estimates = (c_double * nr_class)()
for xi in x:
xi, idx = gen_svm_nodearray(xi, isKernel=(m.param.kernel_type == PRECOMPUTED))
label = libsvm.svm_predict_probability(m, xi, prob_estimates)
values = prob_estimates[:nr_class]
pred_labels += [label]
pred_values += [values]
else:
if is_prob_model:
info("Model supports probability estimates, but disabled in predicton.")
if svm_type in (ONE_CLASS, EPSILON_SVR, NU_SVC):
nr_classifier = 1
else:
nr_classifier = nr_class*(nr_class-1)//2
dec_values = (c_double * nr_classifier)()
for xi in x:
xi, idx = gen_svm_nodearray(xi, isKernel=(m.param.kernel_type == PRECOMPUTED))
label = libsvm.svm_predict_values(m, xi, dec_values)
if(nr_class == 1):
values = [1]
else:
values = dec_values[:nr_classifier]
pred_labels += [label]
pred_values += [values]
ACC, MSE, SCC = evaluations(y, pred_labels)
l = len(y)
if svm_type in [EPSILON_SVR, NU_SVR]:
info("Mean squared error = %g (regression)" % MSE)
info("Squared correlation coefficient = %g (regression)" % SCC)
else:
info("Accuracy = %g%% (%d/%d) (classification)" % (ACC, int(l*ACC/100), l))
return pred_labels, (ACC, MSE, SCC), pred_values
| 7lk_ocr_deploy | /7lk_ocr_deploy-0.1.69.tar.gz/7lk_ocr_deploy-0.1.69/libsvm/svmutil.py | svmutil.py |
#!/usr/bin/env python3
import os
import sys
if __name__ == '__main__':
sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ByteBird.game import main
main()
| 7seg-ByteBird | /7seg_ByteBird-0.2-py3-none-any.whl/ByteBird/__main__.py | __main__.py |
#!/usr/bin/env python3
from ZeroSeg import Button, screen
from time import sleep
from random import randrange
from threading import Thread
import sys
right_button = Button("right")
left_button = Button("left")
def generate_hurdle() -> int:
"""
Generate random number (0 or 1) and because of it create obstacle
on the top of the map or on the bottom.
"""
rand = randrange(2)
if rand == 1:
return 35 # Top hurdle (stalactite).
else:
return 29 # Bottom hurdle.
class ctx(object):
"""
Game context.
"""
if len(sys.argv) > 1:
difficulty = float(sys.argv[1])
else:
difficulty = 0.3 # More == easier.
hero_up = 64
hero_down = 8
hero_position = hero_down
hero_index = 6
hurdles = [generate_hurdle(), generate_hurdle()]
points = 0
game = True
def game_over():
"""
Display game over screen.
"""
ctx.game = False
screen.write_blinking_text(" LOSE ", stop_after=2)
screen.write_text(f"P {ctx.points}")
def draw_hurdles(hurdles_byte: int, position: int):
"""
Simple wrapper function to draw hurdles.
"""
screen.set_byte(hurdles_byte, position)
def draw_hero(position: int, hurdle: int = False) -> bool:
"""
Draw a hero on the screen on specified position. If hero is in a clash
with hurdle, draw hero under or over it.
"""
if hurdle: # Draw hero over or under obstacle.
if position == ctx.hero_down and hurdle == 35:
screen.set_byte(43, ctx.hero_index) # 43 - hero under obstacle.
elif position == ctx.hero_up and hurdle == 29:
screen.set_byte(93, ctx.hero_index) # 93 - hero over obstacle.
else:
game_over()
return False
else:
screen.set_byte(position, ctx.hero_index)
return True
def handle_movements():
"""
Handle button presses in other thread.
"""
while ctx.game:
if right_button.pressed():
ctx.hero_position = ctx.hero_up
elif left_button.pressed():
ctx.hero_position = ctx.hero_down
def main():
screen.write_blinking_text(' ' + '.'*5, stop_after=2)
Thread(target=handle_movements, daemon=True).start()
i = 1
while True:
screen.clear()
if i > 8:
i = 1
del ctx.hurdles[0]
ctx.hurdles.append(generate_hurdle())
ctx.points += 1
if i != ctx.hero_index:
draw_hurdles(ctx.hurdles[0], i)
draw_hero(ctx.hero_position) # Restore hero on previous position.
if i >= 4:
draw_hurdles(ctx.hurdles[1], i - 3)
if i == ctx.hero_index:
if not (draw_hero(ctx.hero_position, ctx.hurdles[0])):
break
if ctx.points > 0:
if i < 4:
if (ctx.hero_index - 1) + i == ctx.hero_index:
if not (draw_hero(ctx.hero_position, ctx.hurdles[0])):
break
else:
draw_hurdles(ctx.hurdles[0], (ctx.hero_index - 1) + i)
i += 1
sleep(ctx.difficulty)
if __name__ == "__main__":
main()
| 7seg-ByteBird | /7seg_ByteBird-0.2-py3-none-any.whl/ByteBird/game.py | game.py |
#!/usr/bin/env python3
from ByteBird import game
| 7seg-ByteBird | /7seg_ByteBird-0.2-py3-none-any.whl/ByteBird/__init__.py | __init__.py |
def print_lol(the_list):
for each_item in the_list:
if isinstance (each_item, list):
peint_lol(each_item)
else:
print(each_item)
| 7th | /7th-1.0.0.zip/7th-1.0.0/7th.py | 7th.py |
from distutils.core import setup
setup(
name = '7th',
version = '1.0.0',
py_modules = ['7th'],
author = '7thTeam'
)
| 7th | /7th-1.0.0.zip/7th-1.0.0/setup.py | setup.py |
<h1 align="center">
<br>
<a href="https://github.com/karthikuj/7uring"><img src="https://raw.githubusercontent.com/karthikuj/karthikuj/master/images/7uring.png" alt="7uring" title="7uring"></a>
<br>
7uring: Not your ordinary hashcracker.
<br>
</h1>
## [-] About 7uring:
7uring is an advanced cryptography tool which works with some of the most popular hashes, encodings and ciphers. 7uring's advanced hash functions can check online rainbow tables before you try to bruteforce the hashes, because of which your hashes are cracked in a matter of seconds.
In the future, we plan to incorporate steganography, cryptanalysis and much more.
In short 7uring can take your CTF rank up a notch.
## [-] Installing 7uring:
You can install `7uring` like this:
1. Clone the repository:
```
git clone https://github.com/karthikuj/7uring.git
```
2. Change the directory:
```
cd 7uring/
```
3. Install required modules:
```
python -m pip install -r requirements.txt
```
4. Install the package:
```
pip install .
```
## [-] Using 7uring:
### Syntax:
```
7uring [subcommand] [format] [option] [suboption] data
```
### Subcommands:
```
hash
```
```
cipher
```
```
encoder
```
### Formats:
#### Hash:
```
--blake2b
```
```
--md4
```
```
--md5
```
```
--ntlm
```
```
--sha1
```
```
--sha224
```
```
--sha256
```
```
--sha384
```
```
--sha512
```
```
--whirlpool
```
#### Ciphers:
```
--bacon
```
```
--caesar
```
```
--monoalphabetic
```
```
--morse
```
```
--multitapsms
```
```
--rot13
```
```
--rot47
```
```
--transposition
```
#### Encodings:
```
--binary
```
```
--octal
```
```
--hexadecimal
```
```
--base64
```
#### Options:
To encrypt:
```
--enc
```
To decrypt:
```
--dec
```
To check online rainbow tables (for hashes only!):
```
--rainbow
```
To bruteforce:
```
--brute
```
#### Suboptions:
The only suboption is ```-w``` to specify wordlist while using ```--brute```
## [-] Examples:
```
7uring --help
```
```
7uring hash --md5 --enc spongebob
```
```
7uring hash --md5 --rainbow e1964798cfe86e914af895f8d0291812
```
```
7uring cipher --caesar --enc spongebob
```
```
7uring hash --md5 --brute -w /usr/share/wordlists/rockyou.txt e1964798cfe86e914af895f8d0291812
```
## [-] Uninstalling 7uring:
#### Sorry to see you go :(
```
pip uninstall 7uring
```
#### Made with ❤️ by <a href="https://www.instagram.com/5up3r541y4n/" target="_blank">@5up3r541y4n</a>
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/README.md | README.md |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="7uring",
version="1.0.0",
author="Karthik UJ",
author_email="karthikuj2001@gmail.com",
description="An advanced cryptography tool.",
long_description=' An advanced cryptography tool for hashing, encrypting, encoding, steganography and more.',
long_description_content_type="text/markdown",
url="https://github.com/karthikuj/7uring",
project_urls={
"Bug Tracker": "https://github.com/karthikuj/7uring/issues",
},
download_url = 'https://github.com/karthikuj/7uring/archive/refs/tags/v1.0.tar.gz',
install_requires=[
'requests',
'beautifulsoup4',
'pyenchant',
],
entry_points = {
'console_scripts': [
'7uring = turing.turing:main'
]
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent",
],
keywords = ['hashing', 'encoding', 'encryption', 'steganography', 'cryptanalysis', 'steganalysis', 'cipher'],
zip_safe = False,
packages=setuptools.find_packages(),
python_requires=">=3.6",
)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/setup.py | setup.py |
#!/usr/bin/python3
from turing.programfiles.cliProcess import *
import sys
def main():
cliPro(sys.argv)
if __name__ == '__main__':
main()
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/turing.py | turing.py |
#!/usr/bin/python3
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/__init__.py | __init__.py |
#!/usr/bin/python3
from turing.programfiles.menu import *
from turing.programfiles.banner import *
import sys
from turing.hashing.hashmd5 import *
from turing.hashing.hashsha512 import *
from turing.hashing.hashsha1 import *
from turing.hashing.hashsha256 import *
from turing.hashing.hashsha224 import *
from turing.hashing.hashsha384 import *
from turing.hashing.hashmd4 import *
from turing.hashing.hashblake2b import *
from turing.hashing.hashwhirlpool import *
from turing.hashing.hashntlm import *
from turing.cipher.caesar import *
from turing.cipher.morse import *
from turing.cipher.rot13 import *
from turing.cipher.transposition import *
from turing.cipher.multitapSMS import *
from turing.cipher.bacon import *
from turing.cipher.monoalphabetic import *
from turing.cipher.rot47 import *
from turing.encoder.binary import *
from turing.encoder.octal import *
from turing.encoder.hexadecimal import *
from turing.encoder.base64 import *
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'header':'\033[94;1m',
'msg':'\033[33;1m[o] '
}
def cliPro(argv):
printBanner()
if 'hash' in argv and '--brute' in argv and '-w' not in argv:
print('\n' + colors['error'] + 'Wordlist (-w) not specified')
sys.exit()
if 'hash' in argv and '--brute' in argv and '-w' in argv and len(argv) < 7:
print('\n' + colors['error'] + 'All arguments not specified! \
7uring --help for help menu.\n')
sys.exit()
if '--brute' in argv and '-w' in argv and len(argv) >= 7:
wordlist = argv[5]
data = ' '.join(argv[6:])
elif len(argv) >= 5:
data = ' '.join(argv[4:])
if len(argv) < 2:
print('\n' + colors['error'] + 'No arguments specified! \
7uring --help for help menu.\n')
sys.exit()
elif '--help' in argv or '-h' in argv:
printMenu()
elif len(argv) < 5:
print('\n' + colors['error'] + 'All arguments not specified! \
7uring --help for help menu.\n')
sys.exit()
elif argv[1].lower() not in subcommand:
print(colors['error'] + 'Unrecognized subcommand.')
sys.exit()
elif argv[1].lower() == 'hash':
if argv[2].lower() not in hashes:
print(colors['error'] + 'Unrecognized hash type.')
sys.exit()
elif argv[3].lower() not in options:
print(colors['error'] + 'Unrecognized option ' + '\'' + argv[3] + '\'')
sys.exit()
elif argv[2].lower() == '--md5':
if argv[3] == '--enc':
print(colors['success'] + stringToMD5(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
md5ToString(data)
else:
md5Brute(data, wordlist)
elif argv[2].lower() == '--blake2b':
if argv[3] == '--enc':
print(colors['success'] + stringToBlake2b(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
blake2bToString(data)
else:
blake2bBrute(data, wordlist)
elif argv[2].lower() == '--md4':
if argv[3] == '--enc':
print(colors['success'] + stringToMD4(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
md4ToString(data)
else:
md4Brute(data, wordlist)
elif argv[2].lower() == '--ntlm':
if argv[3] == '--enc':
print(colors['success'] + stringToNTLM(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
ntlmToString(data)
else:
ntlmBrute(data, wordlist)
elif argv[2].lower() == '--sha1':
if argv[3] == '--enc':
print(colors['success'] + stringToSHA1(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
sha1ToString(data)
else:
sha1Brute(data, wordlist)
elif argv[2].lower() == '--sha224':
if argv[3] == '--enc':
print(colors['success'] + stringToSHA224(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
sha224ToString(data)
else:
sha224Brute(data, wordlist)
elif argv[2].lower() == '--sha256':
if argv[3] == '--enc':
print(colors['success'] + stringToSHA256(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
sha256ToString(data)
else:
sha256Brute(data, wordlist)
elif argv[2].lower() == '--sha384':
if argv[3] == '--enc':
print(colors['success'] + stringToSHA384(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
sha384ToString(data)
else:
sha384Brute(data, wordlist)
elif argv[2].lower() == '--sha512':
if argv[3] == '--enc':
print(colors['success'] + stringToSHA512(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
sha512ToString(data)
else:
sha512Brute(data, wordlist)
elif argv[2].lower() == '--whirlpool':
if argv[3] == '--enc':
print(colors['success'] + stringToWhirlpool(data))
elif argv[3] == '--dec':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for hashes. Use --rainbow or --brute\
instead.')
sys.exit()
elif argv[3] == '--rainbow':
whirlpoolToString(data)
else:
whirlpoolBrute(data, wordlist)
elif argv[1].lower() == 'cipher':
if argv[2].lower() not in ciphers:
print(colors['error'] + 'Unrecognized cipher type.')
sys.exit()
elif argv[3].lower() not in options:
print(colors['error'] + 'Unrecognized option ' + '\'' + argv[3] + '\'')
sys.exit()
elif argv[2].lower() == '--bacon':
if argv[3] == '--enc':
baconEncrypt(data)
elif argv[3] == '--dec':
baconDecrypt(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--caesar':
if argv[3] == '--enc':
shift = int(input(colors['msg'] + 'Enter shift value: '))
caesarEncrypt(data, shift)
elif argv[3] == '--dec':
shift = int(input(colors['msg'] + 'Enter shift value: '))
caesarDecrypt(data, shift)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
caesarBrute(data)
sys.exit()
elif argv[2].lower() == '--monoalphabetic':
if argv[3] == '--enc':
monoalphabeticEncrypt(data)
elif argv[3] == '--dec':
monoalphabeticDecrypt(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--morse':
if argv[3] == '--enc':
morseEncrypt(data)
elif argv[3] == '--dec':
morseDecrypt(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--multitapsms':
if argv[3] == '--enc':
multitapEncrypt(data)
elif argv[3] == '--dec':
multitapDecrypt(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--rot13':
if argv[3] == '--enc':
rot13Encrypt(data)
elif argv[3] == '--dec':
rot13Decrypt(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--rot47':
if argv[3] == '--enc':
rot47Encrypt(data)
elif argv[3] == '--dec':
rot47Decrypt(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--transposition':
if argv[3] == '--enc':
key = input(colors['msg'] + 'Enter key value: ')
transpositionEncrypt(data, key)
elif argv[3] == '--dec':
key = input(colors['msg'] + 'Enter key value: ')
transpositionDecrypt(data, key)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for ciphers(except caesar). Use --enc or --dec\
instead.')
sys.exit()
elif argv[1].lower() == 'encoder':
if argv[2].lower() not in encoders:
print(colors['error'] + 'Unrecognized encoding type.')
sys.exit()
elif argv[3].lower() not in options:
print(colors['error'] + 'Unrecognized option ' + '\'' + argv[3] + '\'')
sys.exit()
elif argv[2].lower() == '--binary':
if argv[3] == '--enc':
binaryEncode(data)
elif argv[3] == '--dec':
binaryDecode(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--octal':
if argv[3] == '--enc':
octalEncode(data)
elif argv[3] == '--dec':
octalDecode(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--hexadecimal':
if argv[3] == '--enc':
hexadecimalEncode(data)
elif argv[3] == '--dec':
hexadecimalDecode(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
elif argv[2].lower() == '--base64':
if argv[3] == '--enc':
base64Encode(data)
elif argv[3] == '--dec':
base64Decode(data)
elif argv[3] == '--rainbow':
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
else:
print(colors['error'] + '\'' + argv[3] + '\'' +
', this option is not for encoders. Use --enc or --dec\
instead.')
sys.exit()
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/programfiles/cliProcess.py | cliProcess.py |
#!/usr/bin/python3
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m',
'header':'\033[94;1m',
'msg':'\033[33;1m[o] '
}
banner = (colors['header'] + '''
_________ .__
\______ \__ _________|__| ____ ____
/ / | \_ __ \ |/ \ / ___\
/ /| | /| | \/ | | \/ /_/ >
/____/ |____/ |__| |__|___| /\___ /
\//_____/
Not your ordinary hashcracker.
By @5up3r541y4n (karthikuj2001@gmail.com)
'''
)
def printBanner():
print(banner)
#Drink all the booze, hack all the things!!
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/programfiles/banner.py | banner.py |
#!/usr/bin/python3
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m '
}
subcommand = ['hash', 'cipher', 'encoder']
hashes = ['--blake2b', '--md4', '--md5', '--ntlm', '--sha1',
'--sha224', '--sha256', '--sha384', '--sha512', '--whirlpool']
ciphers = ['--bacon', '--caesar', '--monoalphabetic', '--morse',
'--multitapsms', '--rot13', '--rot47', '--transposition']
encoders = ['--binary', '--octal', '--hexadecimal', '--base64']
options = ['--enc', '--dec', '--brute', '--rainbow']
menu = colors['msg'] + '''
Usage: 7uring [subcommand] [format] [option] [suboptions] data
[SUBCOMMANDS]
hash - To use hash functions and crack hashes.
cipher - To use cipher tools.
encoder - To encode in some popular encoding mechanisms.
[FORMATS]
[Hashes] [Ciphers] [Encodings]
--blake2b --bacon --binary
--md4 --caesar --octal
--md5 --monoalphabetic --hexadecimal
--ntlm --morse --base64
--sha1 --multitapsms
--sha224 --rot13
--sha256 --rot47
--sha384 --transposition
--sha512
--whirlpool
[OPTIONS]
--enc - To encrypt using that format.
--dec - To decrypt that format. (Not for hashes)
--brute - To bruteforce the hashes and ciphers. Available for all hashes and
caesar cipher.
--rainbow - To crack hashes using rainbow tables.
(Faster than brute but low chances)
[SUBOPTIONS]
[For --brute]
-w - To specify the wordlist path
'''
def printMenu():
print(menu)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/programfiles/menu.py | menu.py |
#!/usr/bin/python3
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/programfiles/__init__.py | __init__.py |
import sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def hexadecimalEncode(text):
res = ' '.join(format(ord(i), '08x').lstrip('0') for i in text)
print(colors['success'] + res)
def hexadecimalDecode(hexadecimal):
bytesObj = bytes.fromhex(hexadecimal)
res = bytesObj.decode('ASCII')
print(colors['success'] + res)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/encoder/hexadecimal.py | hexadecimal.py |
import sys, re
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def binaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return decimal
def binaryEncode(text):
res = ' '.join(format(ord(i), '08b').lstrip('0') for i in text)
print(colors['success'] + res)
def verifyBinary(binary):
binaryRegex = re.compile(r'^(0|1|\s)+$') #Create a regex object
mo = binaryRegex.search(binary) #Create a match object
if mo == None:
return False
else:
return True
def binaryDecode(binary):
res = ''
if ' ' in binary:
binList = binary.split()
for i in binList:
decimal = binaryToDecimal(int(i))
res += chr(decimal)
print(colors['success'] + res)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/encoder/binary.py | binary.py |
import base64, re, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def base64Encode(text):
textBytes = text.encode('ascii')
base64Bytes = base64.b64encode(textBytes)
b64 = base64Bytes.decode('ascii')
print(colors['success'] + b64)
def verifyBase64(b64):
base64Regex = re.compile(r'^[0-9a-zA-Z+=/]+$') #Create a regex object
mo = base64Regex.search(b64) #Create a match object
if mo == None:
return False
else:
return True
def base64Decode(b64):
if not verifyBase64(b64): #Check if bse64 string is valid
print(colors['error'] + 'Invalid base64 string')
sys.exit()
base64Bytes = b64.encode('ascii')
textBytes = base64.b64decode(base64Bytes)
text = textBytes.decode('ascii')
print(colors['success'] + text)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/encoder/base64.py | base64.py |
import sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def octalToDecimal(octal):
octal1 = octal
decimal, base, temp = 0, 1, octal1
while(temp):
lastDigit = temp % 10
temp = int(temp / 10)
decimal += lastDigit * base
base *= 8
return decimal
def octalEncode(text):
res = ' '.join(format(ord(i), '08o').lstrip('0') for i in text)
print(colors['success'] + res)
def octalDecode(octal):
res = ''
if ' ' in octal:
octList = octal.split()
for i in octList:
decimal = octalToDecimal(int(i))
res += chr(decimal)
print(colors['success'] + res)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/encoder/octal.py | octal.py |
def encode():
pass
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/encoder/__init__.py | __init__.py |
from . import caesar
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def rot13Encrypt(text):
caesar.caesarEncrypt(text, 13)
def rot13Decrypt(text):
caesar.caesarDecrypt(text, 13)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/rot13.py | rot13.py |
import sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']
codes = ['2', '22', '222', '3', '33', '333', '4', '44', '444',
'5', '55', '555', '6', '66', '666', '7', '77', '777',
'7777', '8', '88', '888', '9', '99', '999', '9999', '0']
def multitapEncrypt(text):
for i in text:
if not i.isalpha() and not i.isspace(): #Check if characters are valid
print(colors['error'] + 'Only english alphabets and\
whitespaces allowed!')
sys.exit()
cipher = ''
for i in text:
cipher += codes[chars.index(i.lower())] #Find and join codes
cipher += ' '
print(colors['success'] + cipher) #Print the result
def multitapDecrypt(cipher):
for i in cipher:
if not i.isdigit() and not i.isspace(): #Check if cipher is valid
print(colors['error'] + 'Only digits and whitespaces allowed!')
sys.exit()
decipher = ''
for i in cipher.split():
if not i == ' ':
try:
decipher += chars[codes.index(i)] #Find and join characters
except:
print(colors['error'] + 'Invalid code')
sys.exit()
print(colors['success'] + decipher) #Print the result
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/multitapSMS.py | multitapSMS.py |
import sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
code = ['l', 'd', 'm', 'g', 'b', 'v', 's', 'u', 'x', 'i', 't', 'q', 'r',
'z', 'c', 'y', 'w', 'a', 'j', 'f', 'h', 'e', 'o', 'k', 'n', 'p']
def monoalphabeticEncrypt(text):
cipher = ''
for i in text:
if i in char:
cipher += code[char.index(i)] #Find and join correct code
else:
cipher += i
print(colors['success'] + cipher)
def monoalphabeticDecrypt(cipher):
print('\n' + colors['msg'] + 'Monoalphabetic cipher uses mixed sequence of alphabets \
for encryption, so the message encrypted using other tool cannot be decrypted by \
7uring using it\'s default alphabet sequence.\n')
decipher = ''
for i in cipher:
if i in code:
decipher += char[code.index(i)] #Find and join correct character
else:
decipher += i
print(colors['success'] + decipher)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/monoalphabetic.py | monoalphabetic.py |
import sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
codes = [
'AAAAA', 'AAAAB', 'AAABA', 'AAABB', 'AABAA', 'AABAB', 'AABBA', 'AABBB',
'ABAAA', 'ABAAA', 'ABAAB', 'ABABA', 'ABABB', 'ABBAA', 'ABBAB', 'ABBBA',
'ABBBB', 'BAAAA', 'BAAAB', 'BAABA', 'BAABB', 'BAABB', 'BABAA', 'BABAB',
'BABBA', 'BABBB'
]
def baconEncrypt(text):
for i in text:
if not i.isalpha() and not i.isspace(): #Check if characters are valids
print(colors['error'] + 'Only english alphabets and \
whitespaces allowed!')
sys.exit()
cipher = ''
for i in text:
if i == ' ':
cipher += ' '
else:
cipher += codes[chars.index(i.lower())] #Find and join the codes
print(colors['success'] + cipher) #Print the result
def baconDecrypt(cipher):
'''for i in cipher:
if (not i.lower() == 'a' or not i.lower() == 'b') and not i.isspace():
print(colors['error'] + 'Only works with bacon cipher of \'A\' \
and \'B\' as of now')
sys.exit()'''
decipher = ''
i = 0
while i < len(cipher):
if cipher[i] == ' ':
decipher += ' '
i += 1
else:
decipher += chars[codes.index(cipher[i:i+5])]
i += 5
print(colors['success'] + decipher)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/bacon.py | bacon.py |
import sys, math
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def transpositionEncrypt(text, key):
textl = list(text)
if ' ' in textl:
for i in range(textl.count(' ')):
textl.remove(' ')
text = ''.join(textl)
cipher = ''
k = list(key)
ksort = sorted(k)
perm = []
for i in k:
perm.append(ksort.index(i))
ksort[ksort.index(i)] = '§'
message = []
for i in range(math.ceil(len(text)/len(key))): #Create matrix
message.append(list())
message[i] = list(text[i*len(key):(i*len(key))+len(key)])
if len(message[i]) < len(key):
message[i].extend(list(' '*(len(key)-len(message[i]))))
for i in range(len(key)):
for j in range(math.ceil(len(text)/len(key))):
if i == perm[i]:
cipher += message[j][i]
else:
cipher += message[j][perm.index(i)]
print(colors['success'] + cipher)
def transpositionDecrypt(text, key):
decipher = ''
k = list(key)
ksort = sorted(k)
perm = []
for i in k:
perm.append(ksort.index(i))
ksort[ksort.index(i)] = '§'
#permNew = list(range(len(key)))
message = []
for i in range(math.ceil(len(text)/len(key))):
message.append(list())
message[i].extend(list(' '*len(key)))
c = 0
for i in range(len(key)):
for j in range(math.ceil(len(text)/len(key))):
try:
message[j][i] = text[c]
except:
message[j][i] = ' '
c += 1
for i in range(math.ceil(len(text)/len(key))):
for j in range(len(key)):
if j == perm[j]:
decipher += message[i][j]
else:
decipher += message[i][perm[j]]
print(colors['success'] + decipher)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/transposition.py | transposition.py |
import sys
small = ['!', '"', '#', '$', '%', '&', "'", '(', ')',
'*', '+', ',', '-', '.', '/', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', ':', ';',
'<', '=', '>', '?', '@', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'{', '|', '}', '~']
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def rot47Encrypt(text):
res = ''
for i in range(len(text)):
if text[i] in small:
ind = small.index(text[i]) #Find the index of character
res += small[(ind + 47)%94] #Shift the character
elif text[i] == ' ':
res += ' '
else:
print(colors['error'] + 'Invalid characters!') #Check for invalid characters
print(text[i])
sys.exit()
print(colors['success'] + res)
def rot47Decrypt(text):
res = ''
for i in range(len(text)):
if text[i] in small:
ind = small.index(text[i]) #Find the index of character
res += small[ind - 47] #Shift the character
elif text[i] == ' ':
res += ' '
else:
print(colors['error'] + 'Invalid characters!') #Check for invalid characters
sys.exit()
print(colors['success'] + res)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/rot47.py | rot47.py |
def cipher():
pass
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/__init__.py | __init__.py |
import sys, enchant
small = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def caesarEncrypt(text, shift):
res = ''
if shift < 0 or shift > 25:
print(colors['error'] + 'Shift value should be 0-25') #Shift value check
for i in range(len(text)):
if text[i].isupper():
ind = small.index(text[i].lower()) #Find the index of character
res += small[(ind + shift)%26].upper() #Shift the character
elif text[i].islower():
ind = small.index(text[i]) #Find the index of character
res += small[(ind + shift)%26] #Shift the character
elif text[i] == ' ':
res += ' '
else:
print(colors['error'] + 'Invalid characters!') #Check for invalid characters
sys.exit()
print(colors['success'] + res)
def caesarDecrypt(text, shift):
res = ''
if shift < 0 or shift > 25:
print(colors['error'] + 'Shift value should be 0-25') #Shift value check
for i in range(len(text)):
if text[i].isupper():
ind = small.index(text[i].lower()) #Find the index of character
res += small[ind - shift].upper() #Shift the character
elif text[i].islower():
ind = small.index(text[i]) #Find the index of character
res += small[ind - shift] #Shift the character
elif text[i] == ' ':
res += ' '
else:
print(colors['error'] + 'Invalid characters!') #Check for invalid characters
sys.exit()
print(colors['success'] + res)
def caesarBrute(text):
possible = set()
for shift in range(26):
res = ''
for i in range(len(text)):
if text[i].isupper():
ind = small.index(text[i].lower()) #Find the index of character
res += small[ind - shift].upper() #Shift the character
elif text[i].islower():
ind = small.index(text[i]) #Find the index of character
res += small[ind - shift] #Shift the character
elif text[i] == ' ':
res += ' '
else:
print(colors['error'] + 'Invalid characters!') #Check for invalid characters
sys.exit()
print(colors['success'] + 'shift(' + "{:02d}".format(shift) +
')' + ' : ' + res)
dic = enchant.Dict('en_US') #Create a US english Dictionary
for j in res.split():
if len(j) > 2 and dic.check(j): #Check for english words
possible.add('shift(' + "{:02d}".format(shift) +
')' + ' : ' + res)
if len(possible) > 0:
print(colors['success'][:-4] + '\nMost possible solutions:') #Print most possible solutions
for k in possible:
print(colors['success'] + k)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/caesar.py | caesar.py |
import sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
keyList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
',', '.', '?', ':', '-', '"', '(', '=', '/', "'", '_', ')', '+', '@']
valList = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..',
'.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.',
'...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..', '.----',
'..---', '...--', '....-', '.....', '-....', '--...', '---..',
'----.', '-----', '--..--', '.-.-.-', '..--..', '---...', '-...-',
'.-..-.', '-.--.', '-...-', '-..-.', '.---.', '..--.-', '-.--.-',
'.-.-.', '.--.-.']
def morseEncrypt(text):
res = ''
for i in text:
if i == ' ':
res += ' '
elif i.isupper():
res += valList[keyList.index(i.lower())] + ' '
else:
try:
res += valList[keyList.index(i)] + ' '
except:
print(colors['error'] + 'Invalid characters found! (' + i + ')')
sys.exit()
print(colors['success'] + res)
def morseDecrypt(morse):
res = ''
words = morse.split(' ')
for i in words:
chars = i.split()
for j in chars:
try:
res += keyList[valList.index(j)]
except:
print(colors['error'] + 'Invalid morse code!')
print(j)
sys.exit()
res += ' '
print(colors['success'] + res)
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/cipher/morse.py | morse.py |
import hashlib, requests, bs4, re, os, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToMD5(string):
result = hashlib.md5(string.encode()) #Create an MD5 hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifyMD5(md5):
md5Regex = re.compile(r'^[0-9a-f]{32}$') #Create a regex object
mo = md5Regex.search(md5.lower()) #Create a match object
if mo == None:
return False
else:
return True
def md5ToString(md5):
if not verifyMD5(md5):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
url = 'https://md5.gromweb.com/?md5=' + md5 #Create a url
res = requests.get(url) #Query the url
res.raise_for_status()
source = res.content
soup = bs4.BeautifulSoup(source, 'lxml') #Create a beautiful soup object
css_path = 'html body div#page.p-1.p-3-lg div#container section#section article div#content p em.long-content.string'
elem = soup.select(css_path) #Find the required element
try:
print(colors['msg'] + 'Cracked!' + '\n' + colors['success'] + md5 + ':' + elem[0].text) #Print the cracked string
except:
print(colors['msg'] + 'Hash not found in databases')
def md5Brute(md5, wordlist):
md5 = md5.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists and if it is a file
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path') #Exit program if invalid path
sys.exit()
if not verifyMD5(md5): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all lines in a list
for word in words:
md5String = stringToMD5(word.rstrip())
if md5String == md5: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + md5 + ":" + word)
break
else:
print(colors['msg'] + "Not found")
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashmd5.py | hashmd5.py |
import hashlib, requests, bs4, re, os, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToSHA1(string):
result = hashlib.sha1(string.encode()) #Create a SHA1 hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifySHA1(sha1):
sha1Regex = re.compile(r'^[a-f0-9]{40}$') #SHA-1 regex object
mo = sha1Regex.search(sha1.lower()) #Create a match object
if mo == None:
return False
else:
return True
def sha1ToString(sha1):
if not verifySHA1(sha1):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
url = 'https://sha1.gromweb.com/?hash=' + sha1 #Create url for scraping
res = requests.get(url) #Query the url
res.raise_for_status()
source = res.content
soup = bs4.BeautifulSoup(source, 'lxml') #Create a beautiful soup object
css_path = 'html body div#page.p-1.p-3-lg div#container section#section article div#content p em.long-content.string'
elem = soup.select(css_path)
try:
print(colors['msg'] + 'Cracked!\n' + colors['success'] + sha1 + ':' + elem[0].text) #Print the cracked string
except:
print(colors['msg'] + 'Hash not found in databases')
def sha1Brute(sha1, wordlist):
sha1 = sha1.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists and if it is a file
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path')
sys.exit()
if not verifySHA1(sha1): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all words in a list
for word in words:
sha1String = stringToSHA1(word.rstrip())
if sha1String == sha1: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + sha1 + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashsha1.py | hashsha1.py |
import os, re, sys, hashlib
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToSHA224(string):
result = hashlib.sha224(string.encode()) #Create a sha224 hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifySHA224(sha224):
sha224Regex = re.compile(r'^[0-9a-f]{56}$') #Create a regex object
mo = sha224Regex.search(sha224.lower()) #Create a match object
if mo == None:
return False
else:
return True
def sha224ToString(sha224):
print(colors['msg'] + 'The online "de-hashing" facility for sha224\
is not available yet, you can still try to bruteforce the hash using 7uring.')
sys.exit()
def sha224Brute(sha224, wordlist):
sha224 = sha224.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if wordlist exists
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path')
sys.exit()
if not verifySHA224(sha224): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all words in a list
for word in words:
sha224String = stringToSHA224(word.rstrip())
if sha224String == sha224: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + sha224 + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashsha224.py | hashsha224.py |
import hashlib, requests, bs4, re, os, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToSHA384(string):
result = hashlib.sha384(string.encode()) #Create a SHA384 object
return result.hexdigest() #Return the required hexadecimal hash
def verifySHA384(sha384):
sha384Regex = re.compile(r'^[0-9a-f]{96}$') #Create a regex object
mo = sha384Regex.search(sha384.lower()) #Create a match object
if mo == None:
return False
else:
return True
def sha384ToString(sha384):
sha384 = sha384.lower()
if not verifySHA384(sha384):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
URL = 'https://md5decrypt.net/en/Sha384/' #Create a url
myobj = {
'hash':sha384,
'captcha65684':'',
'ahah65684':'30beb54b674b10bf73888fda4d38893f',
'decrypt':'Decrypt'
}
res = requests.post(url=URL, data=myobj) #Send a POST request
res.raise_for_status()
source = res.content
soup = bs4.BeautifulSoup(source, 'lxml') #Create a beautiful soup object
css_path = 'html body div#corps fieldset#answer b'
elem = soup.select(css_path) #Find the required element
try:
print(colors['msg'] + 'Cracked!\n' + colors['success'] + sha384 + ':' + elem[0].text) #Print the cracked string
except:
print(colors['msg'] + 'Hash not found in databases')
def sha384Brute(sha384, wordlist):
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists and if it is a file
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path') #Exit program if invalid path
sys.exit()
if not verifySHA384(sha384): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all lines in a list
for word in words:
sha384String = stringToSHA384(word.rstrip())
if sha384String == sha384: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + sha384 + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashsha384.py | hashsha384.py |
import os, hashlib, requests, bs4, re, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToSHA256(string):
result = hashlib.sha256(string.encode()) #Create a SHA256 hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifySHA256(sha256):
sha256Regex = re.compile(r'^[0-9a-f]{64}$') #Create a regex object
mo = sha256Regex.search(sha256.lower()) #Create a match object
if mo == None:
return False
else:
return True
def sha256ToString(sha256):
if not verifySHA256(sha256):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
URL = 'https://md5decrypt.net/en/Sha256/' #Create a url
myobj = {
'hash':sha256,
'captcha65684':'',
'ahah65684':'30beb54b674b10bf73888fda4d38893f',
'decrypt':'Decrypt'
}
res = requests.post(url=URL, data=myobj) #Send a POST request
res.raise_for_status()
source = res.content
soup = bs4.BeautifulSoup(source, 'lxml') #Create a beautiful soup object
css_path = 'html body div#corps fieldset#answer b'
elem = soup.select(css_path) #Find the required element
try:
print(colors['msg'] + 'Cracked!\n' + colors['success'] + sha256 + ':' + elem[0].text) #Print the cracked string
except:
print(colors['msg'] + 'Hash not found in databases')
def sha256Brute(sha256, wordlist):
sha256 = sha256.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path')
sys.exit()
if not verifySHA256(sha256): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all words in a list
for word in words:
sha256String = stringToSHA256(word.rstrip())
if sha256String == sha256: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + sha256 + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashsha256.py | hashsha256.py |
import hashlib, requests, bs4, re, os, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToBlake2b(string):
result = hashlib.blake2b(string.encode()) #Create a blake2b hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifyBlake2b(blake2b):
blake2bRegex = re.compile(r'^[0-9a-f]{128}$') #Create a regex object
mo = blake2bRegex.search(blake2b.lower()) #Create a match object
if mo == None:
return False
else:
return True
def blake2bToString(blake2b):
if not verifyBlake2b(blake2b):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
print(colors['msg'] + 'The online "de-hashing" facility for blake2b\
is not available yet, you can still try to bruteforce the hash using 7uring.')
sys.exit()
def blake2bBrute(blake2b, wordlist):
blake2b = blake2b.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path')
sys.exit()
if not verifyBlake2b(blake2b): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all words in a list
for word in words:
blake2bString = stringToBlake2b(word.rstrip())
if blake2bString == blake2b: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + blake2b + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashblake2b.py | hashblake2b.py |
import hashlib, re, sys, requests, bs4, os
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToWhirlpool(string):
result = hashlib.new('whirlpool', string.encode('utf-8')) #Create a whirlpool hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifyWhirlpool(whirlpool):
whirlpoolRegex = re.compile(r'^[0-9a-f]{128}$') #Create a regex object
mo = whirlpoolRegex.search(whirlpool.lower()) #Create a match object
if mo == None:
return False
else:
return True
def whirlpoolToString(whirlpool):
if not verifyWhirlpool(whirlpool):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
print(colors['msg'] + 'The online "de-hashing" facility for whirlpool\
is not available yet, you can still try to bruteforce the hash using 7uring.')
sys.exit()
def whirlpoolBrute(whirlpool, wordlist):
whirlpool = whirlpool.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path') #Exit program if invalid path
sys.exit()
if not verifyWhirlpool(whirlpool): #Verify if hash is correct
print(colors['error'] + 'Invalid path') #Exit program if invalid path
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all lines in a list
for word in words:
whirlpoolString = stringToWhirlpool(word.rstrip())
if whirlpoolString == whirlpool: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + whirlpool + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashwhirlpool.py | hashwhirlpool.py |
import hashlib, re, sys, requests, bs4, os
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToMD4(string):
result = hashlib.new('md4',string.encode('utf-8')) #Create an MD4 hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifyMD4(md4):
md4Regex = re.compile(r'^[0-9a-f]{32}$') #Create a regex object
mo = md4Regex.search(md4.lower()) #Create a match object
if mo == None:
return False
else:
return True
def md4ToString(md4):
if not verifyMD4(md4):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
URL = 'https://md5decrypt.net/en/Md4/' #Create a url
myobj = {
'hash':md4,
'captcha65':'',
'ahah65':'ea1f3b6fdf11511d0a4fa2ae757132db',
'decrypt':'Decrypt'
}
res = requests.post(url=URL, data=myobj) #Send a POST request
res.raise_for_status()
source = res.content
soup = bs4.BeautifulSoup(source, 'lxml') #Create a beautiful soup object
css_path = 'html body div#corps fieldset#answer b'
elem = soup.select(css_path) #Find the required element
try:
print(colors['msg'] + 'Cracked!' + '\n' + colors['success'] + md4 + ':' + elem[0].text) #Print the cracked string
except:
print(colors['msg'] + 'Hash not found in databases')
def md4Brute(md4, wordlist):
md4 = md4.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists and if it is a file
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path') #Exit program if invalid path
sys.exit()
if not verifyMD4(md4): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all lines in a list
for word in words:
md4String = stringToMD4(word.rstrip())
if md4String == md4: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + md4 + ":" + word)
break
else:
print(colors['msg'] + "Not found")
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashmd4.py | hashmd4.py |
def hash():
pass
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/__init__.py | __init__.py |
import hashlib, requests, bs4, re, os, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToSHA512(string):
result = hashlib.sha512(string.encode()) #Create a SHA512 hash object
return result.hexdigest() #Return the required hexadecimal hash
def verifySHA512(sha512):
sha512Regex = re.compile(r'^[0-9a-f]{128}$') #Create a regex object
mo = sha512Regex.search(sha512) #Create a match object
if mo == None:
return False
else:
return True
def sha512ToString(sha512):
sha512 = sha512.lower()
if not verifySHA512(sha512):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
URL='https://md5decrypt.net/en/Sha512/' #Create a url
myobj = {
'hash':sha512,
'captcha13126':'',
'ahah13126':'8239e6d5b8e2f67f34cfbd3c77b05523',
'decrypt':'Decrypt'
}
res = requests.post(url=URL, data=myobj) #Send a POST request
res.raise_for_status()
source = res.content
soup = bs4.BeautifulSoup(source, 'lxml') #Create a beautiful soup bject
css_path = 'html body div#corps fieldset#answer b'
elem = soup.select(css_path) #Find the required element
try:
print(colors['msg'] + 'Cracked!\n' + colors['success'] + sha512 + ':' + elem[0].text) #Print the cracked string
except:
print(colors['msg'] + 'Hash not found in databases')
def sha512Brute(sha512, wordlist):
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path')
sys.exit()
if not verifySHA512(sha512): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all words in a list
for word in words:
sha512String = stringToSHA512(word.rstrip())
if sha512String == sha512: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + sha512 + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashsha512.py | hashsha512.py |
import os, hashlib, requests, bs4, re, sys
colors = {
'error':'\033[31;1m[x] ',
'success':'\033[36;1m[-] ',
'msg':'\033[33;1m[o] '
}
def stringToNTLM(string):
result = hashlib.new('md4', string.encode('utf-16le'))
return result.hexdigest()
def verifyNTLM(ntlm):
ntlmRegex = re.compile(r'^[0-9a-f]{32}$') #Create a regex object
mo = ntlmRegex.search(ntlm.lower()) #Create a match object
if mo == None:
return False
else:
return True
def ntlmToString(ntlm):
if not verifyNTLM(ntlm):
print(colors['error'] + 'Invalid hash')
sys.exit()
else:
print(colors['msg'] + 'The online "de-hashing" facility for NTLM\
is not available yet, you can still try to bruteforce the hash using 7uring.')
sys.exit()
def ntlmBrute(ntlm, wordlist):
ntlm = ntlm.lower()
if os.path.exists(wordlist) and os.path.isfile(wordlist): #Check if the wordlist exists
if not os.path.isabs(wordlist): #Check if it is an absolute path
wordlist = os.path.abspath(wordlist)
else:
print(colors['error'] + 'Invalid path')
sys.exit()
if not verifyNTLM(ntlm): #Verify if hash is correct
print(colors['error'] + 'Invalid hash')
sys.exit()
with open(wordlist, 'r', errors='replace') as w:
words = w.readlines() #Store all words in a list
for word in words:
ntlmString = stringToNTLM(word.rstrip())
if ntlmString == ntlm: #Check if hash matches
print(colors['msg'] + 'Cracked!')
print(colors['success'] + ntlm + ':' + word)
break
else:
print(colors['msg'] + 'Not found')
| 7uring | /7uring-1.0.0.tar.gz/7uring-1.0.0/turing/hashing/hashntlm.py | hashntlm.py |
from setuptools import setup, find_packages
setup(
name="7xydothis",
version="0.1.1",
packages=find_packages(),
description = "Utitilies to use the 7xydothis APIs",
long_description = "Utitilies to use the 7xydothis APIs",
author = "bernardfrk",
author_email = "bernard.frk@gmail.com",
maintainer='bernardfrk',
maintainer_email='bernard.frk@gmail.com',
url='https://github.com/frkb/7xydothis',
classifiers = [],
) | 7xydothis | /7xydothis-0.1.1.tar.gz/7xydothis-0.1.1/setup.py | setup.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='8',
version='8',
description='For future projects.',
) | 8 | /8-8.tar.gz/8-8/setup.py | setup.py |
def add_numbers(a, b):
return a + b
def subtract_numbers(a, b):
return a - b
def multiply_numbers(a, b):
return a * b
| 83-numbers | /83_numbers-0.0.1-py3-none-any.whl/83_numbers/calc_numbers_83.py | calc_numbers_83.py |
from setuptools import find_packages, setup
# Package meta-data.
import wu
NAME = '88'
DESCRIPTION = 'A daily useful kit by WU.'
URL = 'https://github.com/username/wu.git'
EMAIL = 'wu@foxmail.com'
AUTHOR = 'WU'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = wu.VERSION
# What packages are required for this module to be executed?
REQUIRED = []
# Setting.
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
author=AUTHOR,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(),
install_requires=REQUIRED,
license="MIT",
platforms=["all"],
long_description=open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type="text/markdown"
) | 88 | /88-0.0.0.tar.gz/88-0.0.0/setup.py | setup.py |
import os
import subprocess
import time
from subprocess import PIPE
from urllib import parse, request
import requests
# TODO:找不到win32api
# from win10toast import ToastNotifier
def getTime():
return time.asctime( time.localtime(time.time()) )
def cmd(cmd):
# 有点问题,自动输出到,还获取不了输出
# return os.system(cmd)
return os.popen(cmd).read()
| 88 | /88-0.0.0.tar.gz/88-0.0.0/wu/wy.py | wy.py |
# this dir as module name,只要有__init__.py,那么那个目录就是module,比如放在上一级目录
# TODO
#这里重点讨论 orbitkit 文件夹,也就是我们的核心代码文件夹。python 和 java 不一样,并不是一个文件就是一个类,在 python 中一个文件中可以写多个类。我们推荐把希望向用户暴漏的类和方法都先导入到 __init__.py 中,并且用关键词 __all__ 进行限定。下面是我的一个 __init__.py 文件。
#这样用户在使用的时候可以清楚的知道哪些类和方法是可以使用的,也就是关键词 __all__ 所限定的类和方法。
from wu import wy
#另外,在写自己代码库的时候,即便我们可以使用相对导入,但是模块导入一定要从项目的根目录进行导入,这样可以避免一些在导入包的时候因路径不对而产生的问题。比如
# from orbitkit.file_extractor.dispatcher import FileDispatcher
name = 'orbitkit'
__version__ = '0.0.0'
VERSION = __version__
__all__ = [
'wy',
]
| 88 | /88-0.0.0.tar.gz/88-0.0.0/wu/__init__.py | __init__.py |
from setuptools import find_packages, setup
# Package meta-data.
import wu
NAME = '888'
DESCRIPTION = 'A daily useful kit by WU.'
URL = 'https://github.com/username/wu.git'
EMAIL = 'wu@foxmail.com'
AUTHOR = 'WU'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = wu.VERSION
# What packages are required for this module to be executed?
REQUIRED = []
# Setting.
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
author=AUTHOR,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(),
install_requires=REQUIRED,
license="MIT",
platforms=["all"],
long_description=open('README.md', 'r', encoding='utf-8').read(),
long_description_content_type="text/markdown"
) | 888 | /888-0.0.0.tar.gz/888-0.0.0/setup.py | setup.py |
import os
import subprocess
import time
from subprocess import PIPE
from urllib import parse, request
import requests
# TODO:找不到win32api
# from win10toast import ToastNotifier
def getTime():
return time.asctime( time.localtime(time.time()) )
def cmd(cmd):
# 有点问题,自动输出到,还获取不了输出
# return os.system(cmd)
return os.popen(cmd).read()
| 888 | /888-0.0.0.tar.gz/888-0.0.0/wu/wy.py | wy.py |
# this dir as module name,只要有__init__.py,那么那个目录就是module,比如放在上一级目录
# TODO
#这里重点讨论 orbitkit 文件夹,也就是我们的核心代码文件夹。python 和 java 不一样,并不是一个文件就是一个类,在 python 中一个文件中可以写多个类。我们推荐把希望向用户暴漏的类和方法都先导入到 __init__.py 中,并且用关键词 __all__ 进行限定。下面是我的一个 __init__.py 文件。
#这样用户在使用的时候可以清楚的知道哪些类和方法是可以使用的,也就是关键词 __all__ 所限定的类和方法。
from wu import wy
#另外,在写自己代码库的时候,即便我们可以使用相对导入,但是模块导入一定要从项目的根目录进行导入,这样可以避免一些在导入包的时候因路径不对而产生的问题。比如
# from orbitkit.file_extractor.dispatcher import FileDispatcher
name = 'orbitkit'
__version__ = '0.0.0'
VERSION = __version__
__all__ = [
'wy',
]
| 888 | /888-0.0.0.tar.gz/888-0.0.0/wu/__init__.py | __init__.py |
from setuptools import setup
setup(
name='88AB6720D79B4CBD93CAB7180920D89C',
version='1.7',
description='i am confused',
author='Someone Confused',
author_email='someone@consused.example',
packages=['confusion'],
)
| 88AB6720D79B4CBD93CAB7180920D89C | /88AB6720D79B4CBD93CAB7180920D89C-1.7.tar.gz/88AB6720D79B4CBD93CAB7180920D89C-1.7/setup.py | setup.py |
# 88 ORM Services Connector
This is a simple example package for connecting to ORM Service
to help you guys. | 88orm-service-connector | /88orm-service-connector-0.3.3.tar.gz/88orm-service-connector-0.3.3/README.md | README.md |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="88orm-service-connector",
version="0.3.3",
author="Rimba Prayoga",
author_email="rimba47prayoga@gmail.com",
description="ORM Service Connector",
long_description=long_description,
long_description_content_type="text/markdown",
url="http://pypi.python.org/pypi/88orm-service-connector/",
packages=["orm_service_connector88"],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=[
"Django >= 2.2.8, < 3",
"django-rest-framework",
"requests"
]
)
| 88orm-service-connector | /88orm-service-connector-0.3.3.tar.gz/88orm-service-connector-0.3.3/setup.py | setup.py |
# -*- coding: utf-8 -*-
# Created at 01/02/2019
__author__ = "Rimba Prayoga"
__copyright__ = "Copyright 2019, 88Spares"
__credits__ = ["88 Tech"]
__maintainer__ = "Rimba Prayoga"
__email__ = "rimba47prayoga@gmail.com"
__status__ = "Development"
import json
from typing import List
from urllib.parse import urljoin
import requests
from django.conf import settings
from django.db import models
from django.db.models import Q, ObjectDoesNotExist
from django.utils.functional import cached_property
from .models import initialize_models, get_model, VirtualModel
initialize_models()
service_settings = getattr(settings, 'ORM_SERVICE', {
"url": "",
"auth_header": ""
})
ORM_SERVICE_URL = service_settings.get("url")
ORM_SERVICE_AUTH_HEADER = service_settings.get("auth_header")
class ORMServices(object):
"""
ORM Services Connector.
because you are familiar with Django ORM.
Use it like Django ORM :D
"""
def __init__(self, model: str, fields=None, **kwargs):
initialize_models()
app_label = None
if len(model.split('.')) == 2:
app_label, model = model.split('.')
if isinstance(model, str):
self._model_name = model
elif isinstance(model, type) and isinstance(model(), models.Model):
self._model_name = model._meta.model_name.lower()
else:
raise TypeError('unsupported type "%s" for model.' % type(model))
self._app_label = app_label
self._payload = {}
if fields is None:
fields = ['__all__']
self._fields = fields
self._exclude_fields = kwargs.get('exclude_fields', None)
self._result_cache = {}
self._CHUNK_SIZE = 20
self.model_info = get_model(model, app_label)
########################
# PYTHON MAGIC METHODS #
########################
def __repr__(self):
if self._payload:
_slice = self._payload.get('slice')
if _slice:
start = _slice.get('start')
stop = _slice.get('stop')
step = _slice.get('step')
data = list(self[start:stop:step])
else:
data = list(self[:self._CHUNK_SIZE])
if len(data) >= self._CHUNK_SIZE:
data[-1] = '...(remaining elements truncated)...'
return f"<Virtual Queryset {data}>"
return super(ORMServices, self).__repr__()
def __iter__(self):
data = self._result_cache.get('result')
if not self._payload:
data = []
if data is None:
self.__bind()
data = self._result_cache.get('result')
return iter(data)
def __len__(self):
count = self._result_cache.get("count", 0)
if not count and self.__last_query:
self.__bind()
count = self._result_cache.get("count", 0)
return count
def __bool__(self):
return bool(len(self))
def __getitem__(self, item):
result_cache = self._result_cache.get('result')
if result_cache:
return result_cache[item]
if isinstance(item, slice):
clone = self._clone()
clone._payload.update({
"slice": {
"start": item.start,
"stop": item.stop,
"step": item.step
}
})
return clone
_self = self.__bind()
if _self == self:
result_cache = self._result_cache.get('result')
return result_cache[item]
return _self
@cached_property
def __exclude_params(self):
return [
"all",
"exists",
"count",
"first",
"last",
"latest",
"values",
"save",
"distinct"
]
@cached_property
def __is_model_instance(self):
for method in ["first", "last", "latest"]:
if self._payload.get(method):
return True
return False
@property
def __payload_request(self):
payload = {
"model": self._model_name,
"payload": self._payload,
"fields": self._fields,
"exclude_fields": self._exclude_fields
}
if self._app_label:
payload.update({
"app_label": self._app_label
})
return payload
@property
def __last_query(self) -> str:
"""
:return: last query
"""
queries = list(self._payload.keys()).copy()
if 'slice' in queries:
queries.pop(queries.index('slice'))
try:
return queries[-1]
except IndexError:
return ''
@property
def __is_return_different_object(self) -> bool:
return self.__last_query in [
'first', 'last', 'get', 'latest',
'exists', 'count', 'create'
]
@property
def __is_return_instance(self) -> bool:
return self.__last_query in ['first', 'last', 'get', 'latest', 'create']
def __update_payload(self, name, data) -> None:
try:
existed = self._payload.get(name).copy() # type: Dict
except AttributeError:
pass
else:
existed = existed.copy()
existed.update({
"args": [*existed.get("args", []), *data.get("args", [])],
"kwargs": {
**existed.get("kwargs"),
**data.get("kwargs")
}
})
data = existed
self._payload.update({
name: data
})
# --- expressions
def __resolve_q(self, args: Q) -> List:
"""
Resolve expression Q. e.g: Q(a=b) | Q(c=d).
:param params:
:param result:
:param extra_params:
:return:
"""
_, params, connector = args.deconstruct()
params = list(params)
for index, param in enumerate(params.copy()):
if isinstance(param, Q):
params[index] = self.__resolve_q(param)
elif isinstance(param, tuple):
params[index] = list(param)
return ['Q', params, connector]
def __resolve_expression(self, expr):
expression_handlers = {
"Q": self.__resolve_q
}
return expression_handlers.get(expr)
def __do_query(self, name, *args, **kwargs):
assert self._payload.get('slice') is None, \
"Cannot filter a query once a slice has been taken."
_args = list(args).copy()
for index, arg in enumerate(_args):
if isinstance(arg, Q):
_args[index] = self.__resolve_q(arg)
clone = self._clone()
payload = {
"args": _args,
"kwargs": kwargs
}
clone.__update_payload(name, data=payload)
if clone.__is_return_different_object:
if clone.__is_return_instance:
return clone.__bind()
return clone.fetch()
return clone
def _clone(self):
"""
:return: clone of current class
"""
exclude_fields = self._exclude_fields
if isinstance(exclude_fields, (dict, list)):
exclude_fields = self._exclude_fields.copy()
model_name = self._model_name
if self._app_label:
model_name = f'{self._app_label}.{model_name}'
clone = self.__class__(
model_name,
self._fields.copy(),
exclude_fields=exclude_fields
)
clone._payload = self._payload.copy()
return clone
def __clear_query(self, name=None):
if name is not None:
try:
del self._payload[name]
except KeyError:
pass
else:
self._payload = {}
def __bind(self, model=None, data=None, with_relation=False):
if data is None:
data = self.fetch()
if isinstance(data, dict):
_model = model
if _model is None:
_model = self._model_name
vi = VirtualModel(
model=_model,
payload=self.__payload_request,
value=data,
model_info=self.model_info
)
return vi
vi = {
"result": [],
"count": 0
}
if isinstance(data, list):
if {'values', 'values_list'} & set(self._payload.keys()):
vi.update({
"result": data,
"count": len(data)
})
else:
for i in data:
_vi = VirtualModel(
model=self._model_name,
payload=self.__payload_request,
value=i,
model_info=self.model_info
)
vi.get('result').append(_vi)
vi.update({
"count": vi.get("count") + 1
})
self._result_cache = vi
return self
def __bind_with_relation(self, relation_data):
data = self.fetch_with_relation(relation_data)
return self.__bind(data=data, with_relation=True)
# for custom method
def call_manager_method(self, name, *args, **kwargs):
return self.__do_query(name, *args, **kwargs)
# --- fetch data from orm services
def __request_get(self, url, payload, params=None):
response = requests.get(url, data=json.dumps(payload), headers={
"content-type": "application/json",
'Authorization': ORM_SERVICE_AUTH_HEADER
}, params=params)
if response.status_code == 400:
raise Exception(response.text)
elif response.status_code == 404:
raise ObjectDoesNotExist(
"%s matching query does not exist." % self._model_name.capitalize())
try:
return response.json()
except json.decoder.JSONDecodeError:
if response.text:
raise Exception(response.text)
def __request_post(self, url, payload):
response = requests.post(url, data=json.dumps(payload), headers={
"content-type": "application/json",
'Authorization': ORM_SERVICE_AUTH_HEADER
})
try:
return response.json()
except json.decoder.JSONDecodeError:
raise Exception(response.text)
def fetch(self):
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/get_queryset")
return self.__request_get(
url=url,
payload=self.__payload_request
)
def fetch_with_relation(self, relation_data):
"""
fetch data with relation object
:param relation_data: -- e.g:
ORMServices(model='partitem').all()
.fetch_with_relation({'member':[{'user': ['id', 'email']}]})
:return: -- response:
[{'member': {'user': {'id': 556, 'email': 'cobacoba@gmail.com'}}},]
"""
payload = self.__payload_request.copy()
payload.update({
"relation_data": relation_data
})
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/get_queryset")
return self.__request_get(
url=url,
payload=payload
)
def get_property(self, property_name):
payload = self.__payload_request.copy()
payload.update({
"property_name": property_name
})
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/get_property")
return self.__request_get(url=url, payload=payload)
def call_property(self, property_name):
payload = self.__payload_request.copy()
payload.update({
"property_name": property_name
})
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/call_property")
return self.__request_get(url=url, payload=payload)
# --- querying
def get_queryset(self, *args, **kwargs):
return self.__do_query('all', *args, **kwargs)
def all(self):
return self.get_queryset()
def exists(self) -> bool:
return self.__do_query('exists')
def get(self, *args, **kwargs) -> VirtualModel:
return self.__do_query('get', *args, **kwargs)
def filter(self, *args, **kwargs):
return self.__do_query('filter', *args, **kwargs)
def exclude(self, *args, **kwargs):
return self.__do_query('exclude', *args, **kwargs)
def values(self, *args, **kwargs):
return self.__do_query('values', *args, **kwargs)
def values_list(self, *args, **kwargs):
return self.__do_query('values_list', *args, **kwargs)
def count(self, *args, **kwargs) -> int:
return self.__do_query('count', *args, **kwargs)
def first(self, *args, **kwargs) -> VirtualModel:
return self.__do_query('first', *args, **kwargs)
def last(self, *args, **kwargs) -> VirtualModel:
return self.__do_query('last', *args, **kwargs)
def latest(self, *args, **kwargs) -> VirtualModel:
return self.__do_query('latest', *args, **kwargs)
def order_by(self, *args, **kwargs):
return self.__do_query('order_by', *args, **kwargs)
def select_related(self, *args, **kwargs):
return self.__do_query('select_related', *args, **kwargs)
def prefetch_related(self, *args, **kwargs):
return self.__do_query('prefetch_related', *args, **kwargs)
def distinct(self, *args, **kwargs):
return self.__do_query('distinct', *args, **kwargs)
def only(self, *args, **kwargs):
return self.__do_query('only', *args, **kwargs)
def defer(self, *args, **kwargs):
return self.__do_query('defer', *args, **kwargs)
def create(self, *args, **kwargs):
return self.__do_query('create', *args, **kwargs)
def update(self, **kwargs):
self.__update_payload('update', data={
'args': [],
'kwargs': kwargs
})
return self.fetch()
def delete(self):
self.__update_payload('delete', data={
'args': [],
'kwargs': {}
})
return self.fetch()
def get_or_create(self, *args, **kwargs):
try:
return self.get(*args, **kwargs), False
except ObjectDoesNotExist:
return self.create(**kwargs), True
def custom(self, name, **kwargs):
return self.__do_query(name, *(), **kwargs)
@classmethod
def execute_many(cls, payloads: List):
payload_requests = list(
map(lambda orm: orm._ORMServices__payload_request, payloads))
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/execute_many")
response = requests.get(url, data=json.dumps(payload_requests), headers={
"content-type": "application/json",
'Authorization': ORM_SERVICE_AUTH_HEADER
})
try:
response = response.json()
except Exception:
raise Exception(response.content)
else:
result = []
for index, orm_service in enumerate(payloads):
result.append(orm_service._ORMServices__bind(data=response[index]))
return result
def _save(self, payload, *args, **kwargs):
self.__do_query('save', *args, **kwargs)
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/save")
return self.__request_post(
url=url,
payload=payload
)
| 88orm-service-connector | /88orm-service-connector-0.3.3.tar.gz/88orm-service-connector-0.3.3/orm_service_connector88/connector.py | connector.py |
from collections import OrderedDict
from typing import Dict
from rest_framework import serializers
from .connector import ORMServices
class ModelSerializer(serializers.Serializer):
map_fields = {
'AutoField': serializers.IntegerField,
'CharField': serializers.CharField,
'IntegerField': serializers.IntegerField,
'ListField': serializers.ListField,
'OneToOneField': serializers.IntegerField,
'ForeignKey': serializers.IntegerField
}
def get_fields(self) -> Dict:
assert hasattr(self, 'Meta'), (
'Class {serializer_class} missing "Meta" attribute'.format(
serializer_class=self.__class__.__name__
)
)
assert hasattr(self.Meta, 'model'), (
'Class {serializer_class} missing "Meta.model" attribute'.format(
serializer_class=self.__class__.__name__
)
)
assert hasattr(self.Meta, 'fields'), (
'Class {serializer_class} missing "Meta.fields" attribute'.format(
serializer_class=self.__class__.__name__
)
)
assert len(self.Meta.fields) > 0, (
'Are you stupid, you\'re put a blank list on "Meta.fields"'
)
ret = super(ModelSerializer, self).get_fields()
uncreated_fields = set(self.Meta.fields) - set(ret.keys())
model_info = self.Meta.model.model_info
model_fields = model_info.get('fields')
model_related = model_info.get('related_names')
if uncreated_fields:
for uncreated_field in uncreated_fields:
if uncreated_field in model_fields:
field = model_fields.get(uncreated_field).get('type')
elif uncreated_field in model_related:
field = 'ListField'
if model_related.get(uncreated_field).get('type') == 'OneToOneRel':
field = 'IntegerField'
else:
field = 'CharField'
field_class = self.map_fields.get(field, serializers.CharField)
ret.update({
uncreated_field: field_class()
})
for key, value in ret.items():
value.bind(key, self)
return ret
def to_representation(self, instance):
ret = OrderedDict()
model_info = self.Meta.model.model_info
model_fields = model_info.get('fields')
for field, field_class in self.get_fields().items():
attr = field_class.source or field
try:
if model_fields.get(attr).get('type') in ['ForeignKey', 'OneToOneField']:
attr = f"{attr}_id"
except AttributeError:
pass
value = getattr(instance, attr, None)
if isinstance(value, ORMServices):
if attr in model_info.get('related_names'):
value = instance.reverse_related(attr)
if field_class.__class__.__name__ == 'SerializerMethodField':
value = instance
if value is not None:
value = field_class.to_representation(value)
ret[field] = value
return ret | 88orm-service-connector | /88orm-service-connector-0.3.3.tar.gz/88orm-service-connector-0.3.3/orm_service_connector88/serializers.py | serializers.py |
name = "88orm-service-connector"
from .connector import ORMServices
__all__ = ["ORMServices"]
| 88orm-service-connector | /88orm-service-connector-0.3.3.tar.gz/88orm-service-connector-0.3.3/orm_service_connector88/__init__.py | __init__.py |
import json
from typing import Dict
from urllib.parse import urljoin
import requests
from django.conf import settings
# NOTE: All models info will be stored here.
# contains fields and related_names,
# keep note don't redefine the MODELS variable
# for keeping the reactivity. If you want to
# change the value, just clear or append it.
MODELS = []
service_settings = getattr(settings, 'ORM_SERVICE', {
"url": "",
"auth_header": ""
})
ORM_SERVICE_URL = service_settings.get("url")
ORM_SERVICE_AUTH_HEADER = service_settings.get("auth_header")
class VirtualModel(object):
def __init__(
self,
model: str,
payload: dict,
value=None,
model_info=None
):
self._payload = payload
app_label = None
if len(model.split('.')) == 2:
app_label, model = model.split('.')
self.__model = model
self._app_label = app_label
self._attrs = {}
if not model_info:
model_info = get_model(model, app_label)
if not app_label:
self._app_label = model_info.get('app_label')
self._fields = model_info.get('fields') # type: Dict
self._related_names = model_info.get('related_names') # type: Dict
if value:
self._set_value(value)
def __repr__(self):
key = self._attrs.get('id') or self._attrs.get(next(iter(self._attrs)))
model_name = self.__model
if model_name.islower():
model_name = model_name.capitalize()
return f"<{model_name}: {key}>"
def __setattr__(self, key, value):
try:
super(VirtualModel, self).__setattr__(key, value)
if key in self._fields:
self._attrs.update({
key: value
})
except Exception:
pass
def _set_attr_single_instance(self, key, value):
from .connector import ORMServices
attr_value = None
if self._attrs.get(f"{key}_id"):
related_model = value.get('related_model')
model = f"{related_model.get('app_label')}.{related_model.get('name')}"
attr_value = ORMServices(model)
setattr(self, key, attr_value)
def _set_related_attributes(self):
from .connector import ORMServices
for key, value in self._fields.items():
if not hasattr(self, key):
type_field = value.get('type')
if type_field in ['ForeignKey', 'OneToOneField']:
self._set_attr_single_instance(key, value)
elif type_field == 'ManyToManyField':
related_model = value.get('related_model')
model = f"{related_model.get('app_label')}.{related_model.get('name')}"
attr_value = ORMServices(model)
setattr(self, key, attr_value)
for key, value in self._related_names.items():
if not hasattr(self, key):
related_model = value.get('related_model')
model = f"{related_model.get('app_label')}.{related_model.get('name')}"
attr_value = ORMServices(model)
setattr(self, key, attr_value)
def _set_value(self, attrs: Dict):
self._attrs.update(attrs)
for key, value in attrs.items():
setattr(self, key, value)
self._set_related_attributes()
def get_related(self, name):
from .connector import ORMServices
attr = getattr(self, name)
if isinstance(attr, ORMServices):
if name in self._fields:
field = self._fields.get(name)
if field.get('type') in ['ForeignKey', 'OneToOneField']:
return attr.get(id=self._attrs.get(f"{name}_id"))
elif field.get('type') == 'ManyToManyField':
key = field.get('related_model').get('related_query_name')
return attr.filter(**{key: self.id})
return attr
def reverse_related(self, related_name):
try:
orm = getattr(self, related_name) # type: ORMServices
rel = self._related_names.get(related_name)
related_model = rel.get('related_model')
filter_kwargs = {
related_model.get('related_field'): self.id
}
if rel.get('type') == 'OneToOneRel':
return orm.get(**filter_kwargs)
return orm.filter(**filter_kwargs)
except AttributeError:
raise AttributeError(f'{self.__model} has no related {related_name}')
def refresh_from_db(self):
from .connector import ORMServices
instance = ORMServices(
model=self.__model,
fields=list(self._attrs)
)
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/get_queryset")
attrs = instance._ORMServices__request_get(
url=url,
payload=self._payload
)
if isinstance(attrs, dict):
for key, value in attrs:
setattr(self, key, value)
def save(self):
from .connector import ORMServices
instance = ORMServices(
model=self.__model,
fields=list(self._attrs)
)
payload = self._payload.copy()
payload.get("payload").update({
"save": self._attrs
})
return instance._save(payload)
class ModelNotFound(Exception):
pass
class MultipleModelsReturned(Exception):
pass
def initialize_models(force=False):
global MODELS
if not MODELS or force:
url = urljoin(ORM_SERVICE_URL, "/api/v1/orm_services/get_models")
response = requests.get(url, headers={
"content-type": "application/json",
'Authorization': ORM_SERVICE_AUTH_HEADER
})
if response.status_code == 400:
raise Exception(response.text)
try:
response = response.json()
except json.decoder.JSONDecodeError:
if response.text:
raise Exception(response.text)
else:
MODELS.clear()
MODELS += response
def get_model(name: str, app_label=None) -> Dict:
initialize_models()
name = name.lower()
result = list(filter(
lambda model: model.get('model') == name,
MODELS
))
if app_label:
result = list(filter(
lambda model: model.get('app_label') == app_label,
result
))
if not result:
msg = f"Cannot find model {name}"
if app_label:
msg = f"{msg} with app_label {app_label}"
raise ModelNotFound(msg)
if len(result) > 1:
multiple = list(map(lambda x: x.get('app_label'), result))
raise MultipleModelsReturned(f"Please provide app_label: {multiple}")
return result[0]
| 88orm-service-connector | /88orm-service-connector-0.3.3.tar.gz/88orm-service-connector-0.3.3/orm_service_connector88/models.py | models.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.