index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
75,126
ashish-iitian/predicting_changes_in_stock_prices
refs/heads/master
/corr_main.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from corr_feature_extractor import feature_extractor from corr_predictor import regression from sklearn import cross_validation def train(lag, y_train, train_set): ''' Training phase: set of features taken, processed duly for lag_param, fed to linear regression module for learning the model. Model learnt is validated through cross-validation. Returns model and features for test phase to the main ''' extractor = feature_extractor(lag) feature_matrix = extractor.processor(train_set) model = regression.learner(feature_matrix[:50], y_train) # print cross_validator(model, feature_matrix[:50], y_train) return model, feature_matrix[50:] ''' --------------------------- for cross validation -------------------------------- ''' def cross_validator(regr, features, Y): ''' does cross validation (here 3-fold) for trained model and returns scores based on r2 metric ''' kfold = cross_validation.cross_val_score(regr, features, Y, cv = 3, scoring='r2') return kfold def test(model, test_data): ''' Test phase: set of features for test set fed to the learned model for predicting unknowns ''' return regression.predictor(model, test_data) def main(): ''' handles the function calls and writes predicted values to a csv file for output ''' df = pd.read_csv(r'./data/stock_returns_base150.csv',skipfooter = 50) dates = df.ix[: , ['date']].iloc[50:].reset_index() dates.drop('index', axis=1, inplace=True) label = df.ix[:49,['S1']].astype(float).values.tolist() data = df.ix[:, ['S2','S3','S4','S5','S6','S7','S8','S9','S10']] for column in data: df[column] = df[column].astype(float) length = len(data) train_data = data.values.tolist() lag_param = 0 model_learned, test_features = train(lag_param, label, train_data) y_pred = test(model_learned, test_features).flatten() value = pd.DataFrame({'Value':y_pred[:]}, index=range(len(y_pred))) result = pd.concat([dates,value],axis=1) result.to_csv('predictions.csv', index=False) if __name__ == "__main__": main()
{"/corr_main.py": ["/corr_feature_extractor.py", "/corr_predictor.py"]}
75,128
datastore/datastore.titan
refs/heads/master
/datastore/titan/test.py
import unittest from datastore import Key from datastore.core.test.test_basic import TestDatastore from . import TitanDatastore class TestTitanDatastore(TestDatastore): pass if __name__ == '__main__': unittest.main()
{"/datastore/titan/test.py": ["/datastore/titan/__init__.py"]}
75,129
datastore/datastore.titan
refs/heads/master
/datastore/titan/__init__.py
__version__ = '0.0.1' __author__ = 'Juan Batiz-Benet' __email__ = 'juan@benet.ai' __doc__ = ''' titan datastore implementation. Tested with: * datastore 0.3.6 * titan 0.3.1 * thunderdome 0.4.7 ''' import thunderdome import datastore.core class TitanDatastore(datastore.Datastore): '''Represents a Titan datastore. Hello World: >>> import thunderdome >>> import datastore.titan >>> >>> from thunderdome.connection import setup >>> setup(['localhost'], 'graph') >>> ds = datastore.titan.TitanDatastore() # uses global connection. >>> >>> class Person(thunderdome.Vertex): >>> name = thunderdome.Text() >>> >>> juan = Person.create(name='Juan BB') >>> juan_key = Key(juan.vid) >>> ds.contains(juan_key) True >>> ds.get(juan_key).name 'Juan BB' >>> ds.delete(juan_key) >>> ds.get(juan_key) None ''' def __init__(self): pass def get(self, key): '''Return the object named by key.''' try: return thunderdome.Vertex.get(key.name) except thunderdome.models.DoesNotExist: return None def put(self, key, vertex): '''Stores the object.''' if key.name != vertex.vid: err = 'TitanDatastore does not support changing keys: ' err += 'key.name != vertex.vid (%s != %s).' % (key.name, vertex.vid) raise ValueError(err) vertex.save() def delete(self, key): '''Removes the object.''' vertex = self.get(key) if vertex: vertex.delete() def query(self, query): '''Returns all outVertices.''' # entire dataset already in memory, so ok to apply query naively vertex = self.get(query.key) return vertex.outV()
{"/datastore/titan/test.py": ["/datastore/titan/__init__.py"]}
75,144
fightBoy-Ing/mctools
refs/heads/master
/mctools/__main__.py
import argparse import sys from mctools.mclient import RCONClient, QUERYClient, PINGClient from mctools.formattertools import FormatterCollection, DefaultFormatter, QUERYFormatter, PINGFormatter import json """ A command line interface for interacting/querying Minecraft servers """ RCON_PORT = 25575 QUERY_PORT = 25565 MINECRAFT_PORT = 25565 SEP = '§9+========================================================================+' class _HelpAction(argparse._HelpAction): """ Custom HelpAction, so we can display all subparser help output """ def __call__(self, parser, namespace, values, option_string=None): parser.print_help() # retrieve subparsers from parser subparsers_actions = [ action for action in parser._actions if isinstance(action, argparse._SubParsersAction)] # there will probably only be one subparser_action, # but better save than sorry for subparsers_action in subparsers_actions: # get all subparsers and print help for choice, subparser in subparsers_action.choices.items(): print("Option: '{}'".format(choice)) print(subparser.format_help()) print("For more information, please check the GitHub page: https://github.com/Owen-Cochell/mctools") parser.exit() class Output: """ Class for outputting values to terminal, as well as writing output to files, if necessary We use the mclient formattertools to handle the formatting for us, As the user probably doesn't want a bunch of ASCII values in their output file. """ def __init__(self, args): self.quiet = args.quiet # Boolean determining if we are in quite mode self.color = args.no_color # Boolean determining if we can use color in output self.show_chars = args.raw # Boolean determining if we display format chars self.output_path = args.output # File path to write, None if not writing self.output_chars = args.output_raw # Boolean determining if we should output format chars into file self.output_replace = args.output_color # Boolean determining if we should replace chars with ASCII values self.formatters = FormatterCollection() # FormatterCollection method, used for formatting text # Adding base formater: self.formatters.add(DefaultFormatter, '', ignore=[self.formatters.QUERY, self.formatters.PING]) try: self.output_favicon = args.show_favicon # Boolean determining if we should output the favicon except Exception: self.output_favicon = False def output(self, text, command='', relevant=False): """ Outputs text with whatever formatting chars we need, Writes text to file if necessary. :param text: Text to output :param command: Command issued when text was generated :param relevant: Value determining if we are working with relevant text(Response from server) :return: """ # Formatting text for terminal output: if not self.quiet: if relevant and type(text) != str: self.recursive_print(self.format_print(text, command, relevant)) else: print(self.format_print(text, command, relevant)) # Formatting text for file output if relevant and self.output_path is not None: file = open(self.output_path, 'a') if type(text) == dict: file.write(json.dumps(self.format_file(text, command))) else: file.write(self.format_file(text, command)) file.close() def format_print(self, text, command, relevant): """ Formats text to be printed to the terminal. :param text: Text to be formatted. :param command: Command issued when text was generated. :param relevant: If text is relevant(Response from server). :return: Formatted text. """ if self.quiet: # We are in quiet mode, should not print anything! return '' if not self.output_favicon and 'favicon' in text and relevant and type(text) == dict: # Removing favicon entry: del text['favicon'] if not relevant and self.color: # Color is enabled, display return self.formatters.format(text, command) elif not relevant: return self.formatters.clean(text, command) # Working with relevant text here: if self.show_chars: # Show formatting chars: return text if not self.color: # No color for relevant text: return self.formatters.clean(text, command) return self.formatters.format(text, command) def format_file(self, text, command): """ Formats text for outputting into file. :param text: Text to output :param command: Command issued :return: """ if self.output_chars: # Show chars in output file return text if self.output_replace: # Replace chars with ASCII values return self.formatters.format(text, command) # Just remove output chars return self.formatters.clean(text, command) def recursive_print(self, data, depth=0): """ Recursively traverses data presented. Formats the data so it is a certain width, and prints each value on a new line. :param data: Data to be traversed. :param depth: Depth we are currently at. :return: """ if type(data) in [dict, list]: if len(data) == 0: print("{}Empty Value".format(' '*3*depth)) return for k, v in (data.items() if type(data) == dict else enumerate(data)): # Iterate through the list/dict if type(v) in [int, float]: # Working with string/int/float data, output this: print("{}[{}]: {}".format(" " * (depth*3), k, v)) continue if type(v) == str: # Working with strings, doing some special formatting stuff: spaces = " " * (depth * 3) if '\n' in v: # We want to output this data to the edge of the screen: print("{}[{}]:\n{}".format(spaces, k, v)) continue # We replace newline chars with spaces, so we can keep out formatting uniform print("{}[{}]: {}".format(spaces, k, v)) continue # Found something we can't work with, move it down print("{}[{}]:".format(" " * (depth*3), k)) self.recursive_print(data[k], depth=depth+1) # Done traversing the data for this level return parser = argparse.ArgumentParser(description="Minecraft RCON/Query/Ping Server List client", add_help=False) # Specifying hostname and port number: parser.add_argument('host', type=str, help='Hostname of the Minecraft server. ' 'You may also specify a port using the \':\' character.') subparser = parser.add_subparsers(title="Connection Options", help="Connection Options", dest='connection') subparser.required = True # Workaround for previous python 3 versions parser.add_argument('-h', '--help', help='Show this help message and exit', action=_HelpAction) # Splitting RCON/Query/Server List Ping into separate sup-parsers # RCON: rcon_parser = subparser.add_parser('rcon', help='Establish a RCON connection and send commands.') rcon_parser.add_argument('password', help='RCON password') rcon_parser.add_argument('-c', '--command', action='append', nargs='+', help='Command to send to the RCON server. May specify multiple.', required=False) rcon_parser.add_argument('-i', '--interactive', help="Starts an interactive session with the RCON server.", action="store_true") # QUERY: query_parser = subparser.add_parser('query', help='Retrieve server statistics via the Query protocol.') query_parser.add_argument('-f', '--full', help='Retrieve full stats.', action='store_true') # PING: ping_parser = subparser.add_parser('ping', help='Retrieve server statistics via the Server List Ping interface.') ping_parser.add_argument('-sf', '--show-favicon', help='Output favicon data to the terminal.', action='store_true') ping_parser.add_argument('-p', '--proto-num', help='Sets the protocol number to use. Use this to emulate different ' 'client versions.', type=int, default=0, metavar='PROTOCOL_NUMBER') # Output Options: output = parser.add_argument_group('Output Options') format_options = output.add_mutually_exclusive_group() output.add_argument('-o', '--output', help="Saves the output to a file in JSON format(Only saves relevant content, " "such as server responses and errors).", metavar="PATH") format_options.add_argument('-oc', '--output-color', help='Replaces format chars with ascii color codes in the output file. ' 'Default action is to remove them.', action='store_true') format_options.add_argument('-or', '--output-raw', help='Leaves formatting chars when outputting to output file. ' 'Default action is to remove them.', action="store_true") # Normal Options parser.add_argument('-nc', '--no-color', help='Disables color output, removes format chars', action='store_false') parser.add_argument('-r', '--raw', help='Shows format chars, does not remove them', action='store_true') parser.add_argument('-t', '--timeout', help='Timeout value for socket operations', default=60, type=int) parser.add_argument('-ri', '--reqid', help='Sets a custom request id, instead of randomly generating one.') parser.add_argument('-q', '--quiet', help="Program will not output anything to the terminal", action="store_true") # Checking for no arguments: def main(): if len(sys.argv) == 1: # No arguments supplied, outputting help menu parser.parse_args(['--help']) sys.exit() args = parser.parse_args() # Formatting the hostname provided: if ':' in args.host: # Defining custom port number: index = args.host.index(':') # Getting port number: port = args.host[index+1:] # getting host name: host = args.host[:index] else: # Set the port on a per-connection basis port = None # Getting hostname host = args.host # Creating output here: out = Output(args) if args.connection == 'rcon': # User wants a RCON connection: if port is None: # Set the port to the default RCON port port = RCON_PORT with RCONClient(host, port, reqid=args.reqid, format_method=RCONClient.RAW, timeout=args.timeout) as rcon: # Starting connection to RCON server: out.output(SEP) out.output("# Starting TCP connection to §2RCON§r server @ §2{}:{}§r ...".format(host, port)) rcon.start() out.output("# Started TCP connection to §2RCON§r server @ §2{}:{}§r!".format(host, port)) # Authenticating to RCON server out.output("# Authenticating with §2RCON§r server ...") val = rcon.authenticate(args.password) if not val: # Authentication failed! out.output("§c# Authentication with §2RCON§c server failed - Incorrect Password!") sys.exit() out.output("# Authentication with §2RCON§r server successful!") # Running user commands: out.output("# Running user commands ...") if args.command: for com in args.command: # Running user command: out.output("# Executing user command: '§2{}§r' ...".format(' '.join(com))) val = rcon.command(' '.join(com)) out.output(val, command=com, relevant=True) out.output("# Done executing command: '§2{}§r'!".format(' '.join(com))) if args.interactive: # User wants to run an interactive session out.output(SEP) out.output("§b§nWelcome to the RCON interactive session!") out.output("§bConnection Info:\n Host: §a{}§b\n Port: §a{}§b".format(host, port)) out.output("§bType 'q' to quit this session.") out.output("§bType 'help' or '?' for info on commands!\n") while True: # Getting input from user: inp = input("rcon@{}:{}>>".format(host, port)) if inp == 'q': # User is done inputting, exit break # Sending input to server: val = rcon.command(inp) out.output(val, command=inp, relevant=True) if args.connection == 'query': # User wants to retrieve stats via Query if port is None: # Set the port to the default Query port port = QUERY_PORT with QUERYClient(host, port, reqid=args.reqid, format_method=0, timeout=args.timeout) as query: out.output(SEP) # Adding relevant formatter out.formatters.add(QUERYFormatter, FormatterCollection.QUERY) if args.full: # User wants to retrieve full stats: out.output("# Authenticating with Query server @ §a{}:{}§r and retrieving full stats ...".format(host, port)) val = query.get_full_stats() out.output("# Retrieved full stats!:\n") out.output(val, command='QUERY_PROTOCOL', relevant=True) else: # User wants to retrieve basic stats: out.output("# Authenticating with Query server @ §a{}:{}§r and retrieving basic stats ...".format(host, port)) val = query.get_basic_stats() out.output("# Retrieved basic stats!:\n") out.output(val, command='QUERY_PROTOCOL', relevant=True) if args.connection == 'ping': # User wants to ping the server, and retrieve some basic stats if port is None: # Set the port to the default Minecraft port: port = MINECRAFT_PORT with PINGClient(host, port, reqid=args.reqid, format_method=0, timeout=60, proto_num=args.proto_num) as ping: out.output(SEP) # Adding relevant formatter out.formatters.add(PINGFormatter, FormatterCollection.PING) out.output("# Pinging Minecraft server @ §a{}:{}§r and retrieving stats ...".format(host, port)) val = ping.get_stats() out.output("# Retrieved stats! Response time: {} milliseconds".format(val['time'])) out.output("# Statistics:\n") out.output(val, command='PING_PROTOCOL', relevant=True) if __name__ == "__main__": # Run the main function: main()
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,145
fightBoy-Ing/mctools
refs/heads/master
/mctools/protocol.py
""" Low-level protocol stuff for RCON, Query and Server List Ping. """ import struct import socket from mctools.packet import RCONPacket, QUERYPacket, PINGPacket from mctools.encoding import PINGEncoder from mctools.errors import RCONCommunicationError, RCONLengthError, ProtoConnectionClosed class BaseProtocol(object): """ Parent Class for protocol implementations. Every protocol instance should inherit this class! """ def __init__(self) -> None: # Dummy init, primarily meant to specify the socket parameter: self.sock: socket.socket def start(self): """ Method to start the connection to remote entity. This raises a NotImplementedErrorException, as it should be overridden in the child class. """ raise NotImplementedError("Override this method in child class!") def stop(self): """ Method to stop the connection to remote entity. This raises a NotImplementedErrorException, as it should be overridden in the child class. """ raise NotImplementedError("Override this method in child class!") def send(self, data): """ Method to send data to remote entity, data type is arbitrary. This raises a NotImplementedErrorException, as it should be overridden in the child class. :param data: Some data in some format. """ raise NotImplementedError("Override this method in child class!") def read(self): """ Method to receive data from remote entity This raises a NotImplementedErrorException, as it should be overridden in the child class. :return: Data received, data type is arbitrary """ raise NotImplementedError("Override this method in child class!") def read_tcp(self, length): """ Reads data over the TCP protocol. :param length: Amount of data to read :type length: int :return: Read bytes """ byts = b'' # We have to read in parts, as our buffsize may not be big enough: while len(byts) < length: last = self.sock.recv(length - len(byts)) byts = byts + last if last == b'': # We received nothing, lets close this connection: self.stop() # Raise the 'ConnectionClosed' excpetion: raise ProtoConnectionClosed("Connection closed by remote host!") return byts def write_tcp(self, byts): """ Writes data over the TCP protocol. :param byts: Bytes to send :return: Data read """ return self.sock.sendall(byts) def read_udp(self): """ Reads data over the UDP protocol. :return: Bytes read """ return self.sock.recvfrom(1024) def write_udp(self, byts, host, port): """ Writes data over the UPD protocol. :param byts: Bytes to write :param host: Hostanme of remote host :param port: Portname of remote host :return: """ self.sock.sendto(byts, (host, port)) def set_timeout(self, timeout): """ Sets the timeout value for the underlying socket object. :param timeout: Value in seconds to set the timeout to :type timeout: int """ # Set the timeout: self.sock.settimeout(timeout) class RCONProtocol(BaseProtocol): """ Protocol implementation fot RCON - Uses TCP sockets. :param host: Hostname of RCON server :type host: str :param port: Port number of the RCON server :type port: int :param timeout: Timeout value for socket operations. :type timeout: int """ def __init__(self, host, port, timeout): self.host = host # Host of the RCON server self.port = int(port) # Port of the RCON server self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creating an ip4 TCP socket self.LOGIN = 3 # Packet type used for logging in self.COMMAND = 2 # Packet type for issuing a command self.RESPONSE = 0 # Packet type for response self.MAX_SIZE = 4096 # Maximum packet size self.connected = False # Value determining if we are connected self.timeout = timeout # Global timeout value self.sock.settimeout(timeout) # Setting timeout value for socket def start(self): """ Starts the connection to the RCON server. """ if self.connected: # Already started return self.sock.connect((self.host, self.port)) self.connected = True def stop(self): """ Stops the connection to the RCON server. """ self.sock.close() self.connected = False def send(self, pack, length_check=False): """ Sends a packet to the RCON server. :param pack: RCON Packet :type pack: RCONPacket :param length_check: Boolean determining if we should check packet length :type length_check: bool .. versionadded:: 1.1.2 The 'length_check' parameter """ # Getting encoded packet data: data = bytes(pack) # Check if data is too big: if length_check and len(data) >= 1460: # Too big, raise an exception! raise RCONLengthError("Packet type is too big!", len(data)) # Sending packet: self.write_tcp(data) def read(self): """ Gets a RCON packet from the RCON server. :param timeout: Timeout value specific to this operation. :type timeout: int, None :return: RCONPacket containing payload :rtype: RCONPacket """ # Getting first 4 bytes to determine length of packet: length_data = self.read_tcp(4) # Unpacking length data: length = struct.unpack("<i", length_data)[0] # Reading the rest of the packet: byts = self.read_tcp(length) # Generating packet: pack = RCONPacket.from_bytes(byts) return pack def __del__(self): """ Attempts to close the socket """ try: self.sock.close() except Exception: pass class QUERYProtocol(BaseProtocol): """ Protocol implementation for Query - Uses UDP sockets. :param host: The hostname of the Query server. :type host: str :param port: Port number of the Query server :type port: int :param timeout: Timeout value for socket operations :type timeout: int """ def __init__(self, host, port, timeout): self.host = host # Host of the Query server self.port = int(port) # Port of the Query server self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Creating a ip4 UDP socket self.started = False # Determining if we have started communicating with the Query server self.sock.settimeout(timeout) # Setting timeout value for socket def start(self): """ Sets the protocol object as ready to communicate. """ self.started = True def stop(self): """ Sets the protocol object as not ready to communicate. """ self.started = False def send(self, pack): """ Sends a packet to the Query server. :param pack: Packet to send :type pack: QUERYPacket """ # Converting packet into bytes: byts = bytes(pack) # Sending packet: self.write_udp(byts, self.host, self.port) def read(self): """ Gets a Query packet from the Query server. :return: QUERYPacket :rtype: QUERYPacket """ # Getting packet: byts, address = self.read_udp() # Converting bytes to packet: pack = QUERYPacket.from_bytes(byts) return pack def __del__(self): """ Attempts to close the socket """ try: self.sock.close() except: pass class PINGProtocol(BaseProtocol): """ Protocol implementation for server list ping - uses TCP sockets. :param host: Hostname of the Minecraft server :type host: str :param port: Port number of the Minecraft server :type port: int :param timeout: Timeout value used for socket operations :type timeout: int """ def __init__(self, host, port, timeout): self.host = host # Host of the Minecraft server self.port = int(port) # Port of the Minecraft server self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creating an ip4 TCP socket self.connected = False # Value determining if we are connected self.sock.settimeout(timeout) # Setting timeout value for socket def start(self): """ Starts the connection to the Minecraft server. """ # Starting connection self.sock.connect((self.host, self.port)) # Setting protocol state self.connected = True def stop(self): """ Stopping the connection to the Minecraft server. """ # Closing connection self.sock.close() # Setting protocol state self.connected = False def send(self, pack): """ Sends a ping packet to the Minecraft server. :param pack: PINGPacket :type pack: PINGPacket """ # Converting packet to bytes: byts = bytes(pack) # Sending bytes: self.write_tcp(byts) def read(self): """ Read data from the Minecraft server and convert it into a PINGPacket. :return: PINGPacket :rtype: PINGPacket """ # Reading length data: # Getting length of ALL data: length = PINGEncoder.decode_sock(self.sock) # Reading the rest of the data: byts = self.read_tcp(length) # Creating packet: pack = PINGPacket.from_bytes(byts) return pack def __del__(self): """ Attempts to close the socket: """ try: self.sock.close() except: pass
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,146
fightBoy-Ing/mctools
refs/heads/master
/mcli.py
from mctools.__main__ import main if __name__ == "__main__": # Run main function: main()
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,147
fightBoy-Ing/mctools
refs/heads/master
/mctools/__init__.py
# Import mclient from mctools.mclient import RCONClient, QUERYClient, PINGClient # Define some metadata here: __version__ = '1.1.2' __author__ = 'Owen Cochell'
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,148
fightBoy-Ing/mctools
refs/heads/master
/mctools/formattertools.py
""" Formatters to alter response output - makes everything look pretty """ # Try to enable colorama support if we have it: try: import colorama # Enable colorama: colorama.init() except: # No colorama support, continue pass CHAR = '\u00A7' # Format char OLD = '\u001b' MAP = {'0': '\033[0m\033[30m', '1': '\033[0m\033[34m', '2': '\033[0m\033[32m', '3': '\033[0m\033[36m', '4': '\033[0m\033[31m', '5': '\033[0m\033[36m', '6': '\033[0m\033[33m', '7': '\033[0m\033[38;5;246m', '8': '\033[0m\033[38;5;243m', '9': '\033[0m\033[34;1m', 'a': '\033[0m\033[32;1m', 'b': '\033[0m\033[36;1m', 'c': '\033[0m\033[31;1m', 'd': '\033[0m\033[35;1m', 'e': '\033[0m\033[33;1m', 'f': '\033[0m\033[37;1m', 'l': '\033[1m', 'k': '\033[5m', 'm': '\033[9m', 'n': '\033[4m', 'o': '\033[3m', 'r': '\033[0m'} # Mapping format chars with ASCII values NAME_MAP = {'black': '0', 'dark_blue': '1', 'dark_green': '2', 'dark_aqua': '3', 'dark_red': '4', 'dark_purple': '5', 'gold': '6', 'gray': '7', 'dark_gray': '8', 'blue': '9', 'green': 'a', 'aqua': 'b', 'red': 'c', 'light_purple': 'd', 'yellow': 'e', 'white': 'f', 'obfuscated': 'k', 'bold': 'l', 'strikethrough': 'm', 'underlined': 'n', 'italic': 'o'} # Added reset value to the front of color codes, as this is normal Java edition operation class BaseFormatter(object): """ Parent class for formatter implementations. """ @staticmethod def format(text): """ Formats text in any way fit. Note: This should not remove format chars, that's what remove is for, Simply replace them with their required values. :param text: Text to be formatted :type text: str :return: Formatted text :rtype: str """ return text @staticmethod def clean(text): """ Removes format chars, instead of replacing them with actual values. Great for if the user does not want/have color support, And wants to remove the unneeded format chars. :param text: Text to be formatted :type text: str :return: Formatted text :rtype: str """ return text @staticmethod def get_id(): """ Should return an integer representing the formatter ID. This is important, as it determines how the formatters are sorted. Sorting goes from least - greatest, meaning that formatters with a lower ID get executed first. :return: Formatter ID :rtype: int """ return 20 class DefaultFormatter(BaseFormatter): """ Formatter with good default operation: - format() - Replaces all formatter codes with ascii values - clean() - Removes all formatter codes This formatter ONLY handles formatting codes and text attributes. """ @staticmethod def format(text): """ Replaces all format codes with their intended values (Color, text effect, ect). :param text: Text to be formatted. :type text: str :return: Formatted text. :rtype: str """ # Iterate through the text until we find the format char: index = 0 while index < len(text) - 1 and type(text) == str: # Checking for CHAR at index: if text[index] == CHAR: # Found a char, getting next value: form = text[index + 1] # Checking if we need to add a reset value to the front the of the color value, # A Minecraft Java edition "Feature" # Replacing format char with ASCII value: if form in MAP: # Character is a valid format char, format it: text = text.replace(CHAR + form, MAP[form], 1) # Decrementing index, as we removed some stuff: index = index - 1 continue # Increment index, nothing was found! index = index + 1 # Adding reset char, so we don't mess up output text = text + MAP['r'] return text @staticmethod def clean(text): """ Removes all format codes. Does not use color/text effects. :param text: Text to be formatted. :type text: str :return: Formatted text. :rtype: str """ index = 0 while index < len(text) - 1 and type(text) == str: # Iterate through text until we find a format char: if text[index] == CHAR: # Found a format char, getting next char: form = text[index + 1] # Checking if format char is valid: if form in MAP: # Yes, format char is valid. Removing all values: text = text.replace(CHAR + form, '') # Decrementing, as we removed some stuff index = index - 1 continue index = index + 1 return text @staticmethod def get_id(): """ Returns this formatters ID, which is 10. :return: Formatter ID :rtype: int """ return 10 class QUERYFormatter(BaseFormatter): """ Formatter for formatting responses from the Query server. Will only format certain parts, as servers SHOULD follow a specific implementation for Query. """ @staticmethod def format(text): """ Replaces format chars with actual values. :param text: Response from Query server(Ideally in dict form). :type text: dict :return: Formatted content. :rtype: dict """ return QUERYFormatter._packet_format(text, 0) @staticmethod def clean(text): """ Removes format chars from the response. :param text: Response from Query server :type text: dict :return: Formatted content. :rtype: dict """ return QUERYFormatter._packet_format(text, 1) @staticmethod def _packet_format(data, format_type): """ Does all the heavy lifting for formatting packets. Will determine if a packet is basic or full stats, and format it accordingly. :param data: Data to be formatted :type data: dict :param format_type: Type of formatting operation :type format_type: int :return: Formatted data :rtype: dict """ # Creating new dictionary so we don't mess up the original: data = dict(data) # Formatting the message of the day: if format_type == 0: # Format the content: data['motd'] = DefaultFormatter.format(data['motd']) if format_type == 1: # Clean the content: data['motd'] = DefaultFormatter.clean(data['motd']) # Checking for player lists: if 'players' in data.keys(): # Players key present, formatting names: final = [] for play in data['players']: if format_type == 0: # Format the data: final.append(DefaultFormatter.format(play)) if format_type == 1: # Clean the data: final.append(DefaultFormatter.clean(play)) # Overriding original with formatted values data['players'] = final return data class PINGFormatter(BaseFormatter): """ Formatter for formatting responses from the server via Server List Ping protocol. We only format relevant content, such as description and player names. We also use special formatters, such as ChatObjectFormatter, and SampleDescriptionFormatter. """ @staticmethod def format(stat_dict): """ Formats a dictionary of stats from the Minecraft server. :param stat_dict: Dictionary to format :type stat_dict: dict :return: Formatted statistics dictionary. :rtype: dict """ # Formatting description: return PINGFormatter._packet_format(stat_dict, 1) @staticmethod def clean(stat_dict): """ Cleaned a dictionary of stats from the Minecraft server. :param stat_dict: Dictionary to format :type stat_dict: dict :return: Formatted statistics dictionary. :rtype: dict """ # Cleaning description: return PINGFormatter._packet_format(stat_dict, 2) @staticmethod def _packet_format(stat_dict, form): """ Does all the heavy lifting for format operations. Will determine if special formatters are necessary, and use them accordingly. :param stat_dict: Dictionary of stats :type stat_dict: dict :param form: Formatting type to use :type form: int :return: Formatted statistics dictionary :rtype: dict """ if 'description' in stat_dict.keys(): # Formatting description: if type(stat_dict['description']) != str: # We need to use ChatObject formatter: stat_dict['description'] = (ChatObjectFormatter.format(stat_dict['description']) if form == 1 else ChatObjectFormatter.clean(stat_dict['description'])) else: # Primitive formatting, handle it: stat_dict['description'] = (DefaultFormatter.format(stat_dict['description']) if form == 1 else DefaultFormatter.clean(stat_dict['description'])) if 'sample' in stat_dict['players'].keys(): # Organizing names: stat_dict['players']['sample'], stat_dict['players']['message'] = SampleDescriptionFormatter.format( stat_dict['players']['sample']) # Formatting the names: final = [] for name in stat_dict['players']['sample']: if form == 1: # Format the content: final.append([DefaultFormatter.format(name['name']), name['id']]) else: # CLean the content: final.append([DefaultFormatter.clean(name['name']), name['id']]) stat_dict['players']['sample'] = final # Formatting the message: stat_dict['players']['message'] = (DefaultFormatter.format(stat_dict['players']['message']) if form == 1 else DefaultFormatter.clean(stat_dict['players']['message'])) return stat_dict class ChatObjectFormatter(BaseFormatter): """ A formatter that handles the formatting scheme of ChatObjects. This description scheme differs from primitive chat objects, as it doesn't use formatting characters. It instead uses a collection of dictionaries to define what colors and attributes should be used. """ @staticmethod def format(chat, color=None, attrib=None): """ Formats a description dictionary, and returns the formatted text. This gets tricky, as the server could define a variable number of child dicts that have their own attributes/extra content. So, we must implement some recursion to be able to parse and understand the entire string. :param chat: Dictionary to be formatted :type chat: dict :param color: Parent text color, only used in recursive operations :type color: str :param attrib: Parent attributes, only used in recursive operations :type attrib: str :return: Formatted text :rtype: str """ # Define some variables for keeping attributes in: attrib = attrib if attrib is not None else '' # Text attributes we should add color = color if color is not None else '' # Color we should make the text extra = '' # Extra text we should add text = '' # Text we should display # Iterate over each value: for val in chat: if val in NAME_MAP: # We have a formatting character, check if we want it or not: if chat[val]: # We want this character, add it to the attributes: attrib = MAP[NAME_MAP[val]] + attrib continue # We don't want this character, remove it if it is present: attrib = attrib.replace(MAP[NAME_MAP[val]], '') continue if val == 'color': # Found a valid color: color = MAP[NAME_MAP[chat[val]]] continue if val == 'text': # Found our text, add it: text = chat[val] continue # See if their is any extra text to format: if 'extra' in chat.keys(): # Some extra junk we have to process, iterate over it: for child in chat['extra']: # Send this extra text down with the parent values: extra = extra + ChatObjectFormatter.format(child, color=color, attrib=attrib) # We have to specify color first, or else our style codes will get lost! # This is only a problem on certain platforms. # We also send the text through the DefaultFormatter, as some servers send info this way return MAP['r'] + color + attrib + DefaultFormatter.format(text) + extra @staticmethod def clean(text): """ Cleans a description directory, and returns the cleaned text. :param text: Dictonary to be formatted :type text: dict :return: Cleaned text :rtype: str """ # Iterate over the values: final = text['text'] if 'extra' in text.keys(): # Iterate over each value and process it: for child in text['extra']: final = final + ChatObjectFormatter.clean(child) # Clean up the text, just in case return DefaultFormatter.clean(final) class SampleDescriptionFormatter(BaseFormatter): """ Some servers like to put special messages in the 'sample players' field. This formatter attempts to handle this, and sort valid players and null players into separate categories. """ NULL_USER = '00000000-0000-0000-0000-000000000000' # UUID for null users. @staticmethod def format(text): """ Formats a sample list of users, removing invalid ones and adding them to a message sublist. We return the message in the playerlist, and also return valid players. :param text: Valid players, Message encoded in the sample list :type text: list, str :return: Dictionary containing message, and valid users. """ # Iterate over players: valid = [] message = '' for player in text: # Check if player is invalid: if player['id'] == SampleDescriptionFormatter.NULL_USER: # Found an invalid user, add it's content to the message. message = message + player['name'] + '\n' # Removing player from player list: text.remove(player) continue # Valid user, add it to the sample list: valid.append(player) # Return values return valid, message @staticmethod def clean(text): """ Does the same operation as format. This is okay because we don't change up any values or alter the content, we just organise them, and the color formatter will handle it later. :param text: Valid players, Message encoded in the sample list :type text: list, str :return: Dictionary containing message, and valid users. """ return SampleDescriptionFormatter.format(text) class FormatterCollection: """ A collection of formatters - Allows for formatting text with multiple formatters, and determining which formatter is relevant to the text. This class offers the following constants: - FormatterCollection.QUERY - Used for identifying Query protocol content. - FormatterCollection.PING - Used for identifying Server List Ping protocol content. """ QUERY = 'QUERY_PROTOCOL' PING = 'PING_PROTOCOL' def __init__(self): self._form = [] # List of formatters def _get_id(self, form): """ Gets the formatter ID, used by sort() for sorting formatters. :param form: Formatter. :return: Formatter ID. """ return form.get_id() def add(self, form, command, ignore=None): """ Adds a formatter, MUST inherit the BaseFormatter class. Your formatter must either be instantiated upon adding it, or the 'clean' and 'format' methods are static, as FormatterCollection will not attempt to instantiate your object. :param form: Formatter to add. :param command: Command(s) to register the formatter with. May be a string or list. \ Supply an empty string('') to affiliate with every command, \ or a list to affiliate with multiple. :type command: str, list :param ignore: Commands to ignore, formatter will not format them, leave blank to accept everything. May be string or list. Supply 'None' to allow all commands, or a list to affiliate with multiple. :type ignore: str, list :return: True for success, False for Failure. :rtype: bool """ # Checking formatter parent class: if not issubclass(form, BaseFormatter): # Form is not a subclass raise Exception("Invalid Formatter! Must inherit from BaseFormatter!") # Checking command type: command = self._convert_type(command, 'Command') # Checking ignore type: ignore = self._convert_type(ignore, 'Ignore') # Adding formatter to list self._form.append([form, command, ignore]) # Sorting list of formatters: self._form.sort(key=lambda x: x[0].get_id()) return True def _convert_type(self, thing, text): """ Attempts to convert data into a compatible type(list or string). :param thing: Thing to convert. :param text: Weather it is a command, or ignore. :return: Converted type """ if type(thing) not in [str, tuple, list] and thing is not None: # Ignore is not a valid type, checking if it is an int so we can convert it: if type(thing) == int: # Converting int to string return str(thing) else: raise Exception("Invalid {}} Type! Must be str, list, or tuple!".format(text)) return thing def remove(self, form): """ Removes a specified formatter from the list. :param form: Formatter to remove :type form: BaseFormatter :return: True on success, False on failure :rtype: bool """ # Attempting to remove formatter: try: self._form.remove(form) except Exception: # Formatter not found, returning return False # Formatter removed! return True def clear(self): """ Removes all formatters from the list. """ # Clearing list: self._form.clear() return def get(self): """ Returns the list of formatters. Can be used to check loaded formatters, or manually edit list. Be aware, that manually editing the list means that the formatters may have some unstable operations. :return: List of formatters. :rtype: list """ return self._form def format(self, text, command): """ Runs the text through the format() function of relevant fomatters. These formatters will be removing and replacing characters, Most likely format chars. :param text: Text to be formatted :type text: str :param command: Command issued - determines which formatters are relevant. You may leave command blank to affiliate with every formatter. :type command: str :return: Formatted text. :rtype: str """ # Iterating through every formatter: for form in self._form: # Checking if formatter is relevant: if self._is_relevant(form, command): # Formatter is relevant, formatting text: text = form[0].format(text) # Return formatted text: return text def clean(self, text, command): """ Runs the text through the clean() method of every formatter. These formatters will remove characters, without replacing them, Most likely format chars. We only send non-string data to specific formatters. :param text: Text to be formatted. :type text: str :param command: Command issued - determines which formatters are relevant. You may leave command blank to affiliate with every formatter. :type command: str :return: Formatted text. :rtype: str """ # Iterating through every formatter: for form in self._form: # Checking if formatter is relevant: if self._is_relevant(form, command): # Formatter is relevant, formatting text: text = form[0].clean(text) # Return formatted text return text def _is_relevant(self, form, command): """ Value determining if the the formatter is relevant to the incoming data. :param form: List of formatter info. :param command: Command issued. :return: True if relevant, False if not. """ # Checking ignore values first: if (type(form[2]) == str and form[2] == command) or (type(form[2]) in [list, tuple] and command in form[2]): # Command is a value we are ignoring return False # Checking if value is one we are accepting: if form[1] == '' or (type(form[1]) == str and form[1] == command) or (type(form[1]) in [list, tuple] and command in form[1]): # Command is a command we can handel: return True return False def __len__(self): """ Returns the amount of formatters in the collection. :return: Number of formatters in collection. """ return len(self._form)
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,149
fightBoy-Ing/mctools
refs/heads/master
/mctools/errors.py
""" Exception objects for mctools. """ class MCToolsError(Exception): """ Base class for mctools exceptions. """ pass class ProtocolError(MCToolsError): """ Base class for protocol errors. A protocol error is raised when an issue arises with the python socket object. These exceptions will be raised for ALL clients, as they all use the same backend. """ class ProtoConnectionClosed(ProtocolError): """ Exception raised when the connection is closed by the socket we are connected to. This occurs when we receive empty bytes from 'recv()', as this means that the remote socket is done writing, meaning that our connection is closed. """ def __init__(self, message) -> None: self.message = message # Explanation of the error # --== RCON Errors: ==-- class RCONError(MCToolsError): """ Base class for RCON errors. """ pass class RCONAuthenticationError(RCONError): """ Exception raised when user is not authenticated to the RCON server. This is raised when a user tries to send a RCON command, and the server refuses to communicate. :param message: Explanation of the error :type message: str :param server_id: ID given to us by the server :type server_id: """ def __init__(self, message): self.message = message # Explanation of the error class RCONMalformedPacketError(RCONError): """ Exception raised if the packet we received is malformed/broken, or not what we were expecting. :param message: Explanation of the error :type message: str """ def __init__(self, message): self.message = message # Explanation of the error class RCONCommunicationError(RCONError): """ Exception raised if the client has trouble communicating with the RCON server. For example, if we don't receive any information when we want a packet. :param message: Explanation of the error :type message: str """ def __init__(self, message): self.message = message # Explanation of the error class RCONLengthError(RCONError): """ Exception raised if the client attempts to send a packet that is too big, greater than length 1460. """ def __init__(self, message, length): self.message = message # Explanation of error self.length = length # Length of data # --== PING Errors: ==-- class PINGError(MCToolsError): """ Base class for PING errors """ class PINGMalformedPacketError(PINGError): """ Exception raised if the ping packet received is malformed/broken, or not what we were expecting. """ def __init__(self, message) -> None: self.message = message
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,150
fightBoy-Ing/mctools
refs/heads/master
/mctools/mclient.py
""" Main Minecraft Connection Clients - Easy to use API for the underlying modules Combines the following: - Protocol Implementations - Packet implementations - Formatting tools """ import time from typing import Union from mctools.protocol import BaseProtocol, RCONProtocol, QUERYProtocol, PINGProtocol from mctools.packet import RCONPacket, QUERYPacket, PINGPacket from mctools.formattertools import BaseFormatter, FormatterCollection, DefaultFormatter, QUERYFormatter, PINGFormatter from mctools.errors import RCONAuthenticationError, RCONMalformedPacketError class BaseClient(object): """ Parent class for Minecraft Client implementations. This class has the following formatting constants, which every client inherits: - BaseClient.RAW - Tells the client to not format any content. - BaseClient.REPLACE - Tells the client to replace format characters. - BaseClient.Remove - Tells the client to remove format characters. You can use these constants in the 'format_method' parameter in each client. """ # Formatting codes RAW = 0 REPLACE = 1 REMOVE = 2 def __init__(self) -> None: # Dummy init method self.proto: BaseProtocol self.formatters: BaseFormatter def gen_reqid(self): """ Generates a request ID using system time. :return: System time as an integer """ return int(time.time()) def set_timeout(self, timeout): """ Sets the timeout for the underlying socket object. :param timeout: Value in seconds to set the timeout to :type timeout: int """ # Have the protocol object set the timeout: self.proto.set_timeout(timeout) def start(self): """ Starts the client, and any protocol objects/formatters in use. (Good idea to put a call to Protocol.start() here). This raises a 'NotImplementedError' exception, as this function should be overridden in the child class. :raises: NotImplementedError: If function is called. """ raise NotImplementedError("Override this method in child class!") def stop(self): """ Stops the client, and any protocol objects/formatters in use. (Again, good idea to put a call to Protocol.stop() here). This raises a 'NotImplementedError' exception, as this function should be overridden in the child class. :raises: NotImplementedError: If function is called. """ raise NotImplementedError("Override this method in child class!") def is_connected(self): """ Determine if we are connected to the remote entity, whatever that may be. This raises a 'NotImplementedError' exception, as this function should be overridden in the child class. :return: True if connected, False if not. :raises: NotImplementedError: If function is called. """ raise NotImplementedError("Override this method in child class!") def raw_send(self, *args): """ For sending packets with user defined values, instead of the wrappers from client. This raises a 'NotImplementedError' exception, as this function should be overridden in the child class. :param args: Arguments specified, varies from client to client. :raises: NotImplementedError: If function is called. """ raise NotImplementedError("Override this method in child class!") def get_formatter(self): """ Returns the formatter used by this instance, Allows the user to change formatter operations. :return: FormatterCollection used by the client. :rtype: FormatterCollection """ return self.formatters def __enter__(self): """ All clients MUST have context manager support! """ raise NotImplementedError("Override this method in child class!") def __exit__(self, exc_type, exc_val, exc_tb): """ All clients MUST have context manager support! (Recommend showing exceptions, AKA returning False) :param exc_type: Exception info :param exc_val: Exception info :param exc_tb: Exception inf :return: False(Can be something else) """ raise NotImplementedError("Override this method in child class!") class RCONClient(BaseClient): """ RCON client, allows for user to interact with the Minecraft server via the RCON protocol. :param host: Hostname of the Minecraft server (Can be an IP address or domain name, anything your computer can resolve) :type host: str :param port: Port of the Minecraft server :type port: int :param reqid: Request ID to use, leave as 'None' to generate an ID based on system time :type reqid: int :param format_method: Format method to use. You should specify this using the Client constants :param format_method: int :param timeout: Sets the timeout value for socket operations :type timeout: int """ def __init__(self, host, port=25575, reqid=None, format_method=BaseClient.REPLACE, timeout=60): self.proto: RCONProtocol = RCONProtocol(host, port, timeout) # RCONProtocol, used for communicating with RCON server self.formatters: FormatterCollection = FormatterCollection() # Formatters instance, formats text from server self.auth = False # Value determining if we are authenticated self.format = format_method # Value determining how to format output self.reqid = self.gen_reqid() if reqid is None else int(reqid) # Generating a request ID # Adding the relevant formatters: self.formatters.add(DefaultFormatter, '', ignore=[self.formatters.PING, self.formatters.QUERY]) def start(self): """ Starts the connection to the RCON server. This is called automatically where appropriate, so you shouldn't have to worry about calling this. """ # Start the protocol instance: if not self.is_connected(): self.proto.start() def stop(self): """ Stops the connection to the RCON server. This function should always be called when ceasing network communications, as not doing so could cause problems server-side. """ # Stop the protocol instance if self.is_connected(): self.auth = False self.proto.stop() def is_connected(self) -> bool: """ Determines if we are connected. :return: True if connected, False if not. :rtype: bool """ return self.proto.connected def is_authenticated(self) -> bool: """ Determines if we are authenticated. :return: True if authenticated, False if not. :rtype: bool """ return self.auth def raw_send(self, reqtype: int, payload: str, frag_check: bool=True, length_check: bool=True) -> RCONPacket: """ Creates a RCON packet based off the following parameters and sends it. This function is used for all networking operations. We automatically check if a packet is fragmented(We check it's length). If this is the case, then we send a junk packet, and we keep reading packets until the server acknowledges the junk packet. This operation can take some time depending on network speed, so we offer the option to disable this feature, with the risk that their might be stability issues. We also check if the packet being sent is too big, and raise an exception of this is the case. This can be disabled by passing False to the 'length_check' parameter, although this is not recommended. .. warning:: Use this function at you own risk! You should really call the high level functions, as not doing so could mess up the state/connection of the client. :param reqtype: Request type :type reqtype: int :param payload: Payload to send :type payload: str :param frag_check: Determines if we should check and handle packet fragmentation. :type frag_check: bool .. warning:: Disabling fragmentation checks could lead to instability! Do so at your own risk! :param length_check: Determines if we should check for outgoing packet length :type length_check: bool .. warning:: Disabling legnth checks could lead to instability! Do so at your own risk! :return: RCONPacket containing response from server :rtype: RCONPacket :raises: RCONAuthenticationError: If the server refuses to server us and we are not authenticated. RCONMalformedPacketError: If the request ID's do not match of the packet is otherwise malformed. .. versionadded:: 1.1.0 The 'frag_check' parameter .. versionadded:: 1.1.2 The 'length_check' parameter """ if not self.is_connected(): # Connection not started, user obviously wants to connect, so start it self.start() # Sending packet: self.proto.send(RCONPacket(self.reqid, reqtype, payload), length_check=length_check) # Receiving response packet: pack = self.proto.read() # Check if our stuff is valid: if pack.reqid != self.reqid and self.is_authenticated() and reqtype != self.proto.LOGIN: # Client/server ID's do not match! raise RCONMalformedPacketError("Client and server request ID's do not match!") elif pack.reqid != self.reqid and reqtype != self.proto.LOGIN: # Authentication issue! raise RCONAuthenticationError("Client and server request ID's do not match! We are not authenticated!") # Check if the packet is fragmented(And if we even care about fragmentation): if frag_check and pack.length >= self.proto.MAX_SIZE: # Send a junk packet: self.proto.send(RCONPacket(self.reqid, 0, '')) # Read until we get a valid response: while True: # Get a packet from the server: temp_pack = self.proto.read() if temp_pack.reqtype == self.proto.RESPONSE and temp_pack.payload == 'Unknown request 0': # Break, we are done here break if temp_pack.reqid != self.reqid: # Client/server ID's do not match! raise RCONMalformedPacketError("Client and server request ID's do not match!") # Add the packet content to the master pack: pack.payload = pack.payload + temp_pack.payload # Return our junk: return pack def login(self, password): """ Authenticates with the RCON server using the given password. If we are already authenticated, then we simply return True. :param password: RCON Password :type password: str :return: True if successful, False if failure :rtype: bool """ # Checking if we are logged in. if self.is_authenticated(): # Already authenticated, no need to do it again. return True # Sending login packet: pack = self.raw_send(self.proto.LOGIN, password) # Checking login packet if pack.reqid != self.reqid: # Login failed, request IDs do not match return False # Request ID matches! self.auth = True return True def authenticate(self, password): """ Convenience function, does the same thing that 'login' does, authenticates you with the RCON server. :param password: Password to authenticate with :type password: str :return: True if successful, False if failure :rtype: bool """ return self.login(password) def command(self, com: str, check_auth: bool=True, format_method: int=None, return_packet: bool=False, frag_check: bool=True, length_check: bool=True) -> Union[RCONPacket, str]: """ Sends a command to the RCON server and gets a response. .. note:: Be sure to authenticate before sending commands to the server! Most servers will simply refuse to talk to you if you do not authenticate. :param com: Command to send :type com: str :param check_auth: Value determining if we should check authentication status before sending our command :type check_auth: bool :param format_method: Determines the format method we should use. If 'None', then we use the global value You should use the Client constants to define this. :type format_method: int :param return_packet: Determines if we should return the entire packet. If not, return the payload :type return_packet: bool :param frag_check: Determines if we should check and handle packet fragmentation .. warning:: Disabling fragmentation checks could lead to instability! Do so at your own risk! :type frag_check: bool :param length_check: Determines if we should check and handel outgoing packet length .. warning:: Disabling length checks could lead to instability! Do so at your own risk! :type legnth_check: bool :return: Response text from server :rtype: str, RCONPacket :raises: RCONAuthenticationError: If we are not authenticated to the RCON server, and authentication checking is enabled. We also raise this if the server refuses to serve us, regardless of weather auth checking is enabled. RCONMalformedPacketError: If the packet we received is broken or is not the correct packet. RCONLengthError: If the outgoing packet is larger than 1460 bytes .. versionadded:: 1.1.0 The 'check_auth', 'format_method', 'return_packet', and 'frag_check' parameters .. versionadded:: 1.1.2 The 'length_check' parameter """ # Checking authentication status: if check_auth and not self.is_authenticated(): # Not authenticated, let the user know this: raise RCONAuthenticationError("Not authenticated to the RCON server!") # Sending command packet: pack = self.raw_send(self.proto.COMMAND, com, frag_check=frag_check) # Get the formatted content: pack = self._format(pack, com, format_method=format_method) if return_packet: # Return the entire packet: return pack # Return just the payload return pack.payload def _format(self, pack, com, format_method=None): """ Sends incoming data to the formatter. :param pack: Packet to format :type pack: RCONPacket :param com: Command issued :type com: str :param format_method: Determines the format method we should use. If 'None', then we use the global value. You should use the Client constants to define this. :type format_method: int :return: Formatted content :rtype: RCONPacket """ if format_method is None: # Use the global format method format_method = self.format # Formatting text: if format_method == 'replace' or format_method == 1: # Replacing format chars pack.payload = self.formatters.format(pack.payload, com) elif format_method == 'clean' or format_method == 2: # Removing format chars pack.payload = self.formatters.clean(pack.payload, com) return pack def __enter__(self): """ In a context manager. :return: This instance """ return self def __exit__(self, exc_type, exc_val, exc_tb): """ Exit the context manager, show any necessary errors as they are important. :param exc_type: Error info :param exc_val: Error info :param exc_tb: Error info :return: False """ # Stopping connection: self.stop() return False class QUERYClient(BaseClient): """ Query client, allows for user to interact with the Minecraft server via the Query protocol. :param host: Hostname of the Minecraft server :type host: str :param port: Port of the Minecraft server :type port: int :param reqid: Request ID to use, leave as 'None' to generate one based on system time :type reqid: int :param format_method: Format method to use. You should specify this using the Client constants :type format_method: int :param timeout: Sets the timeout value for socket operations :type timeout: int """ def __init__(self, host: str, port: int=25565, reqid: int=None, format_method: int=BaseClient.REPLACE, timeout: int=60): self.proto: QUERYProtocol = QUERYProtocol(host, port, timeout) # Query protocol instance self.formatters: FormatterCollection = FormatterCollection() # Formatters instance self.format = format_method # Format type to use self.reqid = self.gen_reqid() if reqid is None else int(reqid) # Adding the relevant formatters self.formatters.add(QUERYFormatter, self.formatters.QUERY) def start(self): """ Starts the Query object. This is called automatically where appropriate, so you shouldn't have to worry about calling this. """ if not self.is_connected(): self.proto.start() def stop(self): """ Stops the connection to the Query server. In this case, it is not strictly necessary to stop the connection, as QueryClient uses the UDP protocol. It is still recommended to stop the instance any way, so you can be explicit in your code as to when you are going to stop communicating over the network. """ if self.is_connected(): self.proto.stop() def is_connected(self) -> bool: """ Determines if we are connected. (UPD doesn't really work that way, so we simply return if we have been started). :return: True if started, False for otherwise. :rtype: bool """ return self.proto.started def raw_send(self, reqtype: int, chall: Union[str, None], packet_type: str) -> QUERYPacket: """ Creates a packet from the given arguments and sends it. Returns a response. :param reqtype: Request type :type reqtype: int :param chall: Challenge Token :type chall: str, None :param packet_type: Packet type(chall, short, full) :type packet_type: str :return: QUERYPacket containing response :rtype: QUERYPacket """ # Sending packet: self.proto.send(QUERYPacket(reqtype, self.reqid, chall, packet_type)) # Receiving response packet: pack = self.proto.read() return pack def get_challenge(self) -> QUERYPacket: """ Gets the challenge token from the Query server. It is necessary to get a token before every operation, as the Query tokens change every 30 seconds. :return: QueryPacket containing challenge token. :rtype: QUERYPacket """ # Sending initial packet: pack = self.raw_send(9, None, "chall") # Returning pack: return pack def get_basic_stats(self, format_method: int=None, return_packet: bool=False) -> Union[dict, QUERYPacket]: """ Gets basic stats from the Query server. :param format_method: Determines the format method we should use. If 'None', then we use the global value. You should use the Client constants to define this :type format_method: int :param return_packet: Determines if we should return the entire packet. If not, return the payload :type return_packet: bool :return: Dictionary of basic stats, or QUERYPacket, depending on 'return_packet'. :rtype: dict, QUERYPacket .. versionadded:: 1.1.0 The 'format_method' and 'return_packet' parameters """ # Getting challenge response: chall = self.get_challenge().chall # Requesting short stats: pack = self.raw_send(0, chall, "basic") # Formatting the packet: pack.data = self._format(pack, format_method=format_method) if return_packet: # Return just the packet: return pack # Return the payload return pack.data def get_full_stats(self, format_method: int=None, return_packet: bool=False) -> Union[dict, QUERYPacket]: """ Gets full stats from the Query server. :param format_method: Determines the format method we should use. If 'None', then we use the global value. You should use the Client constants to define this. :type format_method: int :param return_packet: Determines if we should return the entire packet. If not, return the payload :type return_packet: bool :return: Dictionary of full stats, or QUERYPacket, depending on 'return_packet'. :rtype: dict .. versionadded:: 1.1.0 The 'format_method' and 'return_packet' parameters """ # Getting challenge response: chall = self.get_challenge().chall # Requesting full stats: pack = self.raw_send(0, chall, "full") # Formatting the packet: pack.data = self._format(pack, format_method=format_method) if return_packet: # Return the packet: return pack # Return the payload return pack.data def _format(self, data, format_method=None): """ Sends the incoming data to the formatter. :param data: Data to be formatted :type data: QUERYPacket :param format_method: Format method to use. If 'None', then we use the global value. :type format_method: int :return: Formatted data """ # Check what format type we are using: format_type = format_method if format_method is None: # Use the global format method format_type = self.format # Extracting data from packet: data = data.data if format_type == "replace" or format_type == 1: # Replace format codes with desired values: data = self.formatters.format(data, "QUERY_PROTOCOL") elif format_type in ['clean', 'remove'] or format_type == 2: # Remove format codes: data = self.formatters.clean(data, "QUERY_PROTOCOL") return data def __enter__(self): """ In a context manager. :return: This instance. """ return self def __exit__(self, exc_type, exc_val, exc_tb): """ Exit the context manager, show any errors as they are important. :param exc_type: Error info. :param exc_val: Error info. :param exc_tb: Error info. :return: False. """ # Stopping self.stop() return False class PINGClient(BaseClient): """ Ping client, allows for user to interact with the Minecraft server via the Server List Ping protocol. :param host: Hostname of the Minecraft server :type host: str :param port: Port of the Minecraft server :type port: int :param reqid: Request ID to use, leave as 'None' to generate one based on system time :type reqid: int :param format_method: Format method to use. You should specify this using the Client constants :type format_method: int :param timeout: Sets the timeout value for socket operations :type timeout: int :param proto_num: Protocol number to use, can specify which version we are emulating. Defaults to 0, which is the latest. :type proto_num: int """ def __init__(self, host: str, port: int=25565, reqid: int=None, format_method: int=BaseClient.REPLACE, timeout: int=60, proto_num: int=0): self.proto: PINGProtocol = PINGProtocol(host, port, timeout) self.host = host # Host of the Minecraft server self.port = int(port) # Port of the Minecraft server self.formatters: FormatterCollection = FormatterCollection() # Formatters method self.format = format_method # Formatting method to use self.protonum = proto_num # Protocol number we are using - 0 means we are using the latest self.reqid = self.gen_reqid() if reqid is None else int(reqid) # Adding the relevant formatters self.formatters.add(PINGFormatter, self.formatters.PING) def start(self): """ Starts the connection to the Minecraft server. This is called automatically where appropriate, so you shouldn't have to worry about calling this. """ if not self.is_connected(): self.proto.start() def stop(self): """ Stops the connection to the Minecraft server. This function should always be called when ceasing network communications, as not doing so could cause problems server-side. """ if self.is_connected(): self.proto.stop() def is_connected(self) -> bool: """ Determines if we are connected. :return: True if connected, False if otherwise. :rtype: bool """ return self.proto.connected def raw_send(self, pingnum: Union[int, None], packet_type: str, proto: int=None, host: str=None, port: int=0, noread: bool=False) -> PINGPacket: """ Creates a PingPacket and sends it to the Minecraft server :param pingnum: Pingnumber of the packet(For ping packets only) :type pingnum: int, None :param packet_type: Type of packet we are working with :type packet_type: str :param proto: Protocol number of the Minecraft server(For handshake only) :type proto: int :param host: Hostname of the Minecraft server(For handshake only) :type host: str :param port: Port of the Minecraft server(For handshake only) :type port: int :param noread: Determining if we are expecting a response :type noread: bool :return: PINGPacket if noread if False, otherwise None :rtype: PINGPacket, None """ if proto is None: proto = self.protonum if not self.is_connected(): # We are not connected, obviously the user wants to connect, so start it self.start() # Sending packet: self.proto.send(PINGPacket(pingnum, packet_type, proto=proto, host=host, port=port)) pack = PINGPacket(0, 0, None, 0) if not noread: # Receiving packet: pack = self.proto.read() return pack def _send_handshake(self): """ Sends a handshake packet to the server - Starts the conversation. """ # Sending packet: self.raw_send(None, "handshake", proto=self.protonum, host=self.host, port=self.port, noread=True) def _send_ping(self): """ Sends a ping packet to the server. We send this after we query stats, so the server doesn't have to wait. We also use this to calculate the latency, in nanoseconds. :return: PINGPacket, time. """ # Getting start time here: timestart = time.perf_counter() # Sending packet: pack = self.raw_send(self.reqid, "ping") # Calculating time elapsed, and converting that to milliseconds total = (time.perf_counter() - timestart) * 1000 return pack, total def ping(self) -> float: """ Pings the Minecraft server and calculates the latency. :return: Time elapsed(in milliseconds). :rtype: float """ # Sending handshake packet: self._send_handshake() # Sending request packet: self.raw_send(None, 'req') # Sending ping packet and getting time elapsed ping, time_elapsed = self._send_ping() return time_elapsed def get_stats(self, format_method: int=None, return_packet: bool=False) -> Union[dict, PINGPacket]: """ Gets stats from the Minecraft server. :param format_method: Determines the format method we should use. If 'None', then we use the global value. You should use the Client constants to define this. :type format_method: int :param return_packet: Determines if we should return the entire packet. If not, return the payload :type return_packet: bool :return: Dictionary containing stats, or PINGPacket depending on 'return_packet' :rtype: dict, PINGPacket .. versionadded:: 1.1.0 The 'format_method' and 'return_packet' parameters """ # Sending handshake packet: self._send_handshake() # Sending request packet: pack = self.raw_send(None, "req") # Sending ping packet - trying to be nice so server doesn't have to wait: ping, time_elapsed = self._send_ping() # Getting stop time, and adding it to the dictionary: pack.data["time"] = time_elapsed # Formatting the packet: pack.data = self._format(pack, format_method=format_method) if return_packet: # Return the packet: return pack # Return just the payload return pack.data def _format(self, pack, format_method=None): """ Sends the incoming data to the formatter. :param pack: Packet to be formatted :type pack: PINGPacket :param format_method: Determines the format method we should use. If 'None', then we use the global value. You should use the Client constants to define this. :type format_method: int :return: Formatted data. """ # Figure out what format method we are using: format_type = format_method if format_method is None: # Use the global value: format_type = self.format # Extracting the data from the packet: data = pack.data if format_type == "replace" or format_type == 1: # Replace format codes with desired values: data = self.formatters.format(data, "PING_PROTOCOL") elif format_type in ['clean', 'remove'] or format_type == 2: # Remove format codes: data = self.formatters.clean(data, "PING_PROTOCOL") return data def __enter__(self): """ Enter the context manager. :return: This instance. """ return self def __exit__(self, exc_type, exc_val, exc_tb): """ Exit the context manager. :param exc_type: Error info. :param exc_val: Error info. :param exc_tb: Error info. :return: False. """ # Stop the connection: self.stop() return False
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,151
fightBoy-Ing/mctools
refs/heads/master
/mctools/encoding.py
""" Encoding/Decoding Tools for RCON and Query. """ import struct import json from typing import Tuple, Union from mctools.errors import RCONMalformedPacketError, PINGMalformedPacketError MAP = {''} class BaseEncoder(object): """ Parent class for encoder implementation. """ @staticmethod def encode(data): """ Encodes data, and returns it in byte form. Raises 'NotImplementedError' exception, as this function should be overridden in the child class. :param data: Data to be encoded :return: Bytestring """ raise NotImplementedError("Override this method in child class!") @staticmethod def decode(data): """ Decodes data, and returns it in workable form(Whatever that may be) Raises 'NotImplementedError' exception, as this function should be overridden in the child class. :param data: Data to be decoded :return: Data in workable format """ raise NotImplementedError("Override this method in child class!") class RCONEncoder(BaseEncoder): """ RCON Encoder/Decoder. """ PAD = b'\x00\x00' @staticmethod def encode(data): """ Encodes a RCON packet. :param data: Tuple containing packet data :return: Bytestring of encoded data """ # Encoding the request ID and Request type: byts = struct.pack("<ii", data[0], data[1]) # Encoding payload and padding: byts = byts + data[2].encode("utf8") + RCONEncoder.PAD # Encoding length: byts = struct.pack("<i", len(byts)) + byts return byts @staticmethod def decode(byts): """ Decodes raw bytestring packet from the RCON server. NOTE: DOES NOT DECODE LENGTH! The 'length' vale is omitted, as it is interpreted by the RCONProtocol. If your bytestring contains the encoded length, simply remove the first 4 bytes. :param byts: Bytestring :return: Tuple containing values """ # Getting request ID and request type reqid, reqtype = struct.unpack("<ii", byts[:8]) # Getting payload payload = byts[8:len(byts)-2] # Checking padding: if not byts[len(byts) - 2:] == RCONEncoder.PAD: # No padding detected, something is wrong: raise RCONMalformedPacketError("Missing or malformed padding!") # Returning values: return reqid, reqtype, payload.decode("utf8") class QUERYEncoder(BaseEncoder): """ Query encoder/decoder """ IDENT = b'\xfe\xfd' # Magic bytes to add to the front of the packet KEYS = ['motd', 'gametype', 'map', 'numplayers', 'maxplayers', 'hostport', 'hostip'] # For parsing short-stats @staticmethod def encode(data): """ Encodes a Query Packet. :param data: Tuple of data to encode :return: Encoded data """ # Converting type to bytes byts = data[0].to_bytes(1, "big") # Converting request ID # Bitwise operation is necessary, as Minecraft Query only interprets the lower 4 bytes byts = byts + struct.pack(">i", data[1] & 0x0F0F0F0F) # Adding magic bits: byts = QUERYEncoder.IDENT + byts # Encoding payload - This gets messy, as the payload can be many things if data[3] == "basic" or data[3] == "full": # Must supply a challenge token to authenticate byts = byts + struct.pack(">i", data[2]) if data[3] == "full": # Must add padding, requesting full stats byts = byts + b'\x00\x00\x00\x00' return byts @staticmethod def decode(byts): """ Decodes packets from the Query protocol. This gets really messy, as the payload can be many different things. We also figure out what kind of data we are working with, and return that. :param byts: Bytes to decode :return: Tuple containing decoded items - reqtype, reqid, chall, data, type """ # Getting type here: reqtype = byts[0] # Getting request ID: reqid = struct.unpack(">i", byts[1:5])[0] # Checking the payload to determine what we are working with: # Splitting up payload into parts split = byts[5:].rstrip(b'\x00').split(b'\x00') if len(split) == 1: # Working with challenge token - Getting challenge token: # Returning info: return reqtype, reqid, int(split[0].decode('utf8')), None, "chall" # Working with stats data - This gets messy if split[0] != 'splitnum' and len(split) <= 7: # Working with short stats here: short_dict = {} for num, val in enumerate(split): # Creating short-stats dictionary if num == 5: # Dealing with a short instead of string # Adding short to the dictionary short_dict[QUERYEncoder.KEYS[num]] = str(struct.unpack("<H", val[:2])[0]) # Overriding values, so hostip can be properly added val = val[2:] num = num + 1 short_dict[QUERYEncoder.KEYS[num]] = val.replace(b'\x1b', b'\u001b').decode("ISO-8859-1") # Return info: return reqtype, reqid, None, short_dict, "basic" # Working with full stats - This gets even more messy # Splitting bytes by b'\x00' - Null bytes total = byts[15:].split(b'\x00\x01player_\x00\x00') # Replacing some nulls with actual values, and removing leading/trailing nulls # (And changing a keyvalue to what it should be) total[0] = total[0].replace(b'hostname', b'motd', 1).replace(b'\x00\x00', b'\x00 \x00')\ .replace(b'\x00', b'', 1).rstrip(b'\x00') total[1] = total[1].rstrip(b'\x00') # Parsing stats: stats_split = total[0].split(b'\x00') data_dict = {} for num in range(0, len(stats_split), 2): # Adding first value and second to dictionary data_dict[stats_split[num].decode("utf8")] = stats_split[num + 1].replace(b'\x1b', b'\u001b').\ decode("ISO-8859-1") # Parsing players: data_dict['players'] = [] for val in total[1].split(b'\x00'): # Adding player to list data_dict['players'].append(val.decode("utf8")) # Returning info return reqtype, reqid, None, data_dict, "full" class PINGEncoder(BaseEncoder): """ Ping encoder/decoder. """ ID = b'\x00' PINGID = b'\x01' @staticmethod def encode(data): """ Encodes a Ping packet. :param data: Data to be encoded, in tuple form :return: Bytes """ if data[2] == 'ping': # Encoding ping packet here byts = PINGEncoder.PINGID + struct.pack(">Q", data[1]) return PINGEncoder.encode_varint(len(byts)) + byts if data[2] == 'req': # Working with request packet: return PINGEncoder.encode_varint(len(PINGEncoder.ID)) + PINGEncoder.ID # Working with handshake packet - Starting with the packet ID, always null byte: byts = PINGEncoder.ID # Encoding Protocol version: byts = byts + PINGEncoder.encode_varint(data[3]) # Encoding server address: host_bytes = data[4].encode("utf8") byts = byts + PINGEncoder.encode_varint(len(host_bytes)) + host_bytes # Encoding server port: byts = byts + struct.pack(">H", data[5]) # Encoding next state: byts = byts + PINGEncoder.encode_varint(1) # Encoding length: byts = PINGEncoder.encode_varint(len(byts)) + byts return byts @staticmethod def decode(byts) -> Tuple[dict, None, str]: """ Decodes a ping packet. NOTE: Bytes provided should NOT include the length, that is interpreted and used by the PINGProtocol. :param byts: Bytes to decode :return: Tuple of decoded values """ # Get the packet type: pack_type, type_read = PINGEncoder.decode_varint(byts) if pack_type == 0: # Working with response packet: # Getting length varint: length, length_read = PINGEncoder.decode_varint(byts[type_read:]) return json.loads(byts[length_read+type_read:].decode("utf-8", 'ignore'), strict=False), None, "resp" elif pack_type == 1: # Working with some other packet type: return {}, None, "pong" raise PINGMalformedPacketError("Invalid packet type! Must be 1 or 0, not {}!".format(pack_type)) @staticmethod def encode_varint(num: int) -> bytes: """ Encodes a number into varint bytes. :param num: Number to encode :type num: int :return: Bytes """ byts: bytes = b'' remaining = num # Iterating over the content, and doing the necessary bitwise stuff for b in range(5): if remaining & ~0x7F == 0: # Found our stuff, exit break byts = byts + struct.pack("!B", remaining & 0x7F | 0x80) remaining >>= 7 byts = byts + struct.pack("!B", remaining) return byts @staticmethod def decode_varint(byts) -> Tuple[int, int]: """ Decodes varint bytes into an integer. We also return the amount of bytes read. :param byts: Bytes to decode :return: result, bytes read :rtype: int, int """ result = 0 b = 0 # Iterate over the result, and do the necessary bitwise stuff: for b in range(5): part = byts[b] result |= (part & 0x7F) << (7 * b) if not part & 0x80: # Fond our part, time to exit return result, b + 1 return result, b + 1 @staticmethod def decode_sock(sock) -> int: """ Decodes a var(int/long) of variable length or value. We use a socket to continuously pull values until we reach a valid value, as the length of these var(int/long)s can be either very long or very short. :param sock: Socket object to get bytes from. :return: Decoded integer :rtype: int """ result = 0 # Outcome of the operation read = 0 # Number of times we read while True: # Getting a byte: part = sock.recv(1) if len(part) == 0: # Can't work with this, must be done. break # Change into something we can understand: byte = ord(part) # Do our bitwise operation: result |= (byte & 0x7F) << 7 * read # Increment the amount of times we read: read = read + 1 if not byte & 0x80: # Found the end: break if read > 10: # Varint/long is way too big, throw an error raise Exception("Varint/long is greater than 10!") return result
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,152
fightBoy-Ing/mctools
refs/heads/master
/mctools/packet.py
""" Packet classes to hold RCON and Query data """ from typing import Union from mctools.encoding import RCONEncoder, QUERYEncoder, PINGEncoder class BasePacket(object): """ Parent class for packet implementations. """ @classmethod def from_bytes(cls, byts): """ Classmethod to create a packet from bytes. Rises an NotImplementedError excpetion, as this function should be overidden in the child class. :param byts: Bytes from remote entity :return: Packet object """ raise NotImplementedError("Override this method in child class!") def __repr__(self): """ Show packet type and values """ raise NotImplementedError("Override this method in child class!") def __str__(self): """ Allow for packets to represented in string format, pretty print """ raise NotImplementedError("Override this method in child class!") def __bytes__(self): """ Returns a byte-string representation of the packet :return: Bytestring of object """ raise NotImplementedError("Override this method in child class!") class RCONPacket(BasePacket): """ Class representing a RCON packet. :param reqid: Request ID of the RCON packet :type reqid: int :param reqtype: Request type of the RCON packet :type reqtype: int :param payload: Payload of the RCON packet :type payload: str """ def __init__(self, reqid, reqtype, payload, length=0): self.reqid = reqid # Request ID of the RCON packet self.reqtype = reqtype # Request type of the RCON packet self.payload = payload # Payload of the RCON packet self.length = length # Length of the packet, helps determine if we are fragmented self.type = 'rcon' # Determining what type of packet we are @classmethod def from_bytes(cls, byts): """ Creates a RCON packet from bytes. :param byts: Bytes from RCON server :return: RCONPacket """ reqid, reqtype, payload = RCONEncoder.decode(byts) return cls(reqid, reqtype, payload, length=len(byts)) def __repr__(self): """ Shows packet type and values - formal way. :return: String """ return "packet.RCONPacket({}, {}, {})".format(self.reqid, self.reqtype, self.payload) def __str__(self): """ Shows the packet contents in an easy to read format - informal way. :return: String. """ return "RCON Packet:\n - Request ID: {}\n - Request Type: {}\n - Payload: {}".format(self.reqid, self.reqtype, self.payload) def __bytes__(self): """ Converts packet into byte format. :return: Byte string. """ return RCONEncoder.encode((self.reqid, self.reqtype, self.payload)) class QUERYPacket(BasePacket): """ Class representing a Query Packet. :param reqtype: Type of Query packet :type reqtype: int :param reqid: Request ID of the Query packet :type reqid: int :param chall: Challenge token from Query server :type chall: str, None :param data_type: What type of data we contain :type data_type: str :param data: Data from the Query server :type data: dict """ def __init__(self, reqtype, reqid, chall, data_type, data: dict=None): self.reqtype = reqtype # Type of Query packet self.reqid = reqid # Request ID of the Query packet self.chall = chall # Challenge token from the Query server self.data: dict = data if data is not None else {} # Data from the Query server self.data_type = data_type # Determining what kind of data we contain @classmethod def from_bytes(cls, byts): """ Creates a Query packet from bytes. :param byts: Bytes from Query server :return: QUERYPacket. """ # Decoding bytes: reqtype, reqid, chall, data, data_type = QUERYEncoder.decode(byts) # Creating packet: pack = cls(reqtype, reqid, chall, data_type, data=data) return pack def __repr__(self): """ Shows packet types and values - Formal way. :return: String """ return "packet.QUERYPacket({}, {}, chall={}, data={}, data_type={})".format(self.reqtype, self.reqid, self.chall, self.data, self.data_type) def __str__(self): """ Shows packet in easy to read format - informal way. :return: String. """ return "Query Packet:\nRequest Type: {}\nRequest ID: " \ "{}\nChallenge Token: {}\nData: {}\nData Type: {}".format(self.reqtype, self.reqid, self.chall, self.data, self.data_type) def __bytes__(self): """ Converts the Query packet to bytes. :return: Bytes """ return QUERYEncoder.encode((self.reqtype, self.reqid, self.chall, self.data_type)) class PINGPacket(BasePacket): """ Class representing a Server List Ping Packet(Or ping for short). :param pingnum: Number to use for ping operations :type pingnum: int :param packet_type: Type of packet we are working with :type packet_type: str :param data: Ping data from Minecraft server :type data: dict, None :param proto: Protocol Version used :type proto: str, None :param host: Hostname of the Minecraft server :type host: str, None :param port: Port number of the Minecraft server :type port: int """ def __init__(self, pingnum, packet_type, data: dict=None, proto=None, host=None, port=0): self.proto = proto # Protocol version self.hostname = host # Hostname of the Minecraft server self.port = port # Port of the Minecraft server self.data: dict = data if data is not None else {} # Ping data from Minecraft server self.pingnum = pingnum # Number to use for ping operations self.packet_type = packet_type # Type of packet we are working with @classmethod def from_bytes(cls, byts): """ Creates a PINGPacket from bytes. :param byts: Bytes to decode :return: PINGPacket """ data, pingnum, packet_type = PINGEncoder.decode(byts) return cls(pingnum, packet_type, data=data) def __repr__(self): """ Show packet types and values - formal way. :return: String """ return "packet.PINGPacket({}, {}, {}, {}, {}, {}".format(self.data, self.pingnum, self.packet_type, self.proto, self.hostname, self.port) def __str__(self): """ Show packet in easy to read format - informal way. :return: String """ return "PINGPacket:\nPacket Data: {}\nPing Number: " \ "{}\nPacket Type: {}\nProtocol: {}\nHostname: {}\nPort: {}".format(self.data, self.pingnum, self.packet_type, self.proto, self.hostname, self.port) def __bytes__(self): """ Convert the PINGPacket into bytes. :return: Bytes """ return PINGEncoder.encode((self.data, self.pingnum, self.packet_type, self.proto, self.hostname, self.port))
{"/mctools/__main__.py": ["/mctools/mclient.py", "/mctools/formattertools.py"], "/mctools/protocol.py": ["/mctools/packet.py", "/mctools/encoding.py", "/mctools/errors.py"], "/mcli.py": ["/mctools/__main__.py"], "/mctools/__init__.py": ["/mctools/mclient.py"], "/mctools/mclient.py": ["/mctools/protocol.py", "/mctools/packet.py", "/mctools/formattertools.py", "/mctools/errors.py"], "/mctools/encoding.py": ["/mctools/errors.py"], "/mctools/packet.py": ["/mctools/encoding.py"]}
75,158
savagej/mlflow-torchserve
refs/heads/master
/tests/conftest.py
# flake8: noqa from tests.fixtures.plugin_fixtures import start_torchserve, stop_torchserve, health_checkup
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,159
savagej/mlflow-torchserve
refs/heads/master
/tests/examples/test_torchserve_examples.py
import os import pytest from mlflow import cli from click.testing import CliRunner EXAMPLES_DIR = "examples" @pytest.mark.parametrize( "directory, params", [ ("IrisClassification", ["-P", "max_epochs=10"]), ("MNIST", ["-P", "max_epochs=1"]), ("IrisClassificationTorchScript", ["-P", "max_epochs=10"]), ("BertNewsClassification", ["-P", "max_epochs=1", "-P", "num_samples=100"]), ("E2EBert", ["-P", "max_epochs=1", "-P", "num_samples=100"]), ], ) def test_mlflow_run_example(directory, params): example_dir = os.path.join(EXAMPLES_DIR, directory) cli_run_list = [example_dir] + params res = CliRunner().invoke(cli.run, cli_run_list) assert res.exit_code == 0, "Got non-zero exit code {0}. Output is: {1}".format( res.exit_code, res.output )
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,160
savagej/mlflow-torchserve
refs/heads/master
/examples/TextClassification/predict.py
import json from argparse import ArgumentParser from mlflow.deployments import get_deploy_client def predict(parser_args): with open(parser_args["input_file_path"], "r") as fp: text = fp.read() plugin = get_deploy_client(parser_args["target"]) prediction = plugin.predict(parser_args["deployment_name"], json.dumps(text)) print("Prediction Result {}".format(prediction)) if __name__ == "__main__": parser = ArgumentParser(description="Text classifier example") parser.add_argument( "--target", type=str, default="torchserve", help="MLflow target (default: torchserve)", ) parser.add_argument( "--deployment_name", type=str, default="text_classification", help="Deployment name (default: text_classification)", ) parser.add_argument( "--input_file_path", type=str, default="sample_text.txt", help="Path to input text file for prediction (default: sample_text.txt)", ) args = parser.parse_args() predict(vars(args))
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,161
savagej/mlflow-torchserve
refs/heads/master
/examples/IrisClassification/iris_classification.py
# pylint: disable=W0221 # pylint: disable=W0613 # pylint: disable=W0223 import argparse from argparse import ArgumentParser import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F from pytorch_lightning.metrics import Accuracy class IrisClassification(pl.LightningModule): def __init__(self, **kwargs): super(IrisClassification, self).__init__() self.train_acc = Accuracy() self.val_acc = Accuracy() self.test_acc = Accuracy() self.args = kwargs self.fc1 = nn.Linear(4, 10) self.fc2 = nn.Linear(10, 10) self.fc3 = nn.Linear(10, 3) self.cross_entropy_loss = nn.CrossEntropyLoss() def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) return x @staticmethod def add_model_specific_args(parent_parser): """ Add model specific arguments like learning rate :param parent_parser: Application specific parser :return: Returns the augmented arugument parser """ parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument( "--lr", type=float, default=0.01, metavar="LR", help="learning rate (default: 0.001)", ) return parser def configure_optimizers(self): return torch.optim.Adam(self.parameters(), self.args["lr"]) def training_step(self, batch, batch_idx): x, y = batch logits = self.forward(x) _, y_hat = torch.max(logits, dim=1) loss = self.cross_entropy_loss(logits, y) self.train_acc(y_hat, y) self.log( "train_acc", self.train_acc.compute(), on_step=False, on_epoch=True, ) self.log("train_loss", loss) return {"loss": loss} def validation_step(self, batch, batch_idx): x, y = batch logits = self.forward(x) _, y_hat = torch.max(logits, dim=1) loss = F.cross_entropy(logits, y) self.val_acc(y_hat, y) self.log("val_acc", self.val_acc.compute()) self.log("val_loss", loss, sync_dist=True) def test_step(self, batch, batch_idx): x, y = batch logits = self.forward(x) _, y_hat = torch.max(logits, dim=1) self.test_acc(y_hat, y) self.log("test_acc", self.test_acc.compute()) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Iris Classification model") parser.add_argument( "--max_epochs", type=int, default=100, help="number of epochs to run (default: 100)" ) parser.add_argument( "--gpus", type=int, default=0, help="Number of gpus - by default runs on CPU" ) parser.add_argument( "--save-model", type=bool, default=True, help="For Saving the current Model", ) parser.add_argument( "--accelerator", type=lambda x: None if x == "None" else x, default=None, help="Accelerator - (default: None)", ) from iris_data_module import IrisDataModule parser = IrisClassification.add_model_specific_args(parent_parser=parser) parser = IrisDataModule.add_model_specific_args(parent_parser=parser) args = parser.parse_args() dict_args = vars(args) dm = IrisDataModule(**dict_args) dm.prepare_data() dm.setup(stage="fit") model = IrisClassification(**dict_args) trainer = pl.Trainer.from_argparse_args(args) trainer.fit(model, dm) trainer.test() torch.save(model.state_dict(), "iris.pt")
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,162
savagej/mlflow-torchserve
refs/heads/master
/tests/fixtures/plugin_fixtures.py
import atexit import json import os import shutil import subprocess import time import pytest from tests.resources import linear_model @pytest.fixture(scope="session") def start_torchserve(): linear_model.main() if not os.path.isdir("model_store"): os.makedirs("model_store") cmd = "torchserve --ncs --start --model-store {}".format("./model_store") _ = subprocess.Popen(cmd, shell=True).wait() count = 0 for _ in range(5): value = health_checkup() if value is not None and value != "" and json.loads(value)["status"] == "Healthy": time.sleep(1) break else: count += 1 time.sleep(5) if count >= 5: raise Exception("Unable to connect to torchserve") return True def health_checkup(): curl_cmd = "curl http://localhost:8080/ping" (value, _) = subprocess.Popen([curl_cmd], stdout=subprocess.PIPE, shell=True).communicate() return value.decode("utf-8") def stop_torchserve(): cmd = "torchserve --stop" _ = subprocess.Popen(cmd, shell=True).wait() if os.path.isdir("model_store"): shutil.rmtree("model_store") if os.path.exists("tests/resources/linear_state_dict.pt"): os.remove("tests/resources/linear_state_dict.pt") if os.path.exists("tests/resources/linear_model.pt"): os.remove("tests/resources/linear_model.pt") atexit.register(stop_torchserve)
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,163
savagej/mlflow-torchserve
refs/heads/master
/examples/E2EBert/bert_e2e_datamodule.py
# pylint: disable=arguments-differ # pylint: disable=unused-argument # pylint: disable=abstract-method import os from argparse import ArgumentParser import pandas as pd import pytorch_lightning as pl import requests import torch from pytorch_lightning import seed_everything from sklearn.model_selection import train_test_split from torch.utils.data import Dataset, DataLoader from torchtext.datasets.text_classification import URLS from torchtext.utils import download_from_url, extract_archive from transformers import BertTokenizer class AGNewsDataset(Dataset): def __init__(self, reviews, targets, tokenizer, max_length): """ Performs initialization of tokenizer :param reviews: AG news text :param targets: labels :param tokenizer: bert tokenizer :param max_length: maximum length of the news text """ self.reviews = reviews self.targets = targets self.tokenizer = tokenizer self.max_length = max_length def __len__(self): """ :return: returns the number of datapoints in the dataframe """ return len(self.reviews) def __getitem__(self, item): """ Returns the review text and the targets of the specified item :param item: Index of sample review :return: Returns the dictionary of review text, input ids, attention mask, targets """ review = str(self.reviews[item]) target = self.targets[item] encoding = self.tokenizer.encode_plus( review, add_special_tokens=True, max_length=self.max_length, return_token_type_ids=False, padding="max_length", return_attention_mask=True, return_tensors="pt", truncation=True, ) return { "review_text": review, "input_ids": encoding["input_ids"].flatten(), "attention_mask": encoding["attention_mask"].flatten(), "targets": torch.tensor(target, dtype=torch.long), } class BertDataModule(pl.LightningDataModule): def __init__(self, **kwargs): """ Initialization of inherited lightning data module """ super(BertDataModule, self).__init__() self.PRE_TRAINED_MODEL_NAME = "bert-base-uncased" self.df_train = None self.df_val = None self.df_test = None self.train_data_loader = None self.val_data_loader = None self.test_data_loader = None self.MAX_LEN = 100 self.encoding = None self.tokenizer = None self.args = kwargs self.NUM_SAMPLES_COUNT = self.args["num_samples"] self.VOCAB_FILE_URL = self.args["vocab_file"] self.VOCAB_FILE = "bert_base_uncased_vocab.txt" @staticmethod def process_label(rating): rating = int(rating) return rating - 1 def prepare_data(self): """ Implementation of abstract class """ def setup(self, stage=None): """ Downloads the data, parse it and split the data into train, test, validation data :param stage: Stage - training or testing """ # reading the input dataset_tar = download_from_url(URLS["AG_NEWS"], root=".data") extracted_files = extract_archive(dataset_tar) for fname in extracted_files: if fname.endswith("train.csv"): train_csv_path = fname df = pd.read_csv(train_csv_path) df.columns = ["label", "title", "description"] df.sample(frac=1) df = df.iloc[: self.NUM_SAMPLES_COUNT] df["label"] = df.label.apply(self.process_label) if not os.path.isfile(self.VOCAB_FILE): filePointer = requests.get(self.VOCAB_FILE_URL, allow_redirects=True) if filePointer.ok: with open(self.VOCAB_FILE, "wb") as f: f.write(filePointer.content) else: raise RuntimeError("Error in fetching the vocab file") self.tokenizer = BertTokenizer(self.VOCAB_FILE) RANDOM_SEED = 42 seed_everything(RANDOM_SEED) df_train, df_test = train_test_split( df, test_size=0.2, random_state=RANDOM_SEED, stratify=df["label"] ) df_train, df_val = train_test_split( df_train, test_size=0.25, random_state=RANDOM_SEED, stratify=df_train["label"] ) self.df_train = df_train self.df_test = df_test self.df_val = df_val @staticmethod def add_model_specific_args(parent_parser): """ Returns the review text and the targets of the specified item :param parent_parser: Application specific parser :return: Returns the augmented arugument parser """ parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument( "--batch-size", type=int, default=16, metavar="N", help="input batch size for training (default: 16)", ) parser.add_argument( "--num-workers", type=int, default=3, metavar="N", help="number of workers (default: 3)", ) return parser def create_data_loader(self, df, tokenizer, max_len, batch_size): """ Generic data loader function :param df: Input dataframe :param tokenizer: bert tokenizer :param max_len: Max length of the news datapoint :param batch_size: Batch size for training :return: Returns the constructed dataloader """ ds = AGNewsDataset( reviews=df.description.to_numpy(), targets=df.label.to_numpy(), tokenizer=tokenizer, max_length=max_len, ) return DataLoader( ds, batch_size=self.args["batch_size"], num_workers=self.args["num_workers"] ) def train_dataloader(self): """ :return: output - Train data loader for the given input """ self.train_data_loader = self.create_data_loader( self.df_train, self.tokenizer, self.MAX_LEN, self.args["batch_size"] ) return self.train_data_loader def val_dataloader(self): """ :return: output - Validation data loader for the given input """ self.val_data_loader = self.create_data_loader( self.df_val, self.tokenizer, self.MAX_LEN, self.args["batch_size"] ) return self.val_data_loader def test_dataloader(self): """ :return: output - Test data loader for the given input """ self.test_data_loader = self.create_data_loader( self.df_test, self.tokenizer, self.MAX_LEN, self.args["batch_size"] ) return self.test_data_loader # if __name__ == "__main__": pass
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,164
savagej/mlflow-torchserve
refs/heads/master
/examples/IrisClassification/iris_handler.py
import ast import logging import numpy as np import torch from ts.torch_handler.base_handler import BaseHandler logger = logging.getLogger(__name__) class IRISClassifierHandler(BaseHandler): """ IRISClassifier handler class. This handler takes an input tensor and output the type of iris based on the input """ def __init__(self): super(IRISClassifierHandler, self).__init__() def preprocess(self, data): """ preprocessing step - Reads the input array and converts it to tensor :param data: Input to be passed through the layers for prediction :return: output - Preprocessed input """ input_data_str = data[0].get("data") if input_data_str is None: input_data_str = data[0].get("body") input_data = input_data_str.decode("utf-8") input_tensor = torch.Tensor(ast.literal_eval(input_data)) return input_tensor def postprocess(self, inference_output): """ Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing """ predicted_idx = str(np.argmax(inference_output.cpu().detach().numpy())) if self.mapping: return [self.mapping[str(predicted_idx)]] return [predicted_idx] _service = IRISClassifierHandler()
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,165
savagej/mlflow-torchserve
refs/heads/master
/tests/resources/linear_model.py
# pylint: disable=W0223 # IMPORTS SECTION # import numpy as np import torch from torch.autograd import Variable # SYNTHETIC DATA PREPARATION # x_values = [i for i in range(11)] x_train = np.array(x_values, dtype=np.float32) x_train = x_train.reshape(-1, 1) y_values = [2 * i + 1 for i in x_values] y_train = np.array(y_values, dtype=np.float32) y_train = y_train.reshape(-1, 1) # DEFINING THE NETWORK FOR REGRESSION # class LinearRegression(torch.nn.Module): def __init__(self, inputSize, outputSize): super(LinearRegression, self).__init__() self.linear = torch.nn.Linear(inputSize, outputSize) def forward(self, x): out = self.linear(x) return out def main(): # SECTION FOR HYPERPARAMETERS # inputDim = 1 outputDim = 1 learningRate = 0.01 epochs = 100 # INITIALIZING THE MODEL # model = LinearRegression(inputDim, outputDim) # FOR GPU # if torch.cuda.is_available(): model.cuda() # INITIALIZING THE LOSS FUNCTION AND OPTIMIZER # criterion = torch.nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=learningRate) # TRAINING STEP # for epoch in range(epochs): # Converting inputs and labels to Variable if torch.cuda.is_available(): inputs = Variable(torch.from_numpy(x_train).cuda()) labels = Variable(torch.from_numpy(y_train).cuda()) else: inputs = Variable(torch.from_numpy(x_train)) labels = Variable(torch.from_numpy(y_train)) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() print("epoch {}, loss {}".format(epoch, loss.item())) # EVALUATION AND PREDICTION # with torch.no_grad(): if torch.cuda.is_available(): predicted = model(Variable(torch.from_numpy(x_train).cuda())).cpu().data.numpy() else: predicted = model(Variable(torch.from_numpy(x_train))).data.numpy() print(predicted) # SAVING THE MODEL # torch.save(model.state_dict(), "tests/resources/linear_state_dict.pt") torch.save(model, "tests/resources/linear_model.pt")
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,166
savagej/mlflow-torchserve
refs/heads/master
/examples/MNIST/mnist_handler.py
import json import logging import os import torch from ts.torch_handler.image_classifier import ImageClassifier logger = logging.getLogger(__name__) class MNISTDigitHandler(ImageClassifier): """ MNISTDigitClassifier handler class. This handler takes a greyscale image and returns the digit in that image. """ def __init__(self): super(MNISTDigitHandler, self).__init__() self.mapping_file_path = None def initialize(self, ctx): """ First try to load torchscript else load eager mode state_dict based model :param ctx: System properties """ properties = ctx.system_properties self.device = torch.device( "cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu" ) model_dir = properties.get("model_dir") # Read model serialize/pt file model_pt_path = os.path.join(model_dir, "state_dict.pth") from mnist_model import LightningMNISTClassifier state_dict = torch.load(model_pt_path, map_location=self.device) self.model = LightningMNISTClassifier() self.model.load_state_dict(state_dict) self.model.to(self.device) self.model.eval() logger.debug("Model file %s loaded successfully", model_pt_path) self.mapping_file_path = os.path.join(model_dir, "index_to_name.json") self.initialized = True def preprocess(self, data): """ Scales, crops, and normalizes a PIL image for a MNIST model, returns an Numpy array :param data: Input to be passed through the layers for prediction :return: output - Preprocessed image """ image = data[0].get("data") if image is None: image = data[0].get("body") image = image.decode("utf-8") image = torch.Tensor(json.loads(image)["data"]) return image def inference(self, img): """ Predict the class (or classes) of an image using a trained deep learning model :param img: Input to be passed through the layers for prediction :return: output - Predicted label for the given input """ # Convert 2D image to 1D vector # img = np.expand_dims(img, 0) # img = torch.from_numpy(img) self.model.eval() inputs = img.to(self.device) outputs = self.model.forward(inputs) _, y_hat = outputs.max(1) predicted_idx = str(y_hat.item()) return [predicted_idx] def postprocess(self, inference_output): """ Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing """ if self.mapping_file_path: with open(self.mapping_file_path) as json_file: data = json.load(json_file) inference_output = [json.dumps(data[inference_output[0]])] return inference_output return [inference_output]
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,167
savagej/mlflow-torchserve
refs/heads/master
/examples/MNIST/create_deployment.py
from argparse import ArgumentParser from mlflow.deployments import get_deploy_client def create_deployment(parser_args): plugin = get_deploy_client(parser_args["target"]) config = { "MODEL_FILE": parser_args["model_file"], "HANDLER": parser_args["handler"], "EXTRA_FILES": parser_args["extra_files"], } if parser_args["export_path"] != "": config["EXPORT_PATH"] = parser_args["export_path"] result = plugin.create_deployment( name=parser_args["deployment_name"], model_uri=parser_args["serialized_file_path"], config=config, ) print("Deployment {result} created successfully".format(result=result["name"])) if __name__ == "__main__": parser = ArgumentParser(description="MNIST hand written digits classification example") parser.add_argument( "--target", type=str, default="torchserve", help="MLflow target (default: torchserve)", ) parser.add_argument( "--deployment_name", type=str, default="mnist_classification", help="Deployment name (default: mnist_classification)", ) parser.add_argument( "--model_file", type=str, default="mnist_model.py", help="Model file path (default: mnist_model.py)", ) parser.add_argument( "--handler", type=str, default="mnist_handler.py", help="Handler file path (default: mnist_handler.py)", ) parser.add_argument( "--extra_files", type=str, default="index_to_name.json", help="List of extra files", ) parser.add_argument( "--serialized_file_path", type=str, default="models", help="Pytorch model path (default: models)", ) parser.add_argument( "--export_path", type=str, default="", help="Path to model store (default: '')", ) args = parser.parse_args() create_deployment(vars(args))
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,168
savagej/mlflow-torchserve
refs/heads/master
/examples/IrisClassificationTorchScript/iris_handler.py
import ast import logging import os import numpy as np import torch from ts.torch_handler.base_handler import BaseHandler logger = logging.getLogger(__name__) class IRISClassifierHandler(BaseHandler): """ IRISClassifier handler class. This handler takes an input tensor and output the type of iris based on the input """ def __init__(self): super(IRISClassifierHandler, self).__init__() def initialize(self, context): """First try to load torchscript else load eager mode state_dict based model""" properties = context.system_properties self.map_location = "cuda" if torch.cuda.is_available() else "cpu" self.device = torch.device( self.map_location + ":" + str(properties.get("gpu_id")) if torch.cuda.is_available() else self.map_location ) self.manifest = context.manifest model_dir = properties.get("model_dir") self.batch_size = properties.get("batch_size") serialized_file = self.manifest["model"]["serializedFile"] model_pt_path = os.path.join(model_dir, serialized_file) if not os.path.isfile(model_pt_path): raise RuntimeError("Missing the model.pt file") logger.debug("Loading torchscript model") self.model = self._load_torchscript_model(model_pt_path) self.model.to(self.device) self.model.eval() logger.debug("Model file %s loaded successfully", model_pt_path) self.initialized = True def preprocess(self, data): """ preprocessing step - Reads the input array and converts it to tensor :param data: Input to be passed through the layers for prediction :return: output - Preprocessed input """ input_data_str = data[0].get("data") if input_data_str is None: input_data_str = data[0].get("body") input_data = input_data_str.decode("utf-8") input_tensor = torch.Tensor(ast.literal_eval(input_data)) return input_tensor def postprocess(self, inference_output): """ Does postprocess after inference to be returned to user :param inference_output: Output of inference :return: output - Output after post processing """ predicted_idx = str(np.argmax(inference_output.cpu().detach().numpy())) if self.mapping: return [self.mapping[str(predicted_idx)]] return [predicted_idx] _service = IRISClassifierHandler()
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,169
savagej/mlflow-torchserve
refs/heads/master
/tests/test_cli.py
import json import os import pytest from click.testing import CliRunner from mlflow import deployments from mlflow.deployments import cli f_target = "torchserve" f_deployment_id = "cli_test" f_deployment_name_version = "cli_test/2.0" f_deployment_name_all = "cli_test/all" f_flavor = None f_model_uri = os.path.join("tests/resources", "linear_state_dict.pt") model_version = "1.0" model_file_path = os.path.join("tests/resources", "linear_model.py") handler_file_path = os.path.join("tests/resources", "linear_handler.py") sample_input_file = os.path.join("tests/resources", "sample.json") @pytest.mark.usefixtures("start_torchserve") def test_create_cli_version_success(): version = "VERSION={version}".format(version="1.0") model_file = "MODEL_FILE={model_file_path}".format(model_file_path=model_file_path) handler_file = "HANDLER={handler_file_path}".format(handler_file_path=handler_file_path) _ = deployments.get_deploy_client(f_target) runner = CliRunner() res = runner.invoke( cli.create_deployment, [ "-f", f_flavor, "-m", f_model_uri, "-t", f_target, "--name", f_deployment_id, "-C", model_file, "-C", handler_file, "-C", version, ], ) assert "{} deployment {} is created".format(f_flavor, f_deployment_id + "/1.0") in res.stdout def test_create_cli_success_without_version(): model_file = "MODEL_FILE={model_file_path}".format(model_file_path=model_file_path) handler_file = "HANDLER={handler_file_path}".format(handler_file_path=handler_file_path) _ = deployments.get_deploy_client(f_target) runner = CliRunner() res = runner.invoke( cli.create_deployment, [ "-f", f_flavor, "-m", f_model_uri, "-t", f_target, "--name", f_deployment_id, "-C", model_file, "-C", handler_file, ], ) assert "{} deployment {} is created".format(f_flavor, f_deployment_name_version) in res.stdout @pytest.mark.parametrize( "deployment_name, config", [(f_deployment_name_version, "SET-DEFAULT=true"), (f_deployment_id, "MIN_WORKER=3")], ) def test_update_cli_success(deployment_name, config): runner = CliRunner() res = runner.invoke( cli.update_deployment, [ "--flavor", f_flavor, "--model-uri", f_model_uri, "--target", f_target, "--name", deployment_name, "-C", config, ], ) assert ( "Deployment {} is updated (with flavor {})".format(deployment_name, f_flavor) in res.stdout ) def test_list_cli_success(): runner = CliRunner() res = runner.invoke(cli.list_deployment, ["--target", f_target]) assert "{}".format(f_deployment_id) in res.stdout @pytest.mark.parametrize( "deployment_name", [f_deployment_id, f_deployment_name_version, f_deployment_name_all] ) def test_get_cli_success(deployment_name): runner = CliRunner() res = runner.invoke(cli.get_deployment, ["--name", deployment_name, "--target", f_target]) ret = json.loads(res.stdout.split("deploy:")[1]) if deployment_name == f_deployment_id: assert ret[0]["modelName"] == f_deployment_id elif deployment_name == f_deployment_name_version: assert ret[0]["modelVersion"] == f_deployment_name_version.split("/")[1] else: assert len(ret) == 2 @pytest.mark.parametrize("deployment_name", [f_deployment_name_version, f_deployment_id]) def test_predict_cli_success(deployment_name): runner = CliRunner() res = runner.invoke( cli.predict, ["--name", deployment_name, "--target", f_target, "--input-path", sample_input_file], ) assert res.stdout != "" @pytest.mark.parametrize("deployment_name", [f_deployment_id + "/1.0", f_deployment_name_version]) def test_delete_cli_success(deployment_name): runner = CliRunner() res = runner.invoke( cli.delete_deployment, ["--name", deployment_name, "--target", f_target], ) assert "Deployment {} is deleted".format(deployment_name) in res.stdout
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,170
savagej/mlflow-torchserve
refs/heads/master
/examples/MNIST/predict.py
import os from argparse import ArgumentParser import matplotlib.pyplot as plt from mlflow.deployments import get_deploy_client from torchvision import transforms def predict(parser_args): plugin = get_deploy_client(parser_args["target"]) img = plt.imread(os.path.join(parser_args["input_file_path"])) mnist_transforms = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] ) image_tensor = mnist_transforms(img) prediction = plugin.predict(parser_args["deployment_name"], image_tensor) print("Prediction Result {}".format(prediction)) if __name__ == "__main__": parser = ArgumentParser(description="MNIST hand written digits classification example") parser.add_argument( "--target", type=str, default="torchserve", help="MLflow target (default: torchserve)", ) parser.add_argument( "--deployment_name", type=str, default="mnist_classification", help="Deployment name (default: mnist_classification)", ) parser.add_argument( "--input_file_path", type=str, default="test_data/one.png", help="Path to input image for prediction (default: test_data/one.png)", ) args = parser.parse_args() predict(vars(args))
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,171
savagej/mlflow-torchserve
refs/heads/master
/tests/test_plugin.py
import json import os import pytest import torch from mlflow import deployments from mlflow.exceptions import MlflowException f_target = "torchserve" f_deployment_id = "test" f_deployment_name_version = "test/2.0" f_deployment_name_all = "test/all" f_flavor = None f_model_uri = os.path.join("tests/resources", "linear_state_dict.pt") model_version = "1.0" model_file_path = os.path.join("tests/resources", "linear_model.py") handler_file_path = os.path.join("tests/resources", "linear_handler.py") sample_input_file = os.path.join("tests/resources", "sample.json") sample_output_file = os.path.join("tests/resources", "output.json") @pytest.mark.usefixtures("start_torchserve") def test_create_deployment_success(): client = deployments.get_deploy_client(f_target) ret = client.create_deployment( f_deployment_id, f_model_uri, f_flavor, config={ "VERSION": model_version, "MODEL_FILE": model_file_path, "HANDLER": handler_file_path, }, ) assert isinstance(ret, dict) assert ret["name"] == f_deployment_id + "/" + model_version assert ret["flavor"] == f_flavor def test_create_deployment_no_version(): client = deployments.get_deploy_client(f_target) ret = client.create_deployment( f_deployment_id, f_model_uri, f_flavor, config={"MODEL_FILE": model_file_path, "HANDLER": handler_file_path}, ) assert isinstance(ret, dict) assert ret["name"] == f_deployment_name_version assert ret["flavor"] == f_flavor def test_list_success(): client = deployments.get_deploy_client(f_target) ret = client.list_deployments() isNamePresent = False for i in range(len(ret)): if list(ret[i].keys())[0] == f_deployment_id: isNamePresent = True break if isNamePresent: assert True else: assert False @pytest.mark.parametrize( "deployment_name", [f_deployment_id, f_deployment_name_version, f_deployment_name_all] ) def test_get_success(deployment_name): client = deployments.get_deploy_client(f_target) ret = client.get_deployment(deployment_name) print("Return value is ", json.loads(ret["deploy"])) if deployment_name == f_deployment_id: assert json.loads(ret["deploy"])[0]["modelName"] == f_deployment_id elif deployment_name == f_deployment_name_version: assert ( json.loads(ret["deploy"])[0]["modelVersion"] == f_deployment_name_version.split("/")[1] ) else: assert len(json.loads(ret["deploy"])) == 2 def test_wrong_target_name(): with pytest.raises(MlflowException): deployments.get_deploy_client("wrong_target") @pytest.mark.parametrize( "deployment_name, config", [(f_deployment_name_version, {"SET-DEFAULT": "true"}), (f_deployment_id, {"MIN_WORKER": 3})], ) def test_update_deployment_success(deployment_name, config): client = deployments.get_deploy_client(f_target) ret = client.update_deployment(deployment_name, config) assert ret["flavor"] is None @pytest.mark.parametrize("deployment_name", [f_deployment_name_version, f_deployment_id]) def test_predict_success(deployment_name): client = deployments.get_deploy_client(f_target) with open(sample_input_file) as fp: data = fp.read() pred = client.predict(deployment_name, data) assert pred is not None @pytest.mark.parametrize("deployment_name", [f_deployment_name_version, f_deployment_id]) def test_predict_tensor_input(deployment_name): client = deployments.get_deploy_client(f_target) data = torch.Tensor([5000]) pred = client.predict(deployment_name, data) assert pred is not None @pytest.mark.parametrize("deployment_name", [f_deployment_name_version, f_deployment_id]) def test_delete_success(deployment_name): client = deployments.get_deploy_client(f_target) assert client.delete_deployment(deployment_name) is None f_dummy = "dummy" def test_create_no_handler_exception(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Config Variable HANDLER - missing"): client.create_deployment( f_deployment_id, f_model_uri, f_flavor, config={"VERSION": model_version, "MODEL_FILE": model_file_path}, ) def test_create_wrong_handler_exception(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to create mar file"): client.create_deployment( f_deployment_id, f_model_uri, f_flavor, config={"VERSION": model_version, "MODEL_FILE": model_file_path, "HANDLER": f_dummy}, ) def test_create_wrong_model_exception(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to create mar file"): client.create_deployment( f_deployment_id, f_model_uri, f_flavor, config={"VERSION": model_version, "MODEL_FILE": f_dummy, "HANDLER": handler_file_path}, ) def test_create_mar_file_exception(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="No such file or directory"): client.create_deployment( f_deployment_id, f_dummy, config={ "VERSION": model_version, "MODEL_FILE": model_file_path, "HANDLER": handler_file_path, }, ) def test_update_invalid_name(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to update deployment with name %s" % f_dummy): client.update_deployment(f_dummy) def test_get_invalid_name(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to get deployments with name %s" % f_dummy): client.get_deployment(f_dummy) def test_delete_invalid_name(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to delete deployment for name %s" % f_dummy): client.delete_deployment(f_dummy) def test_predict_exception(): client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to parse input json string"): client.predict(f_dummy, "sample") def test_predict_name_exception(): with open(sample_input_file) as fp: data = fp.read() client = deployments.get_deploy_client(f_target) with pytest.raises(Exception, match="Unable to infer the results for the name %s" % f_dummy): client.predict(f_dummy, data)
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,172
savagej/mlflow-torchserve
refs/heads/master
/examples/MNIST/register.py
from argparse import ArgumentParser from mlflow.deployments import get_deploy_client def register(parser_args): plugin = get_deploy_client(parser_args["target"]) plugin.register_model(mar_file_path=parser_args["mar_file_name"]) print("Registered Successfully") if __name__ == "__main__": parser = ArgumentParser(description="MNIST hand written digits classification example") parser.add_argument( "--target", type=str, default="torchserve", help="MLflow target (default: torchserve)", ) parser.add_argument( "--mar_file_name", type=str, default="", help="mar file name to register (Ex: mnist_test.mar)", ) args = parser.parse_args() register(vars(args))
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,173
savagej/mlflow-torchserve
refs/heads/master
/setup.py
from setuptools import setup, find_packages setup( name="mlflow-torchserve", version="0.1.0", description="Torch Serve Mlflow Deployment", long_description=open("README.md").read(), long_description_content_type="text/markdown", packages=find_packages(), # Require MLflow as a dependency of the plugin, so that plugin users can simply install # the plugin & then immediately use it with MLflow install_requires=[ "mlflow>=1.14.0", "torchserve", "torch-model-archiver", ], entry_points={"mlflow.deployments": "torchserve=mlflow_torchserve"}, )
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,174
savagej/mlflow-torchserve
refs/heads/master
/examples/TextClassification/create_deployment.py
from argparse import ArgumentParser from mlflow.deployments import get_deploy_client def create_deployment(parser_args): plugin = get_deploy_client(parser_args["target"]) config = { "MODEL_FILE": parser_args["model_file"], "HANDLER": parser_args["handler"], "EXTRA_FILES": "source_vocab.pt,index_to_name.json", } result = plugin.create_deployment( name=parser_args["deployment_name"], model_uri=parser_args["serialized_file"], config=config, ) print("Deployment {result} created successfully".format(result=result["name"])) if __name__ == "__main__": parser = ArgumentParser(description="Text Classifier Example") parser.add_argument( "--target", type=str, default="torchserve", help="MLflow target (default: torchserve)", ) parser.add_argument( "--deployment_name", type=str, default="text_classification", help="Deployment name (default: text_classification)", ) parser.add_argument( "--model_file", type=str, default="model.py", help="Model file path (default: model.py)", ) parser.add_argument( "--handler", type=str, default="text_classifier", help="Handler file path (default: text_classifier)", ) parser.add_argument( "--extra_files", type=str, default="source_vocab.pt,index_to_name.json", help="List of extra files", ) parser.add_argument( "--serialized_file", type=str, default="model.pt", help="Pytorch model path (default: model.pt)", ) args = parser.parse_args() create_deployment(vars(args))
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,175
savagej/mlflow-torchserve
refs/heads/master
/mlflow_torchserve/config.py
import os class Config(dict): def __init__(self): """ Initializes constants from Environment variables """ super().__init__() self["export_path"] = os.environ.get("EXPORT_PATH") self["config_properties"] = os.environ.get("CONFIG_PROPERTIES") self["torchserve_address_names"] = ["inference_address", "management_address", "export_url"] self["export_uri"] = os.environ.get("EXPORT_URL")
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,176
savagej/mlflow-torchserve
refs/heads/master
/tests/examples/test_end_to_end_example.py
import pytest import os from mlflow.utils import process @pytest.mark.usefixtures("start_torchserve") def test_mnist_example(): os.environ["MKL_THREADING_LAYER"] = "GNU" home_dir = os.getcwd() mnist_dir = "examples/MNIST" example_command = ["python", "mnist_model.py", "--max_epochs", "1"] process.exec_cmd(example_command, cwd=mnist_dir) assert os.path.exists(os.path.join(mnist_dir, "models", "state_dict.pth")) create_deployment_command = [ "python", "create_deployment.py", "--export_path", os.path.join(home_dir, "model_store"), ] process.exec_cmd(create_deployment_command, cwd=mnist_dir) assert os.path.exists(os.path.join(home_dir, "model_store", "mnist_classification.mar")) predict_command = ["python", "predict.py"] res = process.exec_cmd(predict_command, cwd=mnist_dir) assert "ONE" in res[1] @pytest.mark.usefixtures("start_torchserve") def test_iris_example(tmpdir): iris_dir = os.path.join("examples", "IrisClassification") iris_dir_absolute_path = os.path.join(os.getcwd(), iris_dir) example_command = ["python", "iris_classification.py"] process.exec_cmd(example_command, cwd=iris_dir) model_uri = os.path.join(iris_dir_absolute_path, "iris.pt") model_file_path = os.path.join(iris_dir_absolute_path, "iris_classification.py") handler_file_path = os.path.join(iris_dir_absolute_path, "iris_handler.py") extra_file_path = os.path.join(iris_dir_absolute_path, "index_to_name.json") input_file_path = os.path.join(iris_dir_absolute_path, "sample.json") output_file_path = os.path.join(str(tmpdir), "output.json") create_deployment_command = [ "mlflow deployments create " "--name iris_test_29 " "--target torchserve " "--model-uri {model_uri} " '-C "MODEL_FILE={model_file}" ' '-C "HANDLER={handler_file}" ' '-C "EXTRA_FILES={extra_file}"'.format( model_uri=model_uri, model_file=model_file_path, handler_file=handler_file_path, extra_file=extra_file_path, ), ] process.exec_cmd(create_deployment_command, shell=True) predict_command = [ "mlflow deployments predict " "--name iris_test_29 " "--target torchserve " "--input-path {} --output-path {}".format(input_file_path, output_file_path) ] process.exec_cmd(predict_command, cwd=iris_dir, shell=True) assert os.path.exists(output_file_path) with open(output_file_path) as fp: result = fp.read() assert "SETOSA" in result
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,177
savagej/mlflow-torchserve
refs/heads/master
/tests/resources/linear_handler.py
# IMPORTS SECTION # import logging import os import numpy as np import torch from torch.autograd import Variable import json logger = logging.getLogger(__name__) # CLASS DEFINITION # class LinearRegressionHandler(object): def __init__(self): self.model = None self.mapping = None self.device = None self.initialized = False def initialize(self, ctx): """ Loading the saved model from the serialized file """ properties = ctx.system_properties self.device = torch.device( "cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available() else "cpu" ) model_dir = properties.get("model_dir") # Read model serialize/pt file model_pt_path = os.path.join(model_dir, "linear_state_dict.pt") # Read model definition file model_def_path = os.path.join(model_dir, "linear_model.py") if not os.path.isfile(model_def_path): model_pt_path = os.path.join(model_dir, "linear_model.pt") self.model = torch.load(model_pt_path, map_location=self.device) else: from linear_model import LinearRegression state_dict = torch.load(model_pt_path, map_location=self.device) self.model = LinearRegression(1, 1) self.model.load_state_dict(state_dict) self.model.to(self.device) self.model.eval() logger.debug("Model file %s loaded successfully", model_pt_path) self.initialized = True def preprocess(self, data): """ Preprocess the input to tensor and reshape it to be used as input to the network """ data = data[0] image = data.get("data") if image is None: image = data.get("body") image = image.decode("utf-8") number = float(json.loads(image)["data"][0]) else: number = float(image) np_data = np.array(number, dtype=np.float32) np_data = np_data.reshape(-1, 1) data_tensor = torch.from_numpy(np_data) return data_tensor def inference(self, num): """ Does inference / prediction on the preprocessed input and returns the output """ self.model.eval() inputs = Variable(num).to(self.device) outputs = self.model.forward(inputs) return [outputs.detach().item()] def postprocess(self, inference_output): """ Does post processing on the output returned from the inference method """ return inference_output # CLASS INITIALIZATION # _service = LinearRegressionHandler() def handle(data, context): """ Default handler for the inference api which takes two parameters data and context and returns the predicted output """ if not _service.initialized: _service.initialize(context) if data is None: return None data = _service.preprocess(data) data = _service.inference(data) data = _service.postprocess(data) print("Data: {}".format(data)) return data
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,178
savagej/mlflow-torchserve
refs/heads/master
/examples/IrisClassificationTorchScript/iris_classification.py
import argparse import mlflow.pytorch import pytorch_lightning as pl import torch import torch.nn as nn from sklearn.metrics import accuracy_score from torch.nn import functional as F class IrisClassification(pl.LightningModule): def __init__(self): super(IrisClassification, self).__init__() self.fc1 = nn.Linear(4, 10) self.fc2 = nn.Linear(10, 10) self.fc3 = nn.Linear(10, 3) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = F.log_softmax(x, dim=0) return x def cross_entropy_loss(self, logits, labels): """ Loss Fn to compute loss """ return F.nll_loss(logits, labels) def training_step(self, train_batch, batch_idx): """ training the data as batches and returns training loss on each batch """ x, y = train_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"loss": loss} def validation_step(self, val_batch, batch_idx): """ Performs validation of data in batches """ x, y = val_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"val_loss": loss} def validation_epoch_end(self, outputs): """ Computes average validation accuracy """ avg_loss = torch.stack([x["val_loss"] for x in outputs]).mean() tensorboard_logs = {"val_loss": avg_loss} return {"avg_val_loss": avg_loss, "log": tensorboard_logs} def test_step(self, test_batch, batch_idx): """ Performs test and computes test accuracy """ x, y = test_batch output = self.forward(x) a, y_hat = torch.max(output, dim=1) test_acc = accuracy_score(y_hat.cpu(), y.cpu()) return {"test_acc": torch.tensor(test_acc)} def test_epoch_end(self, outputs): """ Computes average test accuracy score """ avg_test_acc = torch.stack([x["test_acc"] for x in outputs]).mean() return {"avg_test_acc": avg_test_acc} def configure_optimizers(self): """ Creates and returns Optimizer """ self.optimizer = torch.optim.SGD(self.parameters(), lr=0.05, momentum=0.9) return self.optimizer if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--max_epochs", default=3, help="Describes the number of times a neural network has to be trained", ) parser.add_argument( "--gpus", type=int, default=0, help="Number of gpus - by default runs on CPU" ) parser.add_argument( "--accelerator", type=lambda x: None if x == "None" else x, default=None, help="Accelerator - (default: None)", ) args = parser.parse_args() mlflow.pytorch.autolog() trainer = pl.Trainer(max_epochs=int(args.max_epochs)) model = IrisClassification() import iris_datamodule dm = iris_datamodule.IRISDataModule() dm.setup("fit") trainer.fit(model, dm) testloader = dm.setup("test") trainer.test(datamodule=testloader) scripted_model = torch.jit.script(model) torch.jit.save(scripted_model, "iris_ts.pt")
{"/tests/conftest.py": ["/tests/fixtures/plugin_fixtures.py"]}
75,189
AniviaPlayer/TreeLSTM
refs/heads/master
/Learner.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: Learner.py Author: sunprinceS (TonyHsu) Email: sunprince12014@gmail.com Description: train and validate TreeLSTM """ import numpy as np from collections import Counter from util import * from TreeMgr import TreeMgr from TreeLSTM import TreeLSTM ########## ##MARCOS## ########## MEM_DIM = 5 IN_DIM = 300 #GloVe's dimension SENTENCE_FILE="laptop/sents.txt" DESCRIPT_FILE="laptop/cparents.txt" LABEL_FILE = "laptop/labels" class Learner(object): """ must add some parsing function """ def __init__(self,sentence_file,descript_file,label_file,param_file=None): self.mgr = TreeMgr(sentence_file,descript_file) self.num_samples = self.mgr.get_num_sample() self.treelstm = TreeLSTM(self.mgr,np.random.RandomState(123),MEM_DIM,IN_DIM,param_file) self.label_list = io.loadLabel(label_file) def batch_train(self,training_iters=100): print("Batch Training") self.mini_batch_train(self.num_samples) def mini_batch_train(self,batch_size=25,training_iters=1000,lr=1,rho=1e-3): for i in range(training_iters): sentence_iterator = self.mgr.sentence_iterator() batch_cost = 0.0 batch_num = 1 correct = 0 correct_list = [] pred_list = [] print("======") print("Training Iteration {}:".format(i)) print("======") for i ,sentence in enumerate(sentence_iterator): label = int(self.label_list[i]) pred,cost,prob = self.treelstm.forward_pass(sentence,label) print(prob) if pred == label: correct += 1 batch_cost += cost correct_list.append(label) pred_list.append(pred) self.treelstm.back_prop(prob,sentence,label) if (i+1) % batch_size == 0: # batch_cost += rho * np.sum([np.sum(param**2) \ #for param in self.treelstm.params]) #L2 print("GOLDEN : {}".format(Counter(correct_list))) print("PRED : {}".format(Counter(pred_list))) print("Batch {} cost: {} accuracy: {:.3f}%".format(batch_num, batch_cost,float(correct)*100/batch_size)) self.treelstm.update(batch_size) #reset batch_num += 1 batch_cost = 0.0 correct =0 correct_list = [] pred_list = [] # def validate(self): # """ # param_file in constructor must be assigned! # """ # print("Validating...") # pred_list = [] # correct_num = 0 # sentence_iterator = self.mgr.sentence_iterator() # for i ,sentence in enumerate(sentence_iterator): # _,pred = self.treelstm.forward_pass(sentence,self.label_list[i]).sum() # pred_list.append(pred) # if np.argmax(pred) == label_list[i]: # correct_num += 1 # print("Accuracy {:.3f} ({}/{})".format(float(correct_num/self.num_samples),correct_num,self.num_samples)) # print(Counter(label_list)) # print(Counter(pred_list)) def main(): learner = Learner(SENTENCE_FILE,DESCRIPT_FILE,LABEL_FILE) learner.mini_batch_train(100) # validationer = Learner(DEV_SENTENCE_FILE,DEV_DESCRIPT_FILE,DEV_LABEL_FILE) # validationer.validate() if __name__ == "__main__": main()
{"/Learner.py": ["/TreeMgr.py"], "/TreeMgr.py": ["/Tree.py"]}
75,190
AniviaPlayer/TreeLSTM
refs/heads/master
/TreeMgr.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File:TreeMgr.py Author: sunprinceS (TonyHsu) Email: sunprince12014@gmail.com Description: """ from util import * from Tree import Tree class TreeMgr(object): def __init__(self,sentence_file,descript_file): self.vocab_dict = io.loadVocabDict() self.glove_matrix = io.loadGloveVec() self.sentence_tree_map={} # sentence file and descript_file must be in the same order self.sentence_list=[] self.word_seq_list=[] self.description_list=[] with open(sentence_file,'r') as sentences: for sentence in sentences.readlines(): sentence = sentence.rstrip() self.sentence_list.append(sentence) self.word_seq_list.append(sentence.split(' ')) with open(descript_file,'r') as descriptions: for description in descriptions.readlines(): description = description.rstrip() self.description_list.append(list(map(int,description.split(' ')))) assert(len(self.sentence_list) == len(self.description_list)) for sentence,word_seq,description in zip(self.sentence_list,self.word_seq_list,self.description_list): self.sentence_tree_map[sentence] = Tree(word_seq,description) def get_num_sample(self): return len(self.sentence_list) def get_tree(self,sentence): # print(self.sentence_tree_map[sentence].node_list) return self.sentence_tree_map[sentence] def get_glove_vec(self,word): if word in self.vocab_dict: return self.glove_matrix[self.vocab_dict[word]] else: return self.glove_matrix[-1] def sentence_iterator(self): for sentence in self.sentence_list: yield sentence # def tree_iterator(self): # for tree in self.trees: # yield tree # def get_word_index(self,word): # try: # return self.vocab_list.index(word) # except: # return -1 # def get_word_indices(self,word_list): # return tuple([self.get_word_index(word) for word in word_list]) def get_tree_stack(self,sentence): """ return a node list """ # print(len(self.sentence_tree_map[sentence].traversal)) return self.sentence_tree_map[sentence].traversal_list def main(): treeMgr = TreeMgr("data/sents.txt","data/cparents.txt") for sentence in treeMgr.sentence_iterator(): # print(sentence) print(treeMgr.get_tree(sentence).traversal_list) if __name__ == "__main__": main()
{"/Learner.py": ["/TreeMgr.py"], "/TreeMgr.py": ["/Tree.py"]}
75,191
AniviaPlayer/TreeLSTM
refs/heads/master
/TreeLSTM_no_graph.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: treelstm.py Author: sunprinceS (TonyHsu) Email: sunprince12014@gmail.com Description: TreeLSTM """ import numpy as np import theano import theano.tensor as T from theano.tensor.nnet import softmax,sigmoid,categorical_crossentropy class TreeLSTM(object): def __init__(self,mgr,rng,mem_dim,in_dim,param_file=None,num_classes=3,inner_activation=sigmoid,outer_activation=sigmoid): """ mgr rng : random state param_file : param file activation : non-linear function """ self.mgr=mgr self.mem_dim = mem_dim self.in_dim = in_dim self.num_classes = num_classes self.inner_activation = inner_activation self.outer_activation = outer_activation ##Setting params in treeLSTM if param_file == None: self.bi = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,)),dtype=theano.config.floatX),name="bi",borrow=True) self.bf = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,)),dtype=theano.config.floatX),name="bf",borrow=True) self.bo = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,)),dtype=theano.config.floatX),name="bo",borrow=True) self.bu = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,)),dtype=theano.config.floatX),name="bu",borrow=True) self.bs = theano.shared(value=np.asarray( rng.uniform(size=(self.num_classes,)),dtype=theano.config.floatX),name="bs",borrow=True) self.Wi = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,in_dim)),dtype=theano.config.floatX),name="Wi",borrow=True) self.Wf = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,in_dim)),dtype=theano.config.floatX),name="Wf",borrow=True) self.Wo = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,in_dim)),dtype=theano.config.floatX),name="Wo",borrow=True) self.Wu = theano.shared(value=np.asarray( rng.uniform(size=(self.mem_dim,in_dim)),dtype=theano.config.floatX),name="Wu",borrow=True) self.Ws = theano.shared(value=np.asarray(rng.uniform(size=( self.num_classes,self.mem_dim)),dtype=theano.config.floatX),name="Ws",borrow=True) self.Ui_R = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Ui_R",borrow=True) self.Ui_L = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Ui_L",borrow=True) self.Uf_R = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Uf_R",borrow=True) self.Uf_L = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Uf_L",borrow=True) self.Uo_R = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Uo_R",borrow=True) self.Uo_L = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Uo_L",borrow=True) self.Uu_R = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Uu_R",borrow=True) self.Uu_L = theano.shared(value=np.asarray(rng.uniform(size=( self.mem_dim,self.mem_dim)),dtype=theano.config.floatX),name="Uu_L",borrow=True) else: self.load_param(param_file) self.lamda_const = 0.01 self.params= [self.Wi,self.Wf,self.Wo,self.Wu,self.Ws, self.bi,self.bf,self.bo,self.bu,self.bs, self.Ui_R,self.Uf_R,self.Uo_R,self.Uu_R, self.Ui_L,self.Uf_L,self.Uo_L,self.Uu_L] hl = T.dvector('hl') hr = T.dvector('hr') cr = T.dvector('cr') cl = T.dvector('cl') x = T.dvector('x') pred = T.dmatrix('pred') golden = T.dmatrix('golden') c = T.dvector('c') p = T.dvector('p') self.param_error = self.lamda_const *((self.Wi**2).sum() + (self.Wf**2).sum() + (self.Wo**2).sum() + (self.Wu**2).sum() + (self.Ws**2).sum() + (self.bi**2).sum() + (self.bf**2).sum() + (self.bo**2).sum() + (self.bu**2).sum() + (self.bs**2).sum() + (self.Ui_R**2).sum() + (self.Uf_R**2).sum() + (self.Uo_R**2).sum() + (self.Uu_R**2).sum() + (self.Ui_L**2).sum() + (self.Uf_L**2).sum() + (self.Uo_L**2).sum() + (self.Uu_L**2).sum()) self.composer_i = theano.function([hr,hl], self.inner_activation(T.dot(self.Ui_R,hr) + T.dot(self.Ui_L,hl) + self.bi)) self.composer_f = theano.function([hr,hl], self.inner_activation(T.dot(self.Uf_R,hr) + T.dot(self.Uf_L,hl) + self.bf)) self.composer_o = theano.function([hr,hl], self.inner_activation(T.dot(self.Uo_R,hr) + T.dot(self.Uo_L,hl) + self.bo)) self.composer_u = theano.function([hr,hl], self.outer_activation(T.dot(self.Uu_R,hr) + T.dot(self.Uu_L,hl) + self.bu)) self.leaf_i = theano.function([x],self.inner_activation(T.dot(self.Wi,x) + self.bi)) self.leaf_f = theano.function([x],self.inner_activation(T.dot(self.Wf,x) + self.bf)) self.leaf_o = theano.function([x],self.inner_activation(T.dot(self.Wo,x) + self.bo)) self.leaf_u = theano.function([x],self.outer_activation(T.dot(self.Wu,x) + self.bu)) self.get_tanh = theano.function([c],self.outer_activation(c)) self.combine_c = theano.function([cr,cl],cr + cl) # can define different method self.cost_func = theano.function([golden,pred],(pred * T.log(golden)).sum() * -1.0) self.softmax = theano.function([p],T.transpose(softmax(T.dot(self.Ws,p) + self.bs))) def forward_pass(self,sentence,label): """ Given sentence, forward pass """ inpt_tree = self.mgr.get_tree(sentence) golden = label one_hot_golden = np.ones(shape=(self.num_classes,1))*1e-9 one_hot_golden[golden] = 1 stack = self.mgr.get_tree_stack(sentence) node_hidden = [np.zeros(shape=self.mem_dim)] * (len(stack) + 1) node_c = [np.zeros(shape=self.mem_dim)] * ( len(stack) + 1) #level-order traversal for node in stack: if node.is_leaf(): # print(node.word) x = self.mgr.get_glove_vec(node.word) node_c[node.idx] = self.leaf_i(x) * self.leaf_u(x) node_hidden[node.idx] = node_c[node.idx]*self.get_tanh(node_c[node.idx]) # node_hidden[node.idx] = self.leaf_o(x) * self.outer_activation(node_c[node.idx]) # node_hidden[node.idx] = self.leaf_o(node_c[node.idx]) # print(node_c[node.idx]) # print(node_hidden[node.idx]) else: child_l,child_r = node.get_child() node_c[node.idx]=((self.composer_i(node_hidden[child_r.idx],node_hidden[child_l.idx])* self.composer_u(node_hidden[child_r.idx],node_hidden[child_l.idx]))+ (self.composer_f(node_hidden[child_r.idx],node_hidden[child_l.idx]) * self.combine_c(node_c[child_r.idx],node_c[child_l.idx]))) node_hidden[node.idx]=(self.composer_o(node_hidden[child_r.idx], node_hidden[child_l.idx])*self.get_tanh(node_c[node.idx])) # node_c[node.idx]=((self.composer_i(node_c[child_r.idx],node_c[child_l.idx])* # self.composer_u(node_c[child_r.idx],node_c[child_l.idx]))+ # (self.composer_f(node_c[child_r.idx],node_c[child_l.idx]) * # self.combine_c(node_c[child_r.idx],node_c[child_l.idx]))) # node_hidden[node.idx]=(self.composer_o(node_c[child_r.idx],node_c[child_l.idx])) #apply softmax pred = self.softmax(node_hidden[inpt_tree.root.idx]) # print("pred:{} \n golden:{}".format(pred,one_hot_golden)) # pred = self.softmax(node_c[inpt_tree.root.idx]) self.error = categorical_crossentropy(one_hot_golden,pred) + self.param_error # print(self.error) return self.error,pred if __name__ == "__main__": pass
{"/Learner.py": ["/TreeMgr.py"], "/TreeMgr.py": ["/Tree.py"]}
75,192
AniviaPlayer/TreeLSTM
refs/heads/master
/util/io.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: io.py Author: sunprinceS (TonyHsu) Email: sunprince12014@gmail.com Description: """ import joblib as jl import numpy as np def loadLabel(file_name): with open(file_name) as label_file: labels = [] for label in label_file: label = label.rstrip() labels.append(label) return labels def loadVocabDict(): vocab_dict={} with open('glove/vocab.txt') as vocab_file: vocab_data = vocab_file.read().splitlines() for line_no,vocab in enumerate(vocab_data): vocab_dict[vocab] = line_no return vocab_dict def loadGloveVec(): glove_matrix = jl.load('glove/glove.840B.float32.emb') oov_vec = np.mean(glove_matrix,axis=0) glove_matrix = np.vstack([glove_matrix,oov_vec]) return glove_matrix def main(): glove_mat =loadGloveVec() if __name__ == "__main__": main()
{"/Learner.py": ["/TreeMgr.py"], "/TreeMgr.py": ["/Tree.py"]}
75,193
AniviaPlayer/TreeLSTM
refs/heads/master
/Tree.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: Tree.py Author: sunprinceS (TonyHsu) Email: sunprince12014@gmail.com Description: """ from __future__ import print_function import sys class Node(object): def __init__(self,word="",idx=None): self.word = word self.r_child = None self.l_child = None self.idx= idx def __repr__(self): return self.word def get_num_child(self): if self.l_child is None : assert(self.r_child is None) return 2-[self.r_child,self.l_child].count(None) def is_leaf(self): return (self.get_num_child() == 0) def get_child(self): return self.l_child,self.r_child class Tree(object): def __init__(self,word_seq,description): """ sentence : [The food is good .] description will like [6 6 8 8 9 7 0 9 7] """ #node_list[0] is dummy self.traversal_list=[] self.node_list = [Node() for i in range(len(description) + 1)]#shouldn't use []*10(s copy) for i in range(1,len(self.node_list)): self.node_list[i].idx = i for i,word in enumerate(word_seq,1): n = Node(word,i) self.node_list[i] = n for i,des in enumerate(description,1): if des == 0: self.root = self.node_list[i] else: n_child = self.node_list[des].get_num_child() if n_child == 1: #left child has been assigned! self.node_list[des].r_child = self.node_list[i] self.node_list[des].word += self.node_list[i].word elif n_child == 0: self.node_list[des].l_child = self.node_list[i] self.node_list[des].word += (self.node_list[i].word + " ") else: print(" i:{} des:{} went wrong".format(i,des),file=sys.stderr) #Do level-order traversal self.level_order_traversal() def level_order_traversal(self): if self.root is None: return list() queue=[] queue.append(self.root) while(len(queue) > 0): node = queue.pop(0) self.traversal_list.append(node) if node.l_child is not None: queue.append(node.l_child) if node.r_child is not None: queue.append(node.r_child) self.traversal_list.reverse() def main(): # word_seq = ["The","noodles","taste","great","*","but","the","service","is","bad","."] # description=[12,12,18,18,14,15,19,19,21,21,17,13,14,15,16,17,0,13,20,16,20] # tree1 = Tree(word_seq,description) # print(tree1.traversal_list) # for i in range(1,len(tree1.node_list)): # print(tree1.node_list[i]) word_seq = ["The","food","is","good","."] description=[6,6,8,8,9,7,0,9,7] tree2 = Tree(word_seq,description) print(tree2.node_list) if __name__ == "__main__": main()
{"/Learner.py": ["/TreeMgr.py"], "/TreeMgr.py": ["/Tree.py"]}
75,194
AniviaPlayer/TreeLSTM
refs/heads/master
/TreeLSTM_np.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: treelstm.py Author: sunprinceS (TonyHsu) Email: sunprince12014@gmail.com Description: TreeLSTM """ import numpy as np import pickle def sigmoid(x): """ x: a numpy array """ return 1 / (1 + np.exp(-x)) def softmax(w): """ w: a numpy array """ # print(w) e = np.exp(w) return (e / np.sum(e)) def cross_entropy(golden,pred): """ golden: a numpy array (one hot) pred: a numpy array """ cost = -np.log(pred[golden]) return cost class TreeLSTM(object): def __init__(self,mgr,rng,mem_dim,in_dim,param_file=None, num_classes=3,inner_activation=sigmoid,outer_activation=np.tanh,lamda=1e-3): """ mgr: TreeMgr rng : random state param_file : param file (json format) activation : non-linear function """ self.mgr = mgr self.rng = rng self.mem_dim = mem_dim self.in_dim = in_dim self.num_classes = num_classes self.inner_activation = inner_activation self.outer_activation = outer_activation self.lamda = lamda self.init_params() if param_file is not None: self.load_params(param_file) print("Modle Initialization finish!") def init_params(self): self.bi = np.zeros(shape=(self.mem_dim,)) self.bf = np.zeros(shape=(self.mem_dim,)) self.bo = np.zeros(shape=(self.mem_dim,)) self.bu = np.zeros(shape=(self.mem_dim,)) self.bs = np.zeros(shape=(self.num_classes,)) self.Wi = self.rng.uniform(size=(self.mem_dim,self.in_dim)) * 0.5 self.Wo = self.rng.uniform(size=(self.mem_dim,self.in_dim)) * 0.5 self.Ws = self.rng.uniform(size=(self.num_classes,self.mem_dim)) * 0.01 self.Ui = self.rng.uniform(size=(self.mem_dim,self.mem_dim * 2)) * 0.05 self.Uf = self.rng.uniform(size=(self.mem_dim,self.mem_dim * 2)) * 0.05 self.Uo = self.rng.uniform(size=(self.mem_dim,self.mem_dim * 2)) * 0.05 self.Uu = self.rng.uniform(size=(self.mem_dim,self.mem_dim * 2)) * 0.01 self.params = [self.Wi,self.Wo,self.Ws, self.bi,self.bf,self.bo,self.bu,self.bs, self.Ui,self.Uf,self.Uo,self.Uu] self.last_params = self.params self.dWi = np.zeros(self.Wi.shape) self.dWs = np.zeros(self.Ws.shape) self.dWo = np.zeros(self.Wo.shape) self.dbi = np.zeros(self.bi.shape) self.dbf = np.zeros(self.bf.shape) self.dbo = np.zeros(self.bo.shape) self.dbu = np.zeros(self.bu.shape) self.dbs = np.zeros(self.bs.shape) self.dUi = np.zeros(self.Ui.shape) self.dUf = np.zeros(self.Uf.shape) self.dUo = np.zeros(self.Uo.shape) self.dUu = np.zeros(self.Uu.shape) self.grads = [self.dWi,self.dWo,self.dWs, self.dbi,self.dbf,self.dbo,self.dbu,self.dbs, self.dUi,self.dUf,self.dUo,self.dUu] # self.last_grads = self.grads ########## # Gate # ########## def composer_i(self,h): return self.inner_activation(np.dot(self.Ui,h) + self.bi) def composer_f(self,h): return self.inner_activation(np.dot(self.Uf,h) + self.bf) def composer_o(self,h): return self.inner_activation(np.dot(self.Uo,h) + self.bo) def composer_u(self,h): return self.outer_activation(np.dot(self.Uu,h) + self.bu) def leaf_i(self,x): return self.inner_activation(np.dot(self.Wi,x) + self.bi) def leaf_o(self,x): return self.inner_activation(np.dot(self.Wo,x) + self.bo) def combine_c(self,cr,cl): #can define combine method return cr + cl def output_root(self,h): # print(h) # print(self.Ws) return softmax(np.dot(self.Ws,h) + self.bs) ######### # I/O # ######### def load_params(self,param_file): self.params = pickle.load(param_file) def save_params(self,param_file): pickle.dump(self.params) def forward_pass(self,sentence,label): inpt_tree = self.mgr.get_tree(sentence) golden = label # one_hot_golden = np.ones(shape=(self.num_classes,1))*1e-9 # one_hot_golden[golden] = 1 self.forward_pass_node(inpt_tree.root) pred = self.output_root(inpt_tree.root.h) cost = cross_entropy(golden,pred) return np.argmax(pred),cost,pred def forward_pass_node(self,node,test=False): if node.is_leaf(): x = self.mgr.get_glove_vec(node.word) node.c = self.leaf_i(x) node.o = self.leaf_o(x) node.h = node.o * self.outer_activation(node.c) # print(node.h) else: self.forward_pass_node(node.l_child,test) self.forward_pass_node(node.r_child,test) l_child,r_child = node.get_child() children = np.hstack((l_child.h,r_child.h)) node.i = self.composer_i(children) node.f = self.composer_f(children) node.o = self.composer_o(children) node.u = self.composer_u(children) node.c = node.i * node.u + node.f * self.combine_c(l_child.c,r_child.c) node.h = node.o * self.outer_activation(node.c) def back_prop(self,pred,sentence,label): inpt_tree = self.mgr.get_tree(sentence) deltas = pred[int(label)] - 1.0 self.dWs += np.outer(deltas,inpt_tree.root.h) self.dbs += deltas self.back_prop_node(inpt_tree.root,deltas) def back_prop_node(self,node,epsH,epsC=None): epsO = epsH * self.outer_activation(node.c) * node.o * (1-node.o) if epsC is None: epsC = epsH * node.o * (1-(self.outer_activation(node.c) ** 2)) else: epsC += epsH * node.o * (1-(self.outer_activation(node.c) ** 2)) if node.is_leaf(): x = self.mgr.get_glove_vec(node.word) self.dWo += np.outer(epsO,x) self.dbo += epsO self.dWi += np.outer(epsC,x) self.dbi += epsC else: l_child,r_child = node.get_child() childs_h = np.hstack((l_child.h,r_child.h)) self.dUo += np.outer(epsO,childs_h) self.dbo += epsO epsI = epsC * node.u * node.i * (1-node.i) self.dbi += epsI self.dUi += np.outer(epsI,childs_h) epsU = epsC * node.i * (1-(self.outer_activation(node.u) ** 2)) self.dbu += epsU self.dUu += np.outer(epsU,childs_h) epsF = epsC * self.combine_c(l_child.c,r_child.c) * node.f * (1 - node.f) self.dbf = epsF self.dUf = np.outer(epsF,childs_h) epsH = epsO.dot(self.Uo) + epsI.dot(self.Ui) + epsU.dot(self.Uu) + epsF.dot(self.Uf) epsC *= node.f self.back_prop_node(l_child,epsH[:self.mem_dim],epsC) self.back_prop_node(r_child,epsH[self.mem_dim:],epsC) def update(self,scale): # for dP in self.grads: # self.grads = [self.dWi,self.dWo,self.dWs, # self.dbi,self.dbf,self.dbo,self.dbu,self.dbs, # self.dUi,self.dUf,self.dUo,self.dUu] self.params = [P + 1e-1 * (dP/scale) for P,dP in zip(self.params,self.grads)] self.Wi,self.Wo,self.Ws,\ self.bi,self.bf,self.bo,self.bu,self.bs,\ self.Ui,self.Uf,self.Uo,self.Uu = self.params # for p1,p2 in zip(self.params,self.last_params): # print((self.params[1]-self.last_params[1])**2) # print((self.grads[2]) == self.last_grads[2]) # print(self.grads[2] == self.dWs) self.resetgrads() def resetgrads(self): # self.last_params = self.params # self.last_grads = self.grads self.dWi[:] = 0 self.dWs[:] = 0 self.dWo[:] = 0 self.dbi[:] = 0 self.dbf[:] = 0 self.dbo[:] = 0 self.dbu[:] = 0 self.dbs[:] = 0 self.dUi[:] = 0 self.dUf[:] = 0 self.dUo[:] = 0 self.dUu[:] = 0 if __name__ == "__main__": pass
{"/Learner.py": ["/TreeMgr.py"], "/TreeMgr.py": ["/Tree.py"]}
75,195
pemj/mtgimpl
refs/heads/master
/mtg_helpers.py
from mtg_card import * import random import collections # returns 0 on successful damage def dealDamage(source, target, amount): try: target.damage += amount return 0 except AttributeError: print("target no longer valid") return 1 except NameError: print("target no longer valid") return 1 except ReferenceError: print("target no longer valid") return 1 # using a double-ended queue, because there is no (idiomatic) way to # append to the left of an arraylist. class Library: def __init__(self): self.cards = collections.deque() def addToDeck(self, card): if(self.cards.count(card) < 4) or ("Basic" in card.supertype): self.cards.append(card) else: print("Only 4 copies of any card that is not a basic land") def placeCardOnTop(self, card): self.cards.append(card) def placeCardOnBot(self, card): self.cards.appendleft(card) def shuffle(self): random.shuffle(self.cards) class Graveyard(): def __init__(self): self.cards = collections.deque() def placeCardOnTop(self, card): self.cards.append(card) discard = placeCardOnTop def placeCardOnBot(self, card): self.cards.appendleft(card) def shuffle(self): random.shuffle(self.cards) class Hand(): def __init__(self): self.cards = [] self.size= 7 # right in the rulebook class Field(): def __init__(self): self.things = {lands: []}
{"/mtg_helpers.py": ["/mtg_card.py"], "/mtg_game.py": ["/mtg_card.py"], "/mtg_card.py": ["/mtg_helpers.py"]}
75,196
pemj/mtgimpl
refs/heads/master
/mtg_game.py
from mtg_card import * def makeBoard(p1, p2): board = Board("commander") azami = Card("Azami: Lady of Scrolls", [SuperTyp.legend], [Typ.creature], ["Wizard", "Human"], [Color.colorless, Color.colorless, Color.blue, Color.blue, Color.blue], "no other azamis", [Color.blue], [Color.blue], "Tap an untapped Wizard you control: Draw a card.", "", "") heidar = Card("Heidar, Rimewind Master", [SuperTyp.legend], [Typ.creature], ["Wizard", "Human"], [Color.colorless, Color.colorless, Color.colorless, Color.colorless, Color.blue], "no other Heidars", [Color.blue], [Color.blue], "Tap: Return target permanent to its owner's hand. Activate this ability only if you control four or more snow permanents.", "", "") player1 = Player(board, p1, [], [], azami) player2 = Player(board, p2, [], [], heidar) return board
{"/mtg_helpers.py": ["/mtg_card.py"], "/mtg_game.py": ["/mtg_card.py"], "/mtg_card.py": ["/mtg_helpers.py"]}
75,197
pemj/mtgimpl
refs/heads/master
/mtg_card.py
from mtg_helpers import * from enum import Enum class SuperTyp(Enum): legend = 0 basic = 1 snow = 2 ongoing = 3 world = 4 class Typ(Enum): instant = 0 sorcery = 1 planeswalker = 2 land = 3 artifact = 4 creature = 5 enchantment = 6 tribal = 7 class Color(Enum): red = 0 blue = 1 green = 2 white = 3 black = 4 colorless = 5 class Phase(Enum): untap = 0 upkeep = 1 draw = 2 precombat_main = 3 combat = 4 postcombat_main = 5 end = 6 class GameType(Enum): modern = 0 commander = 1 standard = 2 pauper = 3 vintage = 4 two_headed_giant = 5 #this one may have to wait #A zone should have a name and some items (cards, tokens, permanents, etc. class Zone: """A zone of play""" def __init__(self, name): self.name = name self.tenants = [] def add(self, item): self.tenants.append(item) item.zone = self class Board: def __init__(self, gametype): self.players = [] self.gametype = GameType[gametype] self.stack = [] self.turn = 1 self.phase = Phase.untap def addPlayers(self, *args): for arg in args: self.players.append(arg) class Player: """A player""" def __init__(self, board, name, hand, library, commander): # fill this with a default card? make optional when I remember this self.name = name self.poison_counters = 0 self.commandzone = Zone("command") if board.gametype == GameType.commander: self.commandzone.add(commander) commander.zone = self.commandzone self.hand = hand self.library = library self.graveyard = [] board.players.append(self) class Card: """A card""" def __init__(self, name, supertypes, types, subtypes, cost, constraints, color, color_identity, text, owner, zone): self.name = "" self.supertypes = supertypes self.typ = types self.subtyp = subtypes self.cost = cost self.constraints = constraints self.color = color self.color_identity = color_identity self.text = text self.owner = owner self.zone = zone def makePermanent(self, newZone, controller, time_counters, fading_counters, loyalty_counters, static_abilities, activated_abilities, triggered_abilities, tap_status, targets, power, toughness, pt_counters, summoning_sickness): return Permanent(self, newZone, controller, time_counters, fading_counters, loyalty_counters, static_abilities, activated_abilities, triggered_abilities, tap_status, targets, power, toughness, pt_counters, summoning_sickness) def makeSpell(self, newZone, controller, originality, targets, effects): return Spell(self, self.zone, newZone, controller, originality, targets, effects) class Spell(Card): """A spell""" def __init__(self, card, newZone, controller, originality, targets, effects): super(Spell, self).__init__(card.name, card.supertypes, card.types, card.subtypes, card.cost, card.constraints, card.color, card.color_identity, card.text, card.owner, newZone) self.controller = controller self.originality = originality self.targets = targets self.effects = effects class Permanent(Card): """A card""" def __init__(self, card, newZone, controller, time_counters, fading_counters, static_abilities, activated_abilities, triggered_abilities, tap_status, targets, power, toughness, pt_counters, loyalty_counters, summoning_sickness): super(Permanent, self).__init__(card.name, card.types, card.subtypes, card.cost, card.constraints, card.color, card.color_identity, card.text, card.owner, card.zone) self.controller = controller self.time_counters = time_counters self.fading_counters = fading_counters self.loyalty_counters = loyalty_counters self.static_abilities = static_abilities self.activated_abilities = activated_abilities self.triggered_abilities = triggered_abilities self.tap_status = tap_status self.targets = targets self.power = power self.toughness = toughness self.pt_counters = pt_counters self.damage = 0 self.summoning_sickness = summoning_sickness #ppython has multiple inheritance, but we'd have to redefine permanents every time they change state, and that sounds like a pain. #we have permanents, and permanents may be of any permanent type. they always have power and toughness, but they don't matter if it's not a creature.
{"/mtg_helpers.py": ["/mtg_card.py"], "/mtg_game.py": ["/mtg_card.py"], "/mtg_card.py": ["/mtg_helpers.py"]}
75,199
Rasvin-7/python-selenium
refs/heads/master
/Utils/TestUtils.py
import openpyxl from openpyxl import load_workbook class TestUtils: login = "Login" workbook = load_workbook("C:/Users/developer/PycharmProjects/SeleniumPytest/Utils/OrangeHRM TestData.xlsx") def getMaxRow(self): sheet = self.workbook[self.login] return sheet.max_row def getMaxCol(self): sheet = self.workbook[self.login] return sheet.max_column def getData(self): sheet = self.workbook[self.login] cell = [] cell1 = () data1 = [] rows = self.getMaxRow() cols = self.getMaxCol() # for row in sheet.iter_rows(): # for cellv in row: # cell.append(cellv.value) # data1.append(tuple(cell)) # cell.clear() # print(data1) for row in range(2, rows + 1): for col in range(1, cols + 1): data = sheet.cell(row, col).value print(data, "\n") cell.append(data) cell1 = tuple(cell) cell.clear() print(cell1, "\n") data1.append(cell1) return data1 tu = TestUtils() val = tu.getData() print(val)
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,200
Rasvin-7/python-selenium
refs/heads/master
/Configs/configs.py
class Config: # Application URL URL = "https://opensource-demo.orangehrmlive.com/" # Driver Paths chrome_path = "C:/Users/developer/PycharmProjects/SeleniumPytest/Drivers/chromedriver.exe" # chrome_path = "./Driver/chromedriver.exe" firefox_path = "C:/Users/developer/PycharmProjects/SeleniumPytest/Drivers/geckodriver.exe"
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,201
Rasvin-7/python-selenium
refs/heads/master
/Pages/Dashboard.py
from time import sleep from selenium.webdriver.common.by import By from Pages.PageBase import PageBase from selenium.webdriver.common.action_chains import ActionChains from selenium import webdriver from Pages.Users import UsersPage # driver1 = webdriver.Chrome() # driver1.find_element_by_xpath() class Dashboard(PageBase): welcome_link = "//a[@id='welcome']" logout_link = "div:nth-child(1) div.panelContainer:nth-child(15) ul:nth-child(1) li:nth-child(3) > a:nth-child(1)" admin_menu = "//b[contains(text(),'Admin')]" user_mgnt = "//a[@id='menu_admin_UserManagement']" users = "//a[@id='menu_admin_viewSystemUsers']" def __init__(self, driver): self.driver = driver def navigate_to_users(self): action = ActionChains(self.driver) admin = self.driver.find_element_by_xpath(self.admin_menu) umt = self.driver.find_element_by_xpath(self.user_mgnt) user = self.driver.find_element_by_xpath(self.users) action.move_to_element(admin).move_to_element(umt).perform() action.move_to_element(user).click().perform() return UsersPage(self.driver) def logout(self): wel = self.driver.find_element_by_xpath(self.welcome_link) wel.click() # logout = self.driver.find_element_by_xpath(self.logout_link) # logout.click() Log = self.driver.find_element_by_css_selector(self.logout_link) action = ActionChains(self.driver) action.move_to_element(wel).perform() sleep(2) action.move_to_element(Log).perform() Log.click() def check_welcome(self): pb = PageBase(self.driver) return pb.check_elem(self.welcome_link)
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,202
Rasvin-7/python-selenium
refs/heads/master
/Testcases/test_Login.py
import sys from contextlib import suppress from random import random from time import sleep import pytest from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from Configs.configs import Config from Pages.Dashboard import Dashboard from Pages.LoginPage import LoginPage from Pages.Users import UsersPage from Testcases.TestBase import * import allure from Utils.TestUtils import TestUtils # tu = TestUtils() # creds = tu.getData() class Test_Login(TestBase): tu = TestUtils() creds = tu.getData() @allure.severity(severity_level="Blocker") @allure.description("Login Test") @pytest.mark.parametrize("admin,password", argvalues=creds) def test_01_login(self, admin, password): lp = LoginPage(self.driver) Db = Dashboard(self.driver) lp.login(admin, password) sleep(5) try: title = lp.get_page_title() assert title == "OrangeHRM", "Title Not Equal" Db.logout() sleep(5) except Exception: pass # @allure.severity(severity_level="Normal") # @allure.description("Check Users Page") # def test_02_check_users_page(self): # lp = LoginPage(self.driver) # Db = Dashboard(self.driver) # lp.login("Admin", "admin123") # user_ob = Db.navigate_to_users() # user_ob.click_add_user() # sleep(5)
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,203
Rasvin-7/python-selenium
refs/heads/master
/Testcases/TestBase.py
import pytest from pytest import * from selenium import webdriver from Configs import configs from Configs.configs import Config # driver = webdriver.Chrome() @pytest.fixture(scope="class") def init_driver(request): global driver1 driver1 = webdriver.Chrome(executable_path=Config.chrome_path) driver1.get(Config.URL) request.cls.driver = driver1 yield driver1.quit() @pytest.mark.usefixtures("init_driver") class TestBase: pass
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,204
Rasvin-7/python-selenium
refs/heads/master
/Pages/Users.py
from selenium.webdriver.common.by import By from Pages.PageBase import PageBase class UsersPage(PageBase): add_user_button = "//input[@id='btnAdd']" def __init__(self, driver): self.driver = driver def click_add_user(self): pb = PageBase(self.driver) pb.click_on(self.add_user_button)
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,205
Rasvin-7/python-selenium
refs/heads/master
/Pages/PageBase.py
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as ec class PageBase: # driver = webdriver.Chrome() # # driver.find_element_by_xpath().send_keys() def __init__(self, driver): self.driver = driver def enter_text(self, locator, text): elem = self.driver.find_element_by_xpath(locator) elem.clear() elem.send_keys(text) def click_on(self, locator): elem = self.driver.find_element_by_xpath(locator) elem.click() def get_page_title(self): return self.driver.title def select_dropdown(self, locator, text): elem = self.driver.find_element_by_xpath(locator) select = Select(elem) select.select_by_visible_text(text) def check_elem(self, locator): wait = WebDriverWait(self.driver, 5) elem = self.driver.find_element_by_xpath(locator) elem1 = wait.until(ec.visibility_of_element_located(elem)) if elem1: return True else: return False def get_text(self, locator): text = self.driver.find_element_by_xpath(locator).text return text
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,206
Rasvin-7/python-selenium
refs/heads/master
/Pages/LoginPage.py
from Pages.PageBase import PageBase class LoginPage(PageBase): username_xpath = "//input[@id='txtUsername']" password_xpath = "//input[@id='txtPassword']" loginbtn_xpath = "//input[@id='btnLogin']" invalid_text = "//span[@id='spanMessage']" def __init__(self, driver): self.driver = driver def login(self, username, password): base = PageBase(self.driver) base.enter_text(self.username_xpath, username) base.enter_text(self.password_xpath, password) base.click_on(self.loginbtn_xpath) def check_reason(self): base = PageBase(self.driver) base.check_elem(self.invalid_text) text = base.get_text() return text
{"/Pages/Dashboard.py": ["/Pages/PageBase.py", "/Pages/Users.py"], "/Testcases/test_Login.py": ["/Configs/configs.py", "/Pages/Dashboard.py", "/Pages/LoginPage.py", "/Pages/Users.py", "/Testcases/TestBase.py", "/Utils/TestUtils.py"], "/Testcases/TestBase.py": ["/Configs/configs.py"], "/Pages/Users.py": ["/Pages/PageBase.py"], "/Pages/LoginPage.py": ["/Pages/PageBase.py"]}
75,213
Ethik-69/Neural-Network
refs/heads/master
/cell.py
#! /usr/bin/python # -*- coding: utf-8 -*- import sys import random import constants from network import * try: import pygame from pygame.locals import * except ImportError, errmsg: print('Requires PyGame') print(errmsg) sys.exit(1) class ParentCell(object): def __init__(self, grid, n_inputs, n_hidden, n_outputs, color): self.x = 0 self.y = 0 self.random_pos(grid) self.color = color self.alive = True self.feeding = 0 # fitness self.sensor = [0, 0] self.sensor_range = 1 self.view_sensors = False self.brain = None self.num_update = 0 self.error = 0.0 self.n_inputs = n_inputs self.n_hidden = n_hidden self.n_outputs = n_outputs self.create_brain() self.genome_in = self.brain.weights_inputs self.genome_out = self.brain.weights_outputs def init(self, grid): """ Put back all data to the default values """ self.x = 0 self.y = 0 self.feeding = 0 self.random_pos(grid) self.alive = True self.sensor = [0, 0] def create_brain(self): """ Create brain (Neural Network)""" self.brain = Network(self.n_inputs, self.n_hidden, self.n_outputs, True) def random_pos(self, grid): """ Select a random position """ randm = True while randm: self.x = random.randint(0, int(constants.width - 1)) self.y = random.randint(0, int(constants.width - 1)) if grid.grid[self.x][self.y] == 0: randm = False def move(self): """ Move the cell according to the network outputs """ # print(self.brain.array_output) [up, right, down, left] if self.brain.array_output[0] > 0.5: self.y -= 1 if self.y < 0: self.y = constants.height - 1 if self.brain.array_output[1] > 0.5: self.x += 1 if self.x > constants.width - 1: self.x = 0 if self.brain.array_output[2] > 0.5: self.y += 1 if self.y > constants.height - 1: self.y = 0 if self.brain.array_output[3] > 0.5: self.x -= 1 if self.x < 0: self.x = constants.width - 1 class Cell(ParentCell): def __init__(self, grid, n_inputs, n_hidden, n_outputs, color): ParentCell.__init__(self, grid, n_inputs, n_hidden, n_outputs, color) def capture(self, grid): """ Detect the nearest grid cell with food in it """ self.sensor_range = 1 self.sensor = [0, 0] sensor_on = True while sensor_on: x_range = [x for x in range(self.x - self.sensor_range, self.x + self.sensor_range)] y_range = [x for x in range(self.y - self.sensor_range, self.y + self.sensor_range)] for i, item in enumerate(x_range): if x_range[i] < 0: x_range[i] = constants.width + x_range[i] elif x_range[i] > constants.width: x_range[i] = x_range[i] - constants.width for i, item in enumerate(y_range): if y_range[i] < 0: y_range[i] = constants.height + y_range[i] elif y_range[i] > constants.height: y_range[i] = y_range[i] - constants.height for i, x in enumerate(x_range): for i, y in enumerate(y_range): try: if grid[x][y] == 1: self.sensor = [x, y] elif self.view_sensors: grid[x][y] = 3 # Pour "voir" les senseurs except: pass if self.sensor == [0, 0] and self.sensor_range < constants.sensor_limit: self.sensor_range += 1 else: sensor_on = False # "traduit" la position de la nourriture pour le reseau de neurones self.sensor = [(float(self.sensor[0] - self.x))/10, (float(self.sensor[1] - self.y))/10] # self.sensor = [self.sensor[0] - self.x, self.sensor[1] - self.y] def eat(self, grid): """ If the cell is on food, 'eat' it """ if grid.grid[self.x][self.y] == 1 or grid.grid[self.x][self.y] == 2: grid.grid[self.x][self.y] = 0 self.feeding += 1 def update(self, grid): """ Update the cell """ self.num_update += 1 self.capture(grid.grid) self.brain.update(self.sensor) # Back Propagation targets = [0.4, 0.4, 0.4, 0.4] if self.sensor == [0, 0]: pass else: if self.sensor[0] < 0: targets[1] = 0.4 targets[3] = 0.6 elif self.sensor[0] > 0: targets[1] = 0.6 targets[3] = 0.4 if self.sensor[1] < 0: targets[0] = 0.6 targets[2] = 0.4 elif self.sensor[1] > 0: targets[0] = 0.4 targets[2] = 0.6 self.error = 0.0 self.error = self.brain.back_propagate(targets) # ---------------------- grid.grid[self.x][self.y] = 0 self.move() self.eat(grid) grid.grid[self.x][self.y] = self class EvilCell(ParentCell): def __init__(self, grid, n_inputs, n_hidden, n_outputs, color): ParentCell.__init__(self, grid, n_inputs, n_hidden, n_outputs, color) def capture(self, grid): """ Detect the nearest grid cell with food in it """ self.sensor_range = 1 self.sensor = [0, 0] sensor_on = True while sensor_on: x_range = [x for x in range(self.x - self.sensor_range, self.x + self.sensor_range)] y_range = [x for x in range(self.y - self.sensor_range, self.y + self.sensor_range)] for i, item in enumerate(x_range): if x_range[i] < 0: x_range[i] = constants.width + x_range[i] elif x_range[i] > constants.width: x_range[i] = x_range[i] - constants.width for i, item in enumerate(y_range): if y_range[i] < 0: y_range[i] = constants.height + y_range[i] elif y_range[i] > constants.height: y_range[i] = y_range[i] - constants.height for i, x in enumerate(x_range): for i, y in enumerate(y_range): try: if isinstance(grid[x][y], Cell): self.sensor = [x, y] elif self.view_sensors and grid[x][y] != 1: grid[x][y] = 4 # Pour "voir" les senseurs except: pass if self.sensor == [0, 0] and self.sensor_range < constants.bad_sensor_limit: self.sensor_range += 1 else: sensor_on = False # "traduit" la position de la nourriture pour le reseau de neurones self.sensor = [(float(self.sensor[0] - self.x))/10, (float(self.sensor[1] - self.y))/10] def eat(self, grid): """ If the cell is on another cell, 'eat' it """ if isinstance(grid.grid[self.x][self.y], Cell): grid.grid[self.x][self.y].alive = False self.feeding += 1 def update(self, grid): """ Update the cell """ self.num_update += 1 self.capture(grid.grid) self.brain.update(self.sensor) # Back Propagation targets = [0.4, 0.4, 0.4, 0.4] if self.sensor == [0, 0]: pass else: if self.sensor[0] < 0: targets[1] = 0.4 targets[3] = 0.6 elif self.sensor[0] > 0: targets[1] = 0.6 targets[3] = 0.4 if self.sensor[1] < 0: targets[0] = 0.6 targets[2] = 0.4 elif self.sensor[1] > 0: targets[0] = 0.4 targets[2] = 0.6 self.error = 0.0 self.error = self.brain.back_propagate(targets) # ---------------------- grid.grid[self.x][self.y] = 0 self.move() self.eat(grid) grid.grid[self.x][self.y] = self
{"/grid.py": ["/constants.py"]}
75,214
Ethik-69/Neural-Network
refs/heads/master
/network.py
#!/usr/bin/env python # -*- coding:utf-8 -*- import math import random import numpy def sigmoid(x): # return math.tanh(x) return 1 / (1 + numpy.exp(- x)) def dsigmoid(y): return 1.0 - y**2 def rand(a, b): return (b - a) * random.random() + a class Network(object): def __init__(self, inputs, hidden, outputs, random_weight=False, weight_in=[], weight_out=[]): # number of input, hidden... self.num_input = inputs + 1 self.num_hidden = hidden self.num_output = outputs self.array_inputs = [1.0] * self.num_input self.array_hidden = [1.0] * self.num_hidden self.array_output = [1.0] * self.num_output self.weights_inputs = weight_in self.weights_outputs = weight_out if random_weight: self.generate_random_weights() self.change_input = [[0.0] * self.num_hidden for i in range(self.num_input)] self.change_output = [[0.0] * self.num_output for i in range(self.num_hidden)] def generate_random_weights(self): # weight self.weights_inputs = [[0.0] * self.num_hidden for i in range(self.num_input)] self.weights_outputs = [[0.0] * self.num_output for i in range(self.num_hidden)] # make it random for i in range(self.num_input): for j in range(self.num_hidden): self.weights_inputs[i][j] = rand(-1.0, 1) for j in range(self.num_hidden): for k in range(self.num_output): self.weights_outputs[j][k] = rand(-1.0, 1) for weight in range(len(self.weights_inputs[len(self.weights_inputs)-1])): self.weights_inputs[len(self.weights_inputs)-1][weight] = -1.0 def update(self, inputs): # inputs = sensors_up, sensors_down..... if len(inputs) != self.num_input - 1: raise ValueError('Wrong number of inputs') for i in range(self.num_input - 1): self.array_inputs[i] = inputs[i] for j in range(self.num_hidden): sum = 0.0 for i in range(self.num_input): sum += self.array_inputs[i] * self.weights_inputs[i][j] self.array_hidden[j] = sigmoid(sum) for k in range(self.num_output): sum = 0.0 for j in range(self.num_hidden): sum += self.array_hidden[j] * self.weights_outputs[j][k] self.array_output[k] = sigmoid(sum) def back_propagate(self, targets, N=0.5, M=0.1): if len(targets) != self.num_output: raise ValueError('wrong number of target values') # calculate error terms for output output_deltas = [0.0] * self.num_output for k in range(self.num_output): # pour chaque neuronnes de sortie error = targets[k] - self.array_output[k] # cible moins sortie actuel output_deltas[k] = dsigmoid(self.array_output[k]) * error # sortie x taux d'erreur # calculate error terms for hidden hidden_deltas = [0.0] * self.num_hidden for j in range(self.num_hidden): # pour chaque neuronnes de la couche actuel error = 0.0 for k in range(self.num_output): # pour chaque neuronnes de la couche précédente error += output_deltas[k] * self.weights_outputs[j][k] # sortie x taux d'erreur de ce neuronnes x weights correspondante hidden_deltas[j] = dsigmoid(self.array_hidden[j]) * error # update output weights for j in range(self.num_hidden): for k in range(self.num_output): change = output_deltas[k] * self.array_hidden[j] self.weights_outputs[j][k] = self.weights_outputs[j][k] + N * change + M * self.change_output[j][k] # N ? M ? self.change_output[j][k] = change # update input weights for i in range(self.num_input): for j in range(self.num_hidden): change = hidden_deltas[j] * self.array_inputs[i] self.weights_inputs[i][j] = self.weights_inputs[i][j] + N * change + M * self.change_input[i][j] self.change_input[i][j] = change # calculate error error = 0.0 for k in range(len(targets)): error += 0.5 * (targets[k] - self.array_output[k]) ** 2 return error if __name__ == '__main__': wi = [[-0.021858447945422327, 0.15219448821928644, 0.06082195473891955, 0.08347288040659018], [0.1909121994812456, 0.16105687191039053, -0.18769546135253634, -0.014766294761266202], [0.1546242895212776, 0.12797293882949273, -0.0036336475923524902, 0.19020235957394455], [-0.12670289813821722, -0.16469072475937652, -0.18832445439002538, 0.0315962797173035], [-1.0, -1.0, -1.0, -1.0]] wo = [[-0.9560856525569337, 1.361885539452147, -0.46025552144298976, -1.9203233473106556], [-0.7744125106477409, 1.6341349615063914, 1.3810698098353176, 1.8758718034680735], [1.6863192074827609, -0.010694900162080412, -0.9888487949707563, 1.7803953355881577], [1.734576801155785, 1.6756635731090488, -0.44186306886283155, 1.2406913611755344]] wi = [[0.26777949697389036, 0.40576637840820373, 0.5561047626915733, 0.9816730819743473], [0.06295111101015927, 0.4803281330036596, 0.41922086503844636, 0.4069755859410127], [0.1920851487859575, 0.4401183663843169, 0.6417338141656637, 0.29451283631081926], [0.7695015057103675, 0.13194202511124686, 0.4126372777161512, 0.9426528527733363], [-1.0, -1.0, -1.0, -1.0]] wo = [[0.9960964261424552, 0.16616383413273628, 0.400849759641964, 1.0786720627410384], [0.27681258227100125, 1.734382340428455, 0.2374133321110985, 0.9292830818672713], [1.2305083837149202, 0.0025727197721989725, 0.21766866303329557, 0.09266162214256624], [1.911732428688653, 0.9937593684843562, 0.87978178789927, 0.9620244995489264]] net = Network(2, 3, 2, True) net.update([0.1, -0.2]) print(net.weights_inputs) print(net.weights_outputs) for neuron in net.weights_outputs: print(neuron) print("output: ") for out in net.array_output: print(round(out), out)
{"/grid.py": ["/constants.py"]}
75,215
Ethik-69/Neural-Network
refs/heads/master
/interface.py
#! /usr/bin/python # -*- coding: utf-8 -*- import constants try: import pygame from pygame import gfxdraw from pygame.locals import * except ImportError, errmsg: print('Requires PyGame') print(errmsg) sys.exit(1) class Interface(object): def __init__(self, window): self.window = window self.cell_to_display = None def draw_arc(self, surface, center, radius, start_angle, stop_angle, color): x,y = center start_angle = int(start_angle%360) stop_angle = int(stop_angle%360) gfxdraw.arc(surface, x, y, radius, start_angle, stop_angle, color) def update(self, mode, view_sensors): pygame.draw.line(self.window, (255, 255, 255), (constants.pixel_size * constants.width, 0), (constants.pixel_size * constants.width, constants.pixel_size * constants.height)) pygame.draw.line(self.window, (255, 255, 255), (constants.pixel_size * constants.width, constants.pixel_size * constants.height / 2), (constants.pixel_size * constants.width * 1.5, constants.pixel_size * constants.height / 2)) self.draw_play_pause_button(mode) self.draw_sensors_icone(view_sensors) self.draw_evil_button() # Display chosen cell if self.cell_to_display is not None: self.display_cell_info() self.display_neural_net() def draw_play_pause_button(self, mode): if mode == "start": pygame.draw.rect(self.window, (255, 255, 255), [constants.pixel_size * constants.width + 52, constants.pixel_size * constants.height / 2 + 408, 10, 30]) pygame.draw.rect(self.window, (255, 255, 255), [constants.pixel_size * constants.width + 72, constants.pixel_size * constants.height / 2 + 408, 10, 30]) elif mode == "stop": pygame.draw.polygon(self.window, (255, 255, 255), [(constants.pixel_size * constants.width + 52, constants.pixel_size * constants.height / 2 + 408), (constants.pixel_size * constants.width + 79, constants.pixel_size * constants.height / 2 + 422), (constants.pixel_size * constants.width + 52, constants.pixel_size * constants.height / 2 + 438)]) def draw_sensors_icone(self, view_sensors): self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 35, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 34, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 33, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 28, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 27, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 26, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 21, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 20, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 19, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 14, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 13, 225, 315, (255, 255, 255)) self.draw_arc(self.window, (constants.pixel_size * constants.width + 165, constants.pixel_size * constants.height / 2 + 440), 12, 225, 315, (255, 255, 255)) pygame.draw.circle(self.window, (255, 255, 255), (constants.pixel_size * constants.width + 166, constants.pixel_size * constants.height / 2 + 440), 6, 0) if view_sensors: pygame.draw.line(self.window, (255, 0, 0), (constants.pixel_size * constants.width + 140, constants.pixel_size * constants.height / 2 + 400), (constants.pixel_size * constants.width + 190, constants.pixel_size * constants.height / 2 + 450), 3) pygame.draw.line(self.window, (255, 0, 0), (constants.pixel_size * constants.width + 190, constants.pixel_size * constants.height / 2 + 400), (constants.pixel_size * constants.width + 140, constants.pixel_size * constants.height / 2 + 450), 3) def draw_evil_button(self): font = pygame.font.Font('fonts/visitor1.ttf', 20) self.display_text(font, "Add", (255, 0, 0), constants.pixel_size * constants.width + 268, constants.pixel_size * constants.height / 2 + 416) self.display_text(font, "Evil", (255, 0, 0), constants.pixel_size * constants.width + 268, constants.pixel_size * constants.height / 2 + 435) pygame.draw.line(self.window, (255, 0, 0), (constants.pixel_size * constants.width + 240, constants.pixel_size * constants.height / 2 + 400), (constants.pixel_size * constants.width + 240, constants.pixel_size * constants.height / 2 + 450), 3) pygame.draw.line(self.window, (255, 0, 0), (constants.pixel_size * constants.width + 240, constants.pixel_size * constants.height / 2 + 400), (constants.pixel_size * constants.width + 290, constants.pixel_size * constants.height / 2 + 400), 3) pygame.draw.line(self.window, (255, 0, 0), (constants.pixel_size * constants.width + 240, constants.pixel_size * constants.height / 2 + 450), (constants.pixel_size * constants.width + 290, constants.pixel_size * constants.height / 2 + 450), 3) pygame.draw.line(self.window, (255, 0, 0), (constants.pixel_size * constants.width + 290, constants.pixel_size * constants.height / 2 + 400), (constants.pixel_size * constants.width + 290, constants.pixel_size * constants.height / 2 + 450), 3) def display_text(self, font, text, color, x, y): text = font.render(text, 1, color) text_pos = text.get_rect(centerx=x, centery=y) self.window.blit(text, text_pos) def display_cell_info(self): """ Display selected cell data """ font = pygame.font.Font('fonts/visitor1.ttf', 20) self.display_text(font, "fitness:", (255, 255, 255), constants.pixel_size * constants.width + 50, 13) self.display_text(font, "{}".format(self.cell_to_display.feeding), (255, 255, 255), constants.pixel_size * constants.width + 130, 13) # ------------------------------------------------------------------------------------- self.display_text(font, "Pos:", (255, 255, 255), constants.pixel_size * constants.width + 30, 30) self.display_text(font, "x:", (255, 255, 255), constants.pixel_size * constants.width + 100, 30) self.display_text(font, "y:", (255, 255, 255), constants.pixel_size * constants.width + 190, 30) self.display_text(font, "{}".format(self.cell_to_display.x), (255, 255, 255), constants.pixel_size * constants.width + 140, 30) self.display_text(font, "{}".format(self.cell_to_display.y), (255, 255, 255), constants.pixel_size * constants.width + 230, 30) # ------------------------------------------------------------------------------------- self.display_text(font, "Input:", (255, 255, 255), constants.pixel_size * constants.width + 43, 47) self.display_text(font, "x:", (255, 255, 255), constants.pixel_size * constants.width + 100, 47) self.display_text(font, "y:", (255, 255, 255), constants.pixel_size * constants.width + 190, 47) self.display_text(font, "{}".format(self.cell_to_display.sensor[0], 3), (255, 255, 255), constants.pixel_size * constants.width + 140, 47) self.display_text(font, "{}".format(self.cell_to_display.sensor[1], 3), (255, 255, 255), constants.pixel_size * constants.width + 230, 47) # ------------------------------------------------------------------------------------- self.display_text(font, "Output:", (255, 255, 255), constants.pixel_size * constants.width + 50, 64) self.display_text(font, "Up:", (255, 255, 255), constants.pixel_size * constants.width + 120, 64) self.display_text(font, "Right:", (255, 255, 255), constants.pixel_size * constants.width + 260, 64) self.display_text(font, "down:", (255, 255, 255), constants.pixel_size * constants.width + 120, 77) self.display_text(font, "left:", (255, 255, 255), constants.pixel_size * constants.width + 260, 77) self.display_text(font, "{}".format(round(self.cell_to_display.brain.array_output[0], 3)), (255, 255, 255), constants.pixel_size * constants.width + 190, 64) self.display_text(font, "{}".format(round(self.cell_to_display.brain.array_output[1], 3)), (255, 255, 255), constants.pixel_size * constants.width + 320, 64) self.display_text(font, "{}".format(round(self.cell_to_display.brain.array_output[2], 3)), (255, 255, 255), constants.pixel_size * constants.width + 190, 77) self.display_text(font, "{}".format(round(self.cell_to_display.brain.array_output[3], 3)), (255, 255, 255), constants.pixel_size * constants.width + 320, 77) # ------------------------------------------------------------------------------------- self.display_text(font, "Error:", (255, 255, 255), constants.pixel_size * constants.width + 45, 90) self.display_text(font, "{}".format(self.cell_to_display.error), (255, 255, 255), constants.pixel_size * constants.width + 180, 90) # ------------------------------------------------------------------------------------- self.display_text(font, "Update:", (255, 255, 255), constants.pixel_size * constants.width + 50, 110) self.display_text(font, "{}".format(self.cell_to_display.num_update), (255, 255, 255), constants.pixel_size * constants.width + 150, 110) def display_neural_net(self): font = pygame.font.Font('fonts/visitor1.ttf', 15) self.display_text(font, "Not Activated", (255, 255, 255), constants.pixel_size * constants.width + 388, constants.pixel_size * constants.height / 2 - 13) self.display_text(font, "Activated", (255, 20, 20), constants.pixel_size * constants.width + 370, constants.pixel_size * constants.height / 2 - 30) # Inputs ---------------------------------------------------------------- inputs_names = ['X', 'Y'] for i in range(len(self.cell_to_display.brain.array_inputs) - 1): pygame.draw.circle(self.window, (255, 255, 255), (constants.pixel_size * constants.width + 80, 230 + i * 70), 10) # Values text = font.render(str(self.cell_to_display.brain.array_inputs[i]), 1, (255, 255, 255)) text_pos = text.get_rect(centerx=constants.pixel_size * constants.width + 80, centery=200 + i * 70) self.window.blit(text, text_pos) # Names text = font.render(inputs_names[i], 1, (255, 255, 255)) text_pos = text.get_rect(centerx=constants.pixel_size * constants.width + 50, centery=230 + i * 70) self.window.blit(text, text_pos) # Lines for j in range(len(self.cell_to_display.brain.array_hidden)): pygame.draw.line(self.window, (255, 255, 255), (constants.pixel_size * constants.width + 80, 230 + i * 70), (constants.pixel_size * constants.width + 230, 160 + j * 70)) # Hidden ---------------------------------------------------------------- for i in range(len(self.cell_to_display.brain.array_hidden)): pygame.draw.circle(self.window, (255, 255, 255), (constants.pixel_size * constants.width + 230, 160 + i * 70), 10) # Values text = font.render(str(round(self.cell_to_display.brain.array_hidden[i], 3)), 1, (255, 255, 255)) text_pos = text.get_rect(centerx=constants.pixel_size * constants.width + 230, centery=130 + i * 70) self.window.blit(text, text_pos) # Lines for j in range(len(self.cell_to_display.brain.array_output)): pygame.draw.line(self.window, (255, 255, 255), (constants.pixel_size * constants.width + 230, 160 + i * 70), (constants.pixel_size * constants.width + 400, 160 + j * 70)) # Outputs ---------------------------------------------------------------- direction = ['Up', 'Right', 'Down', 'Left'] for i in range(len(self.cell_to_display.brain.array_output)): if self.cell_to_display.brain.array_output[i] > 0.5: pygame.draw.circle(self.window, (255, 20, 20), (constants.pixel_size * constants.width + 400, 160 + i * 70), 10) else: pygame.draw.circle(self.window, (255, 255, 255), (constants.pixel_size * constants.width + 400, 160 + i * 70), 10) text = font.render(str(round(self.cell_to_display.brain.array_output[i], 3)), 1, (255, 255, 255)) text_pos = text.get_rect(centerx=constants.pixel_size * constants.width + 400, centery=130 + i * 70) self.window.blit(text, text_pos) text = font.render(direction[i], 1, (255, 255, 255)) text_pos = text.get_rect(centerx=constants.pixel_size * constants.width + 450, centery=160 + i * 70) self.window.blit(text, text_pos) def display_info(self, average_fitness, average_evil_fitness, len_cells, len_evil_cells, average_output, average_error, average_evil_error): # add evil number # add evil fitness # add evil error """ Display simulation data """ font = pygame.font.Font('fonts/visitor1.ttf', 20) self.display_text(font, "Population Number:", (255, 255, 255), constants.pixel_size * constants.width + 110, constants.pixel_size * constants.height / 2 + 20) self.display_text(font, "{}".format(len_cells), (255, 255, 255), constants.pixel_size * constants.width + 230, constants.pixel_size * constants.height / 2 + 20) # ------------------------------------------------------------------------------------- self.display_text(font, "Evil population number:", (255, 255, 255), constants.pixel_size * constants.width + 137, constants.pixel_size * constants.height / 2 + 45) self.display_text(font, "{}".format(len_evil_cells), (255, 255, 255), constants.pixel_size * constants.width + 280, constants.pixel_size * constants.height / 2 + 45) # ------------------------------------------------------------------------------------- self.display_text(font, "Average Fitness:", (255, 255, 255), constants.pixel_size * constants.width + 99, constants.pixel_size * constants.height / 2 + 80) self.display_text(font, "{}".format(average_fitness), (255, 255, 255), constants.pixel_size * constants.width + 230, constants.pixel_size * constants.height / 2 + 80) # ------------------------------------------------------------------------------------- self.display_text(font, "Average Evil Fitness:", (255, 255, 255), constants.pixel_size * constants.width + 125, constants.pixel_size * constants.height / 2 + 105) self.display_text(font, "{}".format(average_evil_fitness), (255, 255, 255), constants.pixel_size * constants.width + 260, constants.pixel_size * constants.height / 2 + 105) # ------------------------------------------------------------------------------------- self.display_text(font, "Average Error:", (255, 255, 255), constants.pixel_size * constants.width + 91, constants.pixel_size * constants.height / 2 + 140) self.display_text(font, "{}".format(average_error), (255, 255, 255), constants.pixel_size * constants.width + 280, constants.pixel_size * constants.height / 2 + 140) self.display_text(font, "Average Evil Error:", (255, 255, 255), constants.pixel_size * constants.width + 117, constants.pixel_size * constants.height / 2 + 160) self.display_text(font, "{}".format(average_evil_error), (255, 255, 255), constants.pixel_size * constants.width + 330, constants.pixel_size * constants.height / 2 + 160) # ------------------------------------------------------------------------------------- self.display_text(font, "Average Output:", (255, 255, 255), constants.pixel_size * constants.width + 97, constants.pixel_size * constants.height / 2 + 200) self.display_text(font, "x:", (255, 255, 255), constants.pixel_size * constants.width + 60, constants.pixel_size * constants.height / 2 + 220) self.display_text(font, "y:", (255, 255, 255), constants.pixel_size * constants.width + 60, constants.pixel_size * constants.height / 2 + 240) self.display_text(font, "{}".format(round(average_output[0], 3)), (255, 255, 255), constants.pixel_size * constants.width + 100, constants.pixel_size * constants.height / 2 + 220) self.display_text(font, "{}".format(round(average_output[1], 3)), (255, 255, 255), constants.pixel_size * constants.width + 100, constants.pixel_size * constants.height / 2 + 240)
{"/grid.py": ["/constants.py"]}
75,216
Ethik-69/Neural-Network
refs/heads/master
/grid.py
#! /usr/bin/python # -*- coding: utf-8 -*- import constants import random class Grid(object): def __init__(self): self.height = constants.height self.width = constants.width self.pixel_size = constants.pixel_size self.chance_food = constants.chance_food self.chance_add_random_food = constants.chance_add_random_food self.grid = [[0] * self.width for i in xrange(self.height)] self.color_swich = {0: [0, 0, 0], # Empty 1: [0, 100, 100], # Foods 2: [250, 10, 10], 3: [0, 0, 80], # Cells Sensors 4: [0, 255, 0]} # Evil Cells Sensors def random_grid(self): """ Initialise the grid with random 'values' """ for i in xrange(self.height): for j in xrange(self.width): if random.random() < self.chance_food: self.grid[i][j] = 1 else: self.grid[i][j] = 0 def add_random_food(self): """ Add some food in the grid at random position """ for i in range(3): if random.random() < self.chance_add_random_food: x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) if self.grid[x][y] != 3: self.grid[x][y] = 1 def display(self, window): """ Display the grid case by case """ for ligne in xrange(self.height): for colone in xrange(self.width): try: window.fill(self.grid[ligne][colone].color, (ligne * self.pixel_size, colone * self.pixel_size, self.pixel_size - 1, self.pixel_size - 1)) except: try: colour = self.color_swich[self.grid[ligne][colone]] except: colour = [255, 255, 255] if colour != [0, 0, 0]: window.fill(colour, (ligne * self.pixel_size, colone * self.pixel_size, self.pixel_size - 1, self.pixel_size - 1)) def clean_grid(self): """ Clean the grid if 'view sensors' is active """ for i in range(constants.width): for j in range(constants.height): if self.grid[i][j] == 2: self.grid[i][j] = 1 elif self.grid[i][j] == 3: self.grid[i][j] = 0 elif self.grid[i][j] == 4: self.grid[i][j] = 0 def update(self, window): self.add_random_food() self.add_random_food()
{"/grid.py": ["/constants.py"]}
75,217
Ethik-69/Neural-Network
refs/heads/master
/constants.py
#! /usr/bin/python # -*- coding: utf-8 -*- import random width = 200 height = 200 pixel_size = 5 population_limit = 100 # Start population limit number_of_food = 500 chance_food = 0.05 chance_add_random_food = 0.9 mutate_chance = 0.1 sensor_limit = 10 bad_sensor_limit = 20 choice = lambda x: x[int(random.random() * len(x))] n_inputs = 2 n_hidden = 4 n_outputs = 4 reproduction_limit = 100
{"/grid.py": ["/constants.py"]}
75,218
Ethik-69/Neural-Network
refs/heads/master
/game_of_life_style.py
#! /usr/bin/python # -*- coding: utf-8 -*- # input: food plus proche # output: Up, Right, Down, Left import sys import random try: import pygame from pygame.locals import * except ImportError, errmsg: print('Requires PyGame') print(errmsg) sys.exit(1) import constants from cell import Cell from cell import EvilCell from grid import Grid from graph import Graph from interface import Interface class Simulation(object): def __init__(self): pygame.init() width = int(constants.pixel_size * constants.width * 1.5) height = constants.pixel_size * constants.height self.window = pygame.display.set_mode((width, height)) self.background = pygame.Surface(self.window.get_size()) self.background = self.background.convert() self.background.fill((10, 10, 10)) pygame.display.set_caption('Simulation') self.window.blit(self.background, (0, 0)) pygame.display.flip() self.interface = Interface(self.window) self.graph = Graph() self.grid = Grid() self.grid.random_grid() self.cells = [] self.evil_cells = [] self.init_population() self.time = 0 self.run = True self.view_sensors = False self.is_stop = False self.population = None self.average_fitness = 0 self.average_evil_fitness = 0 self.average_error = 0.0 self.average_evil_error = 0.0 self.average_output = [0, 0] self.play_pause_button = None self.sensors_button = None self.bad_cell_button = None def add_cell(self): """ Create a new cell """ return Cell(self.grid, constants.n_inputs, constants.n_hidden, constants.n_outputs, (255, 255, 255)) def add_evil_cell(self): """ Create a new evil cell """ return EvilCell(self.grid, constants.n_inputs, constants.n_hidden, constants.n_outputs, (255, 0, 0)) def init_population(self): """ Initialise all cells """ while len(self.cells) != constants.population_limit: self.cells.append(self.add_cell()) def rand(self, a, b): return (b - a) * random.random() + a def reset_cells(self): """ Put back has zero all cells """ print("[*] Reset self.cells pos and feeding") for cell in self.cells: cell.init(self.grid) def stop(self): """ Pygame pause loop """ is_stop = True self.create_buttons() MOUSEDOWN = False while is_stop: self.window.fill((10, 10, 10)) self.interface.update("stop", self.view_sensors) self.grid.display(self.window) self.interface.display_info(self.average_fitness, self.average_evil_fitness, len(self.cells), len(self.evil_cells), self.average_output, self.average_error, self.average_evil_error) mouse_xy = pygame.mouse.get_pos() self.update_all_cells_stop(mouse_xy) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit(0) elif event.key == K_SPACE: is_stop = False elif event.type == MOUSEBUTTONDOWN: MOUSEDOWN = True if event.button == 1: # left click add/del food if self.play_pause_button.collidepoint(mouse_xy): is_stop = False elif self.bad_cell_button.collidepoint(mouse_xy): self.evil_cells.append(self.add_evil_cell()) elif self.sensors_button.collidepoint(mouse_xy): if self.view_sensors: self.view_sensors = False else: self.view_sensors = True if mouse_xy[0] < constants.width * constants.pixel_size: for cell in self.cells: if cell.x == mouse_xy[0] / constants.pixel_size and cell.y == mouse_xy[1] / constants.pixel_size: print("[*] Cell Chosen") self.interface.cell_to_display = cell elif event.type == MOUSEBUTTONUP: MOUSEDOWN = False if mouse_xy[0] < constants.width * constants.pixel_size and MOUSEDOWN: self.change_cell_on_click(mouse_xy) pygame.time.wait(0) pygame.display.flip() def change_cell_on_click(self, mouse_xy): """ Add or Del food """ if self.grid.grid[(mouse_xy[0]) / constants.pixel_size][mouse_xy[1] / constants.pixel_size] != 1: self.grid.grid[(mouse_xy[0]) / constants.pixel_size][mouse_xy[1] / constants.pixel_size] = 1 else: self.grid.grid[(mouse_xy[0]) / constants.pixel_size][mouse_xy[1] / constants.pixel_size] = 0 def update_all_cells_main(self): # Update and Draw all cells ----------------------------------- for cell in self.cells: if cell.alive: self.average_error += cell.error self.average_fitness += cell.feeding cell.update(self.grid) self.average_output[0] += cell.brain.array_output[0] self.average_output[1] += cell.brain.array_output[1] if self.view_sensors and not cell.view_sensors: cell.view_sensors = True elif not self.view_sensors: cell.view_sensors = False else: self.cells.remove(cell) # Update and Draw all bad cells ----------------------------------- for cell in self.evil_cells: if cell.alive: self.average_evil_error += cell.error self.average_evil_fitness += cell.feeding cell.update(self.grid) if self.view_sensors and not cell.view_sensors: cell.view_sensors = True elif not self.view_sensors: cell.view_sensors = False else: self.cells.remove(cell) def update_all_cells_stop(self, mouse_xy): # Update and Draw cells for cell in self.cells: if cell.x == mouse_xy[0] / constants.pixel_size and cell.y == mouse_xy[1] / constants.pixel_size: print("[*] Cell Chosen") self.interface.cell_to_display = cell # Update and Draw evil cells for cell in self.evil_cells: if cell.x == mouse_xy[0] / constants.pixel_size and cell.y == mouse_xy[1] / constants.pixel_size: print("[*] Evil Cell Chosen") self.interface.cell_to_display = cell def end(self): print("[*] Evil cells Win !") print("[*] Evil population: %s" % len(self.evil_cells)) print("[*] Average Error: %s" % self.average_error) print("[*] Average Fitness: %s" % self.average_fitness) def create_buttons(self): self.play_pause_button = pygame.draw.rect(self.window, (50, 50, 50), [constants.pixel_size * constants.width + 40, constants.pixel_size * constants.height / 2 + 400, 50, 50]) self.sensors_button = pygame.draw.rect(self.window, (255, 255, 255), [constants.pixel_size * constants.width + 140, constants.pixel_size * constants.height / 2 + 400, 50, 50]) self.bad_cell_button = pygame.draw.rect(self.window, (255, 255, 255), [constants.pixel_size * constants.width + 240, constants.pixel_size * constants.height / 2 + 400, 50, 50]) def reset_averages(self): self.average_fitness = 0 self.average_evil_fitness = 0 self.average_output = [0, 0] self.average_error = 0.0 self.average_evil_error = 0.0 def calc_averages(self): self.average_output[0] /= len(self.cells) self.average_output[1] /= len(self.cells) self.average_fitness /= len(self.cells) self.average_error /= len(self.cells) if len(self.evil_cells) != 0: self.average_evil_fitness /= len(self.evil_cells) self.average_evil_error /= len(self.evil_cells) def main(self): """ Pygame main loop """ self.create_buttons() while self.run: self.window.fill((10, 10, 10)) self.interface.update("start", self.view_sensors) self.grid.display(self.window) self.grid.update(self.window) self.grid.clean_grid() self.interface.display_info(self.average_fitness, self.average_evil_fitness, len(self.cells), len(self.evil_cells), self.average_output, self.average_error, self.average_evil_error) self.reset_averages() self.update_all_cells_main() if len(self.cells) == 0: self.end() break self.calc_averages() self.time += 1 if self.time % 25 == 0: self.graph.update(self.time, self.average_error) mouse_xy = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit(0) elif event.key == K_SPACE: self.stop() elif event.type == MOUSEBUTTONDOWN: if event.button == 1: # left click add/del food if self.play_pause_button.collidepoint(mouse_xy): self.stop() elif self.bad_cell_button.collidepoint(mouse_xy): self.evil_cells.append(self.add_evil_cell()) elif self.sensors_button.collidepoint(mouse_xy): if self.view_sensors: self.view_sensors = False else: self.view_sensors = True pygame.time.wait(0) pygame.display.flip() if __name__ == "__main__": simu = Simulation() simu.main() # TODO: food object ! # TODO: corection bug black follow red ! (cell when eat/move calls) # TODO: Refacto + doc # IDEA: enemy detection (priority ? avoid enemy or got to food ?) # IDEA: no more than 1 cell per case # IDEA: add position allies # IDEA: add color to food (different color = different values) and give it to the network
{"/grid.py": ["/constants.py"]}
75,219
Ethik-69/Neural-Network
refs/heads/master
/graph.py
#! /usr/bin/python # -*- coding: utf-8 -*- import sys try: import matplotlib.pyplot as plt except ImportError, errmsg: print('Requires matplotlib') print(errmsg) sys.exit(1) class Graph(object): def __init__(self): plt.style.use('ggplot') plt.xlabel('Time') plt.ylabel('Error') self.x = [] self.y = [] self.best = [] self.axis_x = 0.01 self.axis_y = 0.01 plt.axis([0, self.axis_x, 0, self.axis_y]) plt.ion() plt.show() def update(self, x, y): self.x.append(x) self.y.append(y) if self.axis_x < x: self.axis_x = x if self.axis_y < y: self.axis_y = y plt.axis([0, self.axis_x * 1.1, 0, self.axis_y * 1.1]) plt.pause(0.0001) plt.plot(self.x, self.y, color='black', label="average fitness") #plt.draw()
{"/grid.py": ["/constants.py"]}
75,220
wenmoon/hodlcore
refs/heads/master
/__init__.py
import requests import json import tweepy import math import datetime import time import json import sqlite3 from hodlcore import model, stringformat from sqlite3 import Error from bs4 import BeautifulSoup from operator import attrgetter
{"/db.py": ["/model.py"], "/api.py": ["/model.py"]}
75,221
wenmoon/hodlcore
refs/heads/master
/model.py
#!/usr/bin/env python3 import datetime class MarketCapitalization(object): def __init__(self, mcap_usd, volume_usd_24h, bitcoin_percentage_of_market_cap): self.mcap_usd = mcap_usd self.volume_usd_24h = volume_usd_24h self.bitcoin_percentage_of_market_cap = bitcoin_percentage_of_market_cap @classmethod def from_json(cls, json): return cls(json['total_market_cap_usd'], json['total_24h_volume_usd'], json['bitcoin_percentage_of_market_cap']) def __str__(self): return 'Mcap: {}, 24h vol: {}, BTC: {}'.format(self.mcap, self.volume_usd_24h, self.bitcoin_percentage_of_market_cap) class Token(object): def __init__(self, id, name, symbol, rank, price, price_btc, percent_change_1h, percent_change_24h, percent_change_7d, volume_24h, mcap, available_supply, total_supply, max_supply, balance = 0): self.id = id self.name = name self.symbol = symbol self.rank = rank self.price = price self.price_btc = price_btc self.percent_change_1h = percent_change_1h self.percent_change_24h = percent_change_24h self.percent_change_7d = percent_change_24h self.volume_24h = volume_24h self.mcap = mcap self.available_supply = available_supply self.total_supply = total_supply self.max_supply = max_supply self.balance = balance self.name_str = '{} ({})'.format(self.name, self.symbol) self.url = 'https://coinmarketcap.com/currencies/{}/'.format(self.id) self.logo_url = 'https://chasing-coins.com/api/v1/std/logo/{}'.format(self.symbol) @property def value(self): return self.price * self.balance @property def value_btc(self): return self.price_btc * self.balance @classmethod def from_db_tuple(cls, db_tuple): try: return cls( db_tuple[0], db_tuple[1], db_tuple[2], int(db_tuple[3]), float(db_tuple[4]), float(db_tuple[5]), float(db_tuple[6]), float(db_tuple[7]), float(db_tuple[8]), float(db_tuple[9]), float(db_tuple[10]), float(db_tuple[11]), float(db_tuple[12]) ) except Exception as e: return None @classmethod def from_json(cls, json, balance = 0, currency = 'usd'): try: token_id = json['id'] name = json['name'] symbol = json['symbol'] rank = int(json['rank']) price = float(json['price_{}'.format(currency)]) price_btc = float(json['price_btc']) percent_change_1h = float(json['percent_change_1h']) percent_change_24h = float(json['percent_change_24h']) percent_change_7d = float(json['percent_change_7d']) volume_24h = float(json['24h_volume_{}'.format(currency)]) mcap = float(json['market_cap_{}'.format(currency)]) available_supply = float(json['available_supply']) total_supply = float(json['total_supply']) max_supply = float(json['total_supply']) return cls( token_id, name, symbol, rank, price, price_btc, percent_change_1h, percent_change_24h, percent_change_7d, volume_24h, mcap, available_supply, total_supply, max_supply ) except Exception as e: return None def matches(self, search): search = search.lower() if search in self.id.lower() or search in self.symbol.lower() or search in self.name.lower(): return True return False def matches_score(self, search): score = 0 search = search.lower() if search == self.id.lower(): score += 10 elif search in self.id.lower(): score += 3 if search == self.symbol.lower(): score += 10 elif search in self.symbol.lower(): score += 3 if search == self.name.lower(): score += 10 elif search in self.name.lower(): score += 3 return score @staticmethod def is_bitcoin(token_id): return token_id.lower() == 'btc' def is_bitcoin(self): return self.symbol.lower() == 'btc' def __str__(self): return self.name_str class Portfolio(object): def __init__(self): self.tokens = [] self.value = 0 self.value_btc = 0 def add_token(self, token): self.tokens.append(token) self.value += token.value self.value_btc += token.value_btc def remove_token(self, token): self.tokens.remove(token) self.value -= token.value self.value_btc -= token.value_btc class Subscribable(object): def __init__(self, name, subscribers, url): self.name = name self.subscribers = subscribers self.url = url class PeriodicSummary(object): def __init__(self, name, now, today, yesterday, last_week, last_month, ath, atl, avg_today, avg_last_week, avg_last_month): self.name = name self.now = float(now) self.today = float(today) self.yesterday = float(yesterday) self.last_week = float(last_week) self.last_month = float(last_month) self.atl = float(atl) self.ath = float(ath) self.is_ath = now >= ath self.is_atl = now <= atl self.avg_today = avg_today self.avg_last_week = avg_last_week self.avg_last_month = avg_last_month self.diff_today = now - today self.pct_today = 0 if today == 0 else ((now / float(today)) - 1.0) * 100.0 self.diff_week = now - last_week self.pct_week = 0 if last_week == 0 else ((now / float(last_week)) - 1.0) * 100.0 self.diff_month = now - last_month self.pct_month = 0 if last_month == 0 else ((now / float(last_month)) - 1.0) * 100.0 def __cmp__(self, other): return cmp(self.diff_today, other.diff_today) def __str__(self): return 'PeriodicSummary:\n\tName: {}\n\tATH: {}, ATL: {}\n\tValues (now, last_week, last_month): {}, {}, {}\n\tDiff (d, w, m): {}, {}, {}\n\tPercent (d, w, m): {}, {}, {}'.format(self.name, self.ath, self.atl, self.now, self.last_week, self.last_month, self.diff_today, self.diff_week, self.diff_month, stringformat.percent(self.pct_today), stringformat.percent(self.pct_week), stringformat.percent(self.pct_month)) class OAuthCredentials(object): def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret): self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.access_token = access_token self.access_token_secret = access_token_secret @classmethod def from_json(cls, json): try: consumer_key = json['consumer_key'] consumer_secret = json['consumer_secret'] access_token = json['access_token'] access_token_secret = json['access_token_secret'] return cls(consumer_key, consumer_secret, access_token, access_token_secret) except Exception: return None class Event(object): def __init__(self, title, start, end): self.title = title self.start = start self.end = end @property def when(self): return self.start - datetime.datetime.now() @property def today(self): return self.when.days == 0 @property def ongoing(self): return self.when.days < 0 @property def upcoming(self): return self.when.days > 0 @property def finished(self): return datetime.datetime.now() > self.end
{"/db.py": ["/model.py"], "/api.py": ["/model.py"]}
75,222
wenmoon/hodlcore
refs/heads/master
/db.py
#!/usr/bin/env python3 import time import sqlite3 from sqlite3 import Error import json import os from .model import Portfolio from .model import Token from .model import MarketCapitalization from .model import Subscribable from .model import Event local_path = os.path.dirname(os.path.realpath(__file__)) # # Database operations relating to Market Capitalization # class MarketCapitalizationDB(object): def __init__(self): self.database_file = '{}/data/hodl.db'.format(local_path) self.database_table_cmc_global = 'coinmarketcap_global' dbc = sqlite3.connect(self.database_file) try: dbc.execute('SELECT * FROM {} LIMIT 1').format(self.database_table_cmc_global) except sqlite3.OperationalError: self.create_tables(dbc) dbc.close() def create_tables(self, dbc): try: dbc.execute('''CREATE TABLE {} (timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, mcap TEXT, volume REAL, bitcoin_percentage_of_market_cap REAL)'''.format(self.database_table_cmc_global)) dbc.commit() except Exception as e: print(e) def insert(self, mcap): dbc = sqlite3.connect(self.database_file) try: dbc.execute('''INSERT INTO {} (mcap, volume, bitcoin_percentage_of_market_cap) VALUES (?, ?, ?)'''.format(self.database_table_cmc_global), ( mcap.mcap_usd, mcap.volume_usd_24h, mcap.bitcoin_percentage_of_market_cap)) dbc.commit() except KeyError: print('Error importing mcap: %s' % mcap) dbc.close() def get_latest(self): dbc = sqlite3.connect(self.database_file) dbc.row_factory = sqlite3.Row try: latest = dbc.execute('SELECT mcap, volume, bitcoin_percentage_of_market_cap FROM {} ORDER BY timestamp DESC LIMIT 1'.format(self.database_table_cmc_global)).fetchone() return MarketCapitalization(float(latest[0]), float(latest[1]), float(latest[2])) except Exception as e: print(e) return None dbc.close() # # Database operations relating to Tokens # class TokenDB(object): def __init__(self): self.database_file = '{}/data/hodl.db'.format(local_path) self.database_table_cmc_tokens = 'coinmarketcap_tokens' dbc = sqlite3.connect(self.database_file) try: dbc.execute('SELECT * FROM {} LIMIT 1').format(self.database_table_cmc_tokens) except sqlite3.OperationalError: self.create_tables(dbc) dbc.close() def create_tables(self, dbc): try: # Create table dbc.execute('''CREATE TABLE {} (timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, id TEXT, name TEXT, symbol TEXT, rank INTEGER, price_usd REAL, price_btc REAL, volume_usd REAL, market_cap_usd REAL, available_supply REAL)'''.format(self.database_table_cmc_tokens)) dbc.commit() except Exception as e: print(e) def insert(self, tokens): dbc = sqlite3.connect(self.database_file) for token in tokens: try: dbc.execute('''INSERT INTO {} (id, name, symbol, rank, price_usd, price_btc, volume_usd, market_cap_usd, available_supply) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'''.format(self.database_table_cmc_tokens), ( token.id, token.name, token.symbol, token.rank, token.price, token.price_btc, token.volume_24h, token.mcap, token.available_supply)) except KeyError as e: print(e) dbc.commit() dbc.close() def __get_metric_summary(self, metric_name, token_id): dbc = sqlite3.connect(self.database_file) now = dbc.execute( 'SELECT {metric} FROM {table} WHERE id=? ORDER BY timestamp DESC LIMIT 1'.format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchone() today = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "start of day") AND datetime("now", "localtime") AND id=? ORDER BY timestamp ASC''' .format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchall() yesterday = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "-1 days") AND datetime("now", "localtime") AND id=? ORDER BY timestamp ASC''' .format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchall() last_week = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "-6 days") AND datetime("now", "localtime") AND id=? ORDER BY timestamp ASC''' .format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchall() last_month = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "start of month") AND datetime("now", "localtime") AND id=? ORDER BY timestamp ASC''' .format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchall() ath = dbc.execute( 'SELECT {metric} FROM {table} WHERE id=? ORDER BY {metric} ASC LIMIT 1' .format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchone() atl = dbc.execute( 'SELECT {metric} FROM {table} WHERE id=? ORDER BY {metric} DESC LIMIT 1' .format(table=self.database_table_cmc_tokens, metric=metric_name), (token_id,) ).fetchone() dbc.close() try: avg_today = sum([x[0] for x in today]) / len(today) avg_last_week = sum([x[0] for x in last_week]) / len(last_week) avg_last_month = sum([x[0] for x in last_month]) / len(last_month) return PeriodicSummary(metric_name, now[0], today[0][0], yesterday[0][0], last_week[0][0], last_month[0][0], ath[0], atl[0], avg_today, avg_last_week, avg_last_month) except Exception as e: print('_get_metric_summary({}, {}) Error: {}'.format(metric_name, token_id, e)) return None def get_volumes(self, token_id): return self.__get_metric_summary('volume_usd', token_id) def get_prices_btc(self, token_id): return self.__get_metric_summary('price_btc', token_id) def get_mcaps(self, token_id): return self.__get_metric_summary('market_cap_usd', token_id) def get_ranks(self, token_id): return self.__get_metric_summary('rank', token_id) # # Database operations relating to Subscribables, typically Reddit, Twitter, etc where subscribers (and the change thereof) is an interesting metric # class SubscribableDB(object): def __init__(self, table_name, table_subscribers_name, subscribable_type, defaults = []): self.database_file = '{}/data/hodl.db'.format(local_path) self.database_table_subscribable = table_name self.database_table_subscribable_subscribers = table_subscribers_name self.subscribable_type = subscribable_type dbc = sqlite3.connect(self.database_file) try: dbc.execute('SELECT * FROM {} LIMIT 1'.format(self.database_table_subscribable)) dbc.execute('SELECT * FROM {} LIMIT 1'.format(self.database_table_subscribable_subscribers)) except sqlite3.OperationalError: self.create_tables(dbc) for subscribable in defaults: self.track(subscribable) dbc.close() def create_tables(self, dbc): try: dbc.execute('CREATE TABLE {} (name TEXT PRIMARY KEY, subscribable_type TEXT)'.format(self.database_table_subscribable)) dbc.execute('''CREATE TABLE {} (timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, name TEXT, subscribable_type TEXT, subscribers INTEGER)'''.format(self.database_table_subscribable_subscribers)) dbc.commit() except Exception as e: print(e) def get_tracked(self): dbc = sqlite3.connect(self.database_file) try: tracked = dbc.execute('SELECT * FROM {} WHERE subscribable_type=?'.format(self.database_table_subscribable), (self.subscribable_type,)).fetchall() dbc.close() return list(map(lambda x: x[0], tracked)) except Exception as e: print(e) dbc.close() return [] def track(self, subscribable): dbc = sqlite3.connect(self.database_file) try: dbc.execute( 'INSERT INTO {} (name, subscribable_type) VALUES (?, ?)' .format(self.database_table_subscribable), (subscribable, self.subscribable_type)) except sqlite3.IntegrityError: pass except Error as e: print(e) dbc.commit() dbc.close() def untrack(sefl, subscribable): dbc = sqlite3.connect(self.database_file) try: dbc.execute('DELETE FROM {} WHERE name=? AND subscribable_type=? LIMIT 1'.format(self.database_table_subscribable), (subscribable, self.subscribable_type)) except Exception as e: print(e) dbc.commit() dbc.close() def insert(self, subscribable): dbc = sqlite3.connect(self.database_file) try: dbc.execute('INSERT INTO {} (name, subscribable_type, subscribers) VALUES (?, ?, ?)'.format(self.database_table_subscribable_subscribers), (subscribable.name, self.subscribable_type, subscribable.subscribers)) except Exception as e: print(e) dbc.commit() dbc.close() def insert_many(self, subscribables): dbc = sqlite3.connect(self.database_file) for subscribable in subscribables: try: dbc.execute('INSERT INTO {} (name, subscribable_type, subscribers) VALUES (?, ?, ?)'.format(self.database_table_subscribable_subscribers), (subscribable.name, self.subscribable_type, subscribable.subscribers)) except Exception as e: print(e) dbc.commit() dbc.close() def get_subscribers(self, subscribable): metric_name = 'subscribers' dbc = sqlite3.connect(self.database_file) now = dbc.execute( 'SELECT {metric} FROM {table} WHERE name=? AND subscribable_type=? ORDER BY timestamp DESC LIMIT 1' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchone() today = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "start of day") AND datetime("now", "localtime") AND name=? AND subscribable_type=? ORDER BY timestamp ASC''' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchall() yesterday = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "-1 days") AND datetime("now", "localtime") AND name=? AND subscribable_type=? ORDER BY timestamp ASC''' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchall() last_week = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "-6 days") AND datetime("now", "localtime") AND name=? AND subscribable_type=? ORDER BY timestamp ASC''' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchall() last_month = dbc.execute( '''SELECT {metric} FROM {table} WHERE timestamp BETWEEN datetime("now", "start of month") AND datetime("now", "localtime") AND name=? AND subscribable_type=? ORDER BY timestamp ASC''' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchall() ath = dbc.execute( 'SELECT {metric} FROM {table} WHERE name=? AND subscribable_type=? ORDER BY {metric} ASC LIMIT 1' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchone() atl = dbc.execute( 'SELECT {metric} FROM {table} WHERE name=? AND subscribable_type=? ORDER BY {metric} DESC LIMIT 1' .format(table=self.database_table_subscribable_subscribers, metric=metric_name), (subscribable, self.subscribable_type) ).fetchone() dbc.close() try: avg_today = sum([x[0] for x in today]) / len(today) avg_last_week = sum([x[0] for x in last_week]) / len(last_week) avg_last_month = sum([x[0] for x in last_month]) / len(last_month) return PeriodicSummary(metric_name, now[0], today[0][0], yesterday[0][0], last_week[0][0], last_month[0][0], ath[0], atl[0], avg_today, avg_last_week, avg_last_month) except Exception as e: print('get_subscribers({}, {}) Error: {}'.format(subscribable, self.subscribable_type, e)) return None # # Database operations relating to Twitter # class TwitterDB(SubscribableDB): def __init__(self): super(TwitterDB, self).__init__(table_name='twitter', table_subscribers_name='twitter_subscribers', subscribable_type='twitter') # # Database operations relating to Reddit # class RedditDB(SubscribableDB): def __init__(self): super(RedditDB, self).__init__(table_name='reddit', table_subscribers_name='reddit_subscribers', subscribable_type='reddit')
{"/db.py": ["/model.py"], "/api.py": ["/model.py"]}
75,223
wenmoon/hodlcore
refs/heads/master
/api.py
#!/usr/bin/env python3 import requests import json from bs4 import BeautifulSoup import tweepy import datetime from .model import Portfolio from .model import Token from .model import MarketCapitalization from .model import Subscribable from .model import Event __endpoint_tokens_all = 'https://api.coinmarketcap.com/v1/ticker/?limit=10000' __endpoint_tokens_limit = 'https://api.coinmarketcap.com/v1/ticker/?limit={}' __endpoint_token_scrape = 'https://coinmarketcap.com/currencies/{}' __endpoint_token_scrape_social = 'https://coinmarketcap.com/currencies/{}/#social' __endpoint_token = 'https://api.coinmarketcap.com/v1/ticker/{}/?convert={}' __endpoint_mcap = 'https://api.coinmarketcap.com/v1/global/' __endpoint_subreddits = 'https://www.reddit.com/r/{}/about.json' __endpoint_twitter = 'https://www.reddit.com/r/{}/about.json' __endpoint_ico = 'https://icodrops.com/{}' __endpoint_airdrop = 'https://coindar.org/en/tags/airdrop' __headers_useragent = { 'User-agent': 'hodlcore beta' } __headers_mozilla = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36' } def get_portfolio(portfolio_config, currency): portfolio = Portfolio() for entry in portfolio_config: token = get_token(entry[0]) if token is None: token = search_token(entry[0]) if token is not None: token.balance = entry[1] token.currency = currency portfolio.add_token(token) return portfolio def get_mcap(): mcap_json = requests.get(__endpoint_mcap).json() return MarketCapitalization.from_json(mcap_json) def get_token(name): try: r_token = requests.get(__endpoint_token.format(name, currency)).json()[0] return Token.from_json(r_token) except: return None def get_top_tokens(limit = 100): r_tokens = requests.get(__endpoint_tokens_limit.format(limit)).json() tokens = [] for r_token in r_tokens: try: token = Token.from_json(r_token) if token is not None: tokens.append(token) except: pass return tokens def search_tokens(search, limit = 100): r_tokens = requests.get(__endpoint_tokens_limit.format(1000)).json() tokens = [] for r_token in r_tokens: try: token = Token.from_json(r_token) if token.matches(search): tokens.append(token) if len(tokens) >= limit: break except: pass return tokens def search_token(search): r_tokens = requests.get(__endpoint_tokens_limit.format(1000)).json() match_token = None match_token_score = 0 for r_token in r_tokens: try: token = Token.from_json(r_token) token_score = token.matches_score(search) # if token_score > 0: # print('Search score for {} = {}'.format(token.name_str, token_score)) if token_score > match_token_score: match_token = token match_token_score = token_score except: pass return match_token def get_top_subreddits(limit = 300): top_tokens = get_top_tokens(limit=limit) subscribables = [] for token in top_tokens: r = requests.get(__endpoint_token_scrape_social.format(token.id)) lines = r.text.split('\n') for line in lines: if 'www.reddit.com' in line: try: reddit = line.split('"')[1].split('/')[4].split('.')[0] subscribables.append(reddit) except IndexError: pass return subscribables def get_top_twitters(limit = 300): top_tokens = get_top_tokens(limit=limit) subscribables = [] for token in top_tokens: token_scrape = requests.get(__endpoint_token_scrape.format(token.id)) soup = BeautifulSoup(token_scrape.text, 'html.parser') try: twitter = soup.find('a', 'twitter-timeline').attrs['data-screen-name'] subscribables.append(twitter) except: pass return subscribables def get_subreddit(subreddit): try: r_subreddit = requests.get(__endpoint_subreddits.format(subreddit), headers = __headers_useragent).json()['data'] return Subscribable(subreddit, r_subreddit['subscribers'], r_subreddit['url']) except KeyError: return None def get_twitter(twitter, credentials): auth = tweepy.auth.OAuthHandler(credentials.consumer_key, credentials.consumer_secret) auth.set_access_token(credentials.access_token, credentials.access_token_secret) tweepy_api = tweepy.API(auth) try: user = tweepy_api.get_user(twitter) return Subscribable(twitter, user.followers_count, 'https://twitter.com/{}'.format(twitter)) except tweepy.error.TweepError: return None def get_ico_text(token): try: ico_response = requests.get(__endpoint_ico.format(token.id.lower()), headers=__headers_mozilla) soup = BeautifulSoup(ico_response.text, 'html.parser') rel_sections = soup.find_all('div', 'white-desk ico-desk') fields = [ 'ticker:', 'ico token price:', 'total tokens:', 'accepts:', ] entries = [] for s in rel_sections: if not s.find_all('i', 'fa fa-calendar'): continue # ICO details ico_info = s.find('div', 'col-12 col-md-6') lines = s.find_all('li') for line in lines: for field in fields: if field in line.text.lower(): header, value = line.text.encode('utf-8').split(':') entries.append('\t*{}*: {}\n'.format(header, value)) # Price lists prices = soup.find('div', 'token-price-list').find_all('li') price_list = [] for price in prices: price_list.append('\t\t{}\n'.format(price.text.encode('utf-8'))) # ROIs rois = soup.find('div', 'col-12 col-md-6 ico-roi').find_all('li') roi_list = [] for roi in rois: amount = roi.find('div', 'roi-amount').text.encode('utf-8') currency = roi.find('div', 'roi-currency').text.encode('utf-8') roi_list.append('\t\t*{}*: {}\n'.format(currency, amount)) if entries: text = '*ICO Information for {}{}:*\n'.format(token.name_str, stringformat.emoji('charts')) for entry in entries: text += entry if price_list: text += '\t*Current Price:*\n' for price in price_list: text += price if roi_list: text += '\t*Returns:*\n' for roi in roi_list: text += roi return text else: return None except Exception as e: print(token) print(e) return None def get_airdrops(): airdrop_response = requests.get(__endpoint_airdrop) events = BeautifulSoup(airdrop_response.text, 'html.parser').find_all('div', 'addeventatc') now = datetime.datetime.now() airdrops = [] for e in events: try: start = datetime.datetime.strptime(e.find('span', 'start').text[:10], '%m/%d/%Y') end = datetime.datetime.strptime(e.find('span', 'end').text[:10], '%m/%d/%Y') title = e.find('span', 'title').text airdrop = Event(title, start, end) airdrops.append(airdrop) except Exception as e: print(e) pass return airdrops
{"/db.py": ["/model.py"], "/api.py": ["/model.py"]}
75,224
wenmoon/hodlcore
refs/heads/master
/updater.py
def update_token_metrics(): db.TokenDB().insert(api.get_top_tokens()) db.MarketCapitalizationDB().insert(api.get_mcap()) def update_twitter_data(): try: file = open('api-creds-twitter.json', 'r') creds = model.OAuthCredentials.from_json(json.load(file)) database = db.TwitterDB() names = database.get_tracked() for name in names: twitter = api.get_twitter(name, creds) if twitter is not None: database.insert(twitter) except Exception: print("Could not load Twitter credentials, ensure api-creds-twitter.json exists and has a valid access_token") def update_twitters(): database = db.TwitterDB() for subscribable in api.get_top_twitters(): database.track(subscribable) def update_subreddit_data(): database = db.RedditDB() names = database.get_tracked() for name in names: subreddit = api.get_subreddit(name) if subreddit is not None: database.insert(subreddit) def update_subreddits(): database = db.RedditDB() for subscribable in api.get_top_reddits(): database.track(subscribable) def main(): print("Running HODLCORE updater...") update_token_metrics() update_twitters() update_twitter_data() update_subreddits() update_subreddit_data() print("Done!") if __name__ == '__main__': sys.exit(main())
{"/db.py": ["/model.py"], "/api.py": ["/model.py"]}
75,225
wenmoon/hodlcore
refs/heads/master
/stringformat.py
#!/usr/bin/env python3 import math from operator import attrgetter __emojis = { 'poop': u'\U0001f4a9', 'crashing': u'\U0001f4c9', 'mooning': u'\U0001f4c8', 'rocket': u'\U0001f680', 'charts': u'\U0001f4ca', 'pause': u'\U000023f8', 'sleeping': u'\U0001f634', 'dollar': u'\U0001f4b5', 'triangle_up': u'\U0001f53a', 'triangle_dn': u'\U0001f53b', 'apple_green': u'\U0001f34f', 'apple_red': u'\U0001f34e', 'pear': u'\U0001f350', 'vs': u'\U0001f19a', 'squirt': u'\U0001f4a6', 'umbrella': u'\U00002614', 'fire': u'\U0001f525', 'arrow_up': u'\U00002197', 'arrow_down': u'\U00002198', 'collision': u'\U0001f4a5', 'rainbow': u'\U0001f308', 'carlos': u'\U0001f919', 'skull': u'\u2620\ufe0f', 'broken_heart': u'\U0001f494', 'green_heart': u'\U0001f49a', 'orange_diamond': u'\U0001f538', 'robot': u'\U0001f916', 'link': u'\U0001f517', 'money_bag': u'\U0001f4b0', } def emoji(key): try: return __emojis[key] except Exception: return '' def large_number(n, short=False): """ Return human readable large numbers. """ if short: millnames = ['','k','m','bn','tn'] else: millnames = ['','k','Million','Billion','trillion'] try: n = float(n) millidx = max(0, min(len(millnames)-1, int(math.floor(0 if n == 0 else math.log10(abs(n))/3)))) return '{:.0f} {}'.format(n / 10**(3 * millidx), millnames[millidx]) except TypeError: return '?' def sh_color(n): default_color_prefix = '\033[39m' color_prefix = default_color_prefix if n > 0: color_prefix = '\033[38;5;2m' elif n < 0: color_prefix = '\033[38;5;1m' return '{}{}{}'.format(color_prefix, n, default_color_prefix) def percent(num, emo=True): if not emo: return '{}{:.2f}%'.format('+' if num > 0 else '', num) else: if num > 0: prefix = '{} +'.format(emoji('green_heart')) elif num == 0: prefix = '{} '.format(emoji('orange_diamond')) else: prefix = '{} '.format(emoji('broken_heart')) return '{}{:.2f}%'.format(prefix, num) def mcap_summary(mcap): s = '*Global data {}:*\n'.format(emoji('charts')) s += '\t*Total Market Cap (USD):* ${}\n'.format(large_number(mcap.mcap_usd)) s += '\t*Total 24h Volume USD):* ${}\n'.format(large_number(mcap.volume_usd_24h)) s += '\t*BTC Dominance:* {}'.format(percent(mcap.bitcoin_percentage_of_market_cap, emo=False)) return s def token_summary(token, btc_summary = None): s = '*{} ({}) {}*:\n'.format(token.name, token.symbol.upper(), emoji('charts')) s += '\t*Rank:* #{}\n'.format(token.rank) s += '\t*Price (USD):* ${}\n'.format(token.price) if btc_summary is not None: s += '\t*Price (BTC):* {}\n'.format(token.price_btc) s += '\t*24h Volume:* {}\n'.format(large_number(token.volume_24h)) s += '\t*Market Cap:* {}\n'.format(large_number(token.mcap)) s += '\t*Avail. Supply:* {}\n'.format(large_number(token.available_supply)) s += '\t*Total Supply:* {}\n'.format(large_number(token.total_supply)) s += '\t*Max Supply:* {}\n'.format(large_number(token.max_supply)) s += '\t*Change (USD):*\n' s += '```\t\t 1h: {}\n'.format(percent(token.percent_change_1h, emo=True)) s += '\t\t24h: {}\n'.format(percent(token.percent_change_24h, emo=True)) s += '\t\t 7d: {}```'.format(percent(token.percent_change_7d, emo=True)) if btc_summary is not None: s += '\n\t*Change (BTC)*:\n' s += '```\t\t24h: {}\n'.format(percent(btc_summary.pct_today, emo=True)) s += '\t\t 7d: {}\n'.format(percent(btc_summary.pct_week, emo=True)) s += '\t\t30d: {}```'.format(percent(btc_summary.pct_month, emo=True)) return s def token_compared_summary(token, other_token): s = '*{} {} {}*:\n'.format(token.name, emoji('vs'), other_token.name) s += '\t*Rank:* #{} vs #{}\n'.format(token.rank, other_token.rank) s += '\t*Price (USD):* ${} vs ${}\n'.format(token.price, other_token.price) s += '\t*Price (BTC):* {} vs {}\n'.format(token.price_btc, other_token.price_btc) s += '\t*24h Volume:* {} vs {}\n'.format(large_number(token.volume_24h), large_number(other_token.volume_24h)) s += '\t*Market Cap:* {} vs {}\n'.format(large_number(token.mcap), large_number(other_token.mcap)) s += '\t*Avail. Supply:* {} vs {}\n'.format(large_number(token.available_supply), large_number(other_token.available_supply)) s += '\t*Total Supply:* {} vs {}\n'.format(large_number(token.total_supply), large_number(other_token.total_supply)) s += '\t*Max Supply:* {} vs {}\n'.format(large_number(token.max_supply), large_number(other_token.max_supply)) s += '\t*Change (USD):*\n' s += '```\t\t 1h: {} vs {}\n'.format(percent(token.percent_change_1h, emo=True), percent(other_token.percent_change_1h, emo=True)) s += '\t\t24h: {} vs {}\n'.format(percent(token.percent_change_24h, emo=True), percent(other_token.percent_change_24h, emo=True)) s += '\t\t 7d: {} vs {}```'.format(percent(token.percent_change_7d, emo=True), percent(other_token.percent_change_7d, emo=True)) mcap_factor = other_token.mcap / token.mcap factor_price = mcap_factor * token.price vol_factor = other_token.volume_24h / token.volume_24h s += '\t*{} has {:.2f}x the 24h volume of {}.*\n\n'.format(other_token.name, vol_factor, token.name) s += '\t*If {} had the cap of {}, the USD price would be: ${} ({:.1f}x)*'.format(token.name, other_token.name, factor_price, mcap_factor) return s def airdrop_summary(airdrop): if airdrop.today: return "\t- *{}* (*today*)\n".format(airdrop.title) elif airdrop.ongoing: return "\t- *{}* (*ongoing*)\n".format(airdrop.title) elif airdrop.finished: return "\t- *{}* (*finished*)\n".format(airdrop.title) else: return "\t- *{}* (*in {} days*)\n".format(airdrop.title, airdrop.when.days) def airdrops_summary(airdrops, limit = 20): text = "*Upcoming Airdrops{}:*\n".format(emoji('squirt')) for airdrop in sorted(airdrops, key=attrgetter('when.days'), reverse=False)[:limit]: text += airdrop_summary(airdrop) return text def token_ranks_summary(token, ranks): triangle = stringformat.emoji('triangle_up') return '\t-{}*{}* ({}/{}): *{}* ({}, #{})\n'.format(triangle, -ranks.diff_today, -ranks.diff_week, -ranks.diff_month, token.name, token.symbol, ranks.now) def tokens_ranks_summary(token_ranks): text = '*CoinMarketCap rank climbers (w/m):*\n' for (token, ranks) in token_ranks: text += token_ranks_summary(token, ranks) text += '\nShowing All Time High ranks only {}'.format(stringformat.emoji('fire')) return text
{"/db.py": ["/model.py"], "/api.py": ["/model.py"]}
75,227
Driver2007/SRS_SIM928
refs/heads/master
/SRS_SIM928.py
#!/usr/bin/env python # -*- coding:utf-8 -*- # ############################################################################ # license : # ============================================================================ # # File : SRS_SIM928.py # # Project : SRS_SIM928 # # This file is part of Tango device class. # # Tango is free software: you can redistribute it and/or modify # it under the terms of the MIT licence. # # # $Author : mellguth$ # # $Revision : $ # # $Date : $ # # $HeadUrl : $ # ============================================================================ # This file is generated by POGO # (Program Obviously used to Generate tango Object) # ############################################################################ __all__ = ["SRS_SIM928", "SRS_SIM928Class", "main"] __docformat__ = 'restructuredtext' import PyTango import sys # Add additional import #----- PROTECTED REGION ID(SRS_SIM928.additionnal_import) ENABLED START -----# import time from threading import Thread from SRS_SIM928_Hardware import SRS_SIM928_Hardware #----- PROTECTED REGION END -----# // SRS_SIM928.additionnal_import # Device States Description # No states for this device class SRS_SIM928 (PyTango.Device_4Impl): """SRS SIM928 Isolated VOltage Source""" # -------- Add you global variables here -------------------------- #----- PROTECTED REGION ID(SRS_SIM928.global_variables) ENABLED START -----# #----- PROTECTED REGION END -----# // SRS_SIM928.global_variables def __init__(self, cl, name): PyTango.Device_4Impl.__init__(self,cl,name) self.debug_stream("In __init__()") SRS_SIM928.init_device(self) #----- PROTECTED REGION ID(SRS_SIM928.__init__) ENABLED START -----# #----- PROTECTED REGION END -----# // SRS_SIM928.__init__ def delete_device(self): self.debug_stream("In delete_device()") #----- PROTECTED REGION ID(SRS_SIM928.delete_device) ENABLED START -----# self.polling_thread_stop = True self.polling_thread.join() #----- PROTECTED REGION END -----# // SRS_SIM928.delete_device def init_device(self): self.debug_stream("In init_device()") self.get_device_properties(self.get_device_class()) self.attr_VoltSet_read = 0.0 self.attr_Volt_read = 0.0 self.attr_OutputOn_read = False self.attr_OutputOnSet_read = False self.attr_Battery1State_read = 0 self.attr_Battery1StateStr_read = "" self.attr_Battery2State_read = 0 self.attr_Battery2StateStr_read = "" self.attr_BatteryInfo_read = "" self.attr_DevIdent_read = "" self.attr_Trigger_BatChargeOverride_read = 0 self.attr_Connected_read = False self.attr_BatteryService_read = False self.attr_Trigger_Reconnect_read = 0 self.attr_Trigger_Disconnect_read = 0 #----- PROTECTED REGION ID(SRS_SIM928.init_device) ENABLED START -----# self.hw = SRS_SIM928_Hardware() self.hw.add_connection_listener(self.on_hw_connection_change) self.hw.connect(self.SerialDevice, baudrate=self.Baudrate) ### self.init_info_thread = Thread(target=self.init_sim928_info_thread_body) self.init_info_thread.daemon = True self.init_info_thread.start() ### self.polling_thread_stop = False self.polling_thread = Thread(target=self.polling_thread_body) self.polling_thread.start() #----- PROTECTED REGION END -----# // SRS_SIM928.init_device def always_executed_hook(self): self.debug_stream("In always_excuted_hook()") #----- PROTECTED REGION ID(SRS_SIM928.always_executed_hook) ENABLED START -----# #----- PROTECTED REGION END -----# // SRS_SIM928.always_executed_hook # ------------------------------------------------------------------------- # SRS_SIM928 read/write attribute methods # ------------------------------------------------------------------------- def read_VoltSet(self, attr): self.debug_stream("In read_VoltSet()") #----- PROTECTED REGION ID(SRS_SIM928.VoltSet_read) ENABLED START -----# attr.set_value(self.attr_VoltSet_read) #----- PROTECTED REGION END -----# // SRS_SIM928.VoltSet_read def write_VoltSet(self, attr): self.debug_stream("In write_VoltSet()") data = attr.get_write_value() #----- PROTECTED REGION ID(SRS_SIM928.VoltSet_write) ENABLED START -----# if self.hw.connected: self.hw.write_volt(data) self.attr_VoltSet_read = data #----- PROTECTED REGION END -----# // SRS_SIM928.VoltSet_write def read_Volt(self, attr): self.debug_stream("In read_Volt()") #----- PROTECTED REGION ID(SRS_SIM928.Volt_read) ENABLED START -----# attr.set_value(self.attr_Volt_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Volt_read def read_OutputOn(self, attr): self.debug_stream("In read_OutputOn()") #----- PROTECTED REGION ID(SRS_SIM928.OutputOn_read) ENABLED START -----# attr.set_value(self.attr_OutputOn_read) #----- PROTECTED REGION END -----# // SRS_SIM928.OutputOn_read def read_OutputOnSet(self, attr): self.debug_stream("In read_OutputOnSet()") #----- PROTECTED REGION ID(SRS_SIM928.OutputOnSet_read) ENABLED START -----# attr.set_value(self.attr_OutputOnSet_read) #----- PROTECTED REGION END -----# // SRS_SIM928.OutputOnSet_read def write_OutputOnSet(self, attr): self.debug_stream("In write_OutputOnSet()") data = attr.get_write_value() #----- PROTECTED REGION ID(SRS_SIM928.OutputOnSet_write) ENABLED START -----# if data==True and self.hw.connected: self.hw.write_output_on(True) elif data==False and self.hw.connected: self.hw.write_output_on(False) self.attr_OutputOnSet_read = data #----- PROTECTED REGION END -----# // SRS_SIM928.OutputOnSet_write def read_Battery1State(self, attr): self.debug_stream("In read_Battery1State()") #----- PROTECTED REGION ID(SRS_SIM928.Battery1State_read) ENABLED START -----# attr.set_value(self.attr_Battery1State_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Battery1State_read def read_Battery1StateStr(self, attr): self.debug_stream("In read_Battery1StateStr()") #----- PROTECTED REGION ID(SRS_SIM928.Battery1StateStr_read) ENABLED START -----# attr.set_value(self.attr_Battery1StateStr_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Battery1StateStr_read def read_Battery2State(self, attr): self.debug_stream("In read_Battery2State()") #----- PROTECTED REGION ID(SRS_SIM928.Battery2State_read) ENABLED START -----# attr.set_value(self.attr_Battery2State_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Battery2State_read def read_Battery2StateStr(self, attr): self.debug_stream("In read_Battery2StateStr()") #----- PROTECTED REGION ID(SRS_SIM928.Battery2StateStr_read) ENABLED START -----# attr.set_value(self.attr_Battery2StateStr_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Battery2StateStr_read def read_BatteryInfo(self, attr): self.debug_stream("In read_BatteryInfo()") #----- PROTECTED REGION ID(SRS_SIM928.BatteryInfo_read) ENABLED START -----# attr.set_value(self.attr_BatteryInfo_read) #----- PROTECTED REGION END -----# // SRS_SIM928.BatteryInfo_read def read_DevIdent(self, attr): self.debug_stream("In read_DevIdent()") #----- PROTECTED REGION ID(SRS_SIM928.DevIdent_read) ENABLED START -----# attr.set_value(self.attr_DevIdent_read) #----- PROTECTED REGION END -----# // SRS_SIM928.DevIdent_read def read_Trigger_BatChargeOverride(self, attr): self.debug_stream("In read_Trigger_BatChargeOverride()") #----- PROTECTED REGION ID(SRS_SIM928.Trigger_BatChargeOverride_read) ENABLED START -----# attr.set_value(self.attr_Trigger_BatChargeOverride_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Trigger_BatChargeOverride_read def write_Trigger_BatChargeOverride(self, attr): self.debug_stream("In write_Trigger_BatChargeOverride()") data = attr.get_write_value() #----- PROTECTED REGION ID(SRS_SIM928.Trigger_BatChargeOverride_write) ENABLED START -----# self.BatChargeOverride() #----- PROTECTED REGION END -----# // SRS_SIM928.Trigger_BatChargeOverride_write def read_Connected(self, attr): self.debug_stream("In read_Connected()") #----- PROTECTED REGION ID(SRS_SIM928.Connected_read) ENABLED START -----# attr.set_value(self.attr_Connected_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Connected_read def read_BatteryService(self, attr): self.debug_stream("In read_BatteryService()") #----- PROTECTED REGION ID(SRS_SIM928.BatteryService_read) ENABLED START -----# attr.set_value(self.attr_BatteryService_read) #----- PROTECTED REGION END -----# // SRS_SIM928.BatteryService_read def read_Trigger_Reconnect(self, attr): self.debug_stream("In read_Trigger_Reconnect()") #----- PROTECTED REGION ID(SRS_SIM928.Trigger_Reconnect_read) ENABLED START -----# attr.set_value(self.attr_Trigger_Reconnect_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Trigger_Reconnect_read def write_Trigger_Reconnect(self, attr): self.debug_stream("In write_Trigger_Reconnect()") data = attr.get_write_value() #----- PROTECTED REGION ID(SRS_SIM928.Trigger_Reconnect_write) ENABLED START -----# self.Reconnect() #----- PROTECTED REGION END -----# // SRS_SIM928.Trigger_Reconnect_write def read_Trigger_Disconnect(self, attr): self.debug_stream("In read_Trigger_Disconnect()") #----- PROTECTED REGION ID(SRS_SIM928.Trigger_Disconnect_read) ENABLED START -----# attr.set_value(self.attr_Trigger_Disconnect_read) #----- PROTECTED REGION END -----# // SRS_SIM928.Trigger_Disconnect_read def write_Trigger_Disconnect(self, attr): self.debug_stream("In write_Trigger_Disconnect()") data = attr.get_write_value() #----- PROTECTED REGION ID(SRS_SIM928.Trigger_Disconnect_write) ENABLED START -----# self.Disconnect() #----- PROTECTED REGION END -----# // SRS_SIM928.Trigger_Disconnect_write def read_attr_hardware(self, data): self.debug_stream("In read_attr_hardware()") #----- PROTECTED REGION ID(SRS_SIM928.read_attr_hardware) ENABLED START -----# #----- PROTECTED REGION END -----# // SRS_SIM928.read_attr_hardware # ------------------------------------------------------------------------- # SRS_SIM928 command methods # ------------------------------------------------------------------------- def Reconnect(self): """ """ self.debug_stream("In Reconnect()") #----- PROTECTED REGION ID(SRS_SIM928.Reconnect) ENABLED START -----# if self.hw.connected: return self.hw.connect(self.SerialDevice, baudrate=self.Baudrate) #----- PROTECTED REGION END -----# // SRS_SIM928.Reconnect def Disconnect(self): """ """ self.debug_stream("In Disconnect()") #----- PROTECTED REGION ID(SRS_SIM928.Disconnect) ENABLED START -----# if not self.hw.connected: return self.hw.disconnect() #----- PROTECTED REGION END -----# // SRS_SIM928.Disconnect def BatChargeOverride(self): """ Forces the SIM928 to switch the active output battery """ self.debug_stream("In BatChargeOverride()") #----- PROTECTED REGION ID(SRS_SIM928.BatChargeOverride) ENABLED START -----# if self.attr_Connected_read: self.hw.write_bat_charge_override() #----- PROTECTED REGION END -----# // SRS_SIM928.BatChargeOverride #----- PROTECTED REGION ID(SRS_SIM928.programmer_methods) ENABLED START -----# def on_hw_connection_change(self, connected): if connected: self.set_state(PyTango.DevState.ON) self.attr_Connected_read = True else: self.set_state(PyTango.DevState.OFF) self.attr_Connected_read = False def init_sim928_info_thread_body(self): while not self.attr_Connected_read: time.sleep(0.5) self.attr_DevIdent_read = self.hw.read_ident() time.sleep(0.2) pnum = self.hw.read_battery_info(0) time.sleep(0.2) ser = self.hw.read_battery_info(1) time.sleep(0.2) maxcy = self.hw.read_battery_info(2) time.sleep(0.2) nrcy = self.hw.read_battery_info(3) time.sleep(0.2) pdate = self.hw.read_battery_info(4) batinfo = "" batinfo = batinfo + "Battery pack part number : {p}\n".format(p=pnum) batinfo = batinfo + "Battery pack serial number : {p}\n".format(p=ser) batinfo = batinfo + "Design life, nr of charge cycles : {p}\n".format(p=maxcy) batinfo = batinfo + "nr of charge cycles used : {p}\n".format(p=nrcy) batinfo = batinfo + "Battery pack production date : {p}\n".format(p=pdate) self.attr_BatteryInfo_read = batinfo def polling_thread_body(self): while not self.attr_Connected_read and not self.polling_thread_stop: time.sleep(0.5) if self.polling_thread_stop: return time.sleep(4.0) # wait x seconds before starting to poll the device loopidx = 0 while not self.polling_thread_stop: if not self.attr_Connected_read: time.sleep(1.0) continue if loopidx % 10 == 1: bstate = self.hw.read_battery_state() bstatestr = self.hw.battery_state_str try: self.attr_Battery1State_read = bstate[0] self.attr_Battery2State_read = bstate[1] self.attr_Battery1StateStr_read = bstatestr[0] self.attr_Battery2StateStr_read = bstatestr[1] self.attr_BatteryService_read = bstate[2]==1 except Exception as e: print("Exception in polling thread: ") print(e) time.sleep(0.1) outputon = self.hw.read_output_on() self.attr_OutputOn_read = outputon time.sleep(0.1) voltval = self.hw.read_volt() if voltval!=None: self.attr_Volt_read = voltval time.sleep(0.4) loopidx = (loopidx + 1) % 1000 #----- PROTECTED REGION END -----# // SRS_SIM928.programmer_methods class SRS_SIM928Class(PyTango.DeviceClass): # -------- Add you global class variables here -------------------------- #----- PROTECTED REGION ID(SRS_SIM928.global_class_variables) ENABLED START -----# #----- PROTECTED REGION END -----# // SRS_SIM928.global_class_variables # Class Properties class_property_list = { } # Device Properties device_property_list = { 'SerialDevice': [PyTango.DevString, "Device file for serial\n(the first RS232 PCI card on Ubuntu 14.04\ntypically gets /dev/ttyS4 and /dev/ttyS5 if it\nhas two RS232 ports)", [] ], 'Baudrate': [PyTango.DevString, "Baudrate for RS232 connection\ndefault: 9600", [] ], } # Command definitions cmd_list = { 'Reconnect': [[PyTango.DevVoid, "none"], [PyTango.DevVoid, "none"]], 'Disconnect': [[PyTango.DevVoid, "none"], [PyTango.DevVoid, "none"]], 'BatChargeOverride': [[PyTango.DevVoid, "none"], [PyTango.DevVoid, "none"]], } # Attribute definitions attr_list = { 'VoltSet': [[PyTango.DevDouble, PyTango.SCALAR, PyTango.READ_WRITE], { 'label': "Voltage Setpoint", 'unit': "V", 'standard unit': "V", 'display unit': "V", 'format': "%7.3f", 'max value': "20.0", 'min value': "-20.0", 'Memorized':"true_without_hard_applied" } ], 'Volt': [[PyTango.DevDouble, PyTango.SCALAR, PyTango.READ], { 'label': "Voltage Readback", 'unit': "V", 'standard unit': "V", 'display unit': "V", 'format': "%7.3f", 'max value': "20.0", 'min value': "-20.0", } ], 'OutputOn': [[PyTango.DevBoolean, PyTango.SCALAR, PyTango.READ]], 'OutputOnSet': [[PyTango.DevBoolean, PyTango.SCALAR, PyTango.READ_WRITE]], 'Battery1State': [[PyTango.DevLong, PyTango.SCALAR, PyTango.READ]], 'Battery1StateStr': [[PyTango.DevString, PyTango.SCALAR, PyTango.READ]], 'Battery2State': [[PyTango.DevLong, PyTango.SCALAR, PyTango.READ]], 'Battery2StateStr': [[PyTango.DevString, PyTango.SCALAR, PyTango.READ]], 'BatteryInfo': [[PyTango.DevString, PyTango.SCALAR, PyTango.READ]], 'DevIdent': [[PyTango.DevString, PyTango.SCALAR, PyTango.READ]], 'Trigger_BatChargeOverride': [[PyTango.DevLong, PyTango.SCALAR, PyTango.READ_WRITE], { 'description': "Triggers execution of the BatChargeOverride command when written to", } ], 'Connected': [[PyTango.DevBoolean, PyTango.SCALAR, PyTango.READ]], 'BatteryService': [[PyTango.DevBoolean, PyTango.SCALAR, PyTango.READ], { 'description': "True if service batteries LED on the SIM928 is lit.", } ], 'Trigger_Reconnect': [[PyTango.DevLong, PyTango.SCALAR, PyTango.READ_WRITE]], 'Trigger_Disconnect': [[PyTango.DevLong, PyTango.SCALAR, PyTango.READ_WRITE]], } def main(): try: py = PyTango.Util(sys.argv) py.add_class(SRS_SIM928Class, SRS_SIM928, 'SRS_SIM928') #----- PROTECTED REGION ID(SRS_SIM928.add_classes) ENABLED START -----# #----- PROTECTED REGION END -----# // SRS_SIM928.add_classes U = PyTango.Util.instance() U.server_init() U.server_run() except PyTango.DevFailed as e: print ('-------> Received a DevFailed exception:', e) except Exception as e: print ('-------> An unforeseen exception occured....', e) if __name__ == '__main__': main()
{"/SRS_SIM928.py": ["/SRS_SIM928_Hardware.py"]}
75,228
Driver2007/SRS_SIM928
refs/heads/master
/SRS_SIM928_Hardware.py
### written on python 2.7 PARITY = 'N' STOPBITS = 1 BYTESIZE = 8 XONXOFF = False RTSCTS = True TIMEOUT = 0.1 # in seconds when reading from the device SENDTERMSTR = '\r\n' RESPONSETERMSTR = '\r\n' # used to distinguish whether the received characters form a complete response import serial import time class SRS_SIM928_Hardware: def __init__(self): self.baudrate = None self.devfile = None self.serial = None self.connected = False self.conn_callbacks = [] self.busy = False self.info_ident = "" self.battery_state = (-1,-1,-1) self.battery_state_str = ("unknown", "unknown", "unknown") self.battery_state_desc = {-1: "unknown", 0 : "", 1 : "in use", 2 : "charging", 3 : "ready/standby"} def connect(self, devfile, baudrate=None): if self.connected: return self.devfile = devfile self.baudrate = 9600 if baudrate==None else baudrate self.serial = serial.Serial(self.devfile, baudrate=self.baudrate, parity=PARITY, stopbits=STOPBITS, bytesize=BYTESIZE, timeout=TIMEOUT, xonxoff=XONXOFF, rtscts=RTSCTS) if not self.serial.isOpen(): print("Error while connecting.") return False else: self.connected = True print("Connected.") for c in self.conn_callbacks: c(True) return True def disconnect(self): if not self.serial.isOpen(): return self.serial.close() self.connected = False for c in self.conn_callbacks: c(False) def read_ident(self): self.info_ident = self.send_and_receive("*IDN?") return str(self.info_ident).strip() def read_battery_state(self): answer = self.send_and_receive("BATS?") tokens = answer.split(',') try: self.battery_state = (int(tokens[0]), int(tokens[1]), int(tokens[2])) self.battery_state_str = (self.battery_state_desc[self.battery_state[0]], self.battery_state_desc[self.battery_state[1]], "ok" if self.battery_state[2]==0 else "battery service needed") return self.battery_state except: return (-1,-1,-1) def read_output_on(self): answer = self.send_and_receive("EXON?") try: output_state = int(answer) return output_state except: return -1 def write_output_on(self, on_state=True): if on_state: self.send("OPON") else: self.send("OPOF") def read_volt(self): answer = self.send_and_receive("VOLT?") try: return float(answer) except ValueError: print("Got non-float voltage value from device: ", answer) return None def write_volt(self, volt): try: volt = float(volt) except: return if volt>20.0: volt = 20.0 if volt<-20.0: volt = -20.0 self.send("VOLT {v:5.3f}".format(v=volt)) def clear_status(self): self.send("*CLS") def write_bat_charge_override(self): self.send("BCOR") def read_battery_info(self, parameter=0): """ allowed parameter values are 0 = PNUM (Battery pack part number) 1 = SERIAL (Battery pack serial number) 2 = MAXCY (Design life, number of charge cycles) 3 = CYCLES (number of charge cycles used) 4 = PDATE (Battery pack production date (YYYY-MM-DD)) """ try: parameter = int(parameter) except: return if parameter < 0 or parameter > 4: return answer = self.send_and_receive("BIDN? " + str(parameter)) return str(answer).strip() def add_connection_listener(self, callback): self.conn_callbacks.append(callback) def send(self, sendstr): self.send_and_receive(sendstr, receive=False) def send_and_receive(self, sendstr, receive=True, maxtries=10): if not self.serial or not self.serial.isOpen(): return "" while (self.busy): time.sleep(0.02) self.busy = True try: #print("sending ", sendstr) s=sendstr.strip('\n\r')+SENDTERMSTR #s = bytes(s, "utf-8") # needed only in python3 (?) self.serial.write(s) if not receive: return None #time.sleep(0.1) responsebuf = "" loops = 0 while not responsebuf.endswith(RESPONSETERMSTR) and loops < maxtries: buf = self.serial.read(10000) # insecure, should receive until line ending! responsebuf += buf.decode('utf-8') #print("received " + str(len(buf)) + " bytes.") loops = loops + 1 #print("received ", responsebuf) return responsebuf except: self.busy = False raise finally: self.busy = False
{"/SRS_SIM928.py": ["/SRS_SIM928_Hardware.py"]}
75,240
n3mo-dev/Todo
refs/heads/master
/homepage/views.py
from django.shortcuts import render, HttpResponseRedirect from homepage.models import Todo # Create your views here. def mainpage(request): return render(request, 'mainpage.html') def todo(request): item = Todo.objects.all() dict = { 'item' : item } return render(request, 'todo.html', dict) def addtodo(request): item = Todo(Data = request.POST['data']) item.save() return HttpResponseRedirect('/todo/') def deletetodo(request, itemid): item = Todo.objects.get(id=itemid) item.delete() return HttpResponseRedirect('/todo/')
{"/homepage/views.py": ["/homepage/models.py"]}
75,241
n3mo-dev/Todo
refs/heads/master
/homepage/models.py
from django.db import models class Todo(models.Model): Data = models.TextField()
{"/homepage/views.py": ["/homepage/models.py"]}
75,253
Hoxtygen/flexible-architecture
refs/heads/master
/change_name.py
import requests import time from decouple import config from goto import goto TOKEN = config("TOKEN") DESIRED_NAME = config("NAME") auth = {"Authorization": "Token " + TOKEN} def get_current_room(): res = requests.get( "https://lambda-treasure-hunt.herokuapp.com/api/adv/init/", headers=auth ) res_json = res.json() time.sleep(res_json["cooldown"]) return res_json["room_id"] def change_name(): res = requests.post( "https://lambda-treasure-hunt.herokuapp.com/api/adv/change_name/", headers=auth, json={"name": DESIRED_NAME, "confirm": "aye"} ) return res.json() if __name__ == "__main__": current_room = get_current_room() change_name_room = "467" goto(str(current_room), change_name_room) response = change_name() print(response)
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,254
Hoxtygen/flexible-architecture
refs/heads/master
/examine_well.py
import requests import time from decouple import config from goto import goto TOKEN = config("TOKEN") auth = {"Authorization": "Token " + TOKEN} def get_current_room(): res = requests.get( "https://lambda-treasure-hunt.herokuapp.com/api/adv/init/", headers=auth ) res_json = res.json() time.sleep(res_json["cooldown"]) return res_json["room_id"] def examine(): res = requests.post( "https://lambda-treasure-hunt.herokuapp.com/api/adv/examine/", headers=auth, json={"name": "well"} ) res_json = res.json() time.sleep(res_json["cooldown"]) return res.json() if __name__ == "__main__": # get the current room current_room = get_current_room() # wishing well room wishing_well_room = "55" # go to the room if not there already goto(str(current_room), wishing_well_room) # examine the well response = examine() # write the well prophecy to a file with open("wishing_well_prophecy.txt", "w") as f: f.write(response["description"]) # print response print(response)
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,255
Hoxtygen/flexible-architecture
refs/heads/master
/clean_room_details.py
import json # to hold the rooms room_details = [] with open("room_details.py", "r") as f: # read room_details.py into room_details list room_details = json.loads(f.read()) print("Length before cleaning is: ", len(room_details)) # will hold room ids room_set = set() # will contain a single copy of each room cleaned_rooms = [] # loop through every room in room_details for room in room_details: # check if the room id is not in the set if room["room_id"] not in room_set: # add the room id to set to remove repetition room_set.add(room["room_id"]) # add it to the cleaned_room list cleaned_rooms.append(room) print("Length after cleaning is: ", len(cleaned_rooms)) # write the result to the cleaned room_details file with open("traverse_results/room_details.py", "w") as f: f.write(json.dumps(cleaned_rooms))
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,256
Hoxtygen/flexible-architecture
refs/heads/master
/goto.py
import json import requests from decouple import config from time import sleep import argparse from util import Queue def directionToRoom(room_map, current_room_id, room_id): for d, r in room_map[current_room_id].items(): if r == room_id: return d return None def find_path(room_map, current_room_id, destination_room_id): visited = set() paths = {} q = Queue() q.enqueue(current_room_id) paths[current_room_id] = [current_room_id] while q.size() > 0: room = q.dequeue() visited.add(room) for searched_room_id in room_map[room].values(): if searched_room_id in visited or searched_room_id == '?': continue newPath = paths[room][:] newPath.append(searched_room_id) paths[searched_room_id] = newPath if searched_room_id == destination_room_id: correct_path = paths[searched_room_id] directions = [] for i in range(len(correct_path) - 1): directions.append(directionToRoom( room_map, correct_path[i], correct_path[i + 1])) return directions q.enqueue(searched_room_id) return None def goto(current_room_id, destination_room_id_or_title, can_fly=False, can_dash=False): TOKEN = config("TOKEN") room_details = [] room_map = {} with open("room_details_copy.py", "r") as f: room_details = json.loads(f.read()) with open("room_graph_copy.py", "r") as f: room_map = json.loads(f.read()) destination_room_id = destination_room_id_or_title # if room id not in room_graph if destination_room_id not in room_map: # find room with specified name in room_details destination_room_id_or_title = destination_room_id_or_title.lower() for room_info in room_details: if room_info['title'].lower() == destination_room_id_or_title: destination_room_id = str(room_info['room_id']) break # Traverse the map to find the path path = find_path(room_map, current_room_id, destination_room_id) # If path not found, print "path to {destination_room_id} not found" if not path: print(f"path to {destination_room_id} not found") return # If path found, go through each room to the destination room for i in range(len(path)): used_flight = False used_dash = False data = {} # fly if can fly and terrain is elevated if can_fly: for room_info in room_details: if str(room_info['room_id']) == current_room_id: if room_info['terrain'].lower() == "elevated": data = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/fly/", json={ "direction": path[i]}, headers={'Authorization': f"Token {TOKEN}"}).json() used_flight = True break else: break # dash if can dash and didn't use fly and there is more rooms to dash through than 1 if can_dash and not used_flight: directions_to_dash_through = [path[i]] j = i + 1 while j < len(path): if path[j] == directions_to_dash_through[j - 1]: directions_to_dash_through.append(path[j]) else: break if len(directions_to_dash_through) > 1: # get ids out of to_dash_through ids_to_dash_through = [] cur = current_room_id for direction in directions_to_dash_through: next_room_id = room_map[cur][direction] ids_to_dash_through.append(next_room_id) cur = next_room_id ids_to_dash_through = ','.join(ids_to_dash_through) data = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/dash/", json={ "direction": path[i], "next_room_ids": ids_to_dash_through}, headers={'Authorization': f"Token {TOKEN}"}).json() i += len(directions_to_dash_through) - 1 used_dash = True # just walk if didn't use flight or dash if not used_flight and not used_dash: next_room_id = room_map[current_room_id][path[i]] data = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/move/", json={ "direction": path[i], "next_room_id": next_room_id}, headers={'Authorization': f"Token {TOKEN}"}).json() cooldown = data["cooldown"] print(data) sleep(cooldown) current_room_id = str(data['room_id']) def get_current_room(): TOKEN = config("TOKEN") # make request to the init endpoint response = requests.get("https://lambda-treasure-hunt.herokuapp.com/api/adv/init/", headers={'Authorization': f"Token {TOKEN}"}).json() # get room id room_id = response["room_id"] # get cooldown and sleep for the cooldown period cooldown = response["cooldown"] sleep(cooldown) # return the room_id in string format return str(room_id) if __name__ == "__main__": # instantiate the argument parser parser = argparse.ArgumentParser() # add the filename argument to the parser parser.add_argument("destination", help="The room you want to go to") # parse to get the argument args = parser.parse_args() # get the player's current room current_room = get_current_room() # get the destination room destination_room = args.destination # call goto with the arg and current room goto(current_room, destination_room)
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,257
Hoxtygen/flexible-architecture
refs/heads/master
/mine/mine.py
# import requests # import time # import hashlib # from decouple import config # # TOKEN = config("TOKEN") # # auth = {"Authorization": "Token " + TOKEN} # # # def get_last_proof(): # res = requests.get( # "https://lambda-treasure-hunt.herokuapp.com/api/bc/last_proof/", # headers=auth # ) # return res.json() # # # def mine(new_proof): # res = requests.post( # "https://lambda-treasure-hunt.herokuapp.com/api/bc/mine/", # headers=auth, # json={"proof": new_proof} # ) # print(res) # return res.json() # # # def valid_proof(last_proof, proof, difficulty): # checksum = '0' * difficulty # guess = f'{last_proof}{proof}'.encode() # guess_hash = hashlib.sha256(guess).hexdigest() # return guess_hash[:difficulty] == checksum # # # last_proof_obj = get_last_proof() # last_proof = last_proof_obj['proof'] # diff = last_proof_obj['difficulty'] # time.sleep(last_proof_obj['cooldown']) # # # def proof_of_work(start_point): # print("Mining new block") # # start_time = time.time() # proof = int(start_point) # while valid_proof(last_proof, proof, diff) is False: # proof += 1 # # end_time = time.time() # print( # f'Block mined in {round(end_time-start_time, 2)}sec. Nonce: {str(proof)}') # # print("Mining with proof...") # response = mine(proof) # return response # # # if __name__ == "__main__": # while True: # res = proof_of_work(0) # time.sleep(res["cooldown"]) import requests import time import hashlib from decouple import config TOKEN = config("TOKEN") auth = {"Authorization": "Token " + TOKEN} def get_last_proof(): res = requests.get( "https://lambda-treasure-hunt.herokuapp.com/api/bc/last_proof/", headers=auth ) return res.json() def mine(new_proof): res = requests.post( "https://lambda-treasure-hunt.herokuapp.com/api/bc/mine/", headers=auth, json={"proof": new_proof} ) res_json = res.json() print(res_json) return res_json def valid_proof(last_proof, proof, difficulty): checksum = '0' * difficulty guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:difficulty] == checksum last_proof_obj = get_last_proof() last_proof = last_proof_obj['proof'] diff = last_proof_obj['difficulty'] time.sleep(last_proof_obj['cooldown']) def proof_of_work(start_point): print("Mining new block") start_time = time.time() proof = int(start_point) while valid_proof(last_proof, proof, diff) is False: proof += 1 end_time = time.time() print( f'Block mined in {round(end_time-start_time, 2)}sec. Nonce: {str(proof)}') print("Mining with proof...") response = mine(proof) return response if __name__ == "__main__": while True: res = proof_of_work(0) time.sleep(res["cooldown"])
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,258
Hoxtygen/flexible-architecture
refs/heads/master
/treasure_hunter.py
import json import requests from decouple import config from time import sleep from random import randint from util import Queue from goto import goto, find_path def goto_treasure(current_room_id, destination_room_id_or_title, can_fly=False, can_dash=False): TOKEN = config("TOKEN") room_details = [] room_map = {} with open("room_details_copy.py", "r") as f: room_details = json.loads(f.read()) with open("room_graph_copy.py", "r") as f: room_map = json.loads(f.read()) destination_room_id = destination_room_id_or_title # if room id not in room_graph if destination_room_id not in room_map: # find room with specified name in room_details destination_room_id_or_title = destination_room_id_or_title.lower() for room_info in room_details: if room_info['title'].lower() == destination_room_id_or_title: destination_room_id = str(room_info['room_id']) break # Traverse the map to find the path path = find_path(room_map, current_room_id, destination_room_id) # If path not found, print "path to {destination_room_id} not found" if not path: print(f"path to {destination_room_id} not found") return # If path found, go through each room to the destination room for i in range(len(path)): used_flight = False used_dash = False data = {} # fly if can fly and terrain is elevated if can_fly: for room_info in room_details: if str(room_info['room_id']) == current_room_id: if room_info['terrain'].lower() == "elevated": data = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/fly/", json={ "direction": path[i]}, headers={'Authorization': f"Token {TOKEN}"}).json() used_flight = True break else: break # dash if can dash and didn't use fly and there is more rooms to dash through than 1 if can_dash and not used_flight: directions_to_dash_through = [path[i]] j = i + 1 while j < len(path): if path[j] == directions_to_dash_through[j - 1]: directions_to_dash_through.append(path[j]) else: break if len(directions_to_dash_through) > 1: # get ids out of to_dash_through ids_to_dash_through = [] cur = current_room_id for direction in directions_to_dash_through: next_room_id = room_map[cur][direction] ids_to_dash_through.append(next_room_id) cur = next_room_id ids_to_dash_through = ','.join(ids_to_dash_through) data = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/dash/", json={ "direction": path[i], "next_room_ids": ids_to_dash_through}, headers={'Authorization': f"Token {TOKEN}"}).json() i += len(directions_to_dash_through) - 1 used_dash = True # just walk if didn't use flight or dash if not used_flight and not used_dash: next_room_id = room_map[current_room_id][path[i]] data = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/move/", json={ "direction": path[i], "next_room_id": next_room_id}, headers={'Authorization': f"Token {TOKEN}"}).json() cooldown = data["cooldown"] print(data) sleep(cooldown) current_room_id = str(data['room_id']) # get the items in the current room items = data["items"] # determines if current room has treasure or not has_treasure = False # loop through every item in the room for item in items: # if it is a treasure if item == "tiny treasure": # set has_treasure to true has_treasure = True # if a treasure has been found if has_treasure: # take the treasure response = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/take/", json={ "name": "treasure"}, headers={'Authorization': f"Token {TOKEN}"}).json() # get cooldown and sleep for the cooldown period cooldown = response["cooldown"] sleep(cooldown) print("\n****** Picked up a treasure ******\n") # return True to signify that a treasure has been found return True def get_current_room(): # make request to the init endpoint response = requests.get("https://lambda-treasure-hunt.herokuapp.com/api/adv/init/", headers={'Authorization': f"Token {TOKEN}"}).json() # get room id room_id = response["room_id"] # get cooldown and sleep for the cooldown period cooldown = response["cooldown"] sleep(cooldown) # return the room_id in string format return str(room_id) if __name__ == "__main__": TOKEN = config("TOKEN") # keep hunting until the user stops the script while True: # get the player's current room current_room = get_current_room() # set variable found_treasure to None found_treasure = None # while found_treasure is None while found_treasure is None: # generate a random interval between 2 and 500 target_room = str(randint(2, 499)) # call goto_treasure found_treasure = goto_treasure(current_room, target_room) # get current room current_room = get_current_room() # call goto and pass current location and 1 goto(current_room, "1") # sell the treasure response = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/sell/", json={ "name": "treasure"}, headers={'Authorization': f"Token {TOKEN}"}).json() # get cooldown and sleep for the cooldown period cooldown = response["cooldown"] sleep(cooldown) # sell the treasure response = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/sell/", json={ "name": "treasure", "confirm": "yes"}, headers={'Authorization': f"Token {TOKEN}"}).json() # get cooldown and sleep for the cooldown period cooldown = response["cooldown"] sleep(cooldown) # confirm sale response = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/status/", headers={'Authorization': f"Token {TOKEN}"}).json() # get cooldown and sleep for the cooldown period cooldown = response["cooldown"] sleep(cooldown) # get the gold balance gold = response["gold"] print("\n****** Sold a coin ******\n") print(f"\n****** You have {gold} gold coins ******\n")
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,259
Hoxtygen/flexible-architecture
refs/heads/master
/create_map.py
import json from time import sleep import pip._vendor.requests as requests from decouple import config from util import Queue # GET TOKEN TOKEN = config("TOKEN") # will hold the traversal path traversalPath = [] # shows the room mapping room_map = {} # shows room details room_details = [] with open("room_graph.py", "r") as f: # read the map from the room_graph world room_map = json.loads(f.read()) with open("room_details.py", "r") as f: # read the room details room_details = json.loads(f.read()) # get the player's current room # the current room is the last room in the room details current_room_id = room_details[-1]["room_id"] # reverses the direction reverse_directions = {"n": "s", "s": "n", "e": "w", "w": "e"} def get_unexplored_room(queue): current_room_id = str(room_details[-1]["room_id"]) # get direction available in the player's current room current_room = room_map[current_room_id] # will hold the unexplored_paths unexplored_paths = [] # loop through current room for d in current_room: # check if room direction is unexplored if current_room[d] == '?': # add to unexplored paths unexplored_paths.append(d) # if there are unexplored rooms here if unexplored_paths: # add the first room to the queue queue.enqueue(unexplored_paths[0]) # otherwise else: # call bft_find_other_room to find other unexplored rooms unexplored_path = bft_find_other_room() # if there are unexplored rooms if unexplored_path is not None: # loop through the unexplored paths for path in unexplored_path: # for exit in current curroom for exit in current_room: # if path is in current room, enqueue it if current_room[exit] == path: queue.enqueue(exit) def bft_find_other_room(): current_room_id = str(room_details[-1]["room_id"]) # create new room queue q = Queue() # hold the visited room visited = set() # enqueue the current room as a list q.enqueue([current_room_id]) # while the queue is not empty while q.size() > 0: # get the rooms rooms = q.dequeue() # grab the last room last_room = rooms[-1] # if the last room has not been visited if last_room not in visited: # add it to the visited set visited.add(last_room) # loop through the exits in the last room for exit in room_map[last_room]: # if unexplored, return the current room set if room_map[last_room][exit] == '?': return rooms # otherwise, else: # add the exit direction to the path new_path = list(rooms) new_path.append(room_map[last_room][exit]) # enqueue the new path q.enqueue(new_path) # return None if no unexplored room is found return None # create a queue q = Queue() # call get_unexplored_room with queue and player get_unexplored_room(q) # while there is still an unexplored room while q.size() > 0: with open("room_graph.py", "r") as f: # read the map from the room_graph world room_map = json.loads(f.read()) with open("room_details.py", "r") as f: # read the room details room_details = json.loads(f.read()) # current player position current_player_room = str(room_details[-1]["room_id"]) # the next direction next_direction = q.dequeue() # move the player in that direction response = requests.post("https://lambda-treasure-hunt.herokuapp.com/api/adv/move/", json={ "direction": next_direction}, headers={'Authorization': f"Token {TOKEN}"}) # add it to the traversal path traversalPath.append(next_direction) # get the response data = response.json() # set the player's destination room # add it to the room_datails room_details.append(data) # new player position destination_room = str(room_details[-1]["room_id"]) # update the map with the new discovery room_map[current_player_room][next_direction] = destination_room # if the current room has not been added to the map if destination_room not in room_map: exits = data["exits"] directions = {} for d in exits: directions[d] = "?" # add it and set to empty dictionary room_map[destination_room] = directions # get reverse direction to set it in the previous room r_direction = reverse_directions[next_direction] # point the destination room to the previous room room_map[destination_room][r_direction] = current_player_room # write the new changes to the file with open("room_graph.py", "w") as f: f.write(json.dumps(room_map)) with open("room_details.py", "w") as f: f.write(json.dumps(room_details)) # sleep the thread for the cooldown period cooldown = data["cooldown"] sleep(cooldown) # call get_unexplored_room to add the next direction to the queue get_unexplored_room(q)
{"/change_name.py": ["/goto.py"], "/examine_well.py": ["/goto.py"], "/treasure_hunter.py": ["/goto.py"]}
75,262
rammyblog/localibary
refs/heads/master
/LocalLibary/admin.py
from django.contrib import admin from .models import Book, Author, BookInstance, Language, Genre, Comment admin.site.register(Book) admin.site.register(Author) admin.site.register(BookInstance) admin.site.register(Language) admin.site.register(Genre) admin.site.register(Comment)
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,263
rammyblog/localibary
refs/heads/master
/LocalLibary/migrations/0001_initial.py
# Generated by Django 2.1.4 on 2018-12-18 17:05 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Author', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(help_text='Enter Frist Name of the Author', max_length=200)), ('last_name', models.CharField(help_text='Enter Last Name Of The Author', max_length=10000)), ('date_of_birth', models.DateField()), ('date_of_death', models.DateField(verbose_name='Died')), ], options={ 'ordering': ['first_name', 'last_name'], }, ), migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(help_text='Enter title of the book', max_length=200)), ('summary', models.CharField(help_text='Enter Summary of the book', max_length=10000)), ('isbn', models.CharField(help_text='Enter the 13 digits ISBN of the book ', max_length=13)), ('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='LocalLibary.Author')), ], ), migrations.CreateModel( name='BookInstance', fields=[ ('id', models.UUIDField(default=uuid.uuid4, help_text='Unique Text of Book', primary_key=True, serialize=False)), ('imprint', models.CharField(help_text='Enter imprint of book', max_length=200)), ('due_back', models.DateField(blank=True, null=True)), ('status', models.CharField(blank=True, choices=[('m', 'Mainteanance'), ('o', 'On Loan'), ('a', 'Available'), ('r', 'reserved')], default='m', help_text='Availability Of Book', max_length=1)), ('book', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='LocalLibary.Book')), ], options={ 'ordering': ['due_back'], }, ), migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('genre', models.CharField(help_text='Enter Genre(s) of the book', max_length=100)), ], ), migrations.CreateModel( name='Language', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('language', models.CharField(help_text='Enter the Language in which the book is written', max_length=50)), ], ), migrations.AddField( model_name='book', name='genre', field=models.ManyToManyField(help_text='Enter Genre(s)', to='LocalLibary.Genre'), ), migrations.AddField( model_name='book', name='language', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='LocalLibary.Language'), ), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,264
rammyblog/localibary
refs/heads/master
/LocalLibary/apps.py
from django.apps import AppConfig class LocallibaryConfig(AppConfig): name = 'LocalLibary'
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,265
rammyblog/localibary
refs/heads/master
/LocalLibary/models.py
from django.db import models from django.urls import reverse import uuid from django.contrib.auth.models import User from datetime import date class Genre(models.Model): genre = models.CharField(max_length=100, help_text = 'Enter Genre(s) of the book') def __str__(self): return self.genre class Language(models.Model): language = models.CharField(max_length=50, help_text='Enter the Language in which the book is written') def __str__(self): return self.language class Book(models.Model): title = models.CharField(max_length=200, help_text='Enter title of the book') summary = models.CharField(max_length=10000, help_text='Enter Summary of the book') isbn = models.CharField(max_length=13 , help_text='Enter the 13 digits ISBN of the book ') author = models.ForeignKey('Author', on_delete=models.SET_NULL, null= True) language = models.ForeignKey('Language', on_delete=models.SET_NULL, null= True) genre = models.ManyToManyField('Genre', help_text= "Enter Genre(s)") book_image = models.ImageField(null = True, blank = True) pub_date = models.DateField(null=True) def __str__(self): return f'{self.title}, {self.author}' def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default = uuid.uuid4, help_text = "Unique Text of Book") book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length =200, help_text='Enter imprint of book') due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) LOAN_STATUS = ( ('m', 'Mainteanance'), ('o', 'On Loan'), ('a', 'Available'), ('r', 'reserved'), ) status = models.CharField( max_length=1, choices = LOAN_STATUS, default = 'm', blank = True, help_text = 'Availability Of Book' ) class Meta: ordering = ['due_back'] permissions = (("can_mark_returned", "Set book as returned"),("can_edit_status", "Set status of book")) # permissions = (("can_mark_returned", "Set book as returned"),) @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False def __str__(self): return f'{self.id}, {self.imprint}' class Author(models.Model): first_name = models.CharField(max_length=200, help_text='Enter Frist Name of the Author') last_name = models.CharField(max_length=10000, help_text='Enter Last Name Of The Author') date_of_birth = models.DateField() date_of_death = models.DateField('Died', null=True, blank=True) author_image = models.ImageField(null = True, blank = True) about = models.CharField(max_length=100000, null=True, blank=True) # country = models.CharField(max_length =50, null= True, blank= True) class Meta: ordering = ['last_name', 'first_name'] def __str__(self): return f'{self.last_name}, {self.first_name}' def get_absolute_url(self): return reverse ('author-detail', args=[str(self.id)]) class Comment(models.Model): name = models.CharField(max_length = 30) message = models.TextField(max_length= 4000) book = models.ForeignKey(Book, related_name= 'comments' , on_delete=models.CASCADE) author = models.ForeignKey(Author, related_name= 'author_comments' , on_delete=models.CASCADE) created_at = models.DateField(auto_now_add = True) class Meta: ordering = ['created_at'] def __str__(self): return self.message class AuthorComment(models.Model): name = models.CharField(max_length = 30) message = models.TextField(max_length= 4000) author = models.ForeignKey(Author, related_name= 'author_comment' , on_delete=models.CASCADE) created_at = models.DateField(auto_now_add = True) class Meta: ordering = ['created_at'] def __str__(self): return self.message
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,266
rammyblog/localibary
refs/heads/master
/LocalLibary/migrations/0006_auto_20181218_2012.py
# Generated by Django 2.1.4 on 2018-12-18 19:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('LocalLibary', '0005_auto_20181218_2008'), ] operations = [ migrations.RenameField( model_name='author', old_name='author_about', new_name='about', ), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,267
rammyblog/localibary
refs/heads/master
/LocalLibary/migrations/0010_authorcomment.py
# Generated by Django 2.1.4 on 2018-12-21 11:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('LocalLibary', '0009_comment'), ] operations = [ migrations.CreateModel( name='AuthorComment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30)), ('message', models.TextField(max_length=4000)), ('created_at', models.DateField(auto_now_add=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='author_comment', to='LocalLibary.Author')), ], options={ 'ordering': ['created_at'], }, ), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,268
rammyblog/localibary
refs/heads/master
/LocalLibary/migrations/0007_auto_20181220_0106.py
# Generated by Django 2.1.4 on 2018-12-20 00:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('LocalLibary', '0006_auto_20181218_2012'), ] operations = [ migrations.AlterModelOptions( name='author', options={'ordering': ['last_name', 'first_name']}, ), migrations.AlterModelOptions( name='bookinstance', options={'ordering': ['due_back'], 'permissions': (('can_mark_returned', 'Set book as returned'), ('can_edit_status', 'Set status of book'))}, ), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,269
rammyblog/localibary
refs/heads/master
/LocalLibary/forms.py
import datetime from django import forms from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Comment, AuthorComment class RenewalForm(forms.Form): renewal_date = forms.DateField( widget = forms.TextInput(attrs = {'class':"form-control add-listing_form"}), help_text = 'Default is 4 Weeks') def renewal_date_clean_data(self): data = self.cleaned_data['renewal_date'] if data < datetime.date.today(): raise ValidationError(_("The date inputed is in the PAST!")) if data > datetime.date.today + data.timedelta(weeks = 4): raise ValidationError(_("The date inputed is in above 4 weeks!")) return data class Register(UserCreationForm): first_name = forms.CharField(max_length = 50) last_name = forms.CharField(max_length = 50) email = forms.EmailField() class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] class CommentForm(forms.ModelForm): name = forms.CharField(max_length= 4000, widget = forms.TextInput(attrs = { 'class':"form-control", 'placeholder':"Enter name", 'aria-label':"Name", 'aria-describedby':"add-btn"})) message = forms.CharField(max_length= 4000, widget = forms.TextInput(attrs = {'class':"your-rating-content", 'placeholder':"Enter Your Comments"})) class Meta: model = Comment fields=['name', 'message'] class AuthorCommentForm(forms.ModelForm): name = forms.CharField(max_length= 4000, widget = forms.TextInput(attrs = { 'class':"form-control", 'placeholder':"Enter name", 'aria-label':"Name", 'aria-describedby':"add-btn"})) message = forms.CharField(max_length= 4000, widget = forms.TextInput(attrs = {'class':"your-rating-content", 'placeholder':"Enter Your Comments"})) class Meta: model = AuthorComment fields=['name', 'message']
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,270
rammyblog/localibary
refs/heads/master
/LocalLibary/migrations/0005_auto_20181218_2008.py
# Generated by Django 2.1.4 on 2018-12-18 19:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('LocalLibary', '0004_book_pub_date'), ] operations = [ migrations.AddField( model_name='author', name='author_about', field=models.CharField(blank=True, max_length=100000, null=True), ), migrations.AddField( model_name='author', name='author_image', field=models.ImageField(blank=True, null=True, upload_to=''), ), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,271
rammyblog/localibary
refs/heads/master
/LocalLibary/views.py
import datetime from django.shortcuts import render, get_object_or_404, redirect from .models import Book, BookInstance, Author, Comment, AuthorComment from django.http import HttpResponseRedirect from django.db.models import Q from django.views import generic from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth import login, authenticate from .forms import RenewalForm, Register, CommentForm, AuthorCommentForm from django.urls import reverse, reverse_lazy from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.utils.datastructures import MultiValueDictKeyError def index(request): book_instance = BookInstance.objects.filter(status__exact = 'a') new_books = Book.objects.all()[:10] book_status = BookInstance.objects.filter(Q(status__exact = 'm' ) | Q(status__exact = 'o' ))[:4] author = Author.objects.all()[:4] context = {'new_books':new_books, 'book_status':book_status, 'author':author, 'book_instance':book_instance} return render(request, 'LocalLibary/index.html', context) class BookList(generic.ListView): model = Book context_object_name = 'book_list' paginate_by=5 def bookDetails(request, pk): book = get_object_or_404(Book, pk=pk) comments = book.comments.order_by('-created_at') # comments = Comment.objects.all() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit = False) if request.user.is_authenticated: new_comment.name = request.user.username new_comment.author_id = book.author.id new_comment.book_id = book.id new_comment.save() return redirect('book-detail',pk) else: form = CommentForm() context = {'book':book, 'form': form, 'comments':comments} return render(request, 'LocalLibary/book_details.html', context) def authorDetails(request, pk): author = get_object_or_404(Author, pk=pk) comments = author.author_comment.order_by('-created_at') if request.method == 'POST': form = AuthorCommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit = False) if request.user.is_authenticated: new_comment.name = request.user.username new_comment.author_id = author.id new_comment.save() return redirect('author-detail',pk) else: form = AuthorCommentForm() context = {'author':author, 'form': form, 'comments':comments} return render(request, 'LocalLibary/author_details.html', context) def home(request): return redirect('index') class AuthorList(generic.ListView): model = Author context_object_name = 'author_list' paginate_by =10 @permission_required('LocalLibary.can_mark_returned') def borrowedbooklist(request): borrowed = BookInstance.objects.filter(status__exact = 'o').order_by('due_back') context = {'borrowed':borrowed} return render(request, 'LocalLibary/borrowed_list.html', context) @login_required def borrowedbooklistUser(request): borrowed = BookInstance.objects.filter(borrower=request.user).filter(status__exact = 'o').order_by('due_back') context = {'borrowed':borrowed} return render(request, 'LocalLibary/borrowed_list_user.html', context) @permission_required('LocalLibary.can_mark_returned') def renewalform(request, pk): book = get_object_or_404(BookInstance, pk=pk) if request.method=='POST': form = RenewalForm(request.POST) if form.is_valid(): book.due_back = form.cleaned_data['renewal_date'] book.save() return HttpResponseRedirect(reverse('borrowed_list')) else: proposed_date = datetime.date.today() + datetime.timedelta(weeks = 4) form = RenewalForm(initial = {'renewal_date':proposed_date}) context = {'form':form} return render(request, 'LocalLibary/renew.html', context) def register(request): if request.method == 'POST': form = Register(request.POST) if form.is_valid: form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate (username = username, password = password) login(request, user) return redirect(index) else: form = Register() context = {'form':form} return render(request, 'registration/register.html', context) class BookAdd(LoginRequiredMixin, CreateView): model = Book fields = '__all__' template_name = 'LocalLibary/book_add.html' class BookUpdate(LoginRequiredMixin, UpdateView): model = Book fields = '__all__' template_name = 'LocalLibary/book_add.html' class BookDelete(LoginRequiredMixin, DeleteView): model = Book template_name = 'LocalLibary/book_delete.html' success_url = reverse_lazy('index') class AuthorAdd(LoginRequiredMixin, CreateView): model = Author fields = '__all__' template_name = 'LocalLibary/book_add.html' class AuthorUpdate(LoginRequiredMixin, UpdateView): model = Author fields = '__all__' template_name = 'LocalLibary/book_add.html' class AuthorDelete(LoginRequiredMixin, DeleteView): model = Author template_name = 'LocalLibary/book_delete.html' success_url = reverse_lazy('index') def search(request): try: if request.method == 'GET': author = Author.objects.filter(Q(first_name__icontains = request.GET['q']) | Q(last_name__icontains = request.GET['q'])) search = Book.objects.filter(Q(title__icontains = request.GET['q']) |Q(isbn__icontains = request.GET['q'])) if search or author: context = {'search':search, 'author':author} return render(request, 'LocalLibary/search.html', context) else: return render(request, 'LocalLibary/404.html') except MultiValueDictKeyError as e: return render(request, 'LocalLibary/404.html')
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,272
rammyblog/localibary
refs/heads/master
/LocalLibary/migrations/0004_book_pub_date.py
# Generated by Django 2.1.4 on 2018-12-18 17:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('LocalLibary', '0003_book_book_image'), ] operations = [ migrations.AddField( model_name='book', name='pub_date', field=models.DateField(null=True), ), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,273
rammyblog/localibary
refs/heads/master
/LocalLibary/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('libary/', views.index, name='index'), path('libary/books/',views.BookList.as_view(), name='book_list'), path('libary/book/<int:pk>', views.bookDetails, name='book-detail'), path('libary/author/<int:pk>', views.authorDetails, name='author-detail'), path('libary/authors/',views.AuthorList.as_view(), name='author_list'), path('libary/borrowed/',views.borrowedbooklist, name='borrowed_list'), path('libary/borrowed/user/',views.borrowedbooklistUser, name='borrowed_list_user'), path('libary/renew/<uuid:pk>/book',views.renewalform, name='renewalform'), path('libary/accounts/register', views.register , name='register'), path('libary/search/', views.search , name='search'), path('libary/book/add',views.BookAdd.as_view(), name='book_add'), path('libary/book/<int:pk>/update',views.BookUpdate.as_view(), name='book_update'), path('libary/book/<int:pk>/delete',views.BookDelete.as_view(), name='book_delete'), path('libary/author/add',views.AuthorAdd.as_view(), name='author_add'), path('libary/author/<int:pk>/update',views.AuthorUpdate.as_view(), name='author_update'), path('libary/author/<int:pk>/delete',views.AuthorDelete.as_view(), name='author_delete'), ]
{"/LocalLibary/admin.py": ["/LocalLibary/models.py"], "/LocalLibary/forms.py": ["/LocalLibary/models.py"], "/LocalLibary/views.py": ["/LocalLibary/models.py", "/LocalLibary/forms.py"]}
75,274
piedor/Progetto-Tria
refs/heads/master
/draw_rect_elem_tria.py
""" Programma in Python per verificare le coordinate delle posizioni viste dalla fotocamera """ import cv2 from data import data from settings import * WHITE = [255, 255, 255] # Coordinate posizioni immagine fotocamera x_pos = data.ReturnValue("XposIMG") y_pos = data.ReturnValue("YposIMG") img = cv2.imread('img/aligned.jpg') for i in range(0, len(x_pos)): x_pos[i] -= STRATI for i in range(0, len(y_pos)): y_pos[i] -= STRATI for x, y in zip(x_pos, y_pos): for x_off in range(0, (STRATI * 2) + 1): for y_off in range(0, (STRATI * 2) + 1): img[int(y + y_off), int(x + x_off)] = WHITE cv2.imshow("TXTCamImg", img) cv2.waitKey(0) cv2.destroyAllWindows()
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,275
piedor/Progetto-Tria
refs/heads/master
/settings.py
from data import data OUTMAX = 512 OUTMIN = 0 XPOS = [ 1000, 2665, 4241, 1610, 2590, 3720, 2210, 2665, 3120, 1000, 1530, 2210, 3120, 3720, 4241, 2080, 2665, 3120, 1610, 2665, 3720, 1000, 2665, 4241] YPOS = [760, 760, 760, 1331, 1530, 1331, 2360, 2360, 2360, 3060, 3060, 3060, 3060, 3060, 3060, 3786, 3786, 3786, 4607, 4607, 4607, 5391, 5391, 5391] XPOSIMG = data.ReturnValue("XposIMG") YPOSIMG = data.ReturnValue("YposIMG") XPOSBOARD = [ 470, 682, 895, 542, 682, 823, 614, 682, 750, 470, 542, 614, 750, 823, 895, 614, 682, 750, 542, 682, 823, 470, 682, 895] YPOSBOARD = [ 172, 172, 172, 243, 243, 243, 315, 315, 315, 384, 383, 383, 383, 383, 384, 451, 451, 451, 524, 524, 524, 596, 596, 596] CAM_IMAGE = 'img/TXTCamImg.jpg' IMAGE_ALIGNED = 'img/aligned.jpg' SCIVOLOPALLINE = [120, 4140] CONTENITOREPVR = [5025, 4308] CONTENITOREPVU = [2635, 0] STRATI = 4 EMPTY = 0 ROBOT = 1 USER = 2 for i in range(0, len(XPOSIMG)): XPOSIMG[i] -= STRATI for i in range(0, len(YPOSIMG)): YPOSIMG[i] -= STRATI MINDISTNBU = 6000 MINDISTRBR = 9000 VAL_TRIA_ROBOT = 111 VAL_TRIA_USER = 222 MAIN_MENU = { "Nine Men's Morris": "TT", "Nuova partita": "NP", "Lingua": "LN", "Credits": "CD"} INIT_PLAYER_MENU = { "Scegli il giocatore che inizia per primo:": "TT", "UTENTE": "UT", "ROBOT": "RT", "Indietro": "BK"} LANGUAGES_MENU = { "Scegli la lingua": "TT", "ITALIANO": "IT", "INGLESE": "EN", "Indietro": "BK"}
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,276
piedor/Progetto-Tria
refs/heads/master
/align_TXTCamIMG.py
import time import cv2 from vec import Vec2d import numpy as np import pickle class Point(Vec2d): def __init__(self, x_or_pair, y=None): Vec2d.__init__(self, x_or_pair, y) def xy(self): return int(self.x), int(self.y) SPACE_KEY = 1048608 VERBOSE = False COLOR_RED = 0, 0, 255 # BGR ! COLOR_BLUE = 255, 0, 0 COLOR_GREEN = 0, 255, 0 POS_PICKLE_FILE = "data/pick_pos.txt" def read_image(file): image = cv2.imread(file) return image def show_image(image, title="main"): # Show image IMAGE in a window names (with title) TITLE cv2.imshow(title, image) def write_image(image, file): cv2.imwrite(file, image) def null_back(event, x, y, flags, param): # No-op mouse callback pass def get_point(window): def back(event, x, y, *_): if event == cv2.EVENT_LBUTTONDOWN: out.append((x, y)) out = list() cv2.setMouseCallback(window, back) while cv2.waitKey(10): if out: return Point(out[0]) return None def points_from_image(ima, count): for __ in range(count): show_image(ima, "main") p = get_point("main") yield p def draw_dot(ima, center, radius=3, color=COLOR_RED): # Draw a filled circle on IMA at CENTER with radius RADIUS" cv2.circle(ima, center.xy(), radius, color, thickness=-1) def pick_positions(ima, count): pp = list() if not count: return pp for i, p in enumerate(points_from_image(ima, count)): draw_dot(ima, p, radius=10, color=(0, 0, 255)) show_image(ima) pp.append(p) if VERBOSE: print("Pos %d: %s" % (i, p)) return pp def middle_points(a, b, count=1): step = (b - a) / (count + 1) return [a + step * (i + 1) for i in range(count)] def mid(a, b): return middle_points(a, b)[0] def draw_points(image, pp, radius=5, color=COLOR_RED): for p in pp: draw_dot(image, p, radius=radius, color=color) def inteporlate(tl, tr, bl, br): pp = list() pp.extend((mid(tl, tr), mid(tl, bl), mid(tr, br), mid(bl, br))) pp.extend(middle_points(tl, br, 5)) pp.extend(middle_points(tr, bl, 5)) return pp def pp_to_array(pp): return np.array(pp, np.float32) def make_matrix(pp, qq=None): if qq is None: qq = (Point(0, 0), Point(100, 0), Point(0, 100), Point(100, 100)) return cv2.getPerspectiveTransform( pp_to_array(pp), pp_to_array(qq)) board = read_image("img/TXTCamImg.jpg") try: with open(POS_PICKLE_FILE, "rb") as file: pp = pickle.load(file) except Exception as e: print(e) with open(POS_PICKLE_FILE, "wb") as file: pp = pick_positions(board, count=4) pickle.dump(pp, file) tl, tr, bl, br = pp qq = (tl, Point(tr.x, tl.y), Point(tl.x, bl.y), Point(tr.x, bl.y)) mat = make_matrix(pp, qq) w = max(tr.x, br.x) + 100 h = max(bl.y, br.y) + 100 board = cv2.warpPerspective(board, mat, (w, h)) qq = pp_to_array(pp).dot(mat[:2, :2]) qq = [Point(p) for p in qq] oo = inteporlate(*qq) write_image(board, "img/aligned.jpg")
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,277
piedor/Progetto-Tria
refs/heads/master
/main.py
#!/usr/bin/python # -*- coding: utf-8 -*- from settings import * from tria import Tria import cv2 import math import random import pygame from pygame.locals import * import os import sys val_elem = [0] * 24 terne = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [21, 22, 23], [18, 19, 20], [15, 16, 17], [21, 9, 0], [18, 10, 3], [15, 11, 6], [2, 14, 23], [5, 13, 20], [8, 12, 17], [9, 10, 11], [ 16, 19, 22], [12, 13, 14], [1, 4, 7]] vertici = [[0, 23], [2, 21], [3, 20], [5, 18], [6, 17], [8, 15]] quadrati = [[0, 1, 2, 14, 23, 22, 21, 9], [ 3, 4, 5, 13, 20, 19, 18, 10], [6, 7, 8, 12, 17, 16, 15, 11]] connettori = [[1, 4, 7], [14, 13, 12], [22, 19, 16], [9, 10, 11]] pygame.init() pygame.display.set_caption("Tria") os.environ['SDL_VIDEO_CENTERED'] = '1' clock = pygame.time.Clock() infoDisplay = pygame.display.Info() display_width, display_height = infoDisplay.current_w, infoDisplay.current_h class Game(): def __init__(self,tria): self.tria = tria self.gui = Gui(self.tria) self.fase = 1 self.partita_terminata = False self.val_terna1_mossa = 0 self.val_terna2_mossa = 0 self.val_terna1_mangiare = 0 self.val_terna2_mangiare = 0 self.pos_definited_mossa = -1 self.pos_definited_mangiare = -1 self.player = 0 self.pos_libere = list() self.elem_robot = 8 self.elem_user = 8 self.trie_robot = list() self.trie_user = list() self.val_elem_precedente = [0] * 24 self.user_can_mangia = False def set_init_player(self): self.tria.lamp.setLevel(OUTMAX) self.gui.set_init_player() self.player = self.gui.player self.tria.lamp.setLevel(OUTMIN) def change_turn(self): if self.player == ROBOT: self.player = USER elif self.player == USER: self.player = ROBOT def set_pos_libere(self): self.pos_libere = list() for i in range(0, 24): if val_elem[i] == EMPTY: self.pos_libere.append(i) def index_elements(self, arr, val): index_elements = list() for i in range(0, len(arr)): if arr[i] == val: index_elements.append(i) return(index_elements) def terne_pos(self, pos): t1 = list() t2 = list() for i in range(0, 16): if pos in terne[i]: if len(t1) == 0: t1 = terne[i] else: t2 = terne[i] return(t1, t2) def valore_terna(self, t): val = list() val.extend( [val_elem[t[0]], val_elem[t[1]], val_elem[t[2]]]) val.sort() return(val[0] * 100 + val[1] * 10 + val[2]) def valori_terne_pos(self, pos): t1, t2 = self.terne_pos(pos) return(self.valore_terna(t1), self.valore_terna(t2)) def vertice_opposto(self, v): index_v = -1 for i in range(0, 6): if v in vertici[i]: index_v = vertici[i].index(v) if index_v == 0: return(vertici[i][1]) elif index_v == 1: return(vertici[i][0]) def b_common_element(self, arr1, arr2): if bool(set(arr1).intersection(arr2)): return(True) else: return(False) def vie_vertici_opposti(self, v, v_opp): t1v, t2v = self.terne_pos(v) t1v_opp, t2v_opp = self.terne_pos(v_opp) via1 = list() via2 = list() if self.b_common_element(t1v, t1v_opp): via1.append(t1v) via1.append(t1v_opp) via2.append(t2v) via2.append(t2v_opp) elif self.b_common_element(t1v, t2v_opp): via1.append(t1v) via1.append(t2v_opp) via2.append(t2v) via2.append(t1v_opp) return(via1, via2) def n_percorsi_liberi(self, v, v_opp): cont = 0 via1, via2 = self.vie_vertici_opposti( v, v_opp) temp_val_v_opp = val_elem[v_opp] temp_val_v = val_elem[v] val_elem[v_opp] = 0 val_elem[v] = 0 if self.valore_terna(via1[0]) == 0 and self.valore_terna(via1[1]) == 0: cont += 1 if self.valore_terna(via2[0]) == 0 and self.valore_terna(via2[1]) == 0: cont += 1 val_elem[v_opp] = temp_val_v_opp val_elem[v] = temp_val_v return(cont) def b_tria_robot(self): if self.val_terna1_mossa == 111 or self.val_terna2_mossa == 111: return(True) else: return(False) def b_prevent_tria_user(self): if self.val_terna1_mossa == 122 or self.val_terna2_mossa == 122: return(True) else: return(False) def b_2_pairs_robot(self): if self.val_terna1_mossa == 11 and self.val_terna2_mossa == 11: return(True) else: return(False) def b_prevent_2_pairs_user(self): if self.val_terna1_mossa == 12 and self.val_terna2_mossa == 12: return(True) else: return(False) def b_vertice(self, pos): for i in range(0, 6): if pos in vertici[i]: return(True) return(False) def b_vertici_opposti_2_vie_robot(self, val_v_opp, npl): if val_v_opp == 1 and npl == 2: return(True) else: return(False) def b_prevent_vertici_opposti_2_vie_user(self, val_v_opp, npl): if val_v_opp == 2 and npl == 2: return(True) else: return(False) def b_vertici_opposti_1_via_robot(self, val_v_opp, npl): if val_v_opp == 1 and npl == 1: return(True) else: return(False) def b_prevent_vertici_opposti_1_via_user(self, val_v_opp, npl): if val_v_opp == 2 and npl == 1: return(True) else: return(False) def b_coppia_robot(self): if (self.val_terna1_mossa == 1 and self.val_terna2_mossa != 1) or ( self.val_terna2_mossa == 1 and self.val_terna1_mossa != 1): return(True) else: return(False) def b_prevent_coppia_user(self): if (self.val_terna1_mossa == 2 and self.val_terna2_mossa != 2) or ( self.val_terna2_mossa == 2 and self.val_terna1_mossa != 2): return(True) else: return(False) def val_mossa_fase_1(self, pos): val_elem[pos] = ROBOT self.val_terna1_mossa, self.val_terna2_mossa = self.valori_terne_pos( pos) val_elem[pos] = EMPTY if self.b_tria_robot(): return(1000) elif self.b_prevent_tria_user(): return(900) elif self.b_2_pairs_robot(): return(800) elif self.b_prevent_2_pairs_user(): return(700) elif self.b_vertice(pos): v_opp = self.vertice_opposto(pos) val_v_opp = val_elem[v_opp] npl = self.n_percorsi_liberi( pos, v_opp) if self.b_vertici_opposti_2_vie_robot(val_v_opp, npl): return(600) elif self.b_prevent_vertici_opposti_2_vie_user(val_v_opp, npl): return(500) elif self.b_vertici_opposti_1_via_robot(val_v_opp, npl): return(400) elif self.b_prevent_vertici_opposti_1_via_user(val_v_opp, npl): return(300) elif self.b_coppia_robot(): return(200) elif self.b_prevent_coppia_user(): return(100) return(50) def val_mosse_fase_1(self): self.set_pos_libere() val_mosse_pos = [0] * 24 for i in self.pos_libere: val_mosse_pos[i] = self.val_mossa_fase_1( i) return(val_mosse_pos) def mossa_robot_fase_1(self): val_fase_1 = self.val_mosse_fase_1() val_max = max(val_fase_1) pos_max = self.index_elements( val_fase_1, val_max) self.pos_definited_mossa = random.choice(pos_max) self.tria.aggiungi_pallina( XPOS[self.pos_definited_mossa], YPOS[self.pos_definited_mossa]) val_elem[self.pos_definited_mossa] = ROBOT def set_trie(self, trie): if self.player == ROBOT: self.trie_robot = trie else: self.trie_user = trie def b_new_tria(self): val_tria = 0 terna1 = list() terna2 = list() trie = list() if self.player == ROBOT: terna1, terna2 = self.terne_pos(self.pos_definited_mossa) val_tria = VAL_TRIA_ROBOT trie = self.trie_robot else: terna1, terna2 = self.terne_pos(self.el_camera.pos_modified) val_tria = VAL_TRIA_USER trie = self.trie_user if self.valore_terna(terna1) == val_tria and terna1 not in trie: trie.append(terna1) self.set_trie(trie) return(True) elif self.valore_terna(terna1) != val_tria and terna1 in trie: trie.remove(terna1) elif self.valore_terna(terna2) == val_tria and terna2 not in trie: trie.append(terna2) self.set_trie(trie) return(True) elif self.valore_terna(terna2) != val_tria and terna2 in trie: trie.remove(terna2) self.set_trie(trie) return(False) def pos_adiacenti(self, pos): pos_x = -1 pos_y = -1 pos_adiacenti = list() for i in quadrati: if pos in i: pos_x = quadrati.index(i) pos_y = i.index(pos) if pos_y == 0: pos_adiacenti.append(quadrati[pos_x][7]) pos_adiacenti.append(quadrati[pos_x][pos_y + 1]) elif pos_y == 7: pos_adiacenti.append(quadrati[pos_x][pos_y - 1]) pos_adiacenti.append(quadrati[pos_x][0]) else: pos_adiacenti.append(quadrati[pos_x][pos_y - 1]) pos_adiacenti.append(quadrati[pos_x][pos_y + 1]) for i in connettori: if pos in i: index = i.index(pos) if index == 1: pos_adiacenti.append(i[0]) pos_adiacenti.append(i[2]) else: pos_adiacenti.append(i[1]) return(pos_adiacenti) def b_muovibile(self, pos): for i in self.pos_adiacenti(pos): if val_elem[i] == EMPTY: return(True) return(False) def b_bloccato(self, player): for i in range(0, 24): if val_elem[i] == player: if self.b_muovibile(i): return(False) return(True) def b_pos_user_appartiene_a_una_tria(self, pos): if self.valori_terne_pos(pos)[0] == VAL_TRIA_USER or self.valori_terne_pos(pos)[ 1] == VAL_TRIA_USER: return(True) return(False) def elem_user_non_tria(self): elem = list() for i in range(0, 24): if val_elem[i] == USER and not self.b_pos_user_appartiene_a_una_tria( i): elem.append(i) return(elem) def elem_user_mangiabili(self): return(self.elem_user_non_tria()) def b_avoid_tria_user(self): if self.val_terna1_mangiare == 2 or self.val_terna2_mangiare == 2: return(True) return(False) def b_allow_tria_robot(self): if self.val_terna1_mangiare == 11 or self.val_terna2_mangiare == 11: return(True) return(False) def val_elem_mangiabile(self, pos): val_elem[pos] = EMPTY self.val_terna1_mangiare, self.val_terna2_mangiare = self.valori_terne_pos( pos) val_elem[pos] = USER if self.b_avoid_tria_user(): return(1000) elif self.b_allow_tria_robot(): return(900) return(50) def val_elem_mangiabili(self, vett): val = [0] * 24 for i in vett: val[i] = self.val_elem_mangiabile(i) return(val) def mangia_elem_user(self): elem_mangiabili = self.elem_user_mangiabili() val_elem_mangiabili = self.val_elem_mangiabili(elem_mangiabili) val_max = max(val_elem_mangiabili) pos_max = self.index_elements(val_elem_mangiabili, val_max) self.pos_definited_mangiare = random.choice(pos_max) self.tria.rimuovi_pallina( XPOS[self.pos_definited_mangiare], YPOS[self.pos_definited_mangiare]) val_elem[self.pos_definited_mangiare] = EMPTY def allow_user_mangia(self): print("Puoi mangiare una pallina del robot") self.tria.attendi_utente() self.user_can_mangia = True self.controlli_user() self.user_can_mangia = False def controlli_user(self): errore = False pos_new_user_elements = list() pos_removed_robot_elements = list() if self.fase == 1: if not self.user_can_mangia: pos_new_user_elements = self.el_camera.new_elements_user if len(pos_new_user_elements) == 0: self.gui.showInfo("Non hai posizionato alcuna pallina") print("Non hai posizionato alcuna pallina") errore = True elif len(pos_new_user_elements) > 1: self.gui.showInfo("Hai posizionato più palline") print( "Hai posizionato", len(pos_new_user_elements), "palline nelle posizioni:", pos_new_user_elements, "rimuovine", len(pos_new_user_elements) - 1) errore = True pos_removed_robot_elements = self.el_camera.removed_elements_robot if len(pos_removed_robot_elements) > 0 and not self.user_can_mangia: self.gui.showInfo("Hai rimosso delle palline del robot") print( "Hai rimosso", len(pos_removed_robot_elements), "palline del robot nelle posizioni:", pos_removed_robot_elements, "rimettile a posto tutte") errore = True elif self.user_can_mangia: if len(pos_removed_robot_elements) == 0: self.gui.showInfo( "Non hai rimosso alcuna pallina del robot") print("Non hai rimosso alcuna pallina del robot") errore = True elif len(pos_removed_robot_elements) > 1: self.gui.showInfo("Hai rimosso più palline del robot") print( "Hai rimosso", len(pos_removed_robot_elements), "palline del robot nelle posizioni:", pos_removed_robot_elements, "puoi rimuoverne solo 1 quindi rimetti a posto le altre") errore = True elif len(pos_removed_robot_elements) == 1: for i in self.trie_robot: if pos_removed_robot_elements[0] in i: self.gui.showInfo( "Hai rimosso una pallina che fà parte di una tria del robot") print( "Hai rimosso una pallina del robot che fà parte di una tria") errore = True break if errore: self.tria.attendi_utente() self.el_camera.check_new_or_removed_elements() self.controlli_user() else: for i in pos_new_user_elements: val_elem[i] = USER for i in pos_removed_robot_elements: val_elem[i] = EMPTY for i in self.el_camera.removed_elements_user: val_elem[i] = EMPTY def change_fase(self): if self.fase == 1: if self.player == ROBOT: self.elem_robot -= 1 else: self.elem_user -= 1 if self.elem_robot == 0 and self.elem_user == 0: self.fase = 2 print("Numero trie robot: ", len(self.trie_robot)) print("Numero trie utente: ", len(self.trie_user)) if(len(self.trie_robot) > len(self.trie_user)): self.gui.showInfo("Ha vinto il robot") print("Ha vinto il robot") elif (len(self.trie_user) > len(self.trie_robot)): self.gui.showInfo("Ha vinto l'utente") print("Ha vinto l'utente") else: self.gui.showInfo("pareggio") pygame.time.wait(2000) self.partita_terminata = True def set_partita_terminata(self, value): self._partita_terminata = value def get_partita_terminata(self): return(self._partita_terminata) partita_terminata = property( get_partita_terminata, set_partita_terminata) def run(self): self.set_init_player() for i in range(0,24): val_elem[i]=EMPTY self.el_camera = ElabCamImg(self.tria) self.el_camera.val_pos_camera_update() self.gui.runBoard() while not self.partita_terminata: if self.player == ROBOT: if self.fase == 1: self.mossa_robot_fase_1() elif self.player == USER: self.gui.showInfo("Tocca a te!") self.tria.attendi_utente() self.el_camera.check_new_or_removed_elements() self.controlli_user() self.tria.reset() self.el_camera.val_pos_camera_update() if self.b_new_tria(): if self.player == ROBOT: self.gui.showInfo("Il robot stà mangiando...") self.gui.incrementaTrieRobot() self.mangia_elem_user() else: self.gui.showInfo( "Puoi mangiare una pallina del robot") self.gui.incrementaTrieUtente() self.allow_user_mangia() self.change_fase() self.change_turn() for i in range(0, 24): self.val_elem_precedente[i] = val_elem[i] self.gui.runBoard() class ElabCamImg(): def __init__(self, Tria): self.val_pos_camera_b = [0] * 24 self.val_pos_camera_g = [0] * 24 self.val_pos_camera_r = [0] * 24 self.pos_modified = -1 self.tria = Tria self.new_elements_user = list() self.removed_elements_user = list() self.removed_elements_robot = list() def val_pos_camera_update(self): self.tria.scrivi_img_camera() exec( open("align_TXTCamImg.py").read(), globals()) self.val_pos_camera_b = [ self.rgb_pos(i)[0] for i in range(24)] self.val_pos_camera_g = [ self.rgb_pos(i)[1] for i in range(24)] self.val_pos_camera_r = [ self.rgb_pos(i)[2] for i in range(24)] def rgb_pos(self, pos): img = cv2.imread(IMAGE_ALIGNED, 1) blue = 0 green = 0 red = 0 for j in range(0, (STRATI * 2) + 1): for k in range(0, (STRATI * 2) + 1): b, g, r = img[int(YPOSIMG[pos] + k), int(XPOSIMG[pos] + j)] blue += b green += g red += r return(blue, green, red) def math_distance(self, p1, p2): return(math.sqrt(math.pow(p1 - p2, 2))) def b_val_pos_camera_higher(self, pos, val): blue = self.rgb_pos(pos)[0] green = self.rgb_pos(pos)[1] red = self.rgb_pos(pos)[2] if self.math_distance( self.val_pos_camera_b[pos], blue) + self.math_distance( self.val_pos_camera_g[pos], green) + self.math_distance( self.val_pos_camera_r[pos], red) > val: return True else: return False def check_new_or_removed_elements(self): self.new_elements_user = list() self.removed_elements_user = list() self.removed_elements_robot = list() self.tria.scrivi_img_camera() exec( open("align_TXTCamImg.py").read(), globals()) for i in range(0, 24): if self.b_val_pos_camera_higher( i, MINDISTNBU) and val_elem[i] == EMPTY: self.new_elements_user.append(i) self.pos_modified = i print( "pallina utente nella posizione ", i) elif self.b_val_pos_camera_higher(i, MINDISTNBU) and val_elem[i] == USER: self.removed_elements_user.append(i) print( "pallina utente rimossa dalla posizione ", i) elif self.b_val_pos_camera_higher( i, MINDISTRBR) and val_elem[i] == ROBOT: self.removed_elements_robot.append(i) print( "pallina robot rimossa dalla posizione ", i) class Gui(): def __init__(self, tria): self.tria = tria self.bg = pygame.image.load("img/back.png") self.bgBoard = pygame.image.load("img/back2.png") self.bgBoard = pygame.transform.scale(self.bgBoard, (2000, 1000)) self.bg_width, self.bg_height = self.bg.get_size() self.bgBoard_width, self.bgBoard_height = self.bgBoard.get_size() self.bg_center_x, self.bg_center_y = self.bg_width / 2, self.bg_height / 2 self.bgBoard_center_x, self.bgBoard_center_y = self.bgBoard_width / \ 2, self.bgBoard_height / 2 self.screen = pygame.display.set_mode( (display_width, display_height), 0, 32) self.surface = pygame.Surface(self.screen.get_size()).convert() self.menu = MAIN_MENU self.index = 0 self.text_view_array = list() self.player = 0 self.numeroTrieRobot = 0 self.numeroTrieUtente = 0 def incrementaTrieRobot(self): self.numeroTrieRobot += 1 def incrementaTrieUtente(self): self.numeroTrieUtente += 1 def show_menu(self, dict): TextView(self.surface, display_width / 2, 80, "impact", 80, (255, 0, 0), list(dict.keys())[0]) self.text_view_array = list() nArgs = len(dict) if self.index > nArgs - 2: self.index = 0 counter = 0 for i in range(1, len(dict)): if list(dict.values())[i] != "BK": b = TextView(self.surface, display_width / 2, (display_height - (nArgs - 1) * 100) / nArgs + 100 * (counter + 1), "Verdana", 40, (0, 0, 255), list(dict.keys())[i]) else: b = TextView(self.surface, (display_width / 2) + 300, (display_height - (nArgs - 1) * 100) / nArgs + 100 * (counter + 1) + 250, "Verdana", 40, (0, 0, 255), list(dict.keys())[i]) if counter == self.index: b.set_hover() b.set_id(list(dict.values())[i]) self.text_view_array.append(b) counter += 1 def select_listener(self): if self.tria.in_select.state(): self.index += 1 pygame.time.wait(200) def start_listener(self): if self.tria.in_start.state(): button_id = self.text_view_array[self.index].get_id() if button_id == "NP": self.menu = INIT_PLAYER_MENU elif button_id == "LN": self.menu = LANGUAGES_MENU elif button_id == "UT": self.player = USER elif button_id == "RT": self.player = ROBOT elif button_id == "BK": self.menu = MAIN_MENU pygame.time.wait(200) def set_init_player(self): while not self.player: self.runMenu() def showInfo(self, text): self.surface.fill((0, 0, 0)) TextView(self.surface, display_width / 2, display_height / 2, "Verdana", 40, (255, 255, 255), text) self.updateScreen() def updateBoard(self): TextView(self.surface, 100, 50, "Verdana", 40, (255, 0, 0), "Robot") TextView(self.surface, 300, 50, "Verdana", 40, (255, 0, 0), "Utente") TextView(self.surface, 100, 100, "Verdana", 40, (0, 0, 0), str(self.numeroTrieRobot)) TextView(self.surface, 300, 100, "Verdana", 40, (0, 0, 0), str(self.numeroTrieUtente)) for i in range(0, 24): if val_elem[i] == ROBOT: pygame.draw.circle( self.surface, (105, 105, 105), (XPOSBOARD[i], YPOSBOARD[i]), 20) elif val_elem[i] == USER: pygame.draw.circle( self.surface, (0, 0, 255), (XPOSBOARD[i], YPOSBOARD[i]), 20) def runMenu(self): self.surface.fill((40, 40, 40)) self.surface.blit(self.bg, ((display_width / 2) - (self.bg_width - self.bg_center_x), (display_height / 2) - (self.bg_height - self.bg_center_y))) self.show_menu(self.menu) self.select_listener() self.start_listener() self.updateScreen() def runBoard(self): self.surface.fill((255, 255, 255)) self.surface.blit(self.bgBoard, ((display_width / 2) - (self.bgBoard_width - self.bgBoard_center_x), (display_height / 2) - (self.bgBoard_height - self.bgBoard_center_y))) self.surface.blit(self.bg, ((display_width / 2) - (self.bg_width - self.bg_center_x), (display_height / 2) - (self.bg_height - self.bg_center_y))) self.updateBoard() self.updateScreen() def updateScreen(self): for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() self.screen.blit(self.surface, (0, 0)) pygame.display.flip() pygame.display.update() clock.tick(30) class TextView(): def __init__(self, surface, posX, posY, font, size, color, text): self.posX = posX self.posY = posY self.font = pygame.font.SysFont(font, size) self.text = text self.color = color self.surface = surface self.id = "" self.show_on_surface(self.color) def show_on_surface(self, color): text = self.font.render(self.text, 1, color) textpos = text.get_rect() textpos.centerx = self.posX textpos.centery = self.posY self.surface.blit(text, textpos) def set_hover(self): self.show_on_surface((255, 255, 255)) def set_id(self, id): self.id = id def get_id(self): return(self.id) tria=Tria() while True: game = Game(tria) game.run()
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,278
piedor/Progetto-Tria
refs/heads/master
/tria.py
import ftrobopy from settings import * import time class Tria: def __init__(self): self.txt = ftrobopy.ftrobopy('auto') time.sleep(2) self.txt.startCameraOnline() time.sleep(3) self.asse_y = self.txt.motor(1) self.asse_x = self.txt.motor(2) self.asse_z = self.txt.motor(3) self.ventosa = self.txt.output(7) self.lamp = self.txt.output(8) self.in_resety = self.txt.input(1) self.in_resetx = self.txt.input(4) self.in_downz = self.txt.input(5) self.in_upz = self.txt.input(6) self.in_select = self.txt.input(7) self.in_start = self.txt.input(8) self.pos_asse_x = 0 self.pos_asse_y = 0 self.reset() def muovi_asse(self, asse, verso, dist): if verso: asse.setSpeed(OUTMAX) else: asse.setSpeed(-OUTMAX) asse.setDistance(dist) def aspetta_input(self, input): while True: if input.state(): break if(input == self.in_resetx): self.asse_x.stop() elif(input == self.in_resety): self.asse_y.stop() elif(input == self.in_upz): self.asse_z.stop() def reset(self): self.muovi_asse(self.asse_x, 0, 20000) self.muovi_asse(self.asse_y, 1, 20000) self.muovi_asse(self.asse_z, 0, 20000) self.aspetta_input(self.in_resetx) self.aspetta_input(self.in_resety) self.aspetta_input(self.in_upz) def catch(self): self.muovi_asse(self.asse_z, 1, 20000) self.aspetta_input(self.in_downz) self.ventosa.setLevel(OUTMAX) self.muovi_asse(self.asse_z, 0, 20000) self.aspetta_input(self.in_upz) def release(self): self.muovi_asse(self.asse_z, 1, 20000) self.aspetta_input(self.in_downz) self.ventosa.setLevel(OUTMIN) self.muovi_asse(self.asse_z, 0, 20000) self.aspetta_input(self.in_upz) def fromto(self, x1, y1, x2, y2): start = time.time() self.pos_asse_x = x2 self.pos_asse_y = y2 diffx = x2 - x1 diffy = y2 - y1 distx = abs(diffx) disty = abs(diffy) if diffx != 0: if diffx > 0: self.asse_x.setSpeed(OUTMAX) else: self.asse_x.setSpeed(-OUTMAX) self.asse_x.setDistance(distx) self.txt.incrMotorCmdId(1) if diffy != 0: if diffy > 0: self.asse_y.setSpeed(-OUTMAX) else: self.asse_y.setSpeed(OUTMAX) self.asse_y.setDistance(disty) self.txt.incrMotorCmdId(0) while not(self.asse_y.finished() and self.asse_x.finished()): if time.time() - start >= 30: break self.txt.updateWait() def lampeggio(self, seconds, vel): start = time.time() while True: self.lamp.setLevel(OUTMIN) time.sleep(vel) self.lamp.setLevel(OUTMAX) time.sleep(vel) if time.time() - start >= seconds: self.lamp.setLevel(OUTMIN) break def attendi_utente(self): self.lamp.setLevel(OUTMAX) print("Tocca a te") self.aspetta_input(self.in_start) self.lamp.setLevel(OUTMIN) def aggiungi_pallina(self, x, y): self.fromto(0, 0, SCIVOLOPALLINE[0], SCIVOLOPALLINE[1]) self.catch() self.fromto(SCIVOLOPALLINE[0], SCIVOLOPALLINE[1], x, y) self.release() def rimuovi_pallina(self, x, y): self.fromto(self.pos_asse_x, self.pos_asse_y, x, y) self.catch() self.fromto(x, y, CONTENITOREPVR[0], CONTENITOREPVR[1]) self.ventosa.setLevel(OUTMIN) def muovi_pallina(self, x1, y1, x2, y2): self.fromto(0, 0, x1, y1) self.catch() self.fromto(x1, y1, x2, y2) self.release() def scrivi_img_camera(self): fc = self.txt.getCameraFrame() with open(CAM_IMAGE, 'wb') as f: f.write(bytearray(fc))
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,279
piedor/Progetto-Tria
refs/heads/master
/get_TXTCamImg_coord_elem_tria.py
""" Programma in Python per calibrare le coordinate delle posizioni viste dalla fotocamera """ import cv2 from data import data nx = list() # 'list' is easier to search than '[]' ny = list() XposIMG = [0] * 24 YposIMG = [0] * 24 def draw_circle(event, x, y, flags, params): if event == cv2.EVENT_LBUTTONDOWN: nx.append(x) ny.append(y) def CalCoordinatesQ(nQ): i = nQ * 8 XposIMG[0 + i], XposIMG[7 + i], XposIMG[5 + i], XposIMG[2 + i] = nx * 2 XposIMG[4 + i] = XposIMG[7 + i] XposIMG[3 + i] = XposIMG[0 + i] YposIMG[0 + i], YposIMG[7 + i], YposIMG[2 + i], YposIMG[5 + i] = ny * 2 YposIMG[1 + i] = YposIMG[0 + i] YposIMG[6 + i] = YposIMG[7 + i] XposIMG[1 + i] = ((XposIMG[2 + i] - XposIMG[0 + i]) / 2) + XposIMG[0 + i] XposIMG[6 + i] = ((XposIMG[7 + i] - XposIMG[5 + i]) / 2) + XposIMG[5 + i] YposIMG[3 + i] = ((YposIMG[5 + i] - YposIMG[0 + i]) / 2) + YposIMG[0 + i] YposIMG[4 + i] = ((YposIMG[7 + i] - YposIMG[2 + i]) / 2) + YposIMG[2 + i] def ReorderPos(): x = [0] * 24 y = [0] * 24 p = [0, 1, 2, 8, 9, 10, 16, 17, 18, 3, 11, 19, 20, 12, 4, 21, 22, 23, 13, 14, 15, 5, 6, 7] for i in range(0, 24): x[i], y[i] = XposIMG[p[i]], YposIMG[p[i]] return(x, y) img = cv2.imread("img/aligned.jpg") cv2.namedWindow('image') cv2.setMouseCallback('image', draw_circle) c = 0 while True: cv2.imshow('image', img) if (len(nx) and len(ny)) == 2: CalCoordinatesQ(c) nx = [] ny = [] c += 1 if c == 3: XposIMG, YposIMG = ReorderPos() data.Insert("XposIMG", XposIMG) data.Insert("YposIMG", YposIMG) import draw_rect_elem_tria break cv2.waitKey(33) cv2.destroyAllWindows()
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,280
piedor/Progetto-Tria
refs/heads/master
/data/data.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Modulo python data.py per lavorare con i database composto da due funzioni Insert e ReturnValue """ import sqlite3 as lite db = lite.connect("data/data.db") with db: c = db.cursor() def Insert(name, val): "Inserisce un dato nel database dato il nome(str) e il valore(int,str,list)." with db: try: c.execute("DELETE FROM %s" % (name)) except BaseException: pass c.execute("CREATE TABLE if not exists %s (val)" % (name)) if isinstance(val, list): db.executemany( "INSERT INTO %s (val) VALUES (?)" % (name), [ (x,) for x in val]) elif isinstance(val, str): val = (val,) db.execute("INSERT INTO %s (val) VALUES (?)" % (name), val) else: db.execute("INSERT INTO %s (val) VALUES (%d)" % (name, val)) def ReturnValue(name): "Ritorna i valori della tabella già esistente dato il nome." v = list() with db: try: c.execute("SELECT val FROM %s" % (name)) rr = c.fetchall() if(len(rr) > 1): for r in rr: v.append(r[0]) return(v) else: return([j for r in rr for j in r][0]) except BaseException: return
{"/draw_rect_elem_tria.py": ["/settings.py"], "/main.py": ["/settings.py", "/tria.py"], "/tria.py": ["/settings.py"], "/get_TXTCamImg_coord_elem_tria.py": ["/draw_rect_elem_tria.py"]}
75,281
maor10/pager
refs/heads/master
/src/pager/__init__.py
from .pager import start_recording
{"/src/pager/__init__.py": ["/src/pager/pager.py"]}
75,282
maor10/pager
refs/heads/master
/src/setup.py
import glob import os from setuptools import setup, find_packages, Extension BASE_C_SOURCES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cpager") PATHS = glob.glob(BASE_C_SOURCES_DIRECTORY + '/**/*.c', recursive=True) module = Extension("cpager", sources=PATHS) setup(name='pager', version='1.0', packages=find_packages(), ext_modules=[module])
{"/src/pager/__init__.py": ["/src/pager/pager.py"]}
75,283
maor10/pager
refs/heads/master
/src/pager/pager.py
import sys import cpager def trace(frame, event, arg): if event == "line": cpager.run_on_line() return trace def start_recording(): sys.settrace(trace) if __name__ == '__main__': start_recording()
{"/src/pager/__init__.py": ["/src/pager/pager.py"]}
75,284
GreatGodApollo/bashbot
refs/heads/master
/_config.py
class Config: token = "Your token here" # Retrieved from Discord Developer's portal description = "A cool bot that acts like bash" # Generic description of what your bot does owners = ["YourID"] # Your Discord user ID prefixes = ["./"] # Bot prefix cogs = ["cogs.owner", "cogs.apt", "cogs.misc", "cogs.administration", "cogs.moderation", "cogs.config", "cogs.hidden", "cogs.repl", "cogs.random"] # List of cogs bot should initially load dburl = "DB Connection URL" # Crafted using the sqlalchemy docs workingDirectory = "/your/working/directory/" # Trailing slash is important! serviceName = "yourServiceName" # Systemctl service name
{"/cogs/hidden.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/administration.py": ["/permissions.py"], "/cogs/moderation.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/chance.py": ["/permissions.py"], "/bot.py": ["/utils/db_declarative.py", "/utils/mutes.py"], "/cogs/apt.py": ["/permissions.py"], "/cogs/misc.py": ["/bot.py"], "/cogs/config.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/cogs/owner.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/permissions.py": ["/bot.py", "/utils/db_declarative.py"], "/utils/mutes.py": ["/bot.py", "/utils/db_declarative.py"]}
75,285
GreatGodApollo/bashbot
refs/heads/master
/cogs/hidden.py
import asyncio import discord from discord.ext import commands from permissions import modcheck, guildonly from utils.mutes import * class Hidden: """Gets a reaction, and performs an action""" def __init__(self, bot): self.bot = bot @commands.group(pass_context=True) async def hidden(self, ctx): """The base Hidden command""" bot = self.bot if ctx.invoked_subcommand is None: pages = bot.formatter.format_help_for(ctx, ctx.command) for page in pages: await bot.send_message(ctx.message.channel, page) @hidden.command(pass_context=True) async def message(self, ctx, *, msgToReplace): """Creates a hidden message""" await self.bot.delete_message(ctx.message) msg = await self.bot.send_message(ctx.message.channel, "This message is hidden, react for it to be revealed\nHidden by: " + ctx.message.author.name + "#" + ctx.message.author.discriminator) await self.bot.add_reaction(msg, "❌") def check(reaction, user): return user != self.bot.user res = await self.bot.wait_for_reaction(message=msg, check=check, timeout=120) if res is not None: await self.bot.edit_message(msg, msgToReplace + "\nHidden by: " + ctx.message.author.name + ctx.message.author.discriminator + "\nRevealed by: " + res.user.name + "#" + res.user.discriminator) else: await self.bot.edit_message(msg, "This hidden message expired") await self.bot.clear_reactions(msg) @commands.check(guildonly) @commands.check(modcheck) @hidden.command(pass_context=True, hidden=True) async def mute(self, ctx, emote, *, msg): """Creates a message that mutes people on reaction""" await self.bot.delete_message(ctx.message) mesg = await self.bot.send_message(ctx.message.channel, msg) try: await self.bot.add_reaction(mesg, emote) except: try: await self.bot.add_reaction(mesg, '😄') except: await self.bot.edit_message(mesg, "I don't have the proper permissions to add reactions") return def check(reaction, user): return user != self.bot.user res = await self.bot.wait_for_reaction(message=mesg, check=check, timeout=120) if res is not None: role = discord.utils.get(ctx.message.server.roles, name='Muted') if role is not None: res = await mute(self.bot, ctx.message.server.roles, res.user.id) if res: await self.bot.edit_message(mesg, "User {0} muted.".format(res.user.mention)) else: self.bot.say("I'm missing permissions!") else: permsoverwrite = discord.PermissionOverwrite() permsoverwrite.send_messages = False perms = discord.Permissions(send_messages=False, read_messages=True) role = await self.bot.create_role(ctx.message.server, name="Muted", permissions=perms) for channel in ctx.message.server.channels: await self.bot.edit_channel_permissions(channel, role, permsoverwrite) res = await mute(self.bot, ctx.message.server.roles, res.user.id) if res: await self.bot.edit_message(mesg, "User {0} muted.".format(res.user.mention)) else: self.bot.say("I'm missing permissions!") await asyncio.sleep(1) await self.bot.delete_message(mesg) def setup(bot): bot.add_cog(Hidden(bot))
{"/cogs/hidden.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/administration.py": ["/permissions.py"], "/cogs/moderation.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/chance.py": ["/permissions.py"], "/bot.py": ["/utils/db_declarative.py", "/utils/mutes.py"], "/cogs/apt.py": ["/permissions.py"], "/cogs/misc.py": ["/bot.py"], "/cogs/config.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/cogs/owner.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/permissions.py": ["/bot.py", "/utils/db_declarative.py"], "/utils/mutes.py": ["/bot.py", "/utils/db_declarative.py"]}
75,286
GreatGodApollo/bashbot
refs/heads/master
/cogs/administration.py
import discord from discord.ext import commands from permissions import admincheck, guildonly class Administration: """Admnistration module""" def __init__(self, bot): self.bot = bot @commands.check(guildonly) @commands.group(pass_context=True) async def admin(self, ctx): """This is a command to check if you have admin privileges""" bot = self.bot if admincheck(ctx) and ctx.invoked_subcommand is None: pages = bot.formatter.format_help_for(ctx, ctx.command) for page in pages: await bot.send_message(ctx.message.channel, page) elif not admincheck(ctx): await bot.say("You are not an admin") @commands.check(guildonly) @commands.check(admincheck) @admin.command(pass_context=True) async def setupmute(self, ctx): if discord.utils.get(ctx.message.server.roles, name="Muted") is None: try: msg = await self.bot.say("Please allow some time for this command to work") perms = discord.Permissions(send_messages=False, read_messages=True) role = await self.bot.create_role(ctx.message.server, name="Muted", permissions=perms) override = discord.PermissionOverwrite() override.send_messages = False for r in ctx.message.server.channels: await self.bot.edit_channel_permissions(r, role, override) await self.bot.edit_message(msg, "I finished setting up the Muted role and channel overrides!") except: await self.bot.say("I'm missing permissions!") else: await self.bot.say("A Muted role already exists, please run `admin setupmutechannels` in order to just setup the channel overrides") @commands.check(guildonly) @commands.check(admincheck) @admin.command(pass_context=True) async def setupmutechannels(self, ctx): if discord.utils.get(ctx.message.server.roles, name="Muted") is None: await self.bot.say("It looks like you don't even have a Muted role, run `admin setupmute` in order to get the full setup going") else: message = await self.bot.say("Setting up channel overrides.") role = discord.utils.get(ctx.message.server.roles, name="Muted") override = discord.PermissionOverwrite() override.send_messages = False for r in ctx.message.server.channels: await self.bot.edit_channel_permissions(r, role, override) await self.bot.edit_message(message, "I finished setting up the channel overrides!") def setup(bot): bot.add_cog(Administration(bot))
{"/cogs/hidden.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/administration.py": ["/permissions.py"], "/cogs/moderation.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/chance.py": ["/permissions.py"], "/bot.py": ["/utils/db_declarative.py", "/utils/mutes.py"], "/cogs/apt.py": ["/permissions.py"], "/cogs/misc.py": ["/bot.py"], "/cogs/config.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/cogs/owner.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/permissions.py": ["/bot.py", "/utils/db_declarative.py"], "/utils/mutes.py": ["/bot.py", "/utils/db_declarative.py"]}
75,287
GreatGodApollo/bashbot
refs/heads/master
/cogs/moderation.py
import discord from discord.ext import commands from permissions import modcheck, guildonly from utils.mutes import * class Moderation: """Moderation Commands""" def __init__(self, bot): self.bot = bot @commands.check(guildonly) @commands.check(modcheck) @commands.command(pass_context=True) async def unmute(self, ctx, user: discord.User): """The simple yet majestic unmute command""" res = await un_mute(self.bot, ctx.message.server.id, user.id) if res is True: await self.bot.say("User {0} unmuted.".format(user.mention)) else: await self.bot.say("User {0} isn't currently muted".format(user.mention)) @commands.check(guildonly) @commands.check(modcheck) @commands.command(pass_context=True) async def mute(self, ctx, user: discord.User): """The simple yet majestic mute command""" try: res = await mute(self.bot, ctx.message.server.id, user.id) if res is True: await self.bot.say(f"User {user.mention} muted for {minutes} minute(s).") else: await self.bot.say(f"User {user.mention} already has a mute!") except: await self.bot.say("I'm missing permissions!") def setup(bot): bot.add_cog(Moderation(bot))
{"/cogs/hidden.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/administration.py": ["/permissions.py"], "/cogs/moderation.py": ["/permissions.py", "/utils/mutes.py"], "/cogs/chance.py": ["/permissions.py"], "/bot.py": ["/utils/db_declarative.py", "/utils/mutes.py"], "/cogs/apt.py": ["/permissions.py"], "/cogs/misc.py": ["/bot.py"], "/cogs/config.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/cogs/owner.py": ["/bot.py", "/permissions.py", "/utils/db_declarative.py"], "/permissions.py": ["/bot.py", "/utils/db_declarative.py"], "/utils/mutes.py": ["/bot.py", "/utils/db_declarative.py"]}