コード例 #1
0
def main():
    emoji = ["-", "^_^", "T-T", "@_@", "@.@", "*-*", ":P"]
    price = [0, 20, 60, 100, 150, 200, 250]
    user = login()
    while True:
        # print_vending_machine()
        # print("\n--== Main Menu ==--")
        print(term_io.bgcolor.black + term_io.fgcolor.Yellow)
        os.system("figlet Main Menu")
        print(term_io.bgcolor.black + term_io.fgcolor.default)
        action = term_io.select_menu([
            " Emoji Vending ", "  Emoji Stand  ", "   Minigames   ",
            " Ancient Tower ", "   Show Room   ", " Message Board ",
            "    Library    ", "     Bank      ", "  My Inventory ",
            "  Magic Portal ", "   Exit Game   "
        ],
                                     front_space=15)
        if action == 10:
            user.save()
            return
        if action == 9:
            print(
                term_io.delete.whole_screen +
                "It is a portal standing on the ground formed with blue light. You can only see light inside it."
            )
            print("You are not sure if stepping into it.")
            if term_io.y_or_n():
                user = portal_entry(user)
        if action == 8:
            my_inventory(user, emoji)
        if action == 6:
            library()
        if action == 5:
            run_chatroom(user.username)
        if action == 0:
            user.points, user.emoji_you_have = vending(user.points, price,
                                                       emoji,
                                                       user.emoji_you_have)
            user.save()
        if action == 2:
            user = minigame(user)
        if action == 4:
            print("\n\n")
            show_room()
        if action == 3:
            user = training_room(user)
        if action == 1:
            selling_price = [_ / 2 for _ in price]
            user.points, user.emoji_you_have = selling(
                user.points, selling_price, emoji, user.emoji_you_have
            )  #selling price is some rate of buying price
            user.save()
        if action == 7:
            user = bank_entry(user)
            user.save()
コード例 #2
0
    def __init__(self, surface, event_queue):
        self.imagelibrary = library.library()
        self.soundlibrary = library.library("sound")
        self.musiclibrary = library.library("music")
        self.onscreen = []
        self.surface = surface
        self.count = 0
        self.images = []
        self.texts = []
        self.text = ''
        self.font = pygame.font.Font(None, 24)
        self.eventqueue = event_queue
        self.tabbed = 0
        self.kills = 0
        self.deaths = 0
        self.event = []
        self.escapemenu = 0
        self.sercon = 0

        self.renderer = Renderer()
        self.renderer.set_screen(self.surface)

        self.quitbutton = Button("Quit")
        self.quitbutton.position = 390,120
        self.quitbutton.connect_signal(SIG_CLICKED, sys.exit)
        self.cancelbutton = Button("Cancel")
        self.cancelbutton.position = 390,100
        self.cancelbutton.connect_signal(SIG_CLICKED, self.cancel)
        
        self.tabrenderer = Renderer()
        self.tabrenderer.set_screen(self.surface)

        try:	#default their name to so and so if they don't have one.
	    name = self.name
	except:
	    name = "so and so"
	self.name_label = Label(name + '        ' )
	self.k_label = Label("Kills: ")
	self.k_label.position = 10,25
	self.d_label = Label("Deaths: ")
	self.d_label.position = 10,45
        self.kill_label = Label(str(self.kills))
        self.kill_label.position = 60,25
        self.death_label = Label(str(self.deaths))
        self.death_label.position = 60,45

        self.hpbar = pygame.image.load("hpbar.gif").convert()
	self.hpbar = pygame.transform.scale(self.hpbar,(self.hpbar.get_width()*3,self.hpbar.get_height()*3))
        self.hpinc = pygame.image.load("hp.gif").convert()
        self.hpinc = pygame.transform.scale(self.hpinc,(self.hpinc.get_width()*3,self.hpinc.get_height()*3))
        self.hp = 17
        self.chatbar = pygame.image.load('chatbar.gif').convert()
	self.chatbar.set_alpha(100)
コード例 #3
0
def PyXml(path):
    '''
    Open the Rappture xml file located at 'path' and return a node
    reference to the root.
    '''
    lib = library(path)
    return Node(lib, '')
コード例 #4
0
    def run(self):
        with open(self.tmp_name, 'w') as f:
            f.write(self.xml())

        if self.bin:
            cmd = "PATH=%s:$PATH /apps/bin/rappture -execute %s -tool %s > %s" % \
                (self.bin, self.tmp_name, self.tool_file, self.run_name)
        else:
            cmd = "/apps/bin/rappture -execute %s -tool %s > %s" % (
                self.tmp_name, self.tool_file, self.run_name)

        try:
            ret = subprocess.call(cmd, shell=True)
            if ret:
                print >> sys.stderr, 'Error: "%s"' % cmd
                if ret < 0:
                    print >> sys.stderr, "Terminated by signal", -ret
                else:
                    print >> sys.stderr, "Returncode", ret
        except OSError as e:
            print >> sys.stderr, 'Error: "%s"' % cmd
            print >> sys.stderr, "Failed:", e
            sys.exit(1)

        self.lib = library(self.run_name)
コード例 #5
0
ファイル: name_arg.py プロジェクト: estabenau/appaserver
	def __init__( self, usage_filename ):
		self.usage_filename = usage_filename
		self.comments = queue.queue()
		self.variable_library = library.library()

		self.variable_string_dictionary = \
			string_dictionary.string_dictionary()
コード例 #6
0
 def library(path):
     try:
         return jsonify(L.library(path)), 200, {
             'Access-Control-Allow-Origin': '*'
         }
     except IOError:
         abort(404)
コード例 #7
0
def add_new_book_description(message):
    global new_book
    new_book[1] = message.text
    books = library(constants.filename_book_list)
    books.add(new_book)
    answer = constants.message_addbook_success
    bot.send_message(message.chat.id, answer)
    log(message, answer)
コード例 #8
0
ファイル: __init__.py プロジェクト: markdude701/Batchmark.me
def library_test():
    try:
        uppered = ''
        if request.method == "POST":
            lower = request.form['upper']
            uppered = library(lower)
            return render_template("uppercase.html", uppered=uppered)
        return render_template("uppercase.html", uppered=uppered)
    except Exception as e:
        return str(e)
コード例 #9
0
def is_number(text):
    books = library(constants.filename_book_list)
    a = 0
    range_bool = True
    try:
        a = int(text)
        range_bool = a in range(books.count() + 1)
    except:
        range_bool = False
    num_bool = (text.strip() == str(a))
    return num_bool & range_bool
コード例 #10
0
    def __init__(self, event_queue, background = 0, limits = 0):
        self.imagelibrary = library.library()
        self.sprites = pygame.sprite.Group()
        self.background = self.load_image(background)
        self.limits = limits
        self.views = []
        self.currentid = 0
        self.dirtysprites = pygame.sprite.Group()
        self.moved = []
	self.eventqueue = event_queue
        self.soundlibrary = library.library("sound")
        self.musiclibrary = library.library("music")
	self.currentmusic = None

	self.chatbar = pygame.image.load('chatbar.gif').convert()
	self.chatbar.set_alpha(100)
	
	#game conditions
	self.maxdeath = 0
	self.maxkill  = 0
	self.endtime = 0	#length of game in seconds
	self.starttime = time.time()
コード例 #11
0
def list_of_books(floor="", searchString=""):
    books = library(constants.filename_book_list)

    book_statuses = dict()
    with open(constants.filename_status, 'r') as book_file:
        for line in book_file:
            book_statuses[int(line.split(',')[0])] = [
                line.split(',')[1],
                str(int(line.split(',')[2]))
            ]
            # book status : book_id, user_id, timestamp, floor
            if len(line.split(',')) >= 4:
                book_statuses[int(line.split(',')[0])].append(
                    int(line.split(',')[3]))

    res = "Список книг:\n"

    for item in books.list():

        if int(book_statuses[item[0]]
               [0]) != 0 and floor == "" and searchString == "":
            res += "/" + str(item[0]) + " (отдана) " + item[1]
            res += "\n"
        elif floor == "" and searchString == "":
            res += "/" + str(item[0]) + " " + item[1]
            if len(book_statuses[item[0]]) <= 2:
                res += " (17 этаж)"
            else:
                res += " (" + constants.bookshelfs[book_statuses[item[0]]
                                                   [2]] + ")"
            res += "\n"
        elif int(book_statuses[item[0]]
                 [0]) == 0 and floor != "" and searchString == "":
            if floor == constants.bookshelfs[book_statuses[
                    item[0]][2]] and len(book_statuses[item[0]]) > 2:
                res += "/" + str(item[0]) + " " + item[1]
                res += "\n"
        elif searchString != "":
            if (string_like_enough(searchString.lower(), item[1].lower())):
                if int(book_statuses[item[0]][0]) != 0:
                    res += "/" + str(item[0]) + " (отдана) " + item[1]
                else:
                    res += "/" + str(item[0]) + " " + item[1]
                res += "\n"

    return res
コード例 #12
0
def list_of_self_books(userId):
    books = library(constants.filename_book_list)

    book_statuses = dict()
    with open(constants.filename_status, 'r') as book_file:
        for line in book_file:
            book_statuses[int(line.split(',')[0])] = [
                line.split(',')[1],
                str(int(line.split(',')[2]))
            ]
            # book status : book_id, user_id, timestamp, floor
            if len(line.split(',')) >= 4:
                book_statuses[int(line.split(',')[0])].append(
                    int(line.split(',')[3]))

    res = "Список книг:"

    for item in books.list():
        if int(book_statuses[item[0]][0]) == userId:
            res += "\n/" + str(item[0]) + " " + item[1]

    return res
コード例 #13
0
    def __init__(self, tool):
        """
        tool can be any of the following:

        - Path to a tool.xml file.
        - Name of a published tool.  The current version will be run.

        """
        dirname, xml = os.path.split(tool)
        if dirname == "":
            if xml != "tool.xml":
                # must be tool name
                dirname = "/apps/%s/current" % xml
                xml = dirname + "/rappture/tool.xml"
            else:
                dirname = os.getcwd()
        else:
            xml = tool
            dirname = os.path.abspath(os.path.join(dirname, '..'))

        if not os.path.isfile(xml):
            raise ValueError(
                "tool must ba a toolname or path to a tool.xml file.")

        self.bin = os.path.join(dirname, 'bin')
        if not os.path.isdir(self.bin):
            self.bin = ""

        sessdir = os.path.join(os.environ['HOME'], 'data/sessions',
                               os.environ['SESSION'])
        self.tmp_name = os.path.join(sessdir,
                                     'tool_driver_%s.xml' % os.getpid())
        self.run_name = os.path.join(sessdir, 'tool_run_%s.xml' % os.getpid())
        self.tool_file = xml
        self.lib = library(xml)
        self.path = ''
コード例 #14
0
class User:
    "******"
    Library = library() #Class Variable.Instance of a class library.
    Log = [] #Class Variable. Contains all the logs of all users.
    issuedBId = [] #Class Variable. Contains BId(s) of all the books still in circulation
    def __init__(self,name,age,address,phone_number,aadhar_id,username,password):
        "Constructor"
        self.name = name
        self.age = age
        self.address = address
        self.phoneNumber = phone_number
        self.aadharId = aadhar_id
        self.userName = username
        self.password = password
    @classmethod
    def returnAuthors(cls):
        "Return a set of all the authors."
        return cls.Library.authorSet
    @classmethod
    def returnPublishers(cls):
        "Returns a set of all the publishers."
        return cls.Library.publisherSet
    @classmethod
    def search(cls,by = "all",value = ""):
        "Searches and tabulates books in a library by various parameters and return a dictionary with BId(s) as keys and their respective stock as values.\nVarious parameters for searching are:\nauthor\nname\npublisher\nyear\nall "
        temp = []
        if by == "all":
            temp = cls.Library.searchAll()
            if temp:    
                print(tabulate(temp,headers = ("Book Id","Book Name","Author","Publishing Year","Publisher","Language code","Average Rating","Stock")))
        elif by == "name":
            temp = cls.Library.searchByName(value)
            if temp:    
                print(tabulate(temp,headers = ("Book Id","Book Name","Author","Publishing Year","Publisher","Language code","Average Rating","Stock")))
        elif by == "publisher":
            temp = cls.Library.searchByPublisher(value)
            if temp:    
                print(tabulate(temp,headers = ("Book Id","Book Name","Author","Publishing Year","Publisher","Language code","Average Rating","Stock")))
        elif by == "year":
            temp = cls.Library.searchByYear(value)
            if temp:
                print(tabulate(temp,headers = ("Book Id","Book Name","Author","Publishing Year","Publisher","Language code","Average Rating","Stock")))
        elif by == "author":
            temp = cls.Library.searchByAuthor(value)
            if temp:    
                print(tabulate(temp,headers = ("Book Id","Book Name","Author","Publishing Year","Publisher","Language code","Average Rating","Stock")))
        if temp:
            return {i.id : i.stock for i in temp}
        else:
            return False
    @classmethod 
    def displayLog(cls,memberId = ""):
        "Displays log in a tabulated fashion of a particular member. If memberId is not provided, displays log of all members."
        flag = False
        if memberId != "":
            temp = []
            for log in cls.Log:
                if log.memberId == memberId:
                    temp.append(log)
                    flag = True
        else:
            temp = cls.Log
            if temp:
                flag =  True
        if flag:
            print(tabulate(temp,headers=["Book Id","Book Name","Member Id","Member Name","Issued Date","Returned Date"]))
            return True
        else:
            return False
    @classmethod
    def displayBook(cls,BId):
        cls.Library.displayBook(BId)      
コード例 #15
0
from book import book
from library import library
from library_log import library_log

ll = library()
ll.sign_in_duration = 10

print(ll.id, ll.sign_in_duration)

b = book()
library.books = [b]

print(library.books)

log = library_log()
log.library = ll
log.start_day = 1

print(log.getEndDaySignIn())
コード例 #16
0
from flask import Flask, render_template, request as req
from flaskwebgui import FlaskUI
from library import library

app = Flask(__name__)
ui = FlaskUI(app)
libs = library()


@app.route('/', methods=['GET', 'POST'])
def index():
    if req.method == "GET":
        return render_template('content/index.html')
    else:
        return render_template('content/index.html')


@app.route('/ekstraksi_ciri', methods=['GET', 'POST'])
def ekstraksi_ciri():
    if req.method == 'GET':
        return render_template('content/extract.html')
    else:
        data = req.files['file']
        libs.ekstraksi_ciri.get_rgb(data)
        return render_template('content/extract.html')


@app.route('/pelatihan', methods=['GET', 'POST'])
def pelatihan():
    if req.method == 'GET':
        return render_template('content/pelatihan.html')
コード例 #17
0
ファイル: restlibrary.py プロジェクト: derolf/transcoder
 def library(path):
     try:
         return jsonify(L.library(path)), 200, {'Access-Control-Allow-Origin': '*'}
     except IOError:
         abort(404)
コード例 #18
0
ファイル: web_db.py プロジェクト: josecoelho96/ist-asint-labs
import webapp2
from webapp2_extras import routes
from webapp2_extras import jinja2

from string import Template

import library
import mimetypes
import json

from jinja2 import Environment, select_autoescape, FileSystemLoader
env = Environment(loader=FileSystemLoader('./templates'),
                  autoescape=select_autoescape(['html', 'xml', 'json']))

bd = library.library("mylib")


def sendFile(response, FileName):
    response.headers.add_header('Content-Type',
                                mimetypes.guess_type(FileName)[0])
    f = open(FileName, 'r')
    response.write(f.read())
    f.close()


class MainPage(webapp2.RequestHandler):
    def get(self):
        sendFile(self.response, 'index.html')


class BooksListHandler(webapp2.RequestHandler):
コード例 #19
0
def parse_input(filename):

    f = open(filename)

    # Get parameters
    list_books = []
    list_libraries = []
    flag = 0

    for (counter, line) in enumerate(f):
        line_splitted = line.split()

        if len(line_splitted) == 0:
            break
        else:
            if counter == 0:
                nb_books = int(line_splitted[0])  # to check parsing is correct
                nb_libraries = int(
                    line_splitted[1])  # to check parsing is correct
                nb_days = int(line_splitted[2])

            elif counter == 1:
                for book_id, book_score in enumerate(line_splitted):
                    book_item = book(id=book_id, score=book_score)
                    list_books.append(book_item)
                    del book_item
                assert (len(list_books) == nb_books)

            else:

                if flag == 0:
                    library_item = library(sign_in_duration=line_splitted[1],
                                           max_number_books=line_splitted[2])

                    library_item.id = int(counter / 2)

                    nb_books_in_lib = int(
                        line_splitted[0])  # to check parsing is correct
                    flag += 1

                elif flag == 1:
                    library_item.books = []

                    for book_id_str in line_splitted:
                        book_id = int(book_id_str)
                        library_item.books.append(list_books[book_id])

                    assert (len(library_item.books) == nb_books_in_lib)
                    flag = 0

                    list_libraries.append(library_item)
                    del library_item

                else:
                    raise Exception("Parsing error: Flag greater than 1 ")

    f.close()
    print(
        f'File description: Days {nb_days} - nb_libraries {nb_libraries} - nb_books {nb_books} '
    )
    assert (len(list_libraries) == nb_libraries)
    return nb_days, list_libraries, list_books
コード例 #20
0
ファイル: classify.py プロジェクト: aymanzay/Macaron
from config import sliceSize
from config import genreList

from songToData import createSlicesFromAudio
from audioFilesTools import isMono
from imageFilesTools import getImageData
from subprocess import Popen, PIPE, STDOUT
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from numpy import array
from library import library
from library import song
from knn import kNNclassify

currentPath = os.path.dirname(os.path.realpath(__file__)) 
s = song()
lib = library()

def classify():
    #List genres
    genres = os.listdir(slicesPath)
    genres = [filename for filename in genres if os.path.isdir(slicesPath+filename)]
    nbClasses = len(genres)

    #Create model
    model = createModel(nbClasses, sliceSize)
    #s = song()
    #lib = library()

    #create spectrogram path if it doesn't exist
    if not os.path.exists(os.path.dirname(predictSpect)):
        try:
コード例 #21
0
def book_info(book_id, message):
    books = library(constants.filename_book_list)
    logOperation("operation=Info book=" + str(book_id) +
                 " success=True user="******"\n " + constants.lib[book_id][1])
コード例 #22
0
ファイル: __init__.py プロジェクト: dragonyzl/vsipl
from library import library
_library = library()

from view import *
コード例 #23
0
    print("Los controles son los siguientes: ")
    print("(M) Muestra la lista de los libros que hay en la biblioteca.")
    print("(D) Borrar un libro.")
    print("(E) Editar un libro.")
    print("(A) Añadir un libro.")
    print("(B) Buscar un libro por editorial o autor(sin tildes).")
    print("(O) Opciones disponibles.")
    print("(Q) Salir del programa.")


#Menú de inicio.
print("Bienvenido al Gestor de Bibliotecas.")
showOptions()

#Creamos un objeto 'library' y cargamos un archivo CSV con datos de libros.
biblioteca = lb.library()
filename = input(
    "Introduzca el nombre del archivo de datos: (Presione INTRO para la opción por defecto(data.csv))"
)
if filename:
    biblioteca.loadLibrary(filename)
else:
    biblioteca.loadLibrary('data.csv')

#Realizamos una lectura anticipada de la opción del menú.
option = lb.read("Introduzca una opción: ").upper(
)  #La convertimos a mayúscula para evitar confusión entre minúsculas y mayúsculas.

#El menú lo he implementado con un 'while'(No comentaré nada aquí porque creo que se entiende bien).
while option != "Q":
    if option == "M":
コード例 #24
0
ファイル: merge.py プロジェクト: TwinIsland/CTD
#encoding:utf-8
import library
import fastclean

api = 'E:\GFEC - Global Free Education Center\CTCdata - Chinese Traditional Classical Database\Data\话'
url = 'https://ctd-1257758577.cos.ap-guangzhou.myqcloud.com/data/%E8%AF%9D/'
cid = 54766 + 1
count = 0

library = library.library()
container = fastclean.data()

container.load_data([api])
data = container.data

for i in data:
    title = i.split('\\')[-1].split('-')[0]
    age = i.split('\\')[-1].split('-')[1]
    author = i.split('\\')[-1].split('-')[2].split('.')[0]
    link = url + i.split('\\')[-1].split('\\')[-1]

    re = [cid,title,author,age,link]
    print(re)
    library.addMethod(re,'book')
    cid += 1

library.save_change()

コード例 #25
0
import webapp2
from webapp2_extras import routes
from string import Template
import library
import mimetypes

import json

bd = library.library("mylib")


def sendFile(response, FileName):
    response.headers.add_header('Content-Type', mimetypes.guess_type(FileName)[0])
    f = open(FileName, 'r')
    response.write(f.read())
    f.close()


class MainPage(webapp2.RequestHandler):
    def get(self):
        sendFile(self.response, 'index.html')


class BooksListHandler(webapp2.RequestHandler):
    def get(self):
        # return
        self.response.content_type = 'application/json'
        book_list = json.dumps(bd.listBooks())
        self.response.write(book_list)