branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/main
<file_sep>from flask import Flask from src.api.blueprint import app_blueprint class InitFlaskApp(object): def __init__(self, host='localhost', port=5000, debug=False): self.host = host self.port = port self.debug = debug def create_app(self): # Define a Flask application app = Flask(__name__, instance_relative_config=False) app.config.from_pyfile(filename='flask_config_test.py') # Register the blueprint app.register_blueprint(app_blueprint) return app <file_sep>import json import pytest def _get_formatted_response(response): result_dict={} result_dict['data'] = json.loads(response.data.decode('utf-8')) result_dict['status_code'] = response.status_code return result_dict def test_flask_up_and_running(init_flask_app): response = _get_formatted_response(init_flask_app.get('/up_and_running')) assert(response['data']['text'] == 'OK') assert(response['status_code'] == 200) def test_create_user_correctly(init_users_db_table, init_flask_app): data = {'name': 'Edoardo', 'surname': 'Casiraghi', 'birth_place': 'Merate', 'birth_date': '25/04/1993', 'instruction_level': 'University'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.post('/add_user', data=json.dumps(data), headers=headers)) assert(response['data']['text'] == 'The user has been added to SQLite database with ID auto-generated equal to "1".') assert(response['status_code'] == 201) def test_create_user_with_one_field_none(init_users_db_table, init_flask_app): data = {'name': 'Edoardo', 'surname': None, 'birth_place': 'Merate', 'birth_date': '25/04/1993', 'instruction_level': 'University'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} with pytest.raises(ValueError): _ = init_flask_app.post('/add_user', data=json.dumps(data), headers=headers) def test_create_user_without_data(init_users_db_table, init_flask_app): data = {} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} with pytest.raises(ValueError): _ = init_flask_app.post('/add_user', data=json.dumps(data), headers=headers) def test_create_user_with_many_fields_none(init_users_db_table, init_flask_app): data = {'name': 'Edoardo', 'surname': None, 'birth_place': 'Merate', 'birth_date': None, 'instruction_level': None} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} with pytest.raises(ValueError): _ = init_flask_app.post('/add_user', data=json.dumps(data), headers=headers) def test_delete_user_without_passing_id(examples_users_db_table, init_flask_app): with pytest.raises(json.decoder.JSONDecodeError): response = _get_formatted_response(init_flask_app.delete('/delete_user/')) assert(response['status_code'] == 404) def test_delete_user_by_not_existing_id(examples_users_db_table, init_flask_app): with pytest.raises(ValueError): response = _get_formatted_response(init_flask_app.delete('/delete_user/10')) assert(response['data']['text'] == 'There is no user with ID equal to "10" into the SQLite database.') assert(response['status_code'] == 200) def test_delete_user_by_existing_id(examples_users_db_table, init_flask_app): response = _get_formatted_response(init_flask_app.delete('/delete_user/1')) assert(response['data']['text'] == 'The user with ID equal to "1" has been removed from the SQLite database correctly.') assert(response['status_code'] == 200) def test_get_user_by_existing_id(examples_users_db_table, init_flask_app): response = _get_formatted_response(init_flask_app.get('/get_user/1')) assert(response['data']['text'] == 'The user with ID equal to 1 is <NAME>,' + ' born in 25/04/1993 at Merate and him/her instruction level is University.') assert(response['status_code'] == 200) def test_get_user_without_passing_id(examples_users_db_table, init_flask_app): with pytest.raises(json.decoder.JSONDecodeError): response = _get_formatted_response(init_flask_app.get('/get_user/')) assert(response['status_code'] == 404) def test_get_user_by_not_existing_id(examples_users_db_table, init_flask_app): with pytest.raises(ValueError): response = _get_formatted_response(init_flask_app.get('/get_user/10')) assert(response['data']['text'] == 'There is no user with ID equal to "10" into the SQLite database.') assert(response['status_code'] == 200) def test_update_one_field_user_by_existing_id(examples_users_db_table, init_flask_app): data = {'name': 'Edward'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.put('/update_user/1', headers=headers, data=json.dumps(data))) assert(response['data']['text'] == 'The user with ID equal to "1" has been updated in the SQLite database correctly.') assert(response['status_code'] == 200) def test_update_many_fields_user_by_existing_id(examples_users_db_table, init_flask_app): data = {'name': 'Edward', 'birth_place': 'Milan', 'instruction_level': 'High School'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.put('/update_user/1', headers=headers, data=json.dumps(data))) assert (response['data']['text'] == 'The user with ID equal to "1" has been updated in the SQLite database correctly.') assert (response['status_code'] == 200) def test_update_zero_fields_user_by_existing_id(examples_users_db_table, init_flask_app): with pytest.raises(ValueError): data = {} headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.put('/update_user/1', headers=headers, data=json.dumps(data))) assert(response['data']['text'] == 'No fields to update for user with ID equal to "1" has been received by the server.') assert(response['status_code'] == 200) ########### @pytest.mark.courses def test_create_course_correctly(init_courses_db_table, init_flask_app): data = {'name': 'Programming Languages 1', 'professor': '<NAME>', 'tutor': '<NAME>', 'academic_year': '2020/2021', 'academic_semester': 1, 'credits_number': 8, 'description': 'Python, Java and OOP.'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.post('/create_course', data=json.dumps(data), headers=headers)) assert(response['data']['text'] == 'The course has been created to SQLite database with ID auto-generated equal to "1".') assert(response['status_code'] == 201) @pytest.mark.courses def test_create_course_with_one_field_none_error(init_courses_db_table, init_flask_app): data = {'name': None, 'professor': '<NAME>', 'tutor': '<NAME>', 'academic_year': '2020/2021', 'academic_semester': 1, 'credits_number': 8, 'description': 'Python, Java and OOP.'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} with pytest.raises(ValueError): _ = init_flask_app.post('/create_course', data=json.dumps(data), headers=headers) @pytest.mark.courses def test_create_course_with_one_field_none_correctly(init_courses_db_table, init_flask_app): data = {'name': 'Programming Languages 1', 'professor': '<NAME>', 'tutor': None, 'academic_year': '2020/2021', 'academic_semester': 1, 'credits_number': 8, 'description': 'Python, Java and OOP.'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.post('/create_course', data=json.dumps(data), headers=headers)) assert (response['data']['text'] == 'The course has been created to SQLite database with ID auto-generated equal to "1".') assert (response['status_code'] == 201) @pytest.mark.courses def test_create_course_without_data(init_courses_db_table, init_flask_app): data = {} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} with pytest.raises(ValueError): _ = init_flask_app.post('/create_course', data=json.dumps(data), headers=headers) @pytest.mark.courses def test_create_course_with_many_fields_none_correctly(init_courses_db_table, init_flask_app): data = {'name': 'Programming Languages 1', 'professor': '<NAME>', 'tutor': None, 'academic_year': '2020/2021', 'academic_semester': 1, 'credits_number': 8, 'description': None} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.post('/create_course', data=json.dumps(data), headers=headers)) assert (response['data']['text'] == 'The course has been created to SQLite database with ID auto-generated equal to "1".') assert (response['status_code'] == 201) @pytest.mark.courses def test_create_course_with_many_fields_none_error(init_courses_db_table, init_flask_app): data = {'name': None, 'professor': None, 'tutor': '<NAME>', 'academic_year': '2020/2021', 'academic_semester': 1, 'credits_number': 8, 'description': 'Python, Java and OOP.'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} with pytest.raises(ValueError): _ = init_flask_app.post('/create_course', data=json.dumps(data), headers=headers) def test_delete_course_without_passing_id(examples_courses_db_table, init_flask_app): with pytest.raises(json.decoder.JSONDecodeError): response = _get_formatted_response(init_flask_app.delete('/delete_course/')) assert(response['status_code'] == 404) def test_delete_course_by_not_existing_id(examples_courses_db_table, init_flask_app): with pytest.raises(ValueError): response = _get_formatted_response(init_flask_app.delete('/delete_course/10')) assert(response['data']['text'] == 'There is no course with ID equal to "10" into the SQLite database.') assert(response['status_code'] == 200) def test_delete_course_by_existing_id(examples_courses_db_table, init_flask_app): response = _get_formatted_response(init_flask_app.delete('/delete_course/1')) assert(response['data']['text'] == 'The course with ID equal to "1" has been removed from the SQLite database correctly.') assert(response['status_code'] == 200) def test_get_course_by_existing_id(examples_courses_db_table, init_flask_app): response = _get_formatted_response(init_flask_app.get('/get_course/1')) assert(response['data']['text'] == 'The course with ID equal to "1" is Programming Languages 1, held by' + ' <NAME> during the academic year 2018/2019 in the 2° semester and it is 10 credits.') assert(response['status_code'] == 200) def test_get_course_without_passing_id(examples_courses_db_table, init_flask_app): with pytest.raises(json.decoder.JSONDecodeError): response = _get_formatted_response(init_flask_app.get('/get_course/')) assert(response['status_code'] == 404) def test_get_course_by_not_existing_id(examples_courses_db_table, init_flask_app): with pytest.raises(ValueError): response = _get_formatted_response(init_flask_app.get('/get_course/10')) assert(response['data']['text'] == 'There is no course with ID equal to "10" into the SQLite database.') assert(response['status_code'] == 200) ''' def test_update_one_field_user_by_existing_id(examples_users_db_table, init_flask_app): data = {'name': 'Edward'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.put('/update_user/1', headers=headers, data=json.dumps(data))) assert(response['data']['text'] == 'The user with ID equal to "1" has been updated in the SQLite database correctly.') assert(response['status_code'] == 200) def test_update_many_fields_user_by_existing_id(examples_users_db_table, init_flask_app): data = {'name': 'Edward', 'birth_place': 'Milan', 'instruction_level': 'High School'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.put('/update_user/1', headers=headers, data=json.dumps(data))) assert (response['data']['text'] == 'The user with ID equal to "1" has been updated in the SQLite database correctly.') assert (response['status_code'] == 200) def test_update_zero_fields_user_by_existing_id(examples_users_db_table, init_flask_app): with pytest.raises(ValueError): data = {} headers = {'Content-Type': 'application/json', 'Accept': 'text/plain'} response = _get_formatted_response(init_flask_app.put('/update_user/1', headers=headers, data=json.dumps(data))) assert(response['data']['text'] == 'No fields to update for user with ID equal to "1" has been received by the server.') assert(response['status_code'] == 200) ''' <file_sep>antiorm==1.2.1 appdirs==1.4.4 atomicwrites==1.4.0 attrs==20.3.0 certifi==2020.11.8 chardet==3.0.4 click==7.1.2 colorama==0.4.4 coverage==5.3 db==0.1.1 db-sqlite3==0.0.1 distlib==0.3.1 et-xmlfile==1.0.1 filelock==3.0.12 flake8==3.8.4 Flask==1.1.2 idna==2.10 importlib-metadata==2.1.1 iniconfig==1.1.1 itsdangerous==1.1.0 jdcal==1.4.1 Jinja2==2.11.2 MarkupSafe==1.1.1 mccabe==0.6.1 numpy==1.19.4 openpyxl==3.0.5 packaging==20.7 Pillow==8.0.1 pluggy==0.13.1 py==1.9.0 pycodestyle==2.6.0 pyflakes==2.2.0 pyparsing==2.4.7 pytesseract==0.3.6 pytest==6.1.2 pytest-cov==2.10.1 pytest-flake8==1.0.6 python-dateutil==2.8.1 pytz==2020.4 requests==2.25.0 six==1.15.0 src==0.0.1 toml==0.10.2 tox==3.20.1 tox-interpreters==0.1.0 urllib3==1.26.2 virtualenv==20.2.1 Werkzeug==1.0.1 wincertstore==0.2 zipp==3.4.0 <file_sep>import os import sqlite3 class DAO(object): def __init__(self, path_to_db): # Define the path where to save the SQLite3 database data self._path_to_db = path_to_db # Retrieve the connection to the (already created) database self._connection = sqlite3.connect(database=self._path_to_db) self._connection.row_factory = sqlite3.Row self._cursor = self._connection.cursor() def destroy(self): self._cursor.close() self._connection.close() def _create_table(self, table_name): sql_statement=None if table_name == 'users': sql_statement = """ CREATE TABLE users ( id INTEGER PRIMARY KEY, name varchar NOT NULL, surname varchar NOT NULL, birth_place varchar NOT NULL, birth_date varchar NOT NULL, instruction_level varchar NOT NULL, age INTEGER NOT NULL ); """ elif table_name == 'courses': sql_statement = """ CREATE TABLE courses ( id INTEGER PRIMARY KEY, name varchar NOT NULL, professor varchar NOT NULL, tutor varchar NULL, academic_year varchar NOT NULL, academic_semester varchar NOT NULL, credits_number INT NOT NULL, description varchar NULL ); """ try: self._cursor.execute(sql_statement) self._connection.commit() except Exception as e: print(e) def _truncate_table(self, table_name): sql_statement = """ DELETE FROM {}; """.format(table_name) try: self._cursor.execute(sql_statement) self._connection.commit() except Exception as e: print(e) def create_table(self, table_name): # Check whether the table already exists or not result = self._cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall() # Get the already existing tables in the SQLite database already_existing_table_names = [table_name[0] for table_name in result] if len(result) == 0 or table_name not in already_existing_table_names: # empty database or the database exists but the table does not exist self._create_table(table_name=table_name) else: # truncate table self._truncate_table(table_name=table_name) def add_row_into_table(self, object, table_name): if table_name == 'users': return self._add_user_into_users_table(user=object) elif table_name == 'courses': return self._add_course_into_courses_table(course=object) def _add_course_into_courses_table(self, course): # Define the SQL statement to use for adding a new course in the "courses" database table sql_statement = 'INSERT INTO courses(name, professor, tutor, academic_year, academic_semester, credits_number, description)' + \ 'VALUES (?, ?, ?, ?, ?, ?, ?);' self._cursor.execute(sql_statement, (course.name, course.professor, course.tutor, course.academic_year, course.academic_semester, course.credits_number, course.description)) self._connection.commit() # Retrieve the ID automatically assigned by SQLite database course_id = self._cursor.lastrowid return course_id def _add_user_into_users_table(self, user): # Define the SQL statement to use for adding a new user in the "users" database table sql_statement = 'INSERT INTO users(name, surname, birth_date, age, birth_place, instruction_level)' + \ 'VALUES (?, ?, ?, ?, ?, ?);' self._cursor.execute(sql_statement, (user.name, user.surname, user.birth_date, user.age, user.birth_place, user.instruction_level)) self._connection.commit() # Retrieve the ID automatically assigned by SQLite database user_id = self._cursor.lastrowid return user_id def delete_row_from_table(self, object, table_name): # Get the ID of the object to remove from a specific table in the SQLite database if 'id' in object: object_id = object['id'] # Define the SQL statement to use for removing a specific user with ID equal to the one received sql_statement = """SELECT * FROM {};""".format(table_name) result = self._cursor.execute(sql_statement).fetchall() if object_id not in [element['id'] for element in result]: # The particular row from a table name has not been removed correctly raise ValueError('There is no {} with ID equal to "{}" into the SQLite database.'.format( table_name[:-1], object_id)) sql_statement = """DELETE FROM {} WHERE id = {};""".format(table_name, object_id) self._cursor.execute(sql_statement) self._connection.commit() sql_statement = """SELECT * FROM {};""".format(table_name) result = self._cursor.execute(sql_statement).fetchall() if object_id in [element['id'] for element in result]: raise ValueError('The {} with ID equal to "{}"'.format(table_name[:-1], object_id) +\ ' has not been removed correctly from the SQLite database.') def get_row_from_table(self, object, table_name): # Get the ID of the object to remove from a specific table in the SQLite database if 'id' in object: object_id = object['id'] # Define the SQL statement to use for removing a specific user with ID equal to the one received try: sql_statement = """SELECT * FROM {} WHERE id = {};""".format(table_name, object_id) result = self._cursor.execute(sql_statement).fetchone() # If a specific user with ID does not exist in the SQLite database, raise a KeyError Exception if object_id == result['id']: # The particular row from a table name has been removed correctly # Return the description of a specific user by ID return {field: result[field] for field in list(result.keys()) if field != 'id'} else: # The particular row from a table name has not been removed correctly raise KeyError('ERROR: there is no {} with ID equal to "{}"'.format(table_name[:-1], object_id) + \ ' in the "{}" table of the SQLite database.'.format(table_name)) except Exception as e: raise ValueError def update_row_in_table(self, table_name, object): def _prepare_sql_update_statement(new_data_dict): update_values_stmt = '' for k, v in new_data_dict.items(): update_values_stmt += '{} = "{}", '.format(k, v) update_values_stmt = update_values_stmt.rstrip(', ') return update_values_stmt # Get the ID of the object to remove from a specific table in the SQLite database if 'id' in object: object_id = object['id'] # Define the SQL statement to use for removing a specific user with ID equal to the one received sql_statement = """SELECT * FROM {};""".format(table_name) result = self._cursor.execute(sql_statement).fetchall() if object_id not in [element['id'] for element in result]: # The particular row from a table name has not been removed correctly raise ValueError('There is no {} with ID equal to "{}" into the SQLite database.'.format(table_name[:-1], object_id)) # Remove the 'id' of the user new_data_dict = {k: v for k, v in object.items() if k != 'id'} if len(new_data_dict) == 0: raise ValueError('No fields to update for {} with ID equal to "{}"'.format(table_name[:-1], object_id) +\ ' has been received by the server.') # Define the portion of the SQL DML statement for updating the user field(s) update_values_stmt = _prepare_sql_update_statement(new_data_dict=new_data_dict) # Update the found user with new data values sql_statement = """UPDATE {} SET {} WHERE id = {};""".format(table_name, update_values_stmt, object_id) self._cursor.execute(sql_statement) self._connection.commit() # Check the update operation has been done successfully sql_statement = """SELECT * FROM {} WHERE id = {};""".format(table_name, object_id) result = self._cursor.execute(sql_statement).fetchone() for field, new_value in new_data_dict.items(): if result[field] != new_value: raise AttributeError <file_sep>from setuptools import setup setup( name='src', version='0.0.1', description='TestingApplication description', author='<NAME>', author_email='<EMAIL>', packages=['src'] )<file_sep>from datetime import datetime import math class User(object): def __init__(self, name, surname, birth_date, birth_place, instruction_level): self.name = name self.surname = surname self.birth_date = birth_date self.birth_place = birth_place self.instruction_level = instruction_level self.age = self.compute_age_from_birth_date(self.convert_date_to_standard_format(self.birth_date)) ### GETTER methods ### @property def name(self): return self._name @property def surname(self): return self._surname @property def birth_date(self): return self._birth_date @property def birth_place(self): return self._birth_place @property def instruction_level(self): return self._instruction_level @property def age(self): return self._age ### SETTER methods ### @name.setter def name(self, name): if name is None: raise ValueError('ERROR: the name of a user can not be empty.') self._name = name @surname.setter def surname(self, surname): if surname is None: raise ValueError('ERROR: the surname of a user can not be empty.') self._surname = surname @birth_date.setter def birth_date(self, birth_date): if birth_date is None: raise ValueError('ERROR: the birth date of a user can not be empty.') self._birth_date = birth_date @birth_place.setter def birth_place(self, birth_place): if birth_place is None: raise ValueError('ERROR: the birth place of a user can not be empty.') self._birth_place = birth_place @instruction_level.setter def instruction_level(self, instruction_level): if instruction_level not in ['Middle School', 'High School', 'University']: raise ValueError('ERROR: the instruction level of a user can be only "Middle School",' '"High School or "University".') self._instruction_level = instruction_level @age.setter def age(self, age): self._age = age def compute_age_from_birth_date(self, birth_date): # Retrieve the current date current_date = datetime.now() # Convert the birth date from string type to datetime type birth_date = datetime.strptime(birth_date, '%d/%m/%Y') # Derive the age of a user as the difference between the current date and the birth date of the user age = math.floor( float( (current_date - birth_date).days / 365 ) ) # If the difference between them is negative, then it is a error to capture if age < 0: raise ValueError('ERROR: The birth date can not be after the current date.') return age def convert_date_to_standard_format(self, birth_date): # If there are both "-" and "/" characters that split day, month and year, it is a not understandable format if '-' in birth_date and '/' in birth_date: raise ValueError('ERROR: in a date can not be both "-" and "/" characters.') # Convert "-" to "/" if necessary if '-' in birth_date: birth_date = birth_date.replace('-', '/') # Split the date to its component i.e. day, month, year day, month, year = birth_date.split('/') # If the year is between day and month, it is a not understandable format if len(month) == 4: raise ValueError('ERROR: date format not understandable.') # If the day is at the end of the date and the year is at the beginning of the date, switch them if len(day) == 4 and len(year) == 2: day, year = year, day return '{}/{}/{}'.format(day, month, year) <file_sep>from flask import Blueprint, request, jsonify import json from src.model.user import User from src.model.course import Course from src.dao.dao import DAO app_blueprint = Blueprint('main', __name__) def _get_dao_handler(): # Read a temporary file called "tmp.txt" which contains the path to the test SQLite database with open('tmp.txt', 'r') as input_file: path_to_tmp_db_directory = input_file.readline().rstrip('\n') # Create a connection to the test SQLite database dao_handler = DAO(path_to_db=path_to_tmp_db_directory) return dao_handler @app_blueprint.route('/up_and_running', methods=['GET']) def up_and_running(): return jsonify({'text': 'OK'}), 200 @app_blueprint.route('/add_user', methods=['POST']) def add_user(): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Get the data received by HTTP POST request request_data = json.loads(request.data) if len(request_data) == 0: raise ValueError('ERROR: no data have been received.') # Create a User object with the information about him/her passed by HTTP request u = User(name=request_data['name'], surname=request_data['surname'], birth_date=request_data['birth_date'], birth_place=request_data['birth_place'], instruction_level=request_data['instruction_level']) # Add the user to the SQLite database and retrieve the ID automatically assigned to him/her user_id = dao_handler.add_row_into_table(object=u, table_name='users') return jsonify({'text': 'The user has been added to SQLite database with ID auto-generated' +\ ' equal to "{}".'.format(user_id)}), 201 @app_blueprint.route('/delete_user/<int:user_id>', methods=['DELETE']) def delete_user_by_id(user_id): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Delete the specific user by him/her ID dao_handler.delete_row_from_table(table_name='users', object={'id': user_id}) return jsonify({'text': 'The user with ID equal to "{}" has been removed'.format(user_id) +\ ' from the SQLite database correctly.'}), 200 @app_blueprint.route('/get_user/<int:user_id>', methods=['GET']) def get_user_by_id(user_id): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Get the specific user by him/her ID user_description = dao_handler.get_row_from_table(table_name='users', object={'id': user_id}) # If the specific user does not exist in the SQLite database if user_description is None: return jsonify({'text': 'The user with ID equal to {} does not exist into the SQLite database.'.format(user_id)}, 200) # Prepare the output string return jsonify({'text': 'The user with ID equal to {} is {} {}'.format(user_id, user_description['name'], user_description['surname']) +\ ', born in {} at {} and him/her instruction'.format(user_description['birth_date'], user_description['birth_place']) +\ ' level is {}.'.format(user_description['instruction_level'])}), 200 @app_blueprint.route('/update_user/<int:user_id>', methods=['PUT']) def update_user_by_id(user_id): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Get the data received by HTTP POST request request_data = json.loads(request.data) # Update the user with the new values received as input object = {**{'id': user_id}, **request_data} dao_handler.update_row_in_table(table_name='users', object=object) return jsonify({'text': 'The user with ID equal to "{}" has been updated'.format(user_id) +\ ' in the SQLite database correctly.'}), 200 @app_blueprint.route('/create_course', methods=['POST']) def create_user(): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Get the data received by HTTP POST request request_data = json.loads(request.data) if len(request_data) == 0: raise ValueError('ERROR: no data have been received.') # Create a Course object with the information about him/her passed by HTTP request c = Course(name=request_data['name'], professor=request_data['professor'], tutor=request_data['tutor'], academic_year=request_data['academic_year'], academic_semester=request_data['academic_semester'], credits_number=request_data['credits_number'], description=request_data['description']) # Add the course to the SQLite database and retrieve the ID automatically assigned to it course_id = dao_handler.add_row_into_table(object=c, table_name='courses') return jsonify({'text': 'The course has been created to SQLite database with ID auto-generated' + \ ' equal to "{}".'.format(course_id)}), 201 @app_blueprint.route('/delete_course/<int:course_id>', methods=['DELETE']) def delete_course_by_id(course_id): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Delete the specific course by its ID dao_handler.delete_row_from_table(table_name='courses', object={'id': course_id}) return jsonify({'text': 'The course with ID equal to "{}" has been removed'.format(course_id) +\ ' from the SQLite database correctly.'}), 200 @app_blueprint.route('/get_course/<int:course_id>', methods=['GET']) def get_course_by_id(course_id): # Get a connection to the test SQLite database dao_handler = _get_dao_handler() # Get the specific course by him/her ID course_description = dao_handler.get_row_from_table(table_name='courses', object={'id': course_id}) # If the specific user does not exist in the SQLite database if course_description is None: return jsonify({'text': 'The course with ID equal to "{}" does not exist into the SQLite database.'.format(course_id)}, 200) # Prepare the output string return jsonify({'text': 'The course with ID equal to "{}" is {},'.format(course_id, course_description['name']) +\ ' held by {} during the academic year {}'.format(course_description['professor'], course_description['academic_year']) +\ ' in the {}° semester and it is'.format(course_description['academic_semester']) +\ ' {} credits.'.format(course_description['credits_number'])}), 200 <file_sep>class Course(object): def __init__(self, name, professor, tutor, academic_year, academic_semester, credits_number, description): self.name = name self.professor = professor self.tutor = tutor self.academic_year = academic_year self.academic_semester = academic_semester self.credits_number = credits_number self.description = description @property def name(self): return self._name @property def professor(self): return self._professor @property def tutor(self): return self._tutor @property def academic_year(self): return self._academic_year @property def academic_semester(self): return self._academic_semester @property def credits_number(self): return self._credits_number @property def description(self): return self._description @name.setter def name(self, name): if name is None: raise ValueError('ERROR: the name of the course is mandatory.') self._name = name @professor.setter def professor(self, professor): if professor is None: raise ValueError('ERROR: the professor name and surname of the course is mandatory.') self._professor = professor @tutor.setter def tutor(self, tutor): self._tutor = tutor @academic_year.setter def academic_year(self, academic_year): if academic_year is None: raise ValueError('ERROR: the academic year of the course is mandatory.') self._academic_year = academic_year @academic_semester.setter def academic_semester(self, academic_semester): if academic_semester is None: raise ValueError('ERROR: the academic semester of the course is mandatory.') self._academic_semester = academic_semester @credits_number.setter def credits_number(self, credits_number): if credits_number is None: raise ValueError('ERROR: the number of credits of the course is mandatory.') self._credits_number = credits_number @description.setter def description(self, description): self._description = description <file_sep>########################################################## # # flask_test.cfg is intended to be used for testing a Flask application # ########################################################## # Update later by using a random number generator and moving # the actual key outside of the source code under version control DEBUG = True # Enable the TESTING flag to disable the error catching during request handling # so that you get better error reports when performing test requests against the application. TESTING = True <file_sep>import pytest from src.model.course import Course @pytest.mark.courses @pytest.mark.parametrize('course', [('Programming Languages 1', '<NAME>', '<NAME>', '2020/2021', 1, 8, 'Learning Python, Java and OOP.')]) def test_init_course_correctly(course): name, professor, tutor, academic_year, academic_semester, credits_number, description = course c = Course(name=name, professor=professor, tutor=tutor, academic_year=academic_year, academic_semester=academic_semester, credits_number=credits_number, description=description) assert(c.name == name) assert(c.professor == professor) assert(c.tutor == tutor) assert(c.academic_year == academic_year) assert(c.academic_semester == academic_semester) assert(c.credits_number == credits_number) assert(c.description == description) @pytest.mark.courses @pytest.mark.parametrize('course_description,expected_output', [ ( (None, '<NAME>', '<NAME>', '2020/2021', 1, 8, 'Learning Python, Java and OOP.'), ValueError), ( ('Programming Languages 1', None, '<NAME>', '2020/2021', 1, 8, 'Learning Python, Java and OOP.'), ValueError), ( ('Programming Languages 1', '<NAME>', None, '2020/2021', 1, 8, 'Learning Python, Java and OOP.'), 'OK'), ( ('Programming Languages 1', '<NAME>', '<NAME>', None, 1, 8, 'Learning Python, Java and OOP.'), ValueError), ( ('Programming Languages 1', '<NAME>', '<NAME>', '2020/2021', None, 8, 'Learning Python, Java and OOP.'), ValueError), ( ('Programming Languages 1', '<NAME>', '<NAME>', '2020/2021', 1, None, 'Learning Python, Java and OOP.'), ValueError), ( ('Programming Languages 1', '<NAME>', '<NAME>', '2020/2021', 1, 8, None), 'OK')]) def test_init_user_empty_attributes_error(course_description, expected_output): name, professor, tutor, academic_year, academic_semester, credits_number, description = course_description if expected_output == 'OK': c = Course(name=name, professor=professor, tutor=tutor, academic_year=academic_year, academic_semester=academic_semester, credits_number=credits_number, description=description) assert (c.name == name) assert (c.professor == professor) assert (c.tutor == tutor) assert (c.academic_year == academic_year) assert (c.academic_semester == academic_semester) assert (c.credits_number == credits_number) assert (c.description == description) elif isinstance(expected_output, Exception): with pytest.raises(ValueError): _ = Course(name=name, professor=professor, tutor=tutor, academic_year=academic_year, academic_semester=academic_semester, credits_number=credits_number, description=description) <file_sep>[tox] envlist = py37 [testenv] # run the tests # ... or run any other command line tool you need to run here commands = pytest<file_sep>import pytest from src.model.user import User @pytest.mark.parametrize('user', [('Edoardo', 'Casiraghi', '25/04/1993', 'Merate', 'University')]) def test_init_user_correctly(user): name, surname, birth_date, birth_place, instruction_level = user u = User(name=name, surname=surname, birth_date=birth_date, birth_place=birth_place, instruction_level=instruction_level) assert(u.name == name) assert(u.surname == surname) assert(u.birth_place == birth_place) assert(u.birth_date == birth_date) assert(u.instruction_level == instruction_level) assert(u.age == 27) @pytest.mark.parametrize('user_description', [(None, 'Casiraghi', '25/04/1993', 'Merate', 'University'), ('Edoardo', None, '25/04/1993', 'Merate', 'University'), ('Edoardo', 'Casiraghi', None, 'Merate', 'University'), ('Edoardo', 'Casiraghi', '25/04/1993', None, 'University'), ('Edoardo', 'Casiraghi', '25/04/1993', 'Merate', None)]) def test_init_user_empty_attributes_error(user_description): name, surname, birth_date, birth_place, instruction_level = user_description with pytest.raises(expected_exception=ValueError): _ = User(name=name, surname=surname, birth_date=birth_date, birth_place=birth_place, instruction_level=instruction_level) @pytest.mark.parametrize('input_birth_date,expected_age', [('01/01/2020', 0), ('25/04/1993', 27), ('25/04/2002', 18)]) def test_compute_age_from_birth_date(input_birth_date, expected_age): user = User(name='Edoardo', surname='Casiraghi', birth_date=input_birth_date, birth_place='Merate', instruction_level='University') if isinstance(expected_age, int): # Compute the age given the birth date of a user computed_age = user.compute_age_from_birth_date(birth_date=input_birth_date) assert( computed_age == expected_age ) elif isinstance(expected_age, Exception): with pytest.raises(ValueError): # Compute the age given the birth date of a user user.compute_age_from_birth_date(birth_date=input_birth_date) @pytest.mark.parametrize('input_birth_date, expected_birth_date', [('01/01/2020', '01/01/2020'), ('2020-11-01', '01/11/2020'), ('2020/11-01', ValueError), ('2020-11/01', ValueError), ('1999/11/01', '01/11/1999'), ('1999-11-01', '01/11/1999'), ('11-1999-01', ValueError)]) def test_convert_date_to_standard_format(input_birth_date, expected_birth_date): user = User(name='Edoardo', surname='Casiraghi', birth_date='25/04/1993', birth_place='Merate', instruction_level='University') if isinstance(expected_birth_date, str): # Compute the age given the birth date of a user computed_birth_date = user.convert_date_to_standard_format(birth_date=input_birth_date) assert(computed_birth_date == expected_birth_date) else: with pytest.raises(ValueError): # Compute the age given the birth date of a user _ = user.convert_date_to_standard_format(birth_date=input_birth_date) <file_sep># TestingApplication Experiments with Python testing framework (pytest), CI/CD with Jenkins and TDD. <file_sep>import sqlite3 import os class DataBaseHandler(object): def __init__(self, db_name): # Define the path where to save the SQLite3 database data self._path_to_db = db_name # Create the SQLite database print('INFO: creating the SQLite database...') self._connection = sqlite3.connect(database=self._path_to_db) print('SQLite Database created correctly to "{}".'.format(self._path_to_db)) def destroy(self): print('INFO: destroying the SQLite database...') self._connection.close() #os.remove(self._path_to_db) <file_sep>import configparser class ConfigurationsUtils(object): def __init__(self, config_file='./utils/init_config_test.cfg'): config = configparser.ConfigParser() config.read(config_file) # Read the path to the SQLite database self._path_to_sqlite_database = config.get('DATABASE', 'PathToDatabase') self._database_name = config.get('DATABASE', 'DatabaseName') <file_sep>import pytest import os from src.model.user import User from src.model.course import Course from src.dao.dao import DAO from src.dao.database import DataBaseHandler from src.api.app import InitFlaskApp from utils.configuration_utils import ConfigurationsUtils @pytest.fixture(scope='session', name='init_sqlite3_db') def init_sqlite3_db(tmpdir_factory): ### SET-UP ### # Read the init_config_test.cfg file which contains the path to the SQLite database cfg_handler = ConfigurationsUtils() # Split the path to the SQLite database used for test purposes to its directories and sub-directories main_dir, sub_dir = cfg_handler._path_to_sqlite_database.split('/')[1:] # Add a sub-directory whose name is read from "init_config_test.cfg" file where to save the SQLite database path_to_tmp_db_directory = tmpdir_factory.mktemp(basename=main_dir, numbered=False).mkdir(sub_dir)\ .join(cfg_handler._database_name) # Save in a temporary file called "tmp.txt" the path to the test SQLite database (removed at the end of tests) with open('tmp.txt', 'w') as output_file: output_file.write(str(path_to_tmp_db_directory)+'\n') # Create a SQLite3 database one-shot database_handler = DataBaseHandler(db_name=path_to_tmp_db_directory) yield database_handler ### TEAR-DOWN ### database_handler.destroy() os.remove('tmp.txt') # file where to save the path to the SQLite database @pytest.fixture(scope='session', name='init_sqlite3_db_connection') def init_sqlite3_db_connection(init_sqlite3_db): ### SET-UP ### dao_handler = DAO(path_to_db=init_sqlite3_db._path_to_db) yield dao_handler ### TEAR-DOWN ### dao_handler.destroy() @pytest.fixture(scope='function', name='init_users_db_table') def create_users_table_in_db(init_sqlite3_db, init_sqlite3_db_connection): ### SET-UP ### dao_handler = init_sqlite3_db_connection dao_handler.create_table(table_name='users') yield ### TEAR-DOWN ### #@TODO: drop "users" table in the SQLite database @pytest.fixture(scope='function', name='init_courses_db_table') def create_courses_table_in_db(init_sqlite3_db, init_sqlite3_db_connection): ### SET-UP ### dao_handler = init_sqlite3_db_connection dao_handler.create_table(table_name='courses') yield ### TEAR-DOWN ### #@TODO: drop "courses" table in the SQLite database ################################################################### @pytest.fixture(scope='module', name='return_new_users_correctly') def return_new_users_correctly(): new_users_correct = [User(name='Edoardo', surname='Casiraghi', birth_date='25/04/1993', birth_place='Merate', instruction_level='University'), User(name='Veronica', surname='Lanzi', birth_date='01/05/1994', birth_place='Lecco', instruction_level='University'), User(name='Danilo', surname='Casiraghi', birth_date='11/10/1961', birth_place='Vimercate', instruction_level='High School'), User(name='Daniela', surname='Bonalume', birth_date='18/02/1963', birth_place='Merate', instruction_level='Middle School')] return new_users_correct @pytest.fixture(scope='module', name='init_flask_app') def init_flask_app(init_sqlite3_db): flask_handler = InitFlaskApp() flask_app = flask_handler.create_app() # Create a test client using the Flask application configured for testing with flask_app.test_client() as testing_client: # Establish an application context with flask_app.app_context(): yield testing_client # this is where the testing happens! @pytest.fixture(scope='function', name='examples_users_db_table') def create_users_table_in_db_with_test_users_already_added(init_sqlite3_db, init_sqlite3_db_connection, return_new_users_correctly): ### SET-UP ### dao_handler = init_sqlite3_db_connection ### STEP 1: create an empty "users" table ### dao_handler.create_table(table_name='users') ### STEP 2: # add some test users in the "users" table ### for index, user in enumerate(return_new_users_correctly): # Add a user and retrieve him/her ID user_id = dao_handler.add_row_into_table(object=user, table_name='users') assert (user_id == index + 1) yield ### TEAR-DOWN ### print('teardown init_users_db_table') #@TODO: drop table in the database @pytest.fixture(scope='module', name='return_new_courses_correctly') def return_new_courses_correctly(): new_courses_correct = [Course(name='Programming Languages 1', professor='<NAME>', tutor=None, academic_year='2018/2019', academic_semester=2, credits_number=10, description=None), Course(name='Linear Algebra 1', professor='<NAME>', tutor='<NAME>', academic_year='2015/2016', academic_semester=1, credits_number=5, description='Mathematics.'), Course(name='Database 1', professor='<NAME>', tutor='<NAME>', academic_year='2018/2019', academic_semester=1, credits_number=8, description='SQL.')] return new_courses_correct @pytest.fixture(scope='function', name='examples_courses_db_table') def create_courses_table_in_db_with_test_courses_already_added( init_sqlite3_db, init_sqlite3_db_connection, return_new_courses_correctly): ### SET-UP ### dao_handler = init_sqlite3_db_connection ### STEP 1: create an empty "courses" table ### dao_handler.create_table(table_name='courses') ### STEP 2: # add some test courses in the "courses" table ### for index, course in enumerate(return_new_courses_correctly): # Add a user and retrieve him/her ID course_id = dao_handler.add_row_into_table(object=course, table_name='courses') assert (course_id == index + 1) yield ### TEAR-DOWN ### print('teardown init_courses_db_table') #@TODO: drop table in the database
3a343433988a3f3bbeeddce35f5ddc2d4636b986
[ "Markdown", "Python", "Text", "INI" ]
16
Python
TheEdoardo93/TestingApplication
cbe2ef6a21019b673bdc0c167623691435471de4
2c255af79f873f4b5f8fd5000a384be4019aa3db
refs/heads/master
<repo_name>Neotrickster/RTvPlayer<file_sep>/README.md # RTvPlayer RTv Player xamarin forms scaling background image https://stackoverflow.com/questions/31853389/how-to-prevent-background-image-being-squeezed-when-the-keyboard-opens https://forums.xamarin.com/discussion/64304/how-can-stretch-background-content-image https://github.com/martijn00/XamarinMediaManager/issues/310 https://montemagno.com/beautiful-android-splash-screens/ https://medium.com/@thesultanster/xamarin-splash-screens-the-right-way-3d206120726d https://github.com/eggeggss/Xamarin-Form-SplashScreen-Animation https://auri.net/2016/11/20/how-to-setting-up-macos-x-sierra-on-virtualbox-for-xamarin-development-with-visual-studio/ http://bitsof.net/xamarin-ios-apps-without-physical-mac/ https://plus.google.com/+SysAdminsHowtos/posts/6e98eRghsw1 https://docs.microsoft.com/en-us/xamarin/ios/get-started/installation/windows/connecting-to-mac/ <file_sep>/RTvPlayer/RTvPlayer/ViewModels/RadioTelevisionCanalesViewModel.cs using System; using System.Collections.Generic; using System.Text; using ILCE.ViewModels; namespace RTvPlayer.ViewModels { class RadioTelevisionCanalesViewModel : BaseViewModel { public int screenSizeHeight { get; set; } public RadioTelevisionCanalesViewModel() { Title = "ILCE - Radio y Televisión"; var size = Plugin.XamJam.Screen.CrossScreen.Current.Size; screenSizeHeight = (int)((size.Height - 50) / 4); } } } <file_sep>/RTvPlayer/RTvPlayer/Views/SummaSaberes.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RTvPlayer.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace RTvPlayer.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SummaSaberes : ContentPage { public SummaSaberes () { InitializeComponent (); BindingContext = new SummaSaberesViewModel(); VideoPlayerSS.FullScreenStatusChanged += VideoPlayer_FullScreenStatusChanged; } private void VideoPlayer_FullScreenStatusChanged(object sender, bool value) { NavigationPage.SetHasNavigationBar(this, !value); } private double _width = 0; private double _height = 0; protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); //must be called if (this._width != width || this._height != height) { this._width = width; this._height = height; //reconfigurar layout cuando se gira el teléfono if (width > height) { //outerStack.Orientation = StackOrientation.Horizontal; //outterScroll.IsVisible = true; innerStack.IsVisible = false; outerStack.BackgroundColor = Color.Black; //this.BackgroundColor = Color.Aqua; //innerGrid.IsVisible = false; //Canal.IsVisible = false; //VideoPlayer. //InvalidateMeasure(); } else { //outerStack.Orientation = StackOrientation.Vertical; //outterScroll.IsVisible = false; innerStack.IsVisible = true; outerStack.BackgroundColor = Color.White; //this.BackgroundColor = Color.Chartreuse; //innerGrid.IsVisible = true; //Canal.IsVisible = true; //Canal.Text = Canal.Text + "(" + this._width + ")" + "(" + this._height + ")"; //InvalidateMeasure(); } } } private async Task BtnPlayCI_OnClicked(object sender, EventArgs e) { VideoPlayerSS.Stop(); //VideoPlayerCI.IsVisible = false; //await this.Navigation.PushAsync(new RTvCanales()); //await this.Navigation.PushModalAsync(new RTvCanales()); App.Current.MainPage = new CanalIberoamericano(); //App.Current.MainPage = new NavigationPage(new RTvCanales()); } private void BtnPlayIR_OnClicked(object sender, EventArgs e) { VideoPlayerSS.Stop(); App.Current.MainPage = new IberoamericaRadio(); } } }<file_sep>/RTvPlayer/RTvPlayer/App.xaml.cs using RTvPlayer.Views; using Xamarin.Forms; namespace RTvPlayer { public partial class App : Application { public App () { InitializeComponent(); MainPage = new RadioTelevisionCanales(); //RadioTelevisionCanales(); //IberoamericaRadio(); //CanalIberoamericano(); //RTvCanales(); //MainPage = new NavigationPage(new RadioTelevisionCanales()); //NavigationPage.SetHasNavigationBar(MainPage, false); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } } <file_sep>/RTvPlayer/RTvPlayer/ViewModels/IberoamericaRadioViewModel.cs using System; using System.Collections.Generic; using System.Text; using ILCE.ViewModels; namespace RTvPlayer.ViewModels { class IberoamericaRadioViewModel : BaseViewModel { public int screenSizeHeight { get; set; } public IberoamericaRadioViewModel() { Title = "Iberoamerica Radio"; var size = Plugin.XamJam.Screen.CrossScreen.Current.Size; screenSizeHeight = (int)((size.Height - 270) / 3); } } } <file_sep>/RTvPlayer/RTvPlayer/ViewModels/RTvCanalesViewModel.cs using ILCE.ViewModels; namespace RTvPlayer.ViewModels { class RTvCanalesViewModel : BaseViewModel { public int screenSizeHeight { get; set; } public RTvCanalesViewModel() { Title = "ILCE RTv"; var size = Plugin.XamJam.Screen.CrossScreen.Current.Size; screenSizeHeight = (int)((size.Height - 270) / 4); } } } <file_sep>/RTvPlayer/RTvPlayer/ViewModels/CanalIberoamericanoViewModel.cs using System; using System.Collections.Generic; using System.Text; using ILCE.ViewModels; namespace RTvPlayer.ViewModels { class CanalIberoamericanoViewModel : BaseViewModel { public int screenSizeHeight { get; set; } public CanalIberoamericanoViewModel() { Title = "Canal Iberoamericano"; var size = Plugin.XamJam.Screen.CrossScreen.Current.Size; screenSizeHeight = (int)((size.Height - 270) / 4); } } }
f75b8eca6704b142bd1f5ff09a4374a7b000b10b
[ "Markdown", "C#" ]
7
Markdown
Neotrickster/RTvPlayer
9468367e6e7b60e300cfd47bda51cf34f8f550b6
a0043882be2c1625dbebd90f1b4519df02684e1b
refs/heads/master
<repo_name>kokot300/quiz_flask<file_sep>/flask_app.py #!/usr/bin/python from flask import Flask, render_template, request from models import Question, Category import api_handler from random import shuffle app = Flask(__name__) questions_lst2 = [] api_question_lst = [] @app.route('/', methods=['GET', 'POST']) def root(): if request.method == 'GET': return render_template('index.html') else: return render_template('index.html') @app.route('/quiz', methods=['GET', 'POST']) def quiz(): global questions_lst2 categories = Category.get_all_cat() if request.method == 'GET': return render_template('quiz_select_cat.html', categories=categories) else: where = request.form.get('where') if where == '0': questions_lst2 = [] category = request.form.get('category') if category == 'All': category = None else: category = Category.get_cat_by_name(category) category = category[0] print(category) questions_lst = Question.get_5_random(category) print(questions_lst) for idd in questions_lst: ask = Question.get_from_class_id(idd) ask = str(ask) ask_lst = ask.split('/') questions_lst2.append(ask_lst) return render_template('quiz_challenge.html', questions_lst2=questions_lst2) elif where == '1': answer_lst = [] try: for answer in questions_lst2: ans = answer[6] answer_lst.append(ans) question_id_lst = [] for question_id in questions_lst2: ques = question_id[0] question_id_lst.append(ques) user_answers = [] first_question = request.form.get(question_id_lst[0]) second_question = request.form.get(question_id_lst[1]) third_question = request.form.get(question_id_lst[2]) fourth_question = request.form.get(question_id_lst[3]) fifth_question = request.form.get(question_id_lst[4]) user_answers.append(first_question) user_answers.append(second_question) user_answers.append(third_question) user_answers.append(fourth_question) user_answers.append(fifth_question) print(user_answers) score = 0 for i in range(5): if user_answers[i] == answer_lst[i]: score += 1 return render_template('quiz_results.html', questions_lst2=questions_lst2, user_answers=user_answers, score=score) except IndexError: return render_template('quiz_select_cat.html', categories=categories) else: return render_template('quiz_select_cat.html', categories=categories) @app.route('/quiz_api', methods=['GET', 'POST']) def quiz_api(): global api_question_lst categories = api_handler.get_cats() if request.method == 'GET': return render_template('quiz_api_select_cat.html', categories=categories) else: where = request.form.get('where') print(where) if where == '0': api_question_lst = [] category = request.form.get('category') if category == 'All': category = None print(category) questions = api_handler.get_questions(category) print(questions) question_lst = [] for question in questions: answers = question['incorrect_answers'] answers.append(question['correct_answer']) shuffle(answers) question_lst.append(question['question']) question_lst.append(answers) question_lst.append(question['correct_answer']) api_question_lst.append(question_lst) question_lst = [] return render_template('quiz_api_challenge.html', questions=api_question_lst) elif where == '1': answer_lst = [] try: for answer in api_question_lst: ans = answer[2] answer_lst.append(ans) question_id_lst = [] for question_id in api_question_lst: ques = question_id[0] question_id_lst.append(ques) user_answers = [] first_question = request.form.get(question_id_lst[0]) second_question = request.form.get(question_id_lst[1]) third_question = request.form.get(question_id_lst[2]) fourth_question = request.form.get(question_id_lst[3]) fifth_question = request.form.get(question_id_lst[4]) user_answers.append(first_question) user_answers.append(second_question) user_answers.append(third_question) user_answers.append(fourth_question) user_answers.append(fifth_question) score = 0 for i in range(5): if user_answers[i] == answer_lst[i]: score += 1 except: pass return render_template('quiz_api_results.html', api_question_lst=api_question_lst, user_answers=user_answers, score=score) else: return render_template('quiz_api_select_cat.html', categories=categories) @app.route('/add_question', methods=['GET', 'POST']) def add_question(): if request.method == 'GET': categories = Category.get_all_cat() return render_template('add_question.html', categories=categories) else: categories = Category.get_all_cat() question = request.form.get('question') a = request.form.get('a').lower() b = request.form.get('b').lower() c = request.form.get('c').lower() d = request.form.get('d').lower() correct = request.form.get('correct').lower() category = request.form.get('category').lower() category = Category.get_cat_by_name(category) category = category[0] print(question, a, b, c, d, correct, category) msg = Question.creator(question, a, b, c, d, correct, category) print(msg) return render_template('add_question.html', categories=categories, msg=msg.add_to_db()) @app.route('/add_category', methods=['GET', 'POST']) def add_category(): if request.method == 'GET': return render_template('add_category.html') else: candidate = request.form.get('category').lower() new_cat = Category.creator(candidate) return render_template('add_category.html', msg=new_cat.add_to_db()) if __name__ == '__main__': app.run(debug=True) <file_sep>/models.py #!/usr/bin/python from psycopg2 import connect, OperationalError, errors from random import shuffle USER = 'kokot300' PASSWORD = '' HOST = 'localhost' DATABASE = 'quiz_db' class Question: @classmethod def creator(cls, question, aaa, bbb, ccc, ddd, correct, category_id): if not isinstance(question, str): return 'classmethod says: question must be a string' if not isinstance(aaa, str) or len(aaa) > 60: return 'classmethod says: aaa must be a string of 60 chars max' if not isinstance(bbb, str) or len(bbb) > 60: return 'classmethod says: bbb must be a string of 60 chars max' if not isinstance(ccc, str) or len(ccc) > 60: return 'classmethod says: aaa must be a string of 60 chars max' if not isinstance(ddd, str) or len(ddd) > 60: return 'classmethod says: ddd must be a string of 60 chars max' if not isinstance(correct, str) or len(correct) > 60: return 'classmethod says: correct must be a string of 1 char max' if category_id: pass return cls(question, aaa, bbb, ccc, ddd, correct, category_id) def __init__(self, question, aaa, bbb, ccc, ddd, correct, category_id, idd=-1): self.question = question self.aaa = aaa self.bbb = bbb self.ccc = ccc self.ddd = ddd self.correct = correct self.category_id = category_id # provisory self.id = idd def add_to_db(self): command = f'''INSERT INTO questions(question, aaa, bbb, ccc, ddd, correct, category_id) VALUES (%s, %s, %s, %s, %s, %s, %s);''' tlp = (self.question, self.aaa, self.bbb, self.ccc, self.ddd, self.correct, self.category_id) cursor = Question.connect_me() try: cursor.execute(command, tlp) except OperationalError as e: print(e) return f'{e}' except errors.UniqueViolation as e: return f'{e}' else: cursor.close() return 'added' @staticmethod def get_from_class_id(question_id): command = '''SELECT question, aaa, bbb, ccc, ddd, correct, category_id, id FROM questions WHERE id = %s;''' tlp = (question_id,) cursor = Question.connect_me() try: cursor.execute(command, tlp) data = cursor.fetchone() # tuple except OperationalError as e: print(e) return f'{e}' else: cursor.close() if data is not None: new_question = Question(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]) return new_question @staticmethod def connect_me(): try: cnx = connect( user=USER, password=<PASSWORD>, host=HOST, database=DATABASE ) cnx.autocommit = True cursor = cnx.cursor() return cursor except OperationalError as e: print(e) return f'{e}' def __str__(self): return f'{self.id}/{self.question}/{self.aaa}/{self.bbb}/{self.ccc}/{self.ddd}/{self.correct}/{self.category_id}' @staticmethod def get_5_random(category=None): cursor = Question.connect_me() if category is None: command = '''SELECT id FROM questions;''' try: cursor.execute(command) data = cursor.fetchall() # list of tuples except OperationalError as e: print(e) return f'{e}' else: command = '''SELECT id FROM questions WHERE category_id = %s;''' tlp = (category,) try: cursor.execute(command, tlp) data = cursor.fetchall() # tuple except OperationalError as e: print(e) return f'{e}' cursor.close() shuffle(data) print('data in models', data) return data[0:5] class Category: @classmethod def creator(cls, name): if len(name) <= 60: return cls(name) def __init__(self, name): self.name = name self.id = -1 @staticmethod def connect_me(): try: cnx = connect( user=USER, password=<PASSWORD>, host=HOST, database=DATABASE ) cnx.autocommit = True cursor = cnx.cursor() return cursor except OperationalError as e: print(e) return f'{e}' def add_to_db(self): command = f'''INSERT INTO categories(name) VALUES (%s);''' tlp = (self.name,) cursor = Question.connect_me() try: cursor.execute(command, tlp) except OperationalError as e: print(e) return f'{e}' except errors.UniqueViolation as e: return f'{e}' else: cursor.close() return 'added' @staticmethod def validate_category(name): command = f"""SELECT * FROM categories WHERE name = %s;""" tlp = (name,) cursor = Question.connect_me() try: cursor.execute(command, tlp) except OperationalError as e: print(e) return f'{e}' else: data = cursor.fetchone() cursor.close() print(data) if data is None: return False return True @staticmethod def get_cat_by_name(name): command = f"""SELECT id FROM categories WHERE name = %s;""" tlp = (name,) cursor = Question.connect_me() try: cursor.execute(command, tlp) except OperationalError as e: print(e) return f'{e}' else: data = cursor.fetchone() cursor.close() print(data) return data @staticmethod def get_all_cat(): command = f"""SELECT name FROM categories;""" cursor = Question.connect_me() try: cursor.execute(command) except OperationalError as e: print(e) return f'{e}' else: data = cursor.fetchall() cursor.close() return data def __str__(self): return f'{self.id}, {self.name}' if __name__ == '__main__': pass # q = Question('kto jest najpiękniejszy na świecie?', 'ja', 'ty', 'on', 'ona', 'a', 1) # q.add_to_db() # q = Question.get_from_class_id(2) # print(q) # q = Question.creator('kto jest najsilniejszy na świecie?', 'ja', 'ty', 'on', 'ona', 'd', 1) # print(q) # q.add_to_db() # q = Question.get_5_random() # print(q[0][0]) # Category.validate_category('głupie') <file_sep>/api_handler.py #!/usr/bin/python from requests import get def get_cats(): api_endpoint = 'https://opentdb.com/api_category.php' response = get(api_endpoint) data = response.json() return data['trivia_categories'] def get_questions(category=None): if category is None: api_endpoint = 'https://opentdb.com/api.php?amount=5&type=multiple' else: api_endpoint = f'https://opentdb.com/api.php?amount=5&category={category}&type=multiple' response = get(api_endpoint) data = response.json() return data['results'] if __name__ == '__main__': get_questions() <file_sep>/create_db.py q = """create table questions( id serial, question text, aaa varchar(60), bbb varchar(60), ccc varchar(60), ddd varchar(60), correct varchar(1), category_id int, when_added timestamp NOT NULL, PRIMARY KEY (id), FOREIGN KEY (category_id) REFERENCES categories(id));""" q2="""CREATE TABLE categories( id serial, name varchar(60), PRIMARY KEY (id) );"""<file_sep>/README.md # quiz_flask quiz on flask and postgresql
240a35273824d0b6a9b243d06fe0b32373ca7f1e
[ "Markdown", "Python" ]
5
Python
kokot300/quiz_flask
9a6690fd5069e5ed9110a39dd617b87760c92225
b767ed7371e9463461116f2b579aec98003f19a7
refs/heads/master
<repo_name>42p/bushed-bricks<file_sep>/js/gear.js /* * "Bushed Bricks" JavaScript Game * source code : https://github.com/shtange/bushed-bricks * play it here : https://shtange.github.io/bushed-bricks/ * * Copyright 2016, <NAME> * GitHub : https://github.com/shtange/ * Habr : https://habrahabr.ru/users/shtange/ * email : <EMAIL> * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ var Gear = function (params) { this.config = { size : params.size && [6, 7, 8, 9, 10].indexOf(params.size) > -1 ? params.size : 7, count : params.count && [2, 3, 4].indexOf(params.count) > -1 ? params.count : 2, maxCombo : params.combo && [2, 3, 4, 5].indexOf(params.combo) > -1 ? params.combo : 4, mode : params.mode && ['easy', 'hard'].indexOf(params.mode) > -1 ? params.mode : 'easy', lifeTime : 4, points : 10, }; this.score = 0; this.step = 1; this.gain = {}; this.over = false; this.colour = new Colour(); this.shelter = new Shelter(); this.render = new Render(this.config); this.controls = new ControlsManager(this.api, this); this.grid = new Grid(this.config, this.shelter.list, this.api, this); this.api.game.run.call(this); } Gear.prototype.api = { score: { update: function(data) { var points = this.config.points * ( data.combo || 1 ); this.score += points; this.gain.points = points; this.gain.colour = data.colour; } }, controls: { move: function(key) { var route = { row: 0, col: 0 }; if (key%2 === 0) { route.col = key > 0 ? 1 : -1; // up, down } else { route.row = key > 2 ? -1 : 1; // left, right } if (!this.grid.cellsAvailable()) { this.api.game.over.call(this); } else { this.api.game.update.call(this, key, route); } this.controls.position = []; } }, game: { run: function() { var cell = {}; [].map.call(this.colour.list, function(colour) { cell = this.grid.randomAvailableCell(); this.grid.cells[cell.row][cell.col] = new Tile(colour); }, this); this.render.redraw(this.grid.cells, this.score, this.gain); }, update: function(key, route) { this.grid.update(key, route); this.api.game.step.call(this); this.api.game.redraw.call(this, this.grid.cells, this.score, this.gain, this.step); this.gain = {}; }, step: function() { var cell, colour; for (var i = 0; i < this.config.count; i++) { cell = this.grid.randomAvailableCell(); colour = this.colour.randomByWeight(); this.grid.cells[cell.row][cell.col] = new Tile(colour); } this.step++ }, reload: function() { this.score = 0; this.step = 1; this.over = false; this.grid.clear(); this.render.clear(); this.api.game.run.call(this); }, over: function() { this.over = true; this.render.gameOver(); }, redraw: function(cells, score, gain, step) { this.render.redraw(cells, score, gain, step); } } }
6c1bcdbd50da56f9413d3bd61a400a3091629bcb
[ "JavaScript" ]
1
JavaScript
42p/bushed-bricks
e254849a2ee3a5fe7587413e9e3b2758a428f56b
5b08d5261a9dc0c88528118008313f6fb97ace40
refs/heads/master
<repo_name>SamMurphy/Audio-Switcher-For-Windows<file_sep>/AudioSwitch/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SetDefaultAudioEndpoint; namespace AudioSwitch { class Program { private static List<string> audioDevices = new List<string>(); static void Main(string[] args) { SetDefaultAudioEndpoint.WindowsSound sound = new SetDefaultAudioEndpoint.WindowsSound(); bool switched = false; if (args.Length > 0) { if (args[0].EndsWith(".txt")) { ReadAudioDevices(args[0]); // If txt file is an argument then load audio devices from file } } if (args.Length == 0 || audioDevices.Count <= 0) // If no file then load default devices { audioDevices.Add("Headphones"); audioDevices.Add("Speakers"); } string path = System.Windows.Forms.Application.StartupPath + @"\currentDeviceID.txt"; int i = GetLastSetDevice(path) + 1; while (!switched) { if (i > audioDevices.Count - 1) i = 0; // reset i try { sound.SetDefaultAudioPlaybackDevice(audioDevices[i]); // Try and set it to Headphones sound.Dispose(); Console.WriteLine("SWITCHED TO " + audioDevices[i].ToUpper()); switched = true; System.IO.File.WriteAllText("currentDeviceID.txt", i.ToString()); } catch (Exception e) // If you can't then try set it to Speakers { //Console.WriteLine("EXECPTION:\n"); //Console.WriteLine(e.Message); } finally { i++; } } System.Threading.Thread.Sleep(500); } static void ReadAudioDevices(string fileName) { System.IO.StreamReader file = new System.IO.StreamReader(fileName); string line; int counter = 0; while((line = file.ReadLine()) != null) { audioDevices.Add(line); counter++; } file.Close(); } static int GetLastSetDevice(string fileName) { int deviceNumber = 0; try { bool success = false; System.IO.StreamReader file = new System.IO.StreamReader(fileName); string line; int counter = 0; while ((line = file.ReadLine()) != null) { success = Int32.TryParse(line, out deviceNumber); counter++; } file.Close(); if (success && deviceNumber < audioDevices.Count) return deviceNumber; } catch (Exception e) { } return deviceNumber; } } } <file_sep>/README.md # Windows Audio Switch Command line tool to quickly switch between audio output devices on windows. When launched will set the next audio device to default. Loads the names of the audio devices through a text file that should be passed as an argument. The names of the devices should be the primary name listed in the playback tab of the Windows Sound window. Example audioDevices.txt: Headphones Speakers DELL U2715H FiiO DAC This project uses the SetDefualtAudioEndpoint library ![Alt text](/icon.ico)
b157b4aa17644f044c0c8a5954fe712e0e2644b9
[ "Markdown", "C#" ]
2
C#
SamMurphy/Audio-Switcher-For-Windows
fd0e0dec2e6e3f95ca36519dc18560f922f0d4cf
a27e2c9f530ad7d36ae87887315a403aa746742a
refs/heads/master
<repo_name>Silvian/phishtray<file_sep>/participant/serializer.py from rest_framework import serializers from .models import ( Participant, ParticipantAction, ParticipantProfileEntry, ActionLog) class ParticipantActionSerializer(serializers.ModelSerializer): action_details = serializers.SerializerMethodField() class Meta: model = ParticipantAction fields = ('id', 'action_details',) def get_action_details(self, participant_action): log_entries_queryset = ActionLog.objects.filter(action=participant_action) data = {} for entry in log_entries_queryset: data[entry.name] = entry.value return data class ParticipantProfileEntrySerializer(serializers.ModelSerializer): question = serializers.SerializerMethodField(read_only=True) class Meta: model = ParticipantProfileEntry fields = ('id', 'question', 'answer',) def get_question(self, profile_entry): return profile_entry.question class ParticipantSerializer(serializers.ModelSerializer): actions = serializers.SerializerMethodField(read_only=True) profile = ParticipantProfileEntrySerializer(read_only=True, many=True) class Meta: model = Participant fields = ('id', 'exercise', 'profile', 'actions',) def get_actions(self, participant): participant_actions_queryset = ParticipantAction.objects.filter(participant=participant) return ParticipantActionSerializer(participant_actions_queryset, many=True).data <file_sep>/exercise/serializer.py from rest_framework import serializers from .models import * class DemographicsInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DemographicsInfo fields = ('id', 'question', 'question_type', 'required') class ExerciseEmailReplySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ExerciseEmailReply fields = ('id', 'reply_type', 'message') class ExerciseFileSerializer(serializers.HyperlinkedModelSerializer): date_created = serializers.DateTimeField(source='created_date') file_url = serializers.CharField(source='img_url') class Meta: model = ExerciseFile fields = ('id', 'file_name', 'description', 'date_created', 'file_url') class ExerciseEmailSerializer(serializers.HyperlinkedModelSerializer): replies = ExerciseEmailReplySerializer(many=True) attachments = ExerciseFileSerializer(many=True) class Meta: model = ExerciseEmail fields = ( 'id', 'subject', 'from_address', 'from_name', 'to_address', 'to_name', 'phish_type', 'content', 'attachments', 'replies', ) class EmailDetailsSerializer(serializers.HyperlinkedModelSerializer): replies = ExerciseEmailReplySerializer(many=True) attachments = ExerciseFileSerializer(many=True) from_account = serializers.SerializerMethodField() to_account = serializers.SerializerMethodField() body = serializers.CharField(source='content') class Meta: model = ExerciseEmail fields = ( 'id', 'subject', 'phish_type', 'from_account', 'to_account', 'body', 'attachments', 'replies', ) def get_from_account(self, email): return email.from_account def get_to_account(self, email): return email.to_account class ThreadSerializer(serializers.ModelSerializer): body = serializers.CharField(source='content') from_account = serializers.SerializerMethodField() to_account = serializers.SerializerMethodField() replies = ExerciseEmailReplySerializer(many=True) attachments = ExerciseFileSerializer(many=True) emails = serializers.SerializerMethodField() reveal_time = serializers.SerializerMethodField() class Meta: model = ExerciseEmail fields = ( 'id', 'subject', 'reveal_time', 'from_account', 'to_account', 'body', 'attachments', 'replies', 'emails', ) def get_emails(self, email): belonging_emails_queryset = ExerciseEmail.objects.filter(belongs_to=email.id) return EmailDetailsSerializer(belonging_emails_queryset, many=True).data def get_from_account(self, email): return email.from_account def get_to_account(self, email): return email.to_account def get_reveal_time(self, email): return email.reveal_time class ExerciseSerializer(serializers.HyperlinkedModelSerializer): threads = ThreadSerializer(source='emails', many=True) profile_form = DemographicsInfoSerializer(source='demographics', many=True) files = ExerciseFileSerializer(many=True) class Meta: model = Exercise fields = ( 'id', 'title', 'description', 'introduction', 'afterword', 'length_minutes', 'profile_form', 'threads', 'files' ) <file_sep>/frontend/src/components/WebBrowser/websites/Bluestar/index.js import React, { Component } from 'react'; import { Switch, Route } from 'react-router-dom'; import styled, { css } from 'react-emotion'; import { TextInput, Button, Checkbox, Icon } from 'carbon-components-react'; import { iconStarOutline } from 'carbon-icons'; import Bg from './assets/bg.png'; const LoginContainer = styled('div')({ margin: '120px auto 0', padding: '42px 42px 36px', overflow: 'hidden', width: '80%', // maxWidth: '1500px', flexDirection: 'row', flex: 1, justifyContent: 'space-around', display: 'flex', }); const LoginContainerImage = styled('div')({ flex: 1, }); const LoginContainerForm = styled('div')({ maxWidth: '440px', width: '100%', }); const FieldWrapper = styled('div')({ padding: '12px 12px 23px', overflow: 'hidden', display: 'flex', }); const LoginBanner = styled('div')({ flex: 1, borderBottom: '1px solid #eaeced', display: 'flex', position: 'absolute', top: '70px', width: '100%', padding: '15px 0px ', }); const LoginBannerText = styled('div')({ textAlign: 'center', color: '#4285F4', flexGrow: 1, fontSize: '36px', fontWeight: '800', fontFamily: 'Open Sans', letterSpacing: '3.6px', lineHeight: '40px', }); const ForgotPassLink = styled('a')({ color: '#4285F4', fontSize: '15px', textDecoration: 'none', }); const LoginHeaderText = styled('h2')({ color: '#4285F4', lineHeight: '40px', fontFamily: 'Open Sans', fontSize: '36px', }); const TextInputProps = () => ({ className: css({ display: 'flex' }), disabled: false, labelText: '', }); const ButtonProps = () => ({ className: css({ display: 'flex', flexGrow: 1 }), id: 'button', kind: 'primary', }); export default class MyPayment extends Component { render() { return ( <Switch> <Route path="/congrats" render={() => ( <LoginContainer> <h1>Thanks for visiting Bluestar Technologies.</h1> </LoginContainer> )} /> <Route path="/" render={({ history }) => ( <div> <LoginBanner> <Icon icon={iconStarOutline} name="iconStart" fill="#4285F4" height="40px" width="150px" className={css({ position: 'absolute', })} /> <LoginBannerText>BlueStar Technologies</LoginBannerText> </LoginBanner> <LoginContainer> <LoginContainerImage> <img src={Bg} alt="background" /> </LoginContainerImage> <LoginContainerForm> <FieldWrapper> <LoginHeaderText>Login</LoginHeaderText> </FieldWrapper> <FieldWrapper> <TextInput {...TextInputProps()} id="email" placeholder="Email" type="email" onClick={() => { this.props.logBrowserActions({ event: `clicked_input_email`, }); }} /> </FieldWrapper> <FieldWrapper> <TextInput {...TextInputProps()} id="password" placeholder="<PASSWORD>" type="<PASSWORD>" onClick={() => { this.props.logBrowserActions({ event: `clicked_input_password`, }); }} /> </FieldWrapper> <FieldWrapper> <Checkbox labelText="Remember Me" onChange={value => this.props.logBrowserActions({ event: `set_remember_${value}`, }) } id="checkbox-label-1" /> <Button {...ButtonProps()} onClick={() => { this.props.logBrowserActions({ event: `clicked_${ButtonProps().kind}_button_next`, }); history.push('/congrats'); }} > Login </Button> </FieldWrapper> <FieldWrapper> <ForgotPassLink onClick={() => this.props.logBrowserActions({ event: `clicked_forgotten_password`, }) } > Forgotten your password? </ForgotPassLink> </FieldWrapper> </LoginContainerForm> </LoginContainer> </div> )} /> </Switch> ); } } <file_sep>/exercise/views.py from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from participant.models import Participant from .models import ( Exercise, ExerciseEmail, ) from .serializer import ( ExerciseSerializer, ExerciseEmailSerializer, ThreadSerializer) class ExerciseViewSet(viewsets.ModelViewSet): queryset = Exercise.objects.all() serializer_class = ExerciseSerializer def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated, IsAdminUser] else: permission_classes = [] return [permission() for permission in permission_classes] http_method_names = ['get', 'head', 'options'] @action(methods=['get'], detail=True, permission_classes=[]) def init(self, request, *args, **kwargs): exercise = self.get_object() participant = Participant(exercise=exercise) participant.save() resp = { 'participant': str(participant.id), 'exercise': ExerciseSerializer(exercise).data } return Response(data=resp) class ExerciseEmailViewSet(viewsets.ModelViewSet): queryset = ExerciseEmail.objects.all() serializer_class = ExerciseEmailSerializer def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated, IsAdminUser] else: permission_classes = [] return [permission() for permission in permission_classes] http_method_names = ['get', 'head', 'options'] class ExerciseEmailThreadViewSet(viewsets.ModelViewSet): """ This view retrieves emails in thread style """ queryset = ExerciseEmail.objects.all() serializer_class = ThreadSerializer def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated, IsAdminUser] else: permission_classes = [] return [permission() for permission in permission_classes] http_method_names = ['get', 'head', 'options'] <file_sep>/frontend/src/components/WebBrowser/websites/MyPayment/index.js import React, { Component } from 'react'; import { Switch, Route } from 'react-router-dom'; import styled, { css } from 'react-emotion'; import { TextInput, Button } from 'carbon-components-react'; import Logo from './assets/logo.png'; const LoginContainer = styled('div')({ margin: '120px auto 0', padding: '42px 42px 36px', overflow: 'hidden', width: '500px', border: '1px solid #eaeced', textAlign: 'center', }); const FieldWrapper = styled('div')({ padding: '12px 12px 23px', overflow: 'hidden', display: 'flex', }); const TextInputProps = () => ({ className: css({ display: 'flex' }), id: 'test2', type: 'email', placeholder: 'Email Address', disabled: false, labelText: '', }); const ButtonProps = () => ({ className: css({ display: 'flex', flexGrow: 1 }), id: 'test2', kind: 'primary', }); const ButtonAlternateProps = () => ({ className: css({ display: 'flex', flexGrow: 1 }), id: 'test2', kind: 'secondary', }); export default class MyPayment extends Component { render() { return ( <Switch> <Route path="/congrats" render={() => ( <LoginContainer> <h1> Thank you for checking. Your recent transactions have been verified. </h1> </LoginContainer> )} /> <Route path="/" render={({ history }) => ( <LoginContainer> <img src={Logo} width={323} height={58} alt="logo" /> <FieldWrapper> <TextInput {...TextInputProps()} onClick={() => { this.props.logBrowserActions({ event: `clicked_input_email`, }); }} /> </FieldWrapper> <FieldWrapper> <Button {...ButtonProps()} onClick={() => { this.props.logBrowserActions({ event: `clicked_${ButtonProps().kind}_button_next`, }); history.push('/congrats'); }} > Next </Button> </FieldWrapper> <FieldWrapper>Having trouble logging in?</FieldWrapper> <FieldWrapper> <Button {...ButtonAlternateProps()} onClick={() => this.props.logBrowserActions({ event: `clicked_${ButtonProps().kind}_button_signup`, }) } > Sign Up </Button> </FieldWrapper> </LoginContainer> )} /> </Switch> ); } } <file_sep>/exercise/tests/test_models.py from django.test import TestCase from ..factories import ( EmailFactory, ExerciseFactory ) from ..models import ExerciseEmailProperties class ExerciseModelTests(TestCase): def test_set_email_reveal_times_with_no_emails(self): exercise = ExerciseFactory() self.assertEqual(0, exercise.emails.all().count()) exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise) self.assertEqual(0, exercise_reveal_times.count()) def test_set_email_reveal_times_with_less_than_ten_emails(self): emails = EmailFactory.create_batch(4) exercise = ExerciseFactory.create(emails=emails) exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise) exercise.set_email_reveal_times() received_emails = [e for e in exercise_reveal_times if e.reveal_time is 0] self.assertEqual(4, exercise.emails.all().count()) self.assertEqual(1, len(received_emails)) def test_set_email_reveal_times_with_more_than_ten_emails(self): emails = EmailFactory.create_batch(27) exercise = ExerciseFactory.create(emails=emails) exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise) exercise.set_email_reveal_times() received_emails = [e for e in exercise_reveal_times if e.reveal_time is 0] self.assertEqual(27, exercise.emails.all().count()) self.assertTrue(2 <= len(received_emails) <= 4) def test_sticky_received_emails(self): """ Current logic dictates that received emails shouldn't change after saving the Exercise. """ emails = EmailFactory.create_batch(35) exercise = ExerciseFactory.create(emails=emails) exercise_reveal_times = ExerciseEmailProperties.objects.filter(exercise=exercise) exercise.set_email_reveal_times() received_emails = [e for e in exercise_reveal_times if e.reveal_time is 0] received_email_ids = [re.id for re in exercise.emails.all()] self.assertEqual(35, exercise.emails.all().count()) self.assertTrue(3 <= len(received_emails) <= 5) exercise.title = 'Updated Exercise' exercise.save() received_email_ids_after_update = [re.id for re in exercise.emails.all()] self.assertEqual(set(received_email_ids), set(received_email_ids_after_update)) <file_sep>/frontend/src/pages/Afterward/index.js import React from 'react'; import { connect } from 'react-redux'; import ReactMarkdown from 'react-markdown'; import styled from 'react-emotion'; import { persistor } from '../../redux'; import { getRange } from '../../utils'; const Container = styled('div')({ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', backgroundColor: '#fff', boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.1)', padding: '1rem', flexDirection: 'column', }); const Title = styled('h1')({ display: 'block', fontSize: ' 2.25rem', lineHeight: 1.25, marginBottom: '35px', fontWeight: 300, }); type Props = { afterwardMessage: String, }; const clearSessionStorage = async () => await sessionStorage.clear(); class Afterward extends React.Component<Props> { state = { message: '', }; componentDidMount() { this.setState( { message: this.props.afterwardMessage, }, () => { getRange(0, 100).map(i => clearInterval(i)); //bad habits clearSessionStorage().then(() => { sessionStorage.clear(); persistor.purge(); }); } ); } render() { return ( <Container> <Title>Thanks for taking the exercise.</Title> {this.props.message && <ReactMarkdown source={this.state.message} />} </Container> ); } } export default connect( state => ({ afterwardMessage: state.exercise.afterword, }), {} )(Afterward);
f01459c078a354b1a18aefdd16d6194a015e0978
[ "JavaScript", "Python" ]
7
Python
Silvian/phishtray
4fe0a8c743a32bf3c41220de1b256f1b58c4db32
c769efe74d347edcb8bc8229434f40c218180a16
refs/heads/master
<file_sep>#!/bin/bash # locks: https://stackoverflow.com/questions/185451/quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at ( # Wait for lock on fd 200 for max 1 second - if fail then exit flock -x -w 1 200 || exit 124 echo "got exclusive lock - starting script..." # Do stuff sleep 10 source /pgenv.sh #echo "Running with these environment options" >> /var/log/cron.log #set | grep PG >> /var/log/cron.log MYDATE=`date +%d-%B-%Y` MONTH=$(date +%B) YEAR=$(date +%Y) MYBASEDIR=/backups MYBACKUPDIR=${MYBASEDIR}/${YEAR}/${MONTH} mkdir -p ${MYBACKUPDIR} cd ${MYBACKUPDIR} echo "Backup running to $MYBACKUPDIR" >> /var/log/cron.log # # Loop through each pg database backing it up # DBLIST=`psql -l | awk '{print $1}' | grep -v "+" | grep -v "Name" | grep -v "List" | grep -v "(" | grep -v "template" | grep -v "postgres" | grep -v "|" | grep -v ":"` # echo "Databases to backup: ${DBLIST}" >> /var/log/cron.log for DB in ${DBLIST} do echo "Backing up $DB" >> /var/log/cron.log FILENAME=${MYBACKUPDIR}/${DUMPPREFIX}_${DB}.${MYDATE}.dmp pg_dump -Fc -f ${FILENAME} -x -O ${DB} done ) 200>/var/lock/.backups.exclusivelock
a59373aeb090017c993167e19f7a5d36395dd8c4
[ "Shell" ]
1
Shell
ykasidit/docker-pg-backup
12d2b1c7193eab777b6d41c44955893100cfec5a
b658fa6956ff9ee5f99b09fd54573e4a1bd6f144
refs/heads/master
<repo_name>wellmonge/SwiftyMenu<file_sep>/Example/SwiftyMenu/ViewController.swift // // ViewController.swift // SwiftyMenu // // Created by KEMansour on 04/17/2019. // Copyright (c) 2019 KEMansour. All rights reserved. // import UIKit import SwiftyMenu class ViewController: UIViewController { @IBOutlet private weak var dropDown: SwiftyMenu! private let dropDownOptionsDataSource = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6", "Option 7", "Option 8", "Option 9", "Option 10", "Option 11", "Option 12", "Option 13", "Option 14", "Option 15"] override func viewDidLoad() { super.viewDidLoad() dropDown.updateConstraints { UIView.animate(withDuration: 0.5, animations: { self.view.layoutIfNeeded() }) } dropDown.didSelectOption { (selectedText, index) in print("Selected String: \(selectedText) at index: \(index)") } dropDown.options = dropDownOptionsDataSource } } <file_sep>/SwiftyMenu/Classes/SwiftyMenu.swift // // SwiftyMenu.swift // DropDownMenu // // Created by <NAME> on 4/17/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UIKit @IBDesignable public class SwiftyMenu: UIView { // MARK: - Properties @IBOutlet weak var heightConstraint: NSLayoutConstraint! private var selectButton: UIButton! private var optionsTableView: UITableView! private var state: MenuState = .hidden private enum MenuState { case shown case hidden } private var width: CGFloat! private var height: CGFloat! public var selectedIndex: Int? public var options = [String]() // MARK: - Closures private var updateHeightConstraint: () -> () = { } private var didSelectCompletion: (String, Int) -> () = { selectedText, index in } private var TableWillAppearCompletion: () -> () = { } private var TableDidAppearCompletion: () -> () = { } private var TableWillDisappearCompletion: () -> () = { } private var TableDidDisappearCompletion: () -> () = { } // MARK: - IBInspectable @IBInspectable public var rowHeight: Double = 35 @IBInspectable public var rowBackgroundColor: UIColor = .white @IBInspectable public var selectedRowColor: UIColor = .white @IBInspectable public var hideOptionsWhenSelect = true @IBInspectable public var optionColor: UIColor = UIColor(red: 74.0/255.0, green: 74.0/255.0, blue: 74.0/255.0, alpha: 1.0) @IBInspectable public var placeHolderColor: UIColor = UIColor(red: 149.0/255.0, green: 149.0/255.0, blue: 149.0/255.0, alpha: 1.0) { didSet { selectButton.setTitleColor(placeHolderColor, for: .normal) } } @IBInspectable public var placeHolderText: String? { didSet { selectButton.setTitle(placeHolderText, for: .normal) } } @IBInspectable public var arrow: UIImage? { didSet { selectButton.titleEdgeInsets.left = 5 selectButton.setImage(arrow, for: .normal) } } @IBInspectable public var titleLeftInset: Int = 0 { didSet { selectButton.titleEdgeInsets.left = CGFloat(titleLeftInset) } } @IBInspectable public var borderColor: UIColor = UIColor.lightGray { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var listHeight: CGFloat = 150 { didSet { } } @IBInspectable public var borderWidth: CGFloat = 0.0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius: CGFloat = 8.0 { didSet { layer.cornerRadius = cornerRadius } } // MARK: - Init public override init(frame: CGRect) { super.init(frame: frame) setupUI() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupUI() } private func setupUI () { setupView() getViewWidth() getViewHeight() setupSelectButton() setupDataTableView() } private func setupView() { clipsToBounds = true layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor } private func getViewWidth() { width = self.frame.width } private func getViewHeight() { height = self.frame.height } private func setupSelectButton() { selectButton = UIButton(frame: self.frame) self.addSubview(selectButton) selectButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: selectButton!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: height).isActive = true NSLayoutConstraint(item: selectButton!, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: selectButton!, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: selectButton!, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0).isActive = true let color = placeHolderColor selectButton.setTitleColor(color, for: .normal) selectButton.setTitle(placeHolderText, for: .normal) selectButton.titleLabel?.font = UIFont.systemFont(ofSize: 12) selectButton.imageEdgeInsets.left = width - 16 let frameworkBundle = Bundle(for: SwiftyMenu.self) let image = UIImage(named: "downArrow", in: frameworkBundle, compatibleWith: nil) arrow = image if arrow == nil { selectButton.titleEdgeInsets.left = 16 } if #available(iOS 11.0, *) { selectButton.contentHorizontalAlignment = .leading } else { selectButton.contentHorizontalAlignment = .left } selectButton.addTarget(self, action: #selector(handleMenuState), for: .touchUpInside) } private func setupDataTableView() { optionsTableView = UITableView() self.addSubview(optionsTableView) optionsTableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: optionsTableView!, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: optionsTableView!, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: selectButton, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: optionsTableView!, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: optionsTableView!, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0).isActive = true optionsTableView.delegate = self optionsTableView.dataSource = self optionsTableView.rowHeight = CGFloat(rowHeight) optionsTableView.separatorInset.left = 8 optionsTableView.separatorInset.right = 8 } @objc private func handleMenuState() { switch self.state { case .shown: collapseMenu() case .hidden: expandMenu() } } } // MARK: - UITableViewDataSource extension SwiftyMenu: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = options[indexPath.row] cell.textLabel?.textColor = optionColor cell.textLabel?.font = UIFont.systemFont(ofSize: 12) cell.tintColor = optionColor cell.accessoryType = indexPath.row == selectedIndex ? .checkmark : .none cell.selectionStyle = .none return cell } } // MARK: - UITableViewDelegate extension SwiftyMenu: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(rowHeight) } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndex = indexPath.row let selectedText = self.options[self.selectedIndex!] selectButton.setTitle(selectedText, for: .normal) didSelectCompletion(selectedText, indexPath.row) tableView.reloadData() collapseMenu() } } // MARK: - Private Functions extension SwiftyMenu { private func expandMenu() { self.state = .shown heightConstraint.constant = CGFloat(rowHeight * Double(options.count + 1)) updateHeightConstraint() } private func collapseMenu() { self.state = .hidden heightConstraint.constant = CGFloat(rowHeight) updateHeightConstraint() } } // MARK: - Delegates extension SwiftyMenu { public func updateConstraints(completion: @escaping () -> ()) { updateHeightConstraint = completion } public func didSelectOption(completion: @escaping (_ selectedText: String, _ index: Int) -> ()) { didSelectCompletion = completion } public func listWillAppear(completion: @escaping () -> ()) { TableWillAppearCompletion = completion } public func listDidAppear(completion: @escaping () -> ()) { TableDidAppearCompletion = completion } public func listWillDisappear(completion: @escaping () -> ()) { TableWillDisappearCompletion = completion } public func listDidDisappear(completion: @escaping () -> ()) { TableDidDisappearCompletion = completion } } <file_sep>/README.md # SwiftyMenu [![Facebook: @KarimEbrahemAbdelaziz](http://img.shields.io/badge/contact-%40KarimEbrahem-70a1fb.svg?style=flat)](https://www.facebook.com/KarimEbrahemAbdelaziz) [![License: MIT](http://img.shields.io/badge/license-MIT-70a1fb.svg?style=flat)](https://github.com/KarimEbrahemAbdelaziz/SwiftyMenu/blob/master/README.md) [![CI Status](https://img.shields.io/travis/KarimEbrahemAbdelaziz/SwiftyMenu/master.svg?style=flat)](https://travis-ci.org/KarimEbrahemAbdelaziz/SwiftyMenu.svg?branch=master) [![Version](http://img.shields.io/badge/version-0.1.0-green.svg?style=flat)](https://cocoapods.org/pods/SwiftyMenu) [![Cocoapods](http://img.shields.io/badge/Cocoapods-available-green.svg?style=flat)](https://cocoadocs.org/pods/SwiftyMenu/) <img src="https://github.com/KarimEbrahemAbdelaziz/SwiftyMenu/blob/master/Screenshots/2.gif" width="250" height="500"> <img src="https://github.com/KarimEbrahemAbdelaziz/SwiftyMenu/blob/master/Screenshots/1.png" width="250" height="500"> <img src="https://github.com/KarimEbrahemAbdelaziz/SwiftyMenu/blob/master/Screenshots/3.png" width="250" height="500"> ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements ⚙️ * Xcode 10.2 * Swift 5 * iOS 10+ ## Example 🛠 Do `pod try SwiftyMenu` in your console and run the project to try a demo. To install [CocoaPods](http://www.cocoapods.org), run `sudo gem install cocoapods` in your console. ## Installation 📱 `SwiftyMenu` supports Swift 5.0 since version `0.1.0`. ### CocoaPods Use [CocoaPods](http://www.cocoapods.org). 1. Add `pod 'SwiftyMenu'` to your *Podfile*. 2. Install the pod(s) by running `pod install`. 3. Add `import SwiftyMenu` in the .swift files where you want to use it ## Usage ## Author <NAME>, <EMAIL> ## License SwiftyMenu is available under the MIT license. See the `LICENSE` file for more info. ## Credits You can find me on Twitter [@KarimEbrahem512](https://twitter.com/KarimEbrahem512). It will be updated when necessary and fixes will be done as soon as discovered to keep it up to date. Enjoy!
a5784a5f9522a9b9db85260507e9e69f6d0a8300
[ "Swift", "Markdown" ]
3
Swift
wellmonge/SwiftyMenu
00ae12d9a461bc0977f77874a30b4aecf8d960bb
773ac21a16a8b9601039885805075de222350342
refs/heads/master
<repo_name>comodorop/practicasWeb<file_sep>/practica6.php <?php include_once'./DAOConecction/Conecction.php'; $cn = new Conecction(); $sql = "SELECT * FROM datosPersonales"; $con = $cn->coneccion(); $datos = $con->query($sql); if ($datos == false) { echo 'ocurrio un error'; } else { ?> <html> <head> <title>title</title> <link rel="stylesheet" href=""/> </head> <body> <table> <thead> <th>Id Usuario</th> <th>Nombre</th> <th>Apellido</th> <th>Edad</th> </thead> <?php while ($row = $datos->fetch_array()) { ?> <tr> <td><?php echo $row["idUsuario"] ?></td> <td><?php echo $row["nombre"] ?></td> <td><?php echo $row["apellido"] ?></td> <td><?php echo $row["edad"] ?></td> </tr> <?php } ?> </table> </body> </html> <?php } ?><file_sep>/index.php include_once './DAOConecction/Conecction.php'; $cn = new Conecction(); $sql = "SELECT * FROM login "; $datos = mysqli_query($cn->coneccion(), $sql); if ($datos) { $lstLogin = array(); while ($rs = mysqli_fetch_array($datos)) { $objLogin = new stdClass(); $objLogin->usuario = utf8_encode($rs["usuario"]); $objLogin->pass = $rs["<PASSWORD>"]; $lstLogin[] = $objLogin; } echo json_encode($lstLogin); } else { echo 'Hubo un error'; } <file_sep>/php/innerJoin.php <?php //REALIZAR UN INNER JOIN DE LA TABLA<file_sep>/php/update.php <?php //HACER UN UPDATE CORRESPONDIENTE<file_sep>/php/select.php <?php //REALIZAR UN SELECT DE UNA TABLA<file_sep>/DAOConecction/Conecction.php <?php class Conecction { function coneccion() { //RECORDEMOS QUE AQUI SE PONEN LA CONFIGURACION PARA LA CONECCION A LA BASE DE DATOS if (!$link = mysqli_connect("localhost", "root", "", "cursojosemaria")) { echo 'Coneccion no realizada'; } else { return $link; } } } <file_sep>/php/delete.php <?php //HACER UN DELETE DE UN REGISTRO
4d6f50b5d011d330f175b6e728724d356bf7aa2a
[ "PHP" ]
7
PHP
comodorop/practicasWeb
d2bcaf2796529ede42be3563e3ac4dc4e46699b9
5f15b5edb3c094d0301a6d06f3ec5a3d0554c684
refs/heads/main
<file_sep>from PIL import ImageFont, ImageDraw def make_great_cover(image, str): font_size = 30 font = ImageFont.truetype("/home/KrozeRoll/mysite/wrift.ttf", font_size) text_size = font.getsize(str) draw = ImageDraw.Draw(image) h = image.size[1] w = image.size[0] draw.text(((w - text_size[0]) / 2, h - text_size[1] - 10), str, font=font, fill="white") return image <file_sep>from PIL import Image, ImageDraw, ImageFont, ImageEnhance def is_vowel(ch): return ch in ('А', 'О', 'У', 'Э', 'Ы', 'Я', 'Ё', 'Ю', 'Е', 'И') def make_result_string(str): str = str.upper() if str.find('-ХУ') == -1 and str.find('- ХУ') == -1: pk = 0 while pk < len(str) and is_vowel(str[pk]) == 0: pk = pk + 1 if pk == len(str): pk = 0 if str[pk:][0] == "Е" or str[pk:][0] == "Э": str = str + " - ХУЕ" + str[pk + 1:] elif str[pk:][0] == "У" or str[pk:][0] == "Ю": str = str + " - ХУЮ" + str[pk + 1:] elif str[pk:][0] == "А" or str[pk:][0] == "Я": str = str + " - ХУЯ" + str[pk + 1:] elif str[pk:][0] == "И" or str[pk:][0] == "Ы": str = str + " - ХУИ" + str[pk + 1:] elif str[pk:][0] == "О" or str[pk:][0] == "Ё": str = str + " - ХУЁ" + str[pk + 1:] else: str = str + " - ХУЕ" + str[pk:] return str def make_normal_size(image): w = image.size[0] h = image.size[1] kf = 1024 / w if kf < 768 / h: kf = 768 / h image = image.resize((int(w * kf), int(h * kf))) w = image.size[0] h = image.size[1] if h > 768: area = (0, int((h - 768) / 2), w, int((h - 768) / 2) + 768) image = image.crop(area) elif w > 1024: area = (int((w - 1024) / 2), 0, int((w - 1024) / 2) + 1024, h) image = image.crop(area) return image def bright(source): enhancer = ImageEnhance.Brightness(source) factor = 0.5 result = enhancer.enhance(factor) return result def make_result_image(image, str): w = image.size[0] h = image.size[1] if w * h > 1024 * 768: image = make_normal_size(image) image = bright(image) else: image = bright(image) image = make_normal_size(image) h = 768 w = 1024 draw = ImageDraw.Draw(image) str = make_result_string(str) font_size = 72 font = ImageFont.truetype("/home/KrozeRoll/mysite/wrift.ttf", font_size) text_size = font.getsize(str) while text_size[0] > w - 10: font_size = font_size - 1 font = ImageFont.truetype("/home/KrozeRoll/mysite/wrift.ttf", font_size) text_size = font.getsize(str) draw.text(((w - text_size[0]) / 2, (h - text_size[1]) / 2 - 30), str, font=font, fill="white") return image <file_sep>from PIL import Image, ImageDraw, ImageFont from flask import Flask, request, json import requests import vk from settings import confirmation_token, token, user_token, admin_list from urllib.request import urlopen import wordMaking import coverMaking app = Flask(__name__) GROUP_ID = 146177467 @app.route('/', methods=['POST']) def processing(): data = json.loads(request.data) if 'type' not in data.keys(): return 'not vk' if data['type'] == 'confirmation': return confirmation_token elif data['type'] == 'message_new': session = vk.Session() api = vk.API(session, v=5.68) user_id = data['object']['user_id'] if api.groups.isMember(group_id=GROUP_ID, user_id=user_id, access_token=token) == 0 and user_id != 75614210: api.messages.send(access_token=token, user_id=user_id, message="Сервис доступен только подписчикам сообщества") return 'ok' elif data['object']['body'] == '&&&' and (user_id in admin_list): url = api.photos.getWallUploadServer(access_token=user_token, group_id=GROUP_ID) url = url['upload_url'] files = {'photo': open("Adm_great.jpg", 'rb')} res = requests.post(url, files=files).json(); server = res['server'] photo = res['photo'] res_hash = res['hash'] save_wall_photo_result = api.photos.saveWallPhoto(access_token=user_token, group_id=GROUP_ID, server=server, photo=photo, hash=res_hash) attach = "photo" + str(save_wall_photo_result[0]['owner_id']) + "_" + str(save_wall_photo_result[0]['id']) api.wall.post(access_token=user_token, owner_id=-GROUP_ID, from_group=1, attachment=attach) api.messages.send(access_token=token, user_id=user_id, message='Very nice!') return 'ok' elif ('attachments' in data['object'].keys() and 'photo' in data['object']['attachments'][0].keys() and data['object']['body'] != ""): word = data['object']['body'] if 'photo_2560' in data['object']['attachments'][0]['photo'].keys(): url = data['object']['attachments'][0]['photo']['photo_2560'] elif 'photo_1280' in data['object']['attachments'][0]['photo'].keys(): url = data['object']['attachments'][0]['photo']['photo_1280'] elif 'photo_807' in data['object']['attachments'][0]['photo'].keys(): url = data['object']['attachments'][0]['photo']['photo_807'] elif 'photo_604' in data['object']['attachments'][0]['photo'].keys(): url = data['object']['attachments'][0]['photo']['photo_604'] else: url = data['object']['attachments'][0]['photo']['photo_130'] url = url.replace("\/", '/') image = Image.open(urlopen(url)) image = wordMaking.makeGreateImage(image, word) url = api.photos.getMessagesUploadServer(access_token=token, peer_id=user_id) url = url['upload_url'] if user_id in admin_list: image.save("Adm_great.jpg") files = {'photo': open("Adm_great.jpg", 'rb')} else: image.save("great.jpg") files = {'photo': open("great.jpg", 'rb')} res = requests.post(url, files=files).json() server = res['server'] photo = res['photo'] res_hash = res['hash'] save_wall_photo_result = api.photos.saveMessagesPhoto(access_token=token, server=server, photo=photo, hash=res_hash) attach = "photo" + str(save_wall_photo_result[0]['owner_id']) + "_" + str(save_wall_photo_result[0]['id']) api.messages.send(access_token=token, user_id=user_id, message="Вот, держи", attachment=attach) api.messages.send(access_token=token, user_id=user_id, message='Можешь поделиться с друзьями или предложить новостью в паблик! ;-)') return 'ok' else: user_name = api.users.get(access_token=token, user_ids=user_id) name = user_name[0]['first_name'] api.messages.send(access_token=token, user_id=user_id, message='Привет - хуивет, ' + name + '!\nКак насчёт картинки?') api.messages.send(access_token=token, user_id=user_id, message='Отправь мне любое фото и слово!') return 'ok' elif data['type'] == 'group_join': session = vk.Session() api = vk.API(session, v=5.68) user_id = data['object']['user_id'] user_name = api.users.get(access_token=token, user_ids=user_id) name = user_name[0]['first_name'] + ' ' + user_name[0]['last_name'] word = name + ', <NAME>' image = Image.open('coverTemplate.jpg') image = coverMaking.makeGreatCover(image, word) image.save("cover.jpg") url = api.photos.getOwnerCoverPhotoUploadServer(access_token=token, group_id=GROUP_ID, crop_x2=1590, crop_y2=400) url = url['upload_url'] files = {'photo': open("cover.jpg", 'rb')} res = requests.post(url, files=files).json() photo = res['photo'] res_hash = res['hash'] api.photos.saveOwnerCoverPhoto(access_token=token, hash=res_hash, photo=photo) return 'ok' <file_sep># vk-public-bot Source of message-bot in vk.com public.
eb1bfe2a096c51b43525bd664aa03d8a1d7d3550
[ "Markdown", "Python" ]
4
Python
KrozeRoll/vk-public-bot
a54151a49172d6424c4e3d158b67a0de151bdb62
ff3f91e8eadcd2fa5202acf57899e59be81b337f
refs/heads/master
<repo_name>Samo1289/cmake-embed<file_sep>/EmbedResourcesConfig.cmake list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") <file_sep>/cmake/EmbedResources.cmake # Module for embedding resources in binaries find_program(HEXDUMP_COMMAND NAMES xxd) #[==[ Adds an object library target containing embedded resources and generates a header file for them. Usage: add_embedded_resources( name # Name of the created target OUT_DIR <dir> # Directory where the header and sources will be created HEADER <header> # Name of the generated header ARGS_NAMESPACE [namespace] # Namespace of created symbols (optional) RESOURCE_NAMES <names [...]> # Names (symbols) of the resources RESOURCES <resources [...]> # Resource files ) ]==] function(add_embedded_resources NAME) set(OPTIONS "") set(ONE_VALUE_ARGS OUT_DIR HEADER NAMESPACE) set(MULTI_VALUE_ARGS RESOURCE_NAMES RESOURCES) cmake_parse_arguments(ARGS "${OPTIONS}" "${ONE_VALUE_ARGS}" "${MULTI_VALUE_ARGS}" ${ARGN}) if(NOT HEXDUMP_COMMAND) message(FATAL_ERROR "Cannot embed resources - xxd not found.") endif() set(FULL_HEADER_PATH "${ARGS_OUT_DIR}/${ARGS_HEADER}") add_library("${NAME}" OBJECT) target_compile_features("${NAME}" PUBLIC cxx_std_20) # fPIC not added automatically to object libraries due to defect in CMake set_target_properties( "${NAME}" PROPERTIES POSITION_INDEPENDENT_CODE ON ) file( WRITE "${FULL_HEADER_PATH}" "#pragma once\n" "\n" "#include <cstddef>\n" "#include <span>\n" "\n" ) if(DEFINED ARGS_NAMESPACE) file( APPEND "${FULL_HEADER_PATH}" "namespace ${ARGS_NAMESPACE}\n" "{\n" "\n" ) endif() foreach(RESOURCE_NAME RESOURCE IN ZIP_LISTS ARGS_RESOURCE_NAMES ARGS_RESOURCES) set(FULL_RESOURCE_UNIT_PATH "${ARGS_OUT_DIR}/${RESOURCE_NAME}.cpp") set(FULL_RESOURCE_HEX_PATH "${ARGS_OUT_DIR}/${RESOURCE_NAME}.inc") # Add symbol to header file( APPEND "${FULL_HEADER_PATH}" "[[nodiscard]] auto ${RESOURCE_NAME}() noexcept -> std::span<std::byte const>;\n" "\n" ) # Write .cpp file( WRITE "${FULL_RESOURCE_UNIT_PATH}" "#include \"${ARGS_HEADER}\"\n" "\n" "#include <cstdint>\n" "\n" ) if(DEFINED ARGS_NAMESPACE) file( APPEND "${FULL_RESOURCE_UNIT_PATH}" "namespace ${ARGS_NAMESPACE}\n" "{\n" "\n" ) endif() file( APPEND "${FULL_RESOURCE_UNIT_PATH}" "namespace\n" "{\n" "\n" "std::uint8_t const ${RESOURCE_NAME}_data[] = {\n" "#include \"${RESOURCE_NAME}.inc\"\n" "};\n" "\n" "} // namespace\n" "\n" "auto ${RESOURCE_NAME}() noexcept -> std::span<std::byte const>\n" "{\n" " return std::as_bytes(std::span{${RESOURCE_NAME}_data});\n" "}\n" ) if(DEFINED ARGS_NAMESPACE) file( APPEND "${FULL_RESOURCE_UNIT_PATH}" "\n" "} // namespace ${ARGS_NAMESPACE}\n" ) endif() target_sources("${NAME}" PRIVATE "${FULL_RESOURCE_UNIT_PATH}") add_custom_command( OUTPUT "${FULL_RESOURCE_HEX_PATH}" COMMAND "${HEXDUMP_COMMAND}" -i < "${RESOURCE}" > "${FULL_RESOURCE_HEX_PATH}" MAIN_DEPENDENCY "${RESOURCE}" ) list(APPEND RESOURCES_HEX_FILES "${FULL_RESOURCE_HEX_PATH}") endforeach() if(DEFINED ARGS_NAMESPACE) file( APPEND "${FULL_HEADER_PATH}" "} // namespace ${ARGS_NAMESPACE}\n" ) endif() target_sources("${NAME}" PUBLIC "${FULL_HEADER_PATH}") add_custom_target("${NAME}_hexdump" DEPENDS "${RESOURCES_HEX_FILES}") add_dependencies("${NAME}" "${NAME}_hexdump") endfunction() <file_sep>/conanfile.py from conans import ConanFile class CMakeEmbed(ConanFile): name = "cmake_embed" version = "0.1.0" revision_mode = "scm" exports_sources = "cmake/*", "EmbedResourcesConfig.cmake" def package_id(self): self.info.header_only() def package(self): self.copy("*.cmake", dst="cmake", src="cmake") self.copy("EmbedResourcesConfig.cmake", dst=".", src=".")
d0d4bbbca0e5f8b3542e38ec34457d4620bbdcc2
[ "Python", "CMake" ]
3
CMake
Samo1289/cmake-embed
14440e114cdf3568f77171bbdc2a8ba5049085d3
12dbc7308149987c0010f40f33a934dc2b77e96f
refs/heads/main
<repo_name>bloodnighttw/APCS<file_sep>/README.md # APCS use [OJAT](https://github.com/bloodnighttw/OJAT) to auto test. ### 2020.10 P1 [AC] | P2 [AC] | P3 [No] | P4 [NO] here is the [link](https://github.com/bloodnighttw/APCS/tree/main/2020.10). <file_sep>/2020.10/P1.cpp /* * Author: bloodnighttw * URL: https://zerojudge.tw/ShowProblem?problemid=f312 * ID: f312 * Statue: AC | 2 ms | 328 KB * Note: APCS 2020.10.17 P1 and fuck u 師大 垃圾測資3(是錯的) 害我沒有4 幹 */ #include <bits/stdc++.h> using namespace std; class CaluBuilder{ long a,b,c; public: CaluBuilder(long a1,long b1,long c1){ a = a1; b = b1; c = c1; } long build(long x){ return (a*(x*x)+b*(x)+c); } }; int main(){ long a,b,c,n; cin >> a >> b >> c; CaluBuilder n1(a,b,c); cin >> a >> b >> c; CaluBuilder n2(a,b,c); cin >> n; long max_ = -1000000000000000; // o.301 * 64 ==19. ..... 10^15 won't overflow in long for(long i = 0 ; i <= n ; i++){ long sum = n1.build(i) + n2.build(n-i); if(max_ < sum){ max_ = sum; } } cout << max_ << endl; return 0 ; } <file_sep>/2020.10/P2.cpp /* * Author: bloodnighttw * URL: https://zerojudge.tw/ShowProblem?problemid=f313 * ID: f313 * Statue: AC | 4 ms | 64 KB * Note: APCS 2020.10.17 P2 */ #include <bits/stdc++.h> using namespace std; #define BOUND -1 int v[53][53]; int give[53][53]; int count_[53][53]; int main(){ int min_ = 100000000,max_ = 0; int r,c,k,m; cin >> r >> c >> k >> m; //cout << "// 0" << endl; // set up bound for(int i = 0 ; i <= c+1 ; i++ ){ v[0][i] = BOUND; // v is vector<vector<int>> v[r+1][i] = BOUND; give[0][i] = 0; // give is vector<vector<int>> give[r+1][i] = 0; } //cout << "// 1" << endl; for(int i = 0 ; i <= r+1 ; i++ ){ v[i][0] = BOUND; v[i][c+1] = BOUND; give[i][0] = 0; give[i][c+1] = 0; } // count to 0 for(int i = 0 ; i <= r ; i++ ){ for(int j = 0 ; j <= c ; j++ ){ count_[i][j] = 0; } } // set up bound done // input for(int i = 1 ; i <= r ; i++ ){ for(int j = 1 ; j <= c ; j++ ){ int temp; cin >> temp; if(temp == -1) give[i][j] = 0; else give[i][j] = temp / k; v[i][j] = temp; } } for(int i = 0 ; i < m ; i++ ){ for(int j = 1 ; j <= r ; j++ ){ for(int l = 1 ; l <= c ; l++ ){ if(v[j][l] == BOUND) continue; if(v[j-1][l] != BOUND){ v[j][l] += give[j-1][l]; count_[j-1][l]++; } if(v[j+1][l] != BOUND){ v[j][l] += give[j+1][l]; count_[j+1][l]++; } if(v[j][l-1] != BOUND){ v[j][l] += give[j][l-1]; count_[j][l-1]++; } if(v[j][l+1] != BOUND){ v[j][l] += give[j][l+1]; count_[j][l+1]++; } } } min_ = 100000000,max_ = 0; for(int j = 1 ; j <= r ; j++ ){ for(int l = 1 ; l <= c ; l++ ){ int temp = v[j][l] - count_[j][l]*give[j][l]; v[j][l] = temp; count_[j][l] = 0; give[j][l] = temp/k; if(temp != -1 && temp < min_){ min_ = temp; } if(max_ < temp){ max_ = temp; } } } /* cout << "[o]count print" << endl; show(r,c,count_); cout << "[o]give" << endl; show(r,c,give); */ //show(r,c,v); } cout << min_ << endl << max_ << endl; return 0 ; }
c72b698f8c3db5232026702a3a700a7af9f9de51
[ "Markdown", "C++" ]
3
Markdown
bloodnighttw/APCS
2dd3e418d4e6020444998cf82fb95615e0e30ca8
0b944cd9b8567ad20e1f01415b97dc92bb0c2ca8
refs/heads/main
<repo_name>Dianakove32/api<file_sep>/src/components/ItemList.js import React, { Component } from 'react' import GetInfo from './GetInfo' import '../App.css' import Spiner from './Spiner.js' import Search from './Search'; export default class ItemList extends Component { constructor() { super() this.handleSort = this.handleSort.bind(this) } getInfo = new GetInfo() state = { peopleList: null, characterforSearch: '' } componentDidMount() { this.getInfo.getAllCharacters() .then((peopleList) => { this.setState({ peopleList }) }) } handleSort(characterName) { this.setState({ ...this.state, characterforSearch: characterName }) } renderItems( ) { return this.state.peopleList.filter(person=>person.name.includes(this.state.characterforSearch)).map((person) => { console.log(this.state.characterforSearch) return ( <li className="item_li" key={person.char_id} onClick={() => this.props.hendleInfo(person.char_id)}> {person.name} </li> ) }) } render() { const { peopleList } = this.state if (!peopleList) { return <Spiner /> } const items = this.renderItems() return ( <div> <ul className="item_ul"> <Search handleSort={this.handleSort} /> {items}</ul> </div> ) } } <file_sep>/src/components/Search.js import React, { Component } from 'react' import '../App.css' export default class Search extends Component { render() { return ( <div> <input type='text' placeholder='Search character...' onChange={(e)=>this.props.handleSort(e.target.value)}/> </div> ) } } <file_sep>/src/components/PersonInfo.js import React, { Component } from 'react' import GetInfo from './GetInfo' import '../App.css' import Spiner from './Spiner' export default class PersonInfo extends Component { getInfo = new GetInfo() constructor(props) { super(props) this.state = { person: null } } componentDidMount() { this.updatePerson() } componentDidUpdate(prevProps) { if (this.props.info !== prevProps.info) { this.updatePerson(); } } updatePerson() { const { info } = this.props if (!info) { return } this.getInfo.getPerson(info) .then((person) => { this.setState({ person }) }) } render() { const { person } = this.state if (!person) { return <Spiner /> } return ( <div> {person.map(el => { return <div className="PersonInfo" key={el.char_id}> <img src={el.img} alt="pict" /> <p><b>Name: </b>{el.name}</p> <p><b>Nickname: </b>{el.nickname}</p> <p><b>Portrayed: </b>{el.portrayed}</p> <p><b>Status: </b>{el.status}</p> </div> })} </div> ) } } <file_sep>/src/App.js import './App.css'; import GetInfo from './components/GetInfo'; import ItemList from './components/ItemList'; import PersonInfo from './components/PersonInfo'; import React, { Component } from 'react' export default class App extends Component { constructor() { super() this.state = { info: 1, } this.hendleInfo = this.hendleInfo.bind(this) } hendleInfo(id) { this.setState({ info: id }) } render() { return ( <div> <h1>The Breaking Bad Characters</h1> <h3>Information received using API</h3> <div className="App"> <ItemList hendleInfo={this.hendleInfo} /> <PersonInfo info={this.state.info} /> </div> <h3><NAME> <span>WildCodeSchool</span> </h3> </div> ); } } // fetch(urlCharacters) // .then((res)=>{ // return res.json() // }) // .then((body)=>{ // console.log('what we have2', body) // })
0a3520a87e58999759dc940265901ba59d96cc0d
[ "JavaScript" ]
4
JavaScript
Dianakove32/api
122b6ab23179763e7b2f771a2174319a6d20f5b9
9fea4ba0db4894e7ff4593027322228356c945ef
refs/heads/main
<file_sep>import asyncio from commons.logger import get_logger log = get_logger('mail.py') def delegate(msg:str): log.debug(msg) message = parse(msg) log.debug(message) return message def parse(message:str): log.debug(message) return message <file_sep>""" websockets """ import websocket from commons.logger import get_logger from jobs.mail import delegate log = get_logger('main.py') def on_message(app, message): log.info(app) delegate(message) wsapp = websocket.WebSocketApp("ws://localhost:8080/ws/broker/main/topic/CONSUMER", on_message=on_message) wsapp.run_forever() <file_sep>import logging import logging.config import yaml with open('log4py.yaml', 'r') as f: CONFIG = yaml.safe_load(f.read()) logging.config.dictConfig(CONFIG) def get_logger(logger_name): logger_instance = logging.getLogger(logger_name) return logger_instance """ import asyncio import websockets from jobs.mail import delegate from commons.logger import get_logger logger = get_logger('main.py') async def handler(path): async with websockets.connect(path) as websocket: async for message in websocket: await delegate(message) URI = "ws://localhost:8080/ws/chat/TOPIC/CONSUMER" asyncio.get_event_loop().run_until_complete(handler(URI)) logger.info(' End of the main file') """
1636cc19a2197a0fcaf091aa3ff7c204ff749de6
[ "Python" ]
3
Python
mujahed08/consumer
96d41719d0f95e9bac6c8f4573468e890ba3f2cc
3d0685e323adaae56b5cbc28b605cb88118c81ea
refs/heads/master
<file_sep>#Templates Here you will find a number of templates for various purposes. Inside `/snippets` are a number of snippets for use in your text editor to make filling out these templates simple. Each template has an accompanying `template.example.md/js/txt` file, to show how it should be used. If you want to preserve indenting, use `.js` or `.txt` as a file extension. ## Submissions Alongside the template, provide an example of how it is used in a `.example.md` file. If possible, include a snippet for 1+ text editors too. Porting snippets to other text editor formats is always welcome. <file_sep># MVP start example email --- Hi Joe, We'd like to confirm that the 4 essential features to the MVP that we discussed in our prior meeting are as follows: MVP Specification: Feature 1: Central data storage Essential parts: - Users & Posts collections - Authenticated access: * Users must log in before they can submit content. * Admin & User roles. Admins can edit anything, Users only their own content. Feature 2: Responsive, mobile-first blog UI Essential parts: - Looks good on mobile & desktop Feature 3: User-submitted content Essential parts: - Inline editing and creation of blog posts - Blog posts 'belong' to a particular user * Their name is displayed underneath the blog post as the author For the period: 12 Aug 2015 - 24 Aug 2015 Team: <NAME> - <EMAIL> <NAME> - <EMAIL> If you feel that any part of this specification is not detailed enough, we have missed something, or got anything wrong, please let us know and we will get back to you with a revised edition. Regards, John & Tina <file_sep># Web Development Foundation course ### Outline syllabus ####Week 1: Introduction to software development for the Web Introduction to HTTP and the Web, HTML and CSS, UX, wireframing, the JavaScript programming language, testing, TDD, paired programming, problem solving, using online resources effectively, agile development, Git and GitHub, website hosting, lean product development and MVPs. **Role groups:** vanilla CSS (mobile-first CSS, CSS positioning, @media queries), UX (wireframes), testing, GHPages (deployment) **Expected learning outcomes:** _TBC_ ####Week 2: Web APIs APIs, AJAX, JSON, all with vanilla Javascript (with jQuery stretch goals). **Role groups:** Testing, front end devs (HTTP requests and AJAX), architect group (code and file structure), repo owners (git best practices and git flow). [Expected learning outcomes, week 2](https://hackpad.com/Week-Two-Expected-Learning-XFTPVTmz91p) ####Week 3: Intro to Node.js npm init, install, start, test. The fs and http modules. ####Week 4: Node.js modules, frameworks, databases and deployment Modules, build tasks, databases, deployment, frameworks ####Week 5: The hapi framework Introduction to the Node.js Web framework ####Week 6: Front-end JavaScript ####Week 7: The GitHub API ####Week 8: The missing workshops As usual, all content is subject to change. <file_sep># MVP finished example email --- Hi Joe, Below we have outlined the feature specification for the MVP, along with the outcomes of our work. We hope this is to your satisfaction. If you wish for ownership to be transferred from the team to you, please let us know and we will get back in contact with the necessary steps. MVP Specification: Agreed essential features: Feature 1: Central data storage Solution provided: - MongoDB Database - Users & Posts collections - Create, Read, Update and Delete capabilities - User-specific database access Feature 2: Responsive, mobile-first blog UI Solution provided: - Single-page app - Mobile-first design - Cross-browser & device tested Feature 3: User-submitted content Solution provided: - In-browser markdown editor - .md uploads - Content associated with a particular user Other features: - Video & Picture uploads to S3 bucket - Ranking algorithm for popular posts - Tags for user-categorisation of content - Rating system - Comments section - Social media links for sharing Application deployed to Heroku at: https://heroku-cms.herokuapp.com/ Code & tests located at: https://github.com/someorg/somerepo Pivotal Tracker board at: https://www.pivotaltracker.com/n/projects/123412412412 Dates contracted: 12 Aug 2015 - 24 Aug 2015 Team: <NAME> - <EMAIL> <NAME> - <EMAIL> Regards, John & Tina <file_sep>#House Rules (Work in Progress) + **Whilst you're a student, arrive on time & let people know in advance if you're going to be away**. Lots of people are giving freely of their time and knowledge to make FAC possible and giving up other commitments to be here. + **Tidy up after yourself** (at least!). With so many of us in the space, it's easy for the kitchen area to get dirty really quickly - wash up your crockery rather than forgetting about it in the sink and wipe down the counter area you've been using it and we'll all be a lot happier :blush: + **Clean desk policy**. We have a clean-desk policy. Please leave your desk clear before you leave each day. + **Hot desking**. Please sit anywhere downstairs when you arrive each morning. + **20-minute rule**. Struggle is good, but not too much of it. As a general rule, if you cannot solve a problem within 20 minutes, then stop and talk to somebody about it (there should be a timer on your desk) <file_sep>#Founders &amp; Coders Playbook [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/foundersandcoders/playbook/issues) This playbook repo is intended to be a reference on how we do things at [Founders &amp; Coders](http://www.foundersandcoders.org). **All pull requests welcome** (remember to update the [contents section](#contents) of this readme as part of your PR). If you submit a PR, please **assign one of the following people to review & merge it** as they have all volunteered to peer-review PRs: [@rorysedgwick](https://github.com/rorysedgwick), [@FilWisher](https://github.com/FilWisher), [@besarthoxhaj](https://github.com/besarthoxhaj) [@sofer](https://github.com/sofer), [@iteles](https://github.com/iteles) or [@nelsonic](https://github.com/nelsonic). If there is **something you think should be here, but you don't have time to write it**, please _open an issue_. Someone will get to it eventually! ##Contents + [Before you arrive](/before-arrival.md) + [House Rules](/house-rules.md) ###The programme + [Weeks 1-8: Part 1 - Foundation](/foundation.md) + [Weeks 9-16: Part 2 - Projects](/part2.md) ###The classroom + [Student teams](/teams.md) + [Schedule](/schedule.md) + [Projects](/projects.md) + [Code reviews](/code-reviews.md) + [Pair programming](/pair-programming.md)
84dfeefa314bf99c687f9a87868808797295c03e
[ "Markdown", "JavaScript" ]
6
Markdown
4kd/playbook
916296bba49d54dbc7e939125656a9eb52182167
ed29764fec5aa38f82c74786ec42b340427a83e7
refs/heads/master
<repo_name>IDEO-coLAB/nomad-dht-shim<file_sep>/src/index.js const Hapi = require('hapi') const { applyError, missingDataError, missingNodeIdError } = require('./error') const store = require('./store') const PORT = 8000 const server = new Hapi.Server() server.connection({ // host: 'localhost', port: PORT }) server.route({ method: 'POST', path:'/connect', handler: function (request, reply) { const data = request.payload if (!data) { return applyError(reply, missingDataError) } const nodeId = data.id if (!nodeId) { return applyError(reply, missingNodeIdError) } // TODO: check for multiaddrs return store.set(nodeId, data) .then(() => reply(true)) .catch(err => applyError(reply, err)) } }) server.route({ method: 'DELETE', path:'/connect', handler: function (request, reply) { const data = request.payload if (!data) { return applyError(reply, missingDataError) } const nodeId = data.id if (!nodeId) { return applyError(reply, missingNodeIdError) } return store.remove(nodeId) .then(() => reply(true)) .catch(err => applyError(reply, err)) } }) server.route({ method: 'GET', path:'/connect', handler: function (request, reply) { const nodeId = request.query.id if (!nodeId) { return applyError(reply, missingNodeIdError) } return store.get(nodeId) .then((peerInfo) => { const result = peerInfo || null return reply(JSON.stringify(result)) }) .catch(err => applyError(reply, err)) } }) // Start the shim server server.start((err) => { if (err) { throw err } console.log('Shim server listening on port:', server.info.uri) // console.log(server.info) }) <file_sep>/README.md # Nomad signal server Docker container for running a WebRTCStar signaling server. See https://github.com/libp2p/js-libp2p-webrtc-star for more details. <file_sep>/src/error.js exports = module.exports exports.missingNodeIdError = new Error('Missing node id') exports.missingDataError = new Error('Missing data') exports.applyError = (reply, error) => { const code = 400 return reply({ message: error.message, code: code }).code(code) } <file_sep>/Dockerfile #Choose a base image FROM node:6.9.4 # Create a new folder for our application RUN mkdir -p /app # Set the working dir when our container executes WORKDIR /app # Copy our package.json file ADD package.json /app # Install our packages RUN npm install # Copy the rest of our application COPY . /app #Expose our application port EXPOSE 8000 # Set start command CMD ["npm", "start"] <file_sep>/src/store.js const Datastore = require('nedb') exports = module.exports const DB_PATH = 'store/peer-id-store' class Store { constructor (path = DB_PATH) { this.db = new Datastore({ filename: path, autoload: true }) } get (node) { return new Promise((resolve, reject) => { this.db.findOne({ node }, (err, object) => { if (err) { reject(err) return } if (object === null) { resolve(null) return } resolve(object.object) return }) }) } set (node, object) { const errorUpdateNotFound = new Error(`Failed to update ${node}: Not found`) return new Promise((resolve, reject) => { this.db.findOne({ node }, (err, found) => { if (err) { reject(err) return } // If no object is found, create one if (!found) { this.db.insert({ node, object }, (err, newObj) => { if (err) { reject(err) return } resolve(newObj.object) }) return } // Otherwise update the existing one this.db.update({ node }, { $set: { object: object } }, (err, numUpdated) => { if (err) { reject(err) return } if (numUpdated === 0) { reject(errorUpdateNotFound) return } // Return the most recent one this.db.findOne({ node }, (err, updatedObj) => { if (err) { reject(err) return } resolve(updatedObj.object) }) } ) }) }) } remove (node) { return new Promise((resolve, reject) => { this.db.remove({ node }, (err, numRemoved) => { if (err) { reject(err) return } resolve(numRemoved) return }) }) } } module.exports = new Store()
fc631d1e7240fa20746f2e8f922a079251f4f0c0
[ "JavaScript", "Dockerfile", "Markdown" ]
5
JavaScript
IDEO-coLAB/nomad-dht-shim
8227f3f19b355c8b3cc183239533ef9d7f1a75d6
d21962c874648badf441704330336b50752d30e3
refs/heads/master
<file_sep> // Reverse a linked List /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseWrapper(ListNode *head,ListNode *&HEAD) { // Naive : copy list in another array // : and change original list traversing reverse in array // : time : theta(N) + space : theta(N) // Optimal : IBH method // : Hypothesis => reverseList(head) will return me the last pointer // of the reversed list and has head already set up // : induction => connect current node wiht this last node and make last as current // : base case => when we reach the last node or the nodes is empty // Iterative Optimal : Take first on node 1 // : Take second on node 2 // : preserve the next of node 2 // : reverse the link between node 1 and node 2 // : go on preserve and repeat the same process // : at the end we return the head // Base Case // if(head == NULL||head->next==NULL) { // HEAD = head; // return head; // } // // Hypothesis // ListNode *last = reverseWrapper(head->next,HEAD); // // Induction // last->next = head; // head->next = NULL; // last=head; // return head; } ListNode* reverseList(ListNode* head) { // ListNode *HEAD; // reverseWrapper(head,HEAD); // return HEAD; // Better Recursive Solution taken from most votes // if(head==NULL||head->next==NULL) // return head; // ListNode *node = reverseList(head->next); // head->next->next=head; // head->next=NULL; // return node; //Iterative Solution { most optimal solution } if(head==NULL||head->next==NULL) return head; ListNode *prev = NULL; ListNode *curr = NULL; ListNode *Next = head; while(Next!=NULL) { curr=Next; Next=Next->next; curr->next=prev; prev=curr; } return curr; } };<file_sep> /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { // we can also do it in iterative way which is optimal in space as compared to recursion // For recursion // - solving this using IBH method public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2,int carry = 0) { // Base Case if(l1==NULL&&l2==NULL) { if(carry==0) return NULL; else { ListNode *overFlow = new ListNode(); overFlow->next = NULL; overFlow->val = carry; return overFlow; } } // Induction Step ListNode *currNode = new ListNode(); int l1Value = (l1!=NULL) ? l1->val : 0; int l2Value = (l2!=NULL) ? l2->val : 0; int sum = l1Value + l2Value + carry; currNode->val = sum%10; carry = sum/10; ListNode *l1Next; ListNode *l2Next; if(l1==NULL) l1Next = NULL; else l1Next = l1->next; if(l2==NULL) l2Next = NULL; else l2Next = l2->next; // Hypothesis currNode->next = addTwoNumbers(l1Next,l2Next,carry); // Induction step return currNode; } };<file_sep> // Maximum Depth of binary tree /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int maxDepth(TreeNode* root) { // Base Case -> if root is NULL the depth is 0 if(root==NULL) return 0; // Recursive subProblem int lh = maxDepth(root->left); // get the depth of the left sub tree int rh = maxDepth(root->right); // get the depth of the right sub tree return max(lh,rh)+1; // return the maximum of left depth and right depth + 1 } };<file_sep> // Fibonacci numbers using dp and recursion class Solution { public: int CountFibN(int dp[],int n) { if(n==0||n==1) return n; if(dp[n-1]==-1) dp[n-1] = CountFibN(dp,n-1); if(dp[n-2]==-1) dp[n-2] = CountFibN(dp,n-2); return dp[n-1] + dp[n-2]; } int fib(int n) { int dp[31]; fill(dp,dp+31,-1); return CountFibN(dp,n); } };<file_sep> // Nth tribonacci number // Naive : Using normal formula like fibonacci number // optimal : use dp to optimize it // optimal solution int dp[38]; class Solution { public: int T(int n) { if(n==0||n==1) return n; if(n==2) return 1; if(dp[n-3]==-1) dp[n-3] = T(n-3); if(dp[n-2]==-1) dp[n-2] = T(n-2); if(dp[n-1]==-1) dp[n-1] = T(n-1); return dp[n-3]+dp[n-2]+dp[n-1]; } int tribonacci(int n) { int sum = 0; fill(dp,dp+38,-1); return T(n); } };<file_sep> //Binary Tree Tilt // Naive : O(N^2) - top down approach for each node calculate left sub tree node sum and same for right and maintian sum // Optimal : O(N) - bottom up approach, maintian sum and node sum simultaneously /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int GetSumOfTilts(TreeNode *root,int &sum) { // Base Case if(root==NULL) return 0; // Intermediate Decision State int leftSubTreeNodeSum = GetSumOfTilts(root->left,sum); int rightSubTreeNodeSum = GetSumOfTilts(root->right,sum); sum = sum + abs(leftSubTreeNodeSum-rightSubTreeNodeSum); return (leftSubTreeNodeSum+rightSubTreeNodeSum+root->val); } int findTilt(TreeNode* root) { int sum = 0; GetSumOfTilts(root,sum); return sum; } };<file_sep>bool dp[202][int(1e4+2)]; class Solution { public: bool SubSetSum(vector<int>& nums,int sum,int n) { // writing recursive code and then memoize it and then go for tabulation -> method 1 // this is similar to knapsack problem where given array is weight array // and value arrays are ignored, and this problem can be solved using tabular // derivation of the knapsack problem -> method 2 // Method -> 1 // // Base Case // if(sum==0) // return true; // if(n==0) // return false; // if(dp[n][sum]!=-1) // return dp[n][sum]; // // Choice Diagram // if(nums[n-1]<=sum) // return dp[n][sum] = (SubSetSum(nums,sum-nums[n-1],n-1)||SubSetSum(nums,sum,n-1)); // else // return dp[n][sum] = SubSetSum(nums,sum,n-1); // Method -> 2 { Observed that it's knapsack variation} // initializtion of method 2 for(int j=0;j<sum+1;j++) dp[0][j]=false; for(int i=0;i<nums.size()+1;i++) dp[i][0]=true; for(int i=1;i<n+1;i++){ for(int j=1;j<sum+1;j++){ if(nums[i-1]<=j){ dp[i][j] = dp[i-1][j-nums[i-1]]||dp[i-1][j]; } else dp[i][j] = dp[i-1][j]; } } return dp[n][sum]; } bool canPartition(vector<int>& nums) { // this is the question on equal sum partitation // means there are two subsets/paritation which has equal sum in the array // also there sum add to total array sum // thus since those two subset have equal sum the array sum should be even // for the partitaion to exist // if the sum is even we simply need to check if there exist a subset // with sum equal to sum/2 in the array or not // for method 1, memoization // memset(dp,-1,sizeof(dp)); int sum = 0; for(int i=0;i<nums.size();i++) sum+=nums[i]; if(sum%2 != 0) return false; else return SubSetSum(nums,sum/2,nums.size()); } };<file_sep> // swap nodes in pair /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { // We can solve this using iterative method -> theta(N) // We can solve this using recursion as well -> theta(N) + theta(N) // changing links will be better than swapping ! // 1] Assuming a hypothesis that swapPairs(ListNode*) will return me the head pointer pointing to n-2 nodes list // 2] In the inductio step, we can change the links of the current two nodes and return the head // 3] Base case will, if we have head as NULL [size if even] we returning NULL if head not NULL [size is odd] return head // try out a tail recursive solution // Base Case if(head == NULL) // when size is even return NULL; if(head->next==NULL) // when size is odd return head; // hypothesis ListNode *nextHead = swapPairs(head->next->next); ListNode *newHead = head->next; head->next->next = head; head->next = nextHead; return newHead; } };<file_sep> // Reorder List /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reorderListHelper(bool &isEven,ListNode *head,ListNode *&nextHalf,int &countNode) { if(countNode==0) { if(isEven) { nextHalf = head->next->next; head->next->next = NULL; return head; } else { nextHalf = head->next->next->next; head->next->next->next = head->next; ListNode *temp = head->next; head->next = head->next->next; temp->next = NULL; return head; } } ListNode *newHead = reorderListHelper(isEven,head->next,nextHalf,--countNode); head->next=nextHalf; ListNode *temp = nextHalf->next; nextHalf->next = newHead; nextHalf=temp; return head; } void reorderList(ListNode* head) { // Naive : take extra array and copy all elements into it // : then we can take required elements one by one // optimal 1 : If it's ok to change the original linked list it self // : count the nodes in the linked list -> theta(N) // : move ahead by ceil(n/2) + 1 in the list -> theta(N/2) // : make the next of the current after moving as null // : reverse the next part of the linked list -> Theta(N/2) // : and keep connecting one by one -> Theta(N/2) // : time is theta(N) space is O(1) // optimal 2 : Can we use recursion ? // : then we can solve it recursively // : say a function fun() returns us the head of the ordered internal list // : then the just have to change the links of the current two nodes // : time complexity will be Theta(N) {N/2 less iterations as previous}, space is theta(N/2) if(head == NULL) return; if(head->next == NULL) return; ListNode *curr = head; ListNode *nextHalf = NULL; // counting the nodes in the list int countNode = 0; while(curr!=NULL) { countNode++; curr=curr->next; } bool isEven = ((countNode%2)==0); // reordering the list countNode/=2; countNode--; reorderListHelper(isEven,head,nextHalf,countNode); return; } };<file_sep> // Power of 2 class Solution { public: bool isPowerOfTwo(int n) { // Naive : take mod // : keep dividing the number by 2 if we get odd number except 1 then it's not power of 2 // : time : O(logN) // : we can solve this using both recursive and iterative versions // Optimal : if number is power of 2 then it has only 1 bit set in it's binary // : so total set bits in number should be 1 // : we can iterate on bits in O(logN) // : to optimize this we can use brian kerningam algorithm // Most optimal : n&(n-1) should be 0 brian kerningam algorithm // recursive solution // Base Case // if(n==1) // return true; // if(n<=0||n%2==1) // return false; // return isPowerOfTwo(n/2); // Most optimal return (!(n<=0)&&((n&(n-1))==0)); } };<file_sep> // Convert BST to inorder tree { increasing order search tree } void increasingBSTwrapper(TreeNode *root,TreeNode *&prev,TreeNode *&newRoot) { // Naive : Generate Inorder traversal list and then create a tree form that // : time : theta(N), space : theta(N) {but more than optimal} // Optimal : Traverse in Inorder way, and generate change the same tree, using previous pointer and root pointer // Base case if(root==NULL) return; if(prev==NULL && root->left==NULL) { prev = root; newRoot = prev; } // Inorder traversal increasingBSTwrapper(root->left,prev,newRoot); if(prev!=root) { prev->left=NULL; prev->right=root; root->left=NULL; prev=root; } increasingBSTwrapper(root->right,prev,newRoot); } TreeNode* increasingBST(TreeNode* root) { TreeNode *newRoot; TreeNode *prev = NULL; increasingBSTwrapper(root,prev,newRoot); return newRoot; } // Actual Solution : Best Solution // TreeNode* increasingBST(TreeNode* root, TreeNode* tail = NULL) { // if (!root) return tail; // TreeNode* res = increasingBST(root->left, root); // root->left = NULL; // root->right = increasingBST(root->right, tail); // return res; // }<file_sep> // Finding power x^n where n and x can be negative class Solution { public: double pow(double x,long long int n) { // pow(x,n) = pow(x,n/2)*pow(x,n/2) if n is even // pow(x,n/2)*pow(x,n/2)*x if n is odd if(n==0) return 1.0; if(n==1) return x; double temp = pow(x,n/2); temp*=temp; if( (n%2) == 1 ) return temp*x; else return temp; } double myPow(double x, int n) { long long int n1 = n; if(n<0){ return (1.0/pow(x,abs(n1))); } else return pow(x,n1); } };<file_sep> //Merge Two Sorted Lists /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* MergeHelper(ListNode *l1,ListNode *l2,ListNode *Head,ListNode *prev = NULL) { // Tail Recursive Solution //base case if(l1==NULL) { prev->next = l2; return Head; } else if(l2==NULL) { prev->next = l1; return Head; } //Dealing intermediate decision state if(l1->val <= l2->val) { if(prev==NULL) { Head = l1; prev = Head; } else { prev->next = l1; prev = prev->next; } return MergeHelper(l1->next,l2,Head,prev); } else { if(prev==NULL) { Head = l2; prev = Head; } else { prev->next = l2; prev = prev->next; } return MergeHelper(l1,l2->next,Head,prev); } } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // Non Tail Recursive Solution //Base Case if(l1==NULL) return l2; else if(l2==NULL) return l1; // Intermediate decision state if(l1->val <= l2->val) { l1->next = mergeTwoLists(l1->next,l2); return l1; } else { l2->next = mergeTwoLists(l1,l2->next); return l2; } } };<file_sep> // Range Sum in a BST, VVIMP // Naive : Since it's a BST we can take the inorder into an array which will be sorted, and find the sum // : time : Theta(N), space : O(N) // optimal : take the inorder traversal and which ever number lies in [low, high] we take it into the sum // : time : theta(N), space: O(height) // more optimal : since it's a BST so we can skip some traversals // : if root->val lies in range then we call on both sides // : else if root->val is more than high then call only on left side // : else if root->val is less than low then we call onlhy on right side // : time complexity : O(N), space : O(height) //1] optimal // Base Case // if(root==NULL) // return 0; // // inorder traversal // int leftPossibleNodeVal = rangeSumBST(root->left,low,high); // if( ( root->val >= low ) && ( root->val <= high ) ) { // leftPossibleNodeVal += root->val; // } // int rightPossibleNodeVal = rangeSumBST(root->right,low,high); // return (leftPossibleNodeVal+rightPossibleNodeVal); // 2] most optimal if(root==NULL) return 0; if(root->val >= low && root->val <=high ){ return (rangeSumBST(root->left,low,high) + root->val + rangeSumBST(root->right,low,high)); } else if(root->val<low){ return rangeSumBST(root->right,low,high); } else { return rangeSumBST(root->left,low,high); }<file_sep> // Balanced Binary Tree // Naive : O(N^2) call height for each node and compare // Optimal : O(N) // Optimal Solution /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int height(TreeNode *root) { //base case if(root==NULL) return 0; //intermediate decision state int lh = height(root->left); int rh = height(root->right); int diff = abs(lh-rh); if(lh==-1||rh==-1||diff>1) return -1; else return max(lh,rh) + 1; } bool isBalanced(TreeNode* root) { int h = height(root); if(h==-1) return false; else return true; } };<file_sep> // Minimum distance between two nodes of a BST // Naive : for every node in the tree, we traverse the tree and find the difference and maintain the minimum // : time : theta(N^2), space theta(N) // Optimal : Traverse in inorder way {will be sorted list} and take adjacent differences of sorted list // : time : theta(N), space theta(N) // Inorder : first traverse the left sub tree then come to root then traverse the right sub tree void minDiffInBSTwrapper(TreeNode *root,int &minDiff,TreeNode *&prev) { //base case if(root==NULL) return; // important part of base case to ensure that prev is correctly assigned if(prev==NULL && root->left==NULL) prev = root; // traversing the left sub tree making sure that prev is on correct node minDiffInBSTwrapper(root->left,minDiff,prev); // coming to root and then taking the minDiff, considering extra case if(root!=prev) minDiff = min(abs(root->val - prev->val),minDiff); prev = root; // traversing the right sub tree making sure that root was at correct node minDiffInBSTwrapper(root->right,minDiff,prev); } int minDiffInBST(TreeNode* root) { int minDiff = INT_MAX; TreeNode *prev = NULL; minDiffInBSTwrapper(root,minDiff,prev); return minDiff; }<file_sep> // Delete Nodes with a given value in linked list /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val,ListNode *prev=NULL,ListNode *HEAD = NULL) { // Iterative : maintain a previous pointer and delete current and change links theta(N) + O(1) // Recursive : IBH method // Base case if(head==NULL) return HEAD; // Hypothesis // ListNode *getHead = removeElements(head->next,val); // // Induction Step // if(head->val==val) { // head->next=NULL; // delete head; // head = getHead; // } // else // head->next = getHead; _______________________________________________________________________________________ Trying tail recursive method // ListNode *nextNode=head->next; // if(head->val == val){ // if(prev==NULL) // { // nextNode = head->next; // HEAD = nextNode; // delete head; // } // else { // prev->next=head->next; // head->next=NULL; // delete head; // nextNode = prev->next; // } // } // else { // if(prev==NULL) // HEAD = head; // prev=head; // } // return removeElements(nextNode,val,prev,HEAD); } };<file_sep># LeetCode This Repo has the questions of LeetCode that I have solved currently working on recursion <file_sep> // Check Iterative version also // this can be solved using recursion tree method, as there are multiple choices and decisions class Solution { public: void getCombinations(string source,int index,string &digits,vector<string> &digitsString,vector<string> &result,string curr = "") { // O(4^n) max(n) = 4; { ie : assume the loop as 4 function calls } if(index==digits.length()) { result.push_back(curr); return; } for(int i=0;i<source.length();i++) { string nextSource = index+1<digits.length() ? digitsString[digits[index+1]-50] : "" ; getCombinations(nextSource,index+1,digits,digitsString,result,curr + source[i]); } } vector<string> letterCombinations(string digits) { if(digits.length()==0) return {}; vector<string> digitsString(8); digitsString[0]="abc"; digitsString[1]="def"; digitsString[2]="ghi"; digitsString[3]="jkl"; digitsString[4]="mno"; digitsString[5]="pqrs"; digitsString[6]="tuv"; digitsString[7]="wxyz"; vector<string> result; string source = digitsString[digits[0]-50]; getCombinations(source,0,digits,digitsString,result); return result; } };<file_sep> class Solution { public: // Naive : Useing BIT magic to generate subsets O(n*2^n) // Optimal: Using recursion and maintaining xor and sum // most optimal : checkfrom discussion int subsetXORSum(vector<int>& nums) { int n = nums.size(); int sum = 0; for(int curPattern=0;curPattern<pow(2,n);curPattern++){ int curXOR = 0; for(int j=0;j<n;j++) { if((1<<j)&curPattern){ curXOR = curXOR^nums[j]; } } sum+=curXOR; } return sum; } };
a83dab7d97e109b27f709a892ce14a3eccfe7307
[ "Markdown", "C++" ]
20
C++
Atharva-Vijay-Khade/LeetCode
b893f661dc5c1c09eb4939c8e584c577aeef49f5
2202c3b485f33c33f6438e75f37c4a0cee3718f6
refs/heads/master
<repo_name>axelav/get-time<file_sep>/README.md # get-time Return the current time as an integer. ## usage ```js const getTime = require('get-time') const now = getTime() // 1483772563534 ``` ## install ```sh $ npm install get-time ``` ## test ```sh $ npm test ``` ## license MIT <file_sep>/index.js module.exports = () => new Date().getTime()
42bcba8f6fa63983939355ce8f2d5c4361b4b0ad
[ "Markdown", "JavaScript" ]
2
Markdown
axelav/get-time
905a079a6bd4e257984147b15ea61c9a829fd314
17ee715b5ea830886924b8672fa10807e13553f7
refs/heads/master
<repo_name>1075980722/DormitoryDemo<file_sep>/Assets/Scripts/Player/PlayerMove.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { // 移动速度 public float walkSpeed = 1f; // 奔跑速度 public float runSpeed = 1.5f; // 是否使用重力 public bool useGravity; public float gravity = 9.8f; // 相机的transform private Transform cameraTransform; private float moveSpeed; private CharacterController controller; private float gravitySpeed = 0; public bool canMove = true; void Start() { moveSpeed = walkSpeed; // 获取相机 foreach(Transform transform in GetComponentsInChildren<Transform>()) { if(transform.name =="Main Camera") { Debug.Log("Find Camera!"); cameraTransform = transform; } } if (!cameraTransform) { Debug.LogError("Can not Find Camera in Children"); } controller = this.GetComponent<CharacterController>(); } // Update is called once per frame void Update() { // 如果不能移动 if (!canMove) return; // 获取y轴旋转角度 float yRotation = cameraTransform.rotation.eulerAngles.y; // 角度转弧度 yRotation = yRotation * Mathf.Deg2Rad; // cos值 float cos = Mathf.Cos(yRotation); // sin 值 float sin = Mathf.Sin(yRotation); // 向右移动 moveRight(sin, cos); moveFoward(sin, cos); SpeedUp(); // 如果使用重力 if (useGravity) { SetGravity(); } } // 向右移动 void moveRight(float sin, float cos) { float horizontalValue = Input.GetAxis("Horizontal") * moveSpeed; Vector3 moveDirection = horizontalValue * (-Vector3.forward * sin+Vector3.right * cos); controller.Move(moveDirection * moveSpeed*Time.deltaTime); } // 向前移动 void moveFoward(float sin, float cos) { float verticalValue = Input.GetAxis("Vertical") * moveSpeed; Vector3 moveDirection = verticalValue * (Vector3.forward * cos + Vector3.right * sin); controller.Move(moveDirection* moveSpeed * Time.deltaTime); } //加速 void SpeedUp() { float speed = Input.GetAxis("SpeedUp"); // 如果启动加速键 if (speed == 1f) { moveSpeed = runSpeed; } else { moveSpeed = walkSpeed; } } //设置重力 void SetGravity() { if (controller.isGrounded) { gravitySpeed = 0; } gravitySpeed -= (gravity * Time.deltaTime); Vector3 move = Vector3.zero; move.y += gravitySpeed; controller.Move(move * Time.deltaTime); } } <file_sep>/Assets/Scripts/InteractObj/InteractObj.cs using System.Collections; using System.Collections.Generic; using UnityEngine; // 交互类型 public enum InteractObjType { Reapetdly = 0, Once = 1, Twice = 2, Pickup = 3 } public class InteractObj : MonoBehaviour { public InteractObjType type = InteractObjType.Twice; public bool canInteract; public bool shouldDestroy; public float interactTime = 0.5f; private bool isFirstInteraction = true; //交互时间是否被重写 public bool isTimeOverrided = false; private PickupObj pickupObj; Animator animator; void Start() { if (GetComponent<Animator>()) { animator = GetComponent<Animator>(); } if (GetComponent<PickupObj>()) { type = InteractObjType.Pickup; pickupObj = GetComponent<PickupObj>(); } if (GetComponent<Outline>()) GetComponent<Outline>().SetOutline(false); } void OnEnable() { Debug.Log("Interact Obj on enable:" + gameObject.name); } public void Interact() { // 如果当前不可交互 if (!canInteract) return; canInteract = false; switch (type) { // 两次交互 case InteractObjType.Twice: InteractTwice(); break; case InteractObjType.Pickup: Pickup(); break; } // 延时执行 if(!isTimeOverrided) StartCoroutine(InteractDown()); } public void ReadyToInteract() { Debug.Log("readyfjsdl;fj"); // outline的宽度 if (GetComponent<Outline>()) GetComponent<Outline>().SetOutline(true); } public void CancelInteract() { if (GetComponent<Outline>()) GetComponent<Outline>().SetOutline(false); } IEnumerator InteractDown() { yield return new WaitForSeconds(interactTime); canInteract = true; } private void InteractTwice() { Debug.Log("Interact " + this.name); if (isFirstInteraction) { isFirstInteraction = false; animator.SetBool("Interaction", true); } else { isFirstInteraction = true; animator.SetBool("Interaction", false); } } // 捡起 private void Pickup() { Debug.Log("Pickup"); if (isFirstInteraction) { CancelInteract(); isFirstInteraction = false; pickupObj.Pickup(); } else { ReadyToInteract(); pickupObj.PickDown(); isFirstInteraction = true; } } public bool IsFirstInteraction() { return isFirstInteraction; } } <file_sep>/README.md # unity第一个合作项目 寝室Demo ### 文件结构: scripts里面放的是代码,Animation是动画,shaders是着色器
f7bfde1a06e4896d6cd93cbfd5b2f7a7758f00ca
[ "Markdown", "C#" ]
3
C#
1075980722/DormitoryDemo
b5586625c02ae5f00d3a0db996ff65b99eadcf74
a1d868b1bcaf283523d6911a00c39d35363f261e
refs/heads/master
<file_sep>module("vie.js - Apache Stanbol Service"); /* All known endpoints of Stanbol */ /* The ones marked with a "!!!" are implemented by the StanbolConnector */ /* The ones marked with a "???" are implemented but still broken */ // !!! /enhancer/chain/default // !!! /enhancer/chain/<chainId> // !!! /entityhub/sites/referenced // !!! /entityhub/sites/entity // !!! /entityhub/sites/find // /entityhub/sites/query // !!! /entityhub/sites/ldpath // !!! /entityhub/site/<siteId>/entity // !!! /entityhub/site/<siteId>/find // /entityhub/site/<siteId>/query // !!! /entityhub/site/<siteId>/ldpath // /entityhub/entity (GET, PUT, POST, DELETE) // /entityhub/mapping // !!! /entityhub/find // /entityhub/query // !!! /entityhub/lookup // !!! /entityhub/ldpath // ??? /sparql // /contenthub/contenthub/ldpath // !!! /contenthub/contenthub/store // /contenthub/contenthub/store/raw/<contentId> // /contenthub/contenthub/store/metadata/<contentId> // !!! /contenthub/<coreId>/store // /contenthub/<coreId>/store/raw/<contentId> // /contenthub/<coreId>/store/metadata/<contentId> // ??? /contenthub/content/<contentId> // !!! /factstore/facts // !!! /factstore/query // /ontonet/ontology // /ontonet/ontology/<scopeName> // /ontonet/ontology/<scopeName>/<ontologyId> // /ontonet/ontology/User // /ontonet/session/ // /ontonet/session/<sessionId> // /rules/rule/ // /rules/rule/<ruleId> // /rules/recipe/ // /rules/recipe/<recipeId> // /rules/refactor/ // /rules/refactor/apply // /cmsadapter/map // /cmsadapter/session // /cmsadapter/contenthubfeed var stanbolRootUrl = ["http://demo.iks-project.eu/stanbolfull", "http://dev.iks-project.eu/stanbolfull"]; test("VIE.js StanbolService - Registration", function() { var z = new VIE(); ok(z.StanbolService, "Checking if the Stanbol Service exists.'"); z.use(new z.StanbolService); ok(z.service('stanbol')); }); test("VIE.js StanbolService - API", function() { var z = new VIE(); z.use(new z.StanbolService); ok(z.service('stanbol').init); equal(typeof z.service('stanbol').init, "function"); ok(z.service('stanbol').analyze); equal(typeof z.service('stanbol').analyze, "function"); ok(z.service('stanbol').find); equal(typeof z.service('stanbol').find, "function"); ok(z.service('stanbol').load); equal(typeof z.service('stanbol').load, "function"); ok(z.service('stanbol').connector); ok(z.service('stanbol').connector instanceof z.StanbolConnector); ok(z.service('stanbol').rules); equal(typeof z.service('stanbol').rules, "object"); }); test("VIE.js StanbolConnector - API", function() { var z = new VIE(); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); //API ok(stanbol.connector.analyze); equal(typeof stanbol.connector.analyze, "function"); ok(stanbol.connector.load); equal(typeof stanbol.connector.load, "function"); ok(stanbol.connector.find); equal(typeof stanbol.connector.find, "function"); ok(stanbol.connector.lookup); equal(typeof stanbol.connector.lookup, "function"); ok(stanbol.connector.referenced); equal(typeof stanbol.connector.referenced, "function"); ok(stanbol.connector.sparql); equal(typeof stanbol.connector.sparql, "function"); ok(stanbol.connector.ldpath); equal(typeof stanbol.connector.ldpath, "function"); ok(stanbol.connector.uploadContent); equal(typeof stanbol.connector.uploadContent, "function"); ok(stanbol.connector.createFactSchema); equal(typeof stanbol.connector.createFactSchema, "function"); ok(stanbol.connector.createFact); equal(typeof stanbol.connector.createFact, "function"); ok(stanbol.connector.queryFact); equal(typeof stanbol.connector.queryFact, "function"); }); test("VIE.js StanbolService - Analyze - Default", function () { if (navigator.userAgent === 'Zombie') { return; } expect(8); // Sending a an example with double quotation marks. var elem = $('<p>This is a small test, where <NAME> sings the song \"We want to live forever!\" song.</p>'); var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function", "The StanbolService exists."); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); z.analyze({element: elem}).using('stanbol').execute().done(function(entities) { ok(entities, "The returned results is not null."); ok(entities instanceof Array, "The entities are an array."); ok(entities.length > 0, "At least one entity returned"); if(entities.length > 0){ var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; ok(false, "VIE.js StanbolService - Analyze: Entity is not a Backbone model!"); console.error("VIE.js StanbolService - Analyze: ", entity, "is not a Backbone model!"); } } ok(allEntities, "All result elements are VIE entities."); var firstTextAnnotation = _(entities).filter(function(e){ return e.isof("enhancer:TextAnnotation") && e.get("enhancer:selected-text"); })[0]; ok(firstTextAnnotation); if (firstTextAnnotation) { var s = firstTextAnnotation.get("enhancer:selected-text").toString(); ok(s.substring(s.length-4, s.length-2) != "\"@", "Selected text should be converted into a normal string."); } } start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); test("VIE.js StanbolService - Analyze with wrong URL of Stanbol", function () { if (navigator.userAgent === 'Zombie') { return; } expect(6); // Sending a an example with double quotation marks. var elem = $('<p>This is a small test, where <NAME> sings the song \"We want to live forever!\" song.</p>'); var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var wrongUrls = ["http://www.this-is-wrong.url/", "http://dev.iks-project.eu/stanbolfull", "http://demo.iks-project.eu/stanbolfull"]; z.use(new z.StanbolService({url : wrongUrls})); stop(); z.analyze({element: elem}).using('stanbol').execute().done(function(entities) { ok(entities); ok(entities.length > 0, "At least one entity returned"); ok(entities instanceof Array); var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; ok(false, "VIE.js StanbolService - Analyze: Entity is not a Backbone model!"); console.error("VIE.js StanbolService - Analyze: ", entity, "is not a Backbone model!"); } } ok(allEntities); start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); test("VIE.js StanbolService - Analyze with Enhancement Chain", function () { if (navigator.userAgent === 'Zombie') { return; } expect(4); // Sending a an example with double quotation marks. var elem = $('<p>This is a small test, where <NAME> sings the song \"We want to live forever!\" song.</p>'); var v = new VIE(); v.use(new v.StanbolService({url : stanbolRootUrl, enhancerUrlPostfix: "/enhancer/chain/dbpedia-keyword"})); stop(); v.analyze({element: elem}).using('stanbol').execute().done(function(entities) { ok(entities, "Entities is not null"); ok(entities instanceof Array, "Result is an array"); ok(entities.length > 0, "At least one entity returned"); if(entities.length > 0) { var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; console.error("VIE.js StanbolService - Analyze: ", entity, "is not a Backbone model!"); } } ok(allEntities, "All results are VIE Entities"); } start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); test("VIE.js StanbolConnector - Get all referenced sites", function () { if (navigator.userAgent === 'Zombie') { return; } // Sending a an example with double quotation marks. var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); stanbol.connector.referenced(function (sites) { ok(_.isArray(sites)); ok(sites.length > 0); start(); }, function (err) { ok(false, "No referenced site has been returned!"); start(); }); }); test("VIE.js StanbolConnector - Perform SPARQL Query", function () { if (navigator.userAgent === 'Zombie') { return; } var query = "PREFIX fise: <http://fise.iks-project.eu/ontology/> " + "PREFIX dc: <http://purl.org/dc/terms/> " + "SELECT distinct ?enhancement ?content ?engine ?extraction_time " + "WHERE { " + "?enhancement a fise:Enhancement . " + "?enhancement fise:extracted-from ?content . " + "?enhancement dc:creator ?engine . " + "?enhancement dc:created ?extraction_time . " + "} " + "ORDER BY DESC(?extraction_time) LIMIT 5"; // Sending a an example with double quotation marks. var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); stanbol.connector.sparql(query, function (response) { ok(response instanceof Document); var xmlString = (new XMLSerializer()).serializeToString(response); var myJsonObject = xml2json.parser(xmlString); ok(myJsonObject.sparql); ok(myJsonObject.sparql.results); ok(myJsonObject.sparql.results.result); ok(myJsonObject.sparql.results.result.length); ok(myJsonObject.sparql.results.result.length > 0); start(); }, function (err) { ok(false, "SPARQL endpoint returned no response!"); start(); }); }); test("VIE.js StanbolService - Find - Default", function () { if (navigator.userAgent === 'Zombie') { return; } var term = "München"; var limit = 10; var offset = 0; var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); z.find({term: term, limit: limit, offset: offset}) .using('stanbol').execute().done(function(entities) { ok(entities); ok(entities.length > 0); ok(entities instanceof Array); var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; ok(false, "VIE.js StanbolService - Find: Entity is not a Backbone model!"); console.error("VIE.js StanbolService - Find: ", entity, "is not a Backbone model!"); } } ok(allEntities); start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); /* test("VIE.js StanbolService - Find - Search only in local entities", function () { if (navigator.userAgent === 'Zombie') { return; } var term = "European Union"; var limit = 10; var offset = 0; var z = new VIE(); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); // search only in local entities z.find({term: "P*", limit: limit, offset: offset, local : true}) .using('stanbol').execute().done(function(entities) { ok(entities); ok(entities.length > 0); ok(entities instanceof Array); var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; ok(false, "VIE.js StanbolService - Find: Entity is not a Backbone model!"); console.error("VIE.js StanbolService - Find: ", entity, "is not a Backbone model!"); } } ok(allEntities); start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); */ test("VIE.js StanbolService - Find - Only term given, no limit, no offset", function () { if (navigator.userAgent === 'Zombie') { return; } var term = "European Union"; var limit = 10; var offset = 0; var z = new VIE(); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); z.find({term: term}) // only term given, no limit, no offset .using('stanbol').execute().done(function(entities) { ok(entities); ok(entities.length > 0); ok(entities instanceof Array); var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; ok(false, "VIE.js StanbolService - Find: Entity is not a Backbone model!"); console.error("VIE.js StanbolService - Find: ", entity, "is not a Backbone model!"); } } ok(allEntities); start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); test("VIE.js StanbolService - Find - Empty term", function () { if (navigator.userAgent === 'Zombie') { return; } var term = "European Union"; var limit = 10; var offset = 0; var z = new VIE(); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); z.find({term: "", limit: limit, offset: offset}) .using('stanbol').execute() .done(function(entities) { ok(false, "this should fail, as there is an empty term given!"); start(); }) .fail(function(f){ ok(true, f.statusText); start(); }); }); test("VIE.js StanbolService - Find - No term", function () { if (navigator.userAgent === 'Zombie') { return; } var term = "European Union"; var limit = 10; var offset = 0; var z = new VIE(); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); z.find({limit: limit, offset: offset}) .using('stanbol').execute() .done(function(entities) { ok(false, "this should fail, as there is no term given!"); start(); }) .fail(function(f){ ok(true, f.statusText); start(); }); }); test("VIE.js StanbolService - Load", function () { if (navigator.userAgent === 'Zombie') { return; } var entity = "<http://dbpedia.org/resource/Barack_Obama>"; var z = new VIE(); z.use(new z.StanbolService({url : stanbolRootUrl})); stop(); z.load({entity: entity}) .using('stanbol').execute().done(function(entities) { ok(entities); ok(entities.length > 0); ok(entities instanceof Array); var allEntities = true; for(var i=0; i<entities.length; i++){ var entity = entities[i]; if (! (entity instanceof Backbone.Model)){ allEntities = false; ok(false, "VIE.js StanbolService - Load: Entity is not a Backbone model!"); console.error("VIE.js StanbolService - Analyze: ", entity, "is not a Backbone model!"); } } ok(allEntities); start(); }) .fail(function(f){ ok(false, f.statusText); start(); }); }); test("VIE.js StanbolService - ContentHub: Upload of content / Retrieval of enhancements", function () { if (navigator.userAgent === 'Zombie') { return; } var content = 'This is a small test, where <NAME> sings the song "We want to live forever!" song.'; var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); stanbol.connector.uploadContent(content, function(xml,status,xhr){ var location = xhr.getResponseHeader('Location'); //TODO: This does not work in jQuery :( start(); }, function (err) { ok(false, err); start(); }); }); /* test("VIE.js StanbolService - ContentHub: Lookup", function () { if (navigator.userAgent === 'Zombie') { return; } var entity = 'http://dbpedia.org/resource/Paris'; var z = new VIE(); z.namespaces.add("cc", "http://creativecommons.org/ns#"); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); stanbol.connector.lookup(entity, function (response) { var entities = VIE.Util.rdf2Entities(stanbol, response); ok(entities.length > 0, "With 'create'"); start(); }, function (err) { ok(false, err); start(); }, { create : true }); stop(); stanbol.connector.lookup(entity, function (response) { var entities = VIE.Util.rdf2Entities(stanbol, response); ok(entities.length > 0, "Without 'create'"); start(); }, function (err) { ok(false, err); start(); }); }); */ test("VIE.js StanbolConnector - LDPath - on all sites", function () { if (navigator.userAgent === 'Zombie') { return; } var context = 'http://dbpedia.org/resource/Paris'; var ldpath = "@prefix dct : <http://purl.org/dc/terms/> ;\n" + "@prefix geo : <http://www.w3.org/2003/01/geo/wgs84_pos#> ;\n" + "name = rdfs:label[@en] :: xsd:string;\n" + "labels = rdfs:label :: xsd:string;\n" + "comment = rdfs:comment[@en] :: xsd:string;\n" + "categories = dc:subject :: xsd:anyURI;\n" + "homepage = foaf:homepage :: xsd:anyURI;\n" + "location = fn:concat(\"[\",geo:lat,\",\",geo:long,\"]\") :: xsd:string;\n"; var z = new VIE(); z.namespaces.add("cc", "http://creativecommons.org/ns#"); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); // on all sites stanbol.connector.ldpath(ldpath, context, function (response) { var entities = VIE.Util.rdf2Entities(stanbol, response); ok(entities.length > 0); start(); }, function (err) { ok(false, err); start(); }); }); test("VIE.js StanbolService - LDPath - on one specific site", function () { if (navigator.userAgent === 'Zombie') { return; } var context = 'http://dbpedia.org/resource/Paris'; var ldpath = "@prefix dct : <http://purl.org/dc/terms/> ;\n" + "@prefix geo : <http://www.w3.org/2003/01/geo/wgs84_pos#> ;\n" + "name = rdfs:label[@en] :: xsd:string;\n" + "labels = rdfs:label :: xsd:string;\n" + "comment = rdfs:comment[@en] :: xsd:string;\n" + "categories = dc:subject :: xsd:anyURI;\n" + "homepage = foaf:homepage :: xsd:anyURI;\n" + "location = fn:concat(\"[\",geo:lat,\",\",geo:long,\"]\") :: xsd:string;\n"; var z = new VIE(); z.namespaces.add("cc", "http://creativecommons.org/ns#"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); // on one specific site stanbol.connector.ldpath(ldpath, context, function (response) { var entities = VIE.Util.rdf2Entities(stanbol, response); ok(entities.length > 0); start(); }, function (err) { ok(false, err); start(); }, { site: "dbpedia" }); }); test("VIE.js StanbolService - LDPath - on local entities", function () { if (navigator.userAgent === 'Zombie') { return; } var context = 'http://dbpedia.org/resource/Paris'; var ldpath = "@prefix dct : <http://purl.org/dc/terms/> ;\n" + "@prefix geo : <http://www.w3.org/2003/01/geo/wgs84_pos#> ;\n" + "name = rdfs:label[@en] :: xsd:string;\n" + "labels = rdfs:label :: xsd:string;\n" + "comment = rdfs:comment[@en] :: xsd:string;\n" + "categories = dc:subject :: xsd:anyURI;\n" + "homepage = foaf:homepage :: xsd:anyURI;\n" + "location = fn:concat(\"[\",geo:lat,\",\",geo:long,\"]\") :: xsd:string;\n"; var z = new VIE(); z.namespaces.add("cc", "http://creativecommons.org/ns#"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); // on local entities stanbol.connector.ldpath(ldpath, context, function (response) { var entities = VIE.Util.rdf2Entities(stanbol, response); ok(entities.length > 0); start(); }, function (err) { ok(false, err); start(); }, { local : true }); }); /* TODO: these tests need to be backed by implementations test("VIE.js StanbolService - Create a New Fact Schema", function () { if (navigator.userAgent === 'Zombie') { return; } var employeeOfFact = { "@context" : { "iks" : "http://iks-project.eu/ont/", "@types" : { "person" : "iks:person", "organization" : "iks:organization" } } }; var employeeOfFactURL = "http://iks-project.eu/ont/employeeOf" + (new Date().getTime()); var z = new VIE(); z.namespaces.add("cc", "http://creativecommons.org/ns#"); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); // on all sites stanbol.connector.createFactSchema(employeeOfFactURL, employeeOfFact, function (response) { debugger; start(); }, function (err) { ok(false, err); start(); }); }); test("VIE.js StanbolService - Create a New Fact", function () { if (navigator.userAgent === 'Zombie') { return; } var fact = { "@context" : { "iks" : "http://iks-project.eu/ont/", "upb" : "http://upb.de/persons/" }, "@profile" : "iks:employeeOf", "person" : { "@iri" : "upb:bnagel" }, "organization" : { "@iri" : "http://uni-paderborn.de"} }; var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); stanbol.connector.createFact(fact, function (response) { debugger; start(); }, function (err) { ok(false, err); start(); }); var moreFactsOfSameType = { "@context" : { "iks" : "http://iks-project.eu/ont/", "upb" : "http://upb.de/persons/" }, "@profile" : "iks:employeeOf", "@subject" : [ { "person" : { "@iri" : "upb:bnagel" }, "organization" : { "@iri" : "http://uni-paderborn.de" } }, { "person" : { "@iri" : "upb:fchrist" }, "organization" : { "@iri" : "http://uni-paderborn.de" } } ] }; stop(); stanbol.connector.createFact(moreFactsOfSameType, function (response) { debugger; start(); }, function (err) { ok(false, err); start(); }); var moreFactsOfDifferentType = { "@context" : { "iks" : "http://iks-project.eu/ont/", "upb" : "http://upb.de/persons/" }, "@subject" : [ { "@profile" : "iks:employeeOf", "person" : { "@iri" : "upb:bnagel" }, "organization" : { "@iri" : "http://uni-paderborn.de" } }, { "@profile" : "iks:friendOf", "person" : { "@iri" : "upb:bnagel" }, "friend" : { "@iri" : "upb:fchrist" } } ] }; stop(); stanbol.connector.createFact(moreFactsOfDifferentType, function (response) { debugger; start(); }, function (err) { ok(false, err); start(); }); }); test("VIE.js StanbolService - Query for Facts of a Certain Type", function () { if (navigator.userAgent === 'Zombie') { return; } var query = { "@context" : { "iks" : "http://iks-project.eu/ont/" }, "select" : [ "person" ], "from" : "iks:employeeOf", "where" : [ { "=" : { "organization" : { "@iri" : "http://uni-paderborn.de" } } } ] }; var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); var stanbol = new z.StanbolService({url : stanbolRootUrl}); z.use(stanbol); stop(); stanbol.connector.queryFact(query, function (response) { debugger; start(); }, function (err) { ok(false, err); start(); }); }); test("VIE.js StanbolService - CRUD on local entities", function () { if (navigator.userAgent === 'Zombie') { return; } var z = new VIE(); ok (z.StanbolService); equal(typeof z.StanbolService, "function"); z.use(new z.StanbolService({url : stanbolRootUrl})); //TODO }); */ <file_sep>// VIE - Vienna IKS Editables // (c) 2011 <NAME>, IKS Consortium // (c) 2011 <NAME>, IKS Consortium // (c) 2011 <NAME>, IKS Consortium // VIE may be freely distributed under the MIT license. // For all details and documentation: // http://viejs.org/ /*global escape:false */ // ## VIE - StanbolService service // The StanbolService service allows a VIE developer to directly query // the <a href="http://incubator.apache.org/stanbol/">Apache Stanbol</a> entityhub for entities and their properties. // Furthermore, it gives access to the enhance facilities of // Stanbol to analyze content and semantically enrich it. (function(){ var defaultStanbolUris = ["http://demo.iks-project.eu/stanbolfull", "http://dev.iks-project.eu/stanbolfull"]; // ## VIE.StanbolService(options) // This is the constructor to instantiate a new service to collect // properties of an entity from <a href="http://incubator.apache.org/stanbol/">Apache Stanbol</a>. // **Parameters**: // *{object}* **options** Optional set of fields, ```namespaces```, ```rules```, ```url```, or ```name```. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolService}* : A **new** VIE.StanbolService instance. // **Example usage**: // // var stnblService = new vie.StanbolService({<some-configuration>}); VIE.prototype.StanbolService = function(options) { var defaults = { /* the default name of this service */ name : 'stanbol', /* you can pass an array of URLs which are then tried sequentially */ url: defaultStanbolUris, timeout : 20000, /* 20 seconds timeout */ namespaces : { semdeski : "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#", semdeskf : "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#", skos: "http://www.w3.org/2004/02/skos/core#", foaf: "http://xmlns.com/foaf/0.1/", opengis: "http://www.opengis.net/gml/", dbpedia: "http://dbpedia.org/ontology/", dbprop: "http://dbpedia.org/property/", owl : "http://www.w3.org/2002/07/owl#", geonames : "http://www.geonames.org/ontology#", enhancer : "http://fise.iks-project.eu/ontology/", entityhub: "http://www.iks-project.eu/ontology/rick/model/", entityhub2: "http://www.iks-project.eu/ontology/rick/query/", rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#", rdfs: "http://www.w3.org/2000/01/rdf-schema#", dcterms : 'http://purl.org/dc/terms/', schema: 'http://schema.org/', geo: 'http://www.w3.org/2003/01/geo/wgs84_pos#' }, /* default rules that are shipped with this service */ rules : [ /* rule to add backwards-relations to the triples * this makes querying for entities a lot easier! */ { 'left' : [ '?subject a <http://fise.iks-project.eu/ontology/EntityAnnotation>', '?subject enhancer:entity-type ?type', '?subject enhancer:confidence ?confidence', '?subject enhancer:entity-reference ?entity', '?subject dcterms:relation ?relation', '?relation a <http://fise.iks-project.eu/ontology/TextAnnotation>', '?relation enhancer:selected-text ?selected-text', '?relation enhancer:selection-context ?selection-context', '?relation enhancer:start ?start', '?relation enhancer:end ?end' ], 'right' : [ '?entity a ?type', '?entity enhancer:hasTextAnnotation ?relation', '?entity enhancer:hasEntityAnnotation ?subject' ] } ], enhancer : { chain : "default" }, entityhub : { /* if set to undefined, the Referenced Site Manager @ /entityhub/sites is used. */ /* if set to, e.g., dbpedia, eferenced Site @ /entityhub/site/dbpedia is used. */ site : undefined } }; /* the options are merged with the default options */ this.options = jQuery.extend(true, defaults, options ? options : {}); this.vie = null; /* will be set via VIE.use(); */ /* overwrite options.name if you want to set another name */ this.name = this.options.name; }; VIE.prototype.StanbolService.prototype = { // ### init() // This internal method initializes certain properties of the service and is called // via ```VIE.use()```. // **Parameters**: // *nothing* // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolService}* : The VIE.StanbolService instance itself. init: function(){ for (var key in this.options.namespaces) { var val = this.options.namespaces[key]; this.vie.namespaces.add(key, val); } this.rules = jQuery.extend([], VIE.Util.transformationRules(this)); this.rules = jQuery.merge(this.rules, (this.options.rules) ? this.options.rules : []); this.connector = new this.vie.StanbolConnector(this.options); /* adding these entity types to VIE helps later the querying */ this.vie.types.addOrOverwrite('enhancer:EntityAnnotation', [ /*TODO: add attributes */ ]).inherit("owl:Thing"); this.vie.types.addOrOverwrite('enhancer:TextAnnotation', [ /*TODO: add attributes */ ]).inherit("owl:Thing"); this.vie.types.addOrOverwrite('enhancer:Enhancement', [ /*TODO: add attributes */ ]).inherit("owl:Thing"); }, // ### analyze(analyzable) // This method extracts text from the jQuery element and sends it to Apache Stanbol for analysis. // **Parameters**: // *{VIE.Analyzable}* **analyzable** The analyzable. // **Throws**: // *{Error}* if an invalid VIE.Analyzable is passed. // **Returns**: // *{VIE.StanbolService}* : The VIE.StanbolService instance itself. // **Example usage**: // // vie.analyze({element : jQuery("#foo")}) // .using(new vie.StanbolService({<some-configuration>})) // .execute().success(callback); analyze: function(analyzable) { var service = this; var correct = analyzable instanceof this.vie.Analyzable; if (!correct) {throw "Invalid Analyzable passed";} var element = analyzable.options.element ? analyzable.options.element : jQuery('body'); var text = service._extractText(element); if (text.length > 0) { /* query enhancer with extracted text */ var success = function (results) { _.defer(function(){ var entities = VIE.Util.rdf2Entities(service, results); service.vie.entities.addOrUpdate(entities); analyzable.resolve(entities); }); }; var error = function (e) { analyzable.reject(e); }; var options = { chain : (analyzable.options.chain)? analyzable.options.chain : service.options.enhancer.chain }; this.connector.analyze(text, success, error, options); } else { analyzable.resolve([]); } }, // ### find(findable) // This method finds entities given the term from the entity hub. // **Parameters**: // *{VIE.Findable}* **findable** The findable. // **Throws**: // *{Error}* if an invalid VIE.Findable is passed. // **Returns**: // *{VIE.StanbolService}* : The VIE.StanbolService instance itself. // **Example usage**: // // vie.find({ // term : "Bischofsh", // limit : 10, // offset: 0, // field: "skos:prefLabel", // used for the term lookup, default: "rdfs:label" // properties: ["skos:prefLabel", "rdfs:label"] // are going to be loaded with the result entities // }) // .using(new vie.StanbolService({<some-configuration>})) // .execute() // .success(callback); find: function (findable) { var correct = findable instanceof this.vie.Findable; if (!correct) {throw "Invalid Findable passed";} var service = this; /* The term to find, * as wildcard allowed */ if (!findable.options.term) { findable.reject([]); } var term = findable.options.term; var limit = (typeof findable.options.limit === "undefined") ? 20 : findable.options.limit; var offset = (typeof findable.options.offset === "undefined") ? 0 : findable.options.offset; var success = function (results) { _.defer(function(){ var entities = VIE.Util.rdf2Entities(service, results); findable.resolve(entities); }); }; var error = function (e) { findable.reject(e); }; findable.options.site = (findable.options.site)? findable.options.site : service.options.entityhub.site; var vie = this.vie; if(findable.options.properties){ var properties = findable.options.properties; findable.options.ldPath = _(properties) .map(function(property){ if (vie.namespaces.isCurie(property)){ return vie.namespaces.uri(property) + ";"; } else { return property; } }) .join(""); } if(findable.options.field && vie.namespaces.isCurie(findable.options.field)){ var field = findable.options.field; findable.options.field = vie.namespaces.uri(field); } this.connector.find(term, limit, offset, success, error, findable.options); }, // ### load(loadable) // This method loads the entity that is stored within the loadable into VIE. // **Parameters**: // *{VIE.Loadable}* **lodable** The loadable. // **Throws**: // *{Error}* if an invalid VIE.Loadable is passed. // **Returns**: // *{VIE.StanbolService}* : The VIE.StanbolService instance itself. // **Example usage**: // vie.load({ // entity: "<http://...>" // }) // .using(new vie.StanbolService({<some-configuration>})) // .execute() // .success(callback); load: function(loadable){ var correct = loadable instanceof this.vie.Loadable; if (!correct) {throw "Invalid Loadable passed";} var service = this; var entity = loadable.options.entity; if (!entity){ loadable.resolve([]); } var success = function (results) { _.defer(function(){ var entities = VIE.Util.rdf2Entities(service, results); _.each(entities, function(vieEntity) { service.vie.entities.addOrUpdate(vieEntity); }); loadable.resolve(entities); }); }; var error = function (e) { loadable.reject(e); }; var options = { site : (loadable.options.site)? loadable.options.site : service.options.entityhub.site, local : loadable.options.local }; this.connector.load(entity, success, error, options); }, // ### save(savable) // This method saves the given entity to the Apache Stanbol installation. // **Parameters**: // *{VIE.Savable}* **savable** The savable. // **Throws**: // *{Error}* if an invalid VIE.Savable is passed. // **Returns**: // *{VIE.StanbolService}* : The VIE.StanbolService instance itself. // **Example usage**: // // var entity = new vie.Entity({'name' : '<NAME>'}); // var stnblService = new vie.StanbolService({<some-configuration>}); // stnblService.save(new vie.Savable(entity)); save: function(savable){ var correct = savable instanceof this.vie.Savable; if (!correct) {throw "Invalid Savable passed";} var service = this; var entity = savable.options.entity; if (!entity){ savable.reject("StanbolConnector: No entity to save!"); } var success = function (results) { _.defer(function() { var entities = VIE.Util.rdf2Entities(service, results); savable.resolve(entities); }); }; var error = function (e) { savable.reject(e); }; var options = { site : (savable.options.site)? savable.options.site : service.options.entityhub.site, local : savable.options.local }; this.connector.save(entity, success, error, options); }, /* this private method extracts text from a jQuery element */ _extractText: function (element) { if (element.get(0) && element.get(0).tagName && (element.get(0).tagName == 'TEXTAREA' || element.get(0).tagName == 'INPUT' && element.attr('type', 'text'))) { return element.get(0).val(); } else { var res = element .text() /* get the text of element */ .replace(/\s+/g, ' ') /* collapse multiple whitespaces */ .replace(/\0\b\n\r\f\t/g, ''); /* remove non-letter symbols */ return jQuery.trim(res); } } }; // ## VIE.StanbolConnector(options) // The StanbolConnector is the connection between the VIE Stanbol service // and the actual ajax calls. // **Parameters**: // *{object}* **options** The options. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The **new** VIE.StanbolConnector instance. // **Example usage**: // // var stnblConn = new vie.StanbolConnector({<some-configuration>}); VIE.prototype.StanbolConnector = function (options) { var defaults = { /* you can pass an array of URLs which are then tried sequentially */ url: defaultStanbolUris, timeout : 20000, /* 20 seconds timeout */ enhancer : { urlPostfix : "/enhancer", chain : "default" }, entityhub : { /* if set to undefined, the Referenced Site Manager @ /entityhub/sites is used. */ /* if set to, e.g., dbpedia, referenced Site @ /entityhub/site/dbpedia is used. */ site : undefined, urlPostfix : "/entityhub", local : false }, sparql : { urlPostfix : "/sparql" }, contenthub : { urlPostfix : "/contenthub", index : "contenthub" }, ontonet : { urlPostfix : "/ontonet" }, factstore : { urlPostfix : "/factstore" }, rules : { urlPostfix : "/rules" }, cmsadapter : { urlPostfix : "/cmsadapter" } }; /* the options are merged with the default options */ this.options = jQuery.extend(true, defaults, options ? options : {}); this.options.url = (_.isArray(this.options.url))? this.options.url : [ this.options.url ]; this._init(); this.baseUrl = (_.isArray(options.url))? options.url : [ options.url ]; }; VIE.prototype.StanbolConnector.prototype = { // ### _init() // Basic setup of the stanbol connector. This is called internally by the constructor! // **Parameters**: // *nothing* // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. _init : function () { var connector = this; /* basic setup for the ajax connection */ jQuery.ajaxSetup({ converters: {"text application/rdf+json": function(s){return JSON.parse(s);}}, timeout: connector.options.timeout }); return this; }, _iterate : function (params) { if (!params) { return; } if (params.urlIndex >= this.options.url.length) { params.error.call(this, "Could not connect to the given Stanbol endpoints! Please check for their setup!"); return; } var retryErrorCb = function (c, p) { /* in case a Stanbol backend is not responding and * multiple URLs have been registered */ return function () { p.urlIndex = p.urlIndex+1; c._iterate(p); }; }(this, params); if (typeof exports !== "undefined" && typeof process !== "undefined") { /* We're on Node.js, don't use jQuery.ajax */ return params.methodNode.call( this, params.url.call(this, params.urlIndex, params.args.options), params.args, params.success, retryErrorCb); } return params.method.call( this, params.url.call(this, params.urlIndex, params.args.options), params.args, params.success, retryErrorCb); }, // ### analyze(text, success, error, options) // This method sends the given text to Apache Stanbol returns the result by the success callback. // **Parameters**: // *{string}* **text** The text to be analyzed. // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, like the ```format```, or the ```chain``` to be used. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. // **Example usage**: // // var stnblConn = new vie.StanbolConnector(opts); // stnblConn.analyze("This is some text.", // function (res) { ... }, // function (err) { ... }); analyze: function(text, success, error, options) { options = (options)? options : {}; var connector = this; connector._iterate({ method : connector._analyze, methodNode : connector._analyzeNode, url : function (idx, opts) { var chain = (opts.chain)? opts.chain : this.options.enhancer.chain; var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.enhancer.urlPostfix + "/chain/" + chain.replace(/\/$/, ''); return u; }, args : { text : text, format : options.format || "application/rdf+json", options : options }, success : success, error : error, urlIndex : 0 }); }, _analyze : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "POST", data: args.text, dataType: args.format, contentType: "text/plain", accepts: {"application/rdf+json": "application/rdf+json"} }); }, _analyzeNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body: args.text, headers: { Accept: args.format, 'Content-Type': 'text/plain' } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### load(uri, success, error, options) // This method loads all properties from an entity and returns the result by the success callback. // **Parameters**: // *{string}* **uri** The URI of the entity to be loaded. // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, like the ```format```, the ```site```. If ```local``` is set, only the local entities are accessed. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. // **Example usage**: // // var stnblConn = new vie.StanbolConnector(opts); // stnblConn.load("<http://dbpedia.org/resource/Barack_Obama>", // function (res) { ... }, // function (err) { ... }); load: function (uri, success, error, options) { var connector = this; options = (options)? options : {}; options.uri = uri.replace(/^</, '').replace(/>$/, ''); connector._iterate({ method : connector._load, methodNode : connector._loadNode, success : success, error : error, url : function (idx, opts) { var site = (opts.site)? opts.site : this.options.entityhub.site; site = (site)? "/" + site : "s"; var isLocal = opts.local; var u = this.options.url[idx].replace(/\/$/, '') + this.options.entityhub.urlPostfix; if (isLocal) { u += "/entity?id=" + encodeURIComponent(opts.uri); } else { u += "/site" + site + "/entity?id=" + encodeURIComponent(opts.uri); } return u; }, args : { format : options.format || "application/rdf+json", options : options }, urlIndex : 0 }); }, _load : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "GET", dataType: args.format, contentType: "text/plain", accepts: {"application/rdf+json": "application/rdf+json"} }); }, _loadNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "GET", uri: url, body: args.text, headers: { Accept: args.format } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### find(term, limit, offset, success, error, options) // This method finds entities given the term from the entity hub and returns the result by the success callback. // **Parameters**: // *{string}* **term** The term to be searched for. // *{int}* **limit** The limit of results to be returned. // *{int}* **offset** The offset to be search for. // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, like the ```format```. If ```local``` is set, only the local entities are accessed. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. // **Example usage**: // // var stnblConn = new vie.StanbolConnector(opts); // stnblConn.find("Bishofsh", 10, 0, // function (res) { ... }, // function (err) { ... }); find: function(term, limit, offset, success, error, options) { options = (options)? options : {}; /* curl -X POST -d "name=Bishofsh&limit=10&offset=0" http://localhost:8080/entityhub/sites/find */ var connector = this; if (!term || term === "") { error ("No term given!"); return; } offset = (offset)? offset : 0; limit = (limit)? limit : 10; connector._iterate({ method : connector._find, methodNode : connector._findNode, success : success, error : error, url : function (idx, opts) { var site = (opts.site)? opts.site : this.options.entityhub.site; site = (site)? "/" + site : "s"; var isLocal = opts.local; var u = this.options.url[idx].replace(/\/$/, '') + this.options.entityhub.urlPostfix; if (isLocal) { u += "/sites/find"; } else { u += "/site" + site + "/find"; } return u; }, args : { term : term, offset : offset, limit : limit, format : options.format || "application/rdf+json", options : options }, urlIndex : 0 }); }, _find : function (url, args, success, error) { var fields={ "name": args.term, "limit": args.limit, "offset": args.offset }; jQuery.ajax({ success: success, error: error, url: url, type: "POST", data: jQuery.param(fields), dataType: args.format, contentType : "application/x-www-form-urlencoded", accepts: {"application/rdf+json": "application/rdf+json"} }); }, _findNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body : "name=" + args.term + "&limit=" + args.limit + "&offset=" + args.offset, headers: { Accept: args.format } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### lookup(uri, success, error, options) // TODO. // **Parameters**: // *{string}* **uri** The URI of the entity to be loaded. // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, ```create```. // If the parsed ID is a URI of a Symbol, than the stored information of the Symbol are returned in the requested media type ('accept' header field). // If the parsed ID is a URI of an already mapped entity, then the existing mapping is used to get the according Symbol. // If "create" is enabled, and the parsed URI is not already mapped to a Symbol, than all the currently active referenced sites are searched for an Entity with the parsed URI. // If the configuration of the referenced site allows to create new symbols, than a the entity is imported in the Entityhub, a new Symbol and EntityMapping is created and the newly created Symbol is returned. // In case the entity is not found (this also includes if the entity would be available via a referenced site, but create=false) a 404 "Not Found" is returned. // In case the entity is found on a referenced site, but the creation of a new Symbol is not allowed a 403 "Forbidden" is returned. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. lookup: function(uri, success, error, options) { options = (options)? options : {}; /*/lookup/?id=http://dbpedia.org/resource/Paris&create=false"*/ var connector = this; uri = uri.replace(/^</, '').replace(/>$/, ''); options.uri = uri; options.create = (options.create)? options.create : false; connector._iterate({ method : connector._lookup, methodNode : connector._lookupNode, success : success, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, '') + this.options.entityhub.urlPostfix; u += "/lookup?id=" + encodeURIComponent(opts.uri) + "&create=" + opts.create; return u; }, args : { format : options.format || "application/rdf+json", options : options }, urlIndex : 0 }); }, _lookup : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "GET", dataType: args.format, contentType: "text/plain", accepts: {"application/rdf+json": "application/rdf+json"} }); }, _lookupNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "GET", uri: url, body: args.text, headers: { Accept: args.format } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### referenced(success, error, options) // This method returns a list of all referenced sites that the entityhub comprises. // **Parameters**: // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, unused here. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. // **Example usage**: // // var stnblConn = new vie.StanbolConnector(opts); // stnblConn.referenced( // function (res) { ... }, // function (err) { ... }); referenced: function(success, error, options) { options = (options)? options : {}; var connector = this; var successCB = function (sites) { if (!_.isArray(sites)) { sites = JSON.parse(sites); } var sitesStripped = []; for (var s = 0, l = sites.length; s < l; s++) { sitesStripped.push(sites[s].replace(/.+\/(.+?)\/?$/, "$1")); } return success(sitesStripped); }; connector._iterate({ method : connector._referenced, methodNode : connector._referencedNode, success : successCB, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.entityhub.urlPostfix + "/sites/referenced"; return u; }, args : { options : options }, urlIndex : 0 }); }, _referenced : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "GET", accepts: {"application/rdf+json": "application/rdf+json"} }); }, _referencedNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "GET", uri: url, headers: { Accept: args.format } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### sparql(query, success, error, options) // TODO. // **Parameters**: // TODO // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, unused here. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. sparql: function(query, success, error, options) { options = (options)? options : {}; var connector = this; connector._iterate({ method : connector._sparql, methodNode : connector._sparqlNode, success : success, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.sparql.urlPostfix.replace(/\/$/, ''); return u; }, args : { query : query, options : options }, urlIndex : 0 }); }, _sparql : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "POST", data : "query=" + args.query, contentType : "application/x-www-form-urlencoded" }); }, _sparqlNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body : JSON.stringify({query : args.query}), headers: { Accept: args.format } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### ldpath(query, success, error, options) // TODO. // **Parameters**: // TODO // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, unused here. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. ldpath: function(ldpath, context, success, error, options) { options = (options)? options : {}; var connector = this; context = (_.isArray(context))? context : [ context ]; var contextStr = ""; for (var c = 0; c < context.length; c++) { contextStr += "&context=" + context[c]; } connector._iterate({ method : connector._ldpath, methodNode : connector._ldpathNode, success : success, error : error, url : function (idx, opts) { var site = (opts.site)? opts.site : this.options.entityhub.site; site = (site)? "/" + site : "s"; var isLocal = opts.local; var u = this.options.url[idx].replace(/\/$/, '') + this.options.entityhub.urlPostfix; if (!isLocal) u += "/site" + site; u += "/ldpath"; return u; }, args : { ldpath : ldpath, context : contextStr, format : options.format || "application/rdf+json", options : options }, urlIndex : 0 }); }, _ldpath : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "POST", data : "ldpath=" + args.ldpath + args.context, contentType : "application/x-www-form-urlencoded", dataType: args.format, accepts: {"application/rdf+json": "application/rdf+json"} }); }, _ldpathNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body : "ldpath=" + args.ldpath + args.context, headers: { Accept: args.format } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, // ### uploadContent(content, success, error, options) // TODO. // **Parameters**: // TODO // *{function}* **success** The success callback. // *{function}* **error** The error callback. // *{object}* **options** Options, unused here. // **Throws**: // *nothing* // **Returns**: // *{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. uploadContent: function(content, success, error, options) { options = (options)? options : {}; var connector = this; connector._iterate({ method : connector._uploadContent, methodNode : connector._uploadContentNode, success : success, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.contenthub.urlPostfix.replace(/\/$/, ''); var index = (opts.index)? opts.index : this.options.contenthub.index; u += "/" + index.replace(/\/$/, ''); u += "/store"; return u; }, args : { content: content, options : options }, urlIndex : 0 }); }, _uploadContent : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "POST", data : args.content, contentType : "text/plain" }); }, _uploadContentNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body : args.content, headers: { Accept: "application/rdf+xml", "Content-Type" : "text/plain" } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, //### createFactSchema(url, schema, success, error, options) //TODO. //**Parameters**: //TODO //*{function}* **success** The success callback. //*{function}* **error** The error callback. //*{object}* **options** Options, unused here. //**Throws**: //*nothing* //**Returns**: //*{VIE.StanbolConnector}* : The VIE.StanbolConnector instance itself. createFactSchema: function(url, schema, success, error, options) { options = (options)? options : {}; var connector = this; options.url = url; connector._iterate({ method : connector._createFactSchema, methodNode : connector._createFactSchemaNode, success : success, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.factstore.urlPostfix.replace(/\/$/, ''); u += "/facts/" + encodeURIComponent(opts.url); return u; }, args : { url : url, schema : schema, options : options }, urlIndex : 0 }); }, _createFactSchema : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "PUT", data : args.schema, contentType : "application/json", dataType: "application/json" }); }, _createFactSchemaNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "PUT", uri: url, body : args.schema, headers: { Accept: "application/json", "Content-Type" : "application/json" } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, createFact: function(fact, success, error, options) { options = (options)? options : {}; var connector = this; connector._iterate({ method : connector._createFact, methodNode : connector._createFactNode, success : success, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.factstore.urlPostfix.replace(/\/$/, ''); u += "/facts"; return u; }, args : { fact : fact, options : options }, urlIndex : 0 }); }, _createFact : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "POST", data : args.fact, contentType : "application/json", dataType: "application/json" }); }, _createFactNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body : args.fact, headers: { Accept: "application/json", "Content-Type" : "application/json" } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); }, queryFact: function(query, success, error, options) { options = (options)? options : {}; var connector = this; connector._iterate({ method : connector._queryFact, methodNode : connector._queryFactNode, success : success, error : error, url : function (idx, opts) { var u = this.options.url[idx].replace(/\/$/, ''); u += this.options.factstore.urlPostfix.replace(/\/$/, ''); u += "/query"; return u; }, args : { query : query, options : options }, urlIndex : 0 }); }, _queryFact : function (url, args, success, error) { jQuery.ajax({ success: success, error: error, url: url, type: "POST", data : args.query, contentType : "application/json", dataType: "application/json" }); }, _queryFactNode: function(url, args, success, error) { var request = require('request'); var r = request({ method: "POST", uri: url, body : args.query, headers: { Accept: "application/json", "Content-Type" : "application/json" } }, function(err, response, body) { try { success({results: JSON.parse(body)}); } catch (e) { error(e); } }); r.end(); } }; })(); <file_sep>module("Core - Entity"); test('toJSONLD export to JSON', function() { var z = new VIE(); z.namespaces.add('example', 'http://example.net/foo/'); z.namespaces.add("foaf", "http://xmlns.com/foaf/0.1/"); var person = z.types.add("foaf:Person").inherit(z.types.get('owl:Thing')); var musician = z.types.add("example:Musician").inherit(z.types.get('owl:Thing')); z.entities.add({ '@subject': 'http://example.net/Madonna', '@type': ['foaf:Person', 'example:Musician'] }); var model = z.entities.get('http://example.net/Madonna'); var exportedJson = JSON.stringify(model.toJSONLD()); var parsedJson = JSON.parse(exportedJson); equal(parsedJson['@subject'], '<http://example.net/Madonna>'); deepEqual(parsedJson['@type'], ['<http://xmlns.com/foaf/0.1/Person>', '<http://example.net/foo/Musician>']); }); <file_sep>module("vie.js - RDFa Service"); test("Test simple RDFa parsing", function() { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-simple div'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { ok(entities); equal(entities.length, 2); var albert = z.entities.get('<http://dbpedia.org/resource/Albert_Einstein>'); var germany = z.entities.get('<http://dbpedia.org/resource/Germany>'); equal(albert.id, '<http://dbpedia.org/resource/Albert_Einstein>'); equal(albert.get('foaf:name'), '<NAME>'); equal(germany.get('dbp:conventionalLongName'), 'Federal Republic of Germany'); start(); }); }); test("Test updating RDFa views", function() { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-updating div'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { ok(entities); equal(entities.length, 2); var germany = z.entities.get('<http://dbpedia.org/resource/Germany>'); equal(germany.get('dbp:conventionalLongName'), 'Federal Republic of Germany'); germany.set({'dbp:conventionalLongName': 'Switzerland'}); equal(germany.get('dbp:conventionalLongName'), 'Switzerland'); jQuery('[property="dbp:conventionalLongName"]', html).each(function() { equal(jQuery(this).html(), 'Switzerland'); }); start(); }); }); test("Test simple RDFa nested tags", function() { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-nested div'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { equal(entities.length, 1); equal(jQuery.trim(entities[0].get('dcterms:title')).toUpperCase(), '<span>News item title</span>'.toUpperCase()); start(); }); }); test("Test RDFa property content", function() { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-property-content div'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { equal(entities.length, 1); equal(entities[0].get('iks:online'), 0); entities[0].set({'iks:online': 1}); equal(entities[0].get('iks:online'), 1); equal(jQuery('[property="iks:online"]', html).attr('content'), 1); equal(jQuery('[property="iks:online"]', html).text(), ''); start(); }); }); test("Test RDFa example from Wikipedia", function() { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-wikipedia p'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { var objectInstance = z.entities.get('<http://www.example.com/books/wikinomics>'); equal(objectInstance.get('dc:title'), 'Wikinomics'); equal(objectInstance.get('dc:creator'), '<NAME>'); start(); }); }); test("Test RDFa image entitization", function() { var options = {}; if (navigator.userAgent === 'Zombie') { options.attributeExistenceComparator = ''; } var z = new VIE(); z.use(new z.RdfaService(options)); var html = jQuery('#qunit-fixture .rdfa-image-entitization div'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { var icons = z.entities.get('<http://example.net/blog/news_item>').get('mgd:icon'); // Ensure we have the image correctly read ok(icons instanceof z.Collection, "Icons should be a collection"); if (!icons) { start(); return; } equal(icons.at(0).id, '<http://example.net/image.jpg>'); equal(jQuery('img', html).length, 1); // Remove it and replace with another image icons.remove(icons.at(0)); equal(jQuery('img', html).length, 0); icons.add({'@subject': '<http://example.net/otherimage.jpg>'}); equal(jQuery('img', html).length, 1); equal(jQuery('img[src="http://example.net/otherimage.jpg"]', html).length, 1); start(); }); }); test("Test collection reset with RDFa", function() { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-collection-reset'); stop(); z.load({element: html}).from('rdfa').execute().done(function(entities) { var entity = z.entities.get('<http://example.net/collectionreset>'); ok(entity.isEntity); var collection = entity.get('collection'); ok(collection.isCollection); equal(collection.length, 1); equal(collection.at(0).get('@type')[1].id, '<http://rdfs.org/sioc/ns#Post>'); equal(jQuery('li[about]', html).length, 1); entity.set({ collection: ['<http://example.net/collectionreset/item>', '<http://example.net/collectionreset/item2>'] }); collection = entity.get('collection'); ok(collection.isCollection); equal(collection.length, 2); equal(jQuery('li[about]', html).length, 2); equal(jQuery('[about="http://example.net/collectionreset/item"]', html).length, 1); equal(jQuery('[about="http://example.net/collectionreset/item2"]', html).length, 1); // Add a blank node collection.add({}); equal(jQuery('li[about]', html).length, 3); var newItem = collection.at(2); ok(newItem.isNew()); newItem.set('@subject', 'http://example.net/collectionreset/item3'); equal(jQuery('li[about]', html).length, 3); equal(jQuery('[about="http://example.net/collectionreset/item"]', html).length, 1); equal(jQuery('[about="http://example.net/collectionreset/item2"]', html).length, 1); equal(jQuery('[about="http://example.net/collectionreset/item3"]', html).length, 1); // Re-reset entity.set({ collection: ['<http://example.net/collectionreset/item>', '<http://example.net/collectionreset/item2>', '<http://example.net/collectionreset/item3>'] }); equal(jQuery('li[about]', html).length, 3); equal(jQuery('[about="http://example.net/collectionreset/item"]', html).length, 1); equal(jQuery('[about="http://example.net/collectionreset/item2"]', html).length, 1); equal(jQuery('[about="http://example.net/collectionreset/item3"]', html).length, 1); start(); }); }); test("Test type-specific collection RDFa templates", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-collection-twotemplates'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { var mainEntity = z.entities.get('<http://example.net/mycollection>'); ok(mainEntity.isEntity); var collection = mainEntity.get('section'); ok(collection.isCollection); equal(collection.length, 2); equal(jQuery('div[about]', html).length, 3); equal(jQuery('h1', html).length, 1); equal(jQuery('h2', html).length, 1); collection.add({ '@type': 'first' }); equal(collection.length, 3); equal(jQuery('h1', html).length, 2); equal(jQuery('h2', html).length, 1); collection.remove(collection.at(2)); equal(collection.length, 2); equal(jQuery('h1', html).length, 1); collection.add({ '@type': 'second' }); equal(collection.length, 3); equal(jQuery('h2', html).length, 2); equal(jQuery('h1', html).length, 1); collection.remove(collection.at(2)); equal(collection.length, 2); equal(jQuery('h2', html).length, 1); // Add a model of unspecified type, should add using the second template collection.add({}); equal(collection.length, 3); equal(jQuery('h2', html).length, 2); equal(jQuery('h1', html).length, 1); collection.remove(collection.at(2)); equal(collection.length, 2); equal(jQuery('h2', html).length, 1); start(); }); }); test("Test collection with custom RDFa template", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-collection-scripttemplate'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { var mainEntity = z.entities.get('<http://example.net/mycollection>'); ok(mainEntity.isEntity); var collection = mainEntity.get('section'); ok(collection.isCollection); equal(collection.length, 0); equal(jQuery('div[rel="section"]', html).children().length, 0); // We should not be able to add to DOM without template collection.add({}); equal(jQuery('div[rel="section"]', html).children().length, 0); equal(collection.length, 1); collection.remove(collection.at(0)); equal(collection.length, 0); // Register a template with the RDFa service z.service('rdfa').setTemplate('second', 'section', jQuery('.template', html).html()); // Now adding should work collection.add({ '@type': 'second' }); equal(jQuery('div[rel="section"]', html).children().length, 1); equal(collection.length, 1); equal(jQuery('div[rel="section"] h2', html).length, 1); collection.remove(collection.at(0)); equal(jQuery('div[rel="section"]', html).children().length, 0); start(); }); }); test("Test collection with custom RDFa template function", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-collection-scripttemplate2'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { var mainEntity = z.entities.get('<http://example.net/mycollection>'); ok(mainEntity.isEntity); var collection = mainEntity.get('section'); ok(collection.isCollection); equal(collection.length, 0); equal(jQuery('div[rel="section"]', html).children().length, 0); // We should not be able to add to DOM without template collection.add({}); equal(jQuery('div[rel="section"]', html).children().length, 0); equal(collection.length, 1); collection.remove(collection.at(0)); equal(collection.length, 0); // Register a template with the RDFa service z.service('rdfa').setTemplate('second', 'section', function (entity, callback, collectionView) { ok(collectionView instanceof z.view.Collection); window.setTimeout(function () { callback(jQuery(jQuery.trim(jQuery('.template', html).html())).clone(false)); }, 0); }); // Now adding should work collection.add({ '@type': 'second' }); window.setTimeout(function () { equal(jQuery('div[rel="section"]', html).children().length, 1); equal(collection.length, 1); equal(jQuery('div[rel="section"] h2', html).length, 1); collection.remove(collection.at(0)); equal(jQuery('div[rel="section"]', html).children().length, 0); start(); }, 1); }); }); test("Test direct RDFa collection", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-collection-twotemplates'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { var mainEntity = z.entities.get('<http://example.net/mycollection>'); ok(mainEntity.isEntity); var collection = mainEntity.get('section'); ok(collection.isCollection); equal(collection.length, 2); equal(collection.at(0).get('title'), 'Content'); equal(jQuery('div[about]', html).length, 3); equal(jQuery('h1', html).length, 1); equal(jQuery('h2', html).length, 1); collection.add({ '@type': 'first' }); equal(collection.length, 3); equal(jQuery('h1', html).length, 2); equal(jQuery('h2', html).length, 1); collection.remove(collection.at(2)); equal(collection.length, 2); equal(jQuery('h1', html).length, 1); collection.add({ '@type': 'second' }); equal(collection.length, 3); equal(jQuery('h2', html).length, 2); start(); }); }); test("Test RDFa datatype parsing", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-datatypes'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { var entity = z.entities.get('<http://example.net/datatypes>'); ok(_.isBoolean(entity.get('boolean'))); ok(_.isBoolean(entity.get('boolean2'))); equal(entity.get('boolean'), false); equal(entity.get('boolean2'), true); ok(_.isDate(entity.get('date'))); equal(entity.get('date').getFullYear(), 2012); ok(_.isNumber(entity.get('number'))); equal(entity.get('number'), 123); // Test writing as well equal(jQuery('[property="boolean"]', html).attr('content'), 'false'); entity.set('boolean', true); equal(jQuery('[property="boolean"]', html).attr('content'), 'true'); entity.set('date', new Date('1999-05-08T21:00:01Z')); equal(jQuery('[property="date"]', html).attr('content'), '1999-05-08T21:00:01.000Z'); entity.set('number', 42); equal(jQuery('[property="number"]', html).text(), '42'); start(); }); }); test("Test multiple RDFa instances of same entity", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-twoinstances'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { // Freshly parsed, there should be no recorded changes in the entity var entity = z.entities.get('<http://example.net/example>'); equal(entity.changedAttributes(), false); equal(entity.hasChanged('<http://purl.org/dc/terms/description>'), false); // Change one value, now changes should be recorded entity.set('dcterms:description', 'Baz'); equal(entity.get('<http://purl.org/dc/terms/description>'), 'Baz'); equal(entity.hasChanged('<http://purl.org/dc/terms/description>'), true); start(); }); }); test("Test anonymous relation", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-anonrelation'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { start(); var entity = z.entities.get('<http://example.net/example>'); ok(entity); equal(entity.get('dcterms:title'), 'Foo'); var relations = entity.get('relations'); equal(relations.length, 1); equal(relations.at(0).get('dcterms:title'), 'Bar'); }); }); test("Test deep relations", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-deeprelation'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { start(); var entity = z.entities.get('<http://example.net/example>'); ok(entity); equal(entity.get('dcterms:title'), 'Foo'); equal(jQuery('div[about]', html).length, 3); var relations = entity.get('relations'); equal(relations.length, 1); var first = relations.at(0); equal(first.get('dcterms:title'), 'Bar'); equal(jQuery('[rel="relations"] > div[about]', html).length, 1); relations.add({ 'dcterms:title': 'BarFoo' }); equal(relations.length, 2); equal(relations.at(1).get('dcterms:title'), 'BarFoo'); equal(jQuery('[rel="relations"] > div[about]', html).length, 2); equal(jQuery('div[property]', jQuery('[rel="relations"] > div[about]', html).get(1)).html(), 'BarFoo'); relations.at(1).set('dcterms:title', 'BarFooBaz'); equal(jQuery('div[property]', jQuery('[rel="relations"] > div[about]', html).get(1)).html(), 'BarFooBaz'); relations.remove(relations.at(1)); equal(relations.length, 1); equal(jQuery('[rel="relations"] > div[about]', html).length, 1); equal(jQuery('[rel="relations"] > div[about] div[property]', html).html(), 'Bar'); var subrelations = first.get('subrelations'); equal(subrelations.length, 1); var second = subrelations.at(0); equal(second.get('dcterms:title'), 'Baz'); equal(jQuery('[rel="subrelations"] div[about]', html).length, 1); subrelations.add({ 'dcterms:title': 'BazFoo' }); equal(subrelations.length, 2); equal(jQuery('[rel="subrelations"] div[about]', html).length, 2); equal(jQuery('div[property]', jQuery('[rel="subrelations"] div[about]', html).get(1)).html(), 'BazFoo'); subrelations.at(1).set('dcterms:title', 'BazFooBar'); equal(jQuery('div[property]', jQuery('[rel="subrelations"] > div[about]', html).get(1)).html(), 'BazFooBar'); subrelations.remove(subrelations.at(1)); equal(subrelations.length, 1); equal(jQuery('[rel="subrelations"] div[about]', html).length, 1); equal(jQuery('[rel="subrelations"] > div[about] div[property]', html).html(), 'Baz'); }); }); test("Test local namespace declaration", function () { var z = new VIE(); z.use(new z.RdfaService()); var html = jQuery('#qunit-fixture .rdfa-localns'); stop(); z.load({element: html}).from('rdfa').execute().done(function (entities) { start(); ok(entities.length); var entity = z.entities.at(0); ok(entity); ok(entity.isof('foo:Bar')); equal(entity.get('foo:Baz'), 'Foo'); }); }); <file_sep>(function(){ var entity = undefined; /* JSLitmus.test('Type: register + unregister new type', function() { var newPersonType = new VIE2.Type('PersonWithAge', 'Person', [ {id : 'age', datatype : 'Integer' }], {}); VIE2.unregisterType('PersonWithAge'); }); JSLitmus.test('Model: create without props', function() { new VIE2.Entity(); }); JSLitmus.test('Model: create with props', function() { entity = new VIE2.Entity({ a: 'Person', name : '<NAME>', description : 'This is a test' }); }); JSLitmus.test('Model: change props', function() { entity.set({ name: '<NAME>', description : ['This is a test', 'This is another test'] }); }); */ })();<file_sep>VIE ChangeLog ============= ## 2.2.0 (January 21st 2015) * Use dependencies from Bower * Minor fixes regarding updated dependencies ## 2.1.2 (September 10th 2013) * Namespace registration is now less strict, allowing multiple prefixes pointing to same URI ## 2.1.1 (September 10th 2013) * `VIE.Entity` was refactored to use regular Backbone Model semantics, allowing it to be [extended as needed](https://groups.google.com/d/topic/viejs/Chg-sO7dw6s/discussion) * Default [Apache Stanbol](http://stanbol.apache.org/) configuration was swithed to use the IKS-hosted [demo server](http://demo.iks-project.eu/stanbolfull) * Compatibility with Backbone.js 1.0.0 * Build system was switched from Ant to [Grunt](http://gruntjs.com) * Dependencies moved to using Bower ## 2.1.0 (December 5th 2012) See the [release announcement](https://groups.google.com/d/topic/viejs/RYKfp0Fhuag/discussion). ## 2.0.0 (April 25th 2012) See the [introductory blog post](http://blog.iks-project.eu/vie-towards-v2-0-update/).
0441a48f7d6c7f321e84a8a26a48ab464eab3670
[ "JavaScript", "Markdown" ]
6
JavaScript
enterstudio/VIE
78f989e65e96f8982257bfc33f19f81dce89d691
30559309ffb20628d491f6611497de660648989a
refs/heads/master
<repo_name>Rayyz47/Prog_2019<file_sep>/Exemple DLL/DemoDll/DemoDll/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using DLL_VB; using Dll_cSharpe; namespace DemoDll { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { DLL dllCSharpe = new DLL(); Class1 dllVB = new Class1(); decimal nb1 = dllCSharpe.validationNumber(txtNb1.Text); decimal nb2 = dllCSharpe.validationNumber(txtNb2.Text); decimal nb3 = dllCSharpe.validationNumber(txtNb3.Text); decimal nb4 = dllCSharpe.validationNumber(txtNb4.Text); nb1 = dllVB.add(nb1, nb2); nb3 = dllVB.add(nb3, nb4); txtResult.Text = dllVB.add(nb1, nb3).ToString(); clean(); } private void clean() { txtNb1.Text = ""; txtNb2.Text = ""; txtNb3.Text = ""; txtNb4.Text = ""; } } } <file_sep>/programme_Vierge/cCat.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { class cCat : cAnimal { // recoir en parametre commbien de legs le chats a dans ce cas ci c est 4 public cCat() : base(4) { } //Cette void override la void Talk pour donner une specificiter a comment un chat parle public override void Talk() { frmPoly2.affichageTotal += ("Miow \r\n"); } //Cette void override la void virtuel Eat pour donner une specificiter a comment un chat mange public override void Eat() { frmPoly2.affichageTotal += ($"{Name} eats a fancy meal. \r\n"); } } } <file_sep>/programme_Vierge/cGermanShepard.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace programme_Vierge { class cGermanShepard : cDog { } } <file_sep>/programme_Vierge/frmAccueilPoly.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { public partial class frmAccueilPoly : Form { string name = ""; string content = ""; string dateToDisplay = ""; public frmAccueilPoly() { InitializeComponent(); } private void btnInfoPoly_Click(object sender, EventArgs e) { cPolymorphismInfos poly = new cPolymorphismInfos(); poly.isAuthor(); name = poly.nameChild; this.txtAuthor.Text = name; poly.isContent(); content = poly.contentChild; txtContent.Text = content; poly.isDate(); dateToDisplay = poly.dateEntryChild.ToString(); txtDate.Text = dateToDisplay; string txtboxTitle = txtTitle.Text; if (poly.IsTitle(txtboxTitle)) { MessageBox.Show(txtboxTitle); this.BackColor = Color.Gray; } else { MessageBox.Show("Veuillez entrer des lettres uniquement!"); this.BackColor = Color.GreenYellow; } } private void btnInterface_Click(object sender, EventArgs e) { cInterface interFace = new cInterface(); interFace.isAuthor(); name = interFace.nameChild; txtAuthor.Text = name; interFace.isContent(); content = interFace.contentChild; txtContent.Text = content; interFace.isDate(); dateToDisplay = interFace.dateEntryChild.ToString(); txtDate.Text = dateToDisplay; } private void btnInfoDll_Click(object sender, EventArgs e) { cDllInfos dllinfos = new cDllInfos(); dllinfos.isAuthor(); name = dllinfos.nameChild; txtAuthor.Text = name; dllinfos.isContent(); content = dllinfos.contentChild; txtContent.Text = content; dllinfos.isDate(); dateToDisplay = dllinfos.dateEntryChild.ToString(); txtDate.Text = dateToDisplay; } private void btnInfoGitGithub_Click(object sender, EventArgs e) { cGit git = new cGit(); git.isAuthor(); name = git.nameChild; txtAuthor.Text = name; git.isContent(); content = git.contentChild; txtContent.Text = content; git.isDate(); dateToDisplay = git.dateEntryChild.ToString(); txtDate.Text = dateToDisplay; string txtboxTitle = txtTitle.Text; if (git.IsTitle(txtboxTitle)) { MessageBox.Show(txtboxTitle); this.BackColor = Color.Blue; } else { MessageBox.Show("Veuillez entrer des lettres uniquement!"); this.BackColor = Color.Fuchsia; } } } } <file_sep>/programme_Vierge/cTemplateInfos.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace programme_Vierge { public abstract class cTemplateInfos { /// <summary> /// -- Ces 4 éléments seront envoyés aux héritiers /// </summary> /// <returns></returns> public abstract string isAuthor(); public abstract string isContent(); public abstract int isDate(); /// <summary> /// Must start with an alphabetic character. Can contain the following characters: a-z A-Z 0-9 - and _ /// </summary> /// <param name="titleEntry">Entrée de titre à valider</param> /// <returns>bool</returns> public virtual bool IsTitle(string titleEntry) { Regex validEntry = new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$"); Match match = validEntry.Match(titleEntry); if (match.Success) { return true; } return false; } } } <file_sep>/programme_Vierge/cAnimal.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { public abstract class cAnimal { //ici est envoiyer le nom qu on a mis dans le formulaire qui est lue public string Name; public int NumberOfLegs { get; } public cAnimal(int numberOfLegs) { NumberOfLegs = numberOfLegs; } //Void abstract pour dire que l animal parle public abstract void Talk(); //Une void virtuel pour dire que l animal mange donc le nom de l animal avec la caracterisque de manger public virtual void Eat() { frmPoly2.affichageTotal+=($"{Name} eats! \r\n"); } } } <file_sep>/programme_Vierge/cGit.cs namespace programme_Vierge { class cGit : cTemplateInfos { /// <summary> /// -- Variables publiques contenues dans la classe enfant uniquement. Leurs valeurs seront attribuées par les éléments /// hérités du parent /// </summary> public string nameChild = ""; public string contentChild = ""; public int dateEntryChild = 0; /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> string de nom</returns> public override string isAuthor() { nameChild = "<NAME>"; return nameChild; } public override string isContent() { contentChild = "gitgitgitgit"; return contentChild; } /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> Int représentant la date</returns> public override int isDate() { dateEntryChild = 20190409; return dateEntryChild; } } } <file_sep>/programme_Vierge/frmAccueil.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { public partial class frmAccueil : Form { public frmAccueil() { InitializeComponent(); } private void btnToPoly_Click(object sender, EventArgs e) { frmAccueilPoly poly = new frmAccueilPoly(); poly.Show(); } private void button1_Click(object sender, EventArgs e) { frmInterface frm = new frmInterface(); frm.Show(); Hide(); } private void button2_Click(object sender, EventArgs e) { frmPoly2 frm = new frmPoly2(); frm.ShowDialog(); } } } <file_sep>/programme_Vierge/cSnake.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { class cSnake : cAnimal { // recoit en parametre commbien de legs le serpant a dans ce cas ci c est 0 public cSnake() : base(0) { } //Cette void override la void Talk pour donner une specificiter a comment un serpant parle public override void Talk() { frmPoly2.affichageTotal += ("Hissssss \r\n"); } } } <file_sep>/Exemple DLL/DLL_cSharpe/Dll_cSharpe/DLL.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dll_cSharpe { public class DLL { /// <summary> /// Envoye un texte en paramettre et verifie si le texte contien ou est un nombre si oui retounre le nombre en question /// </summary> /// <param name="textToVal">String</param> /// <returns>Decimal</returns> public decimal validationNumber(string textToVal) { //Declare le nombre qui va etre retourner decimal number; //Verifie si le texte envoyer est bien un nombre bool success = decimal.TryParse(textToVal, out number); //Si oui on retourne le nombre en question if (success) { return number; } //Si non on retourne 0 pour eviter que le code plante else { return 0;} } /// <summary> /// Recois 2 nombre et retourne le resultat de ces deux nombres additionnés /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <returns>Decimal</returns> //Fonction de retour d'addition possibliter de surcharge jusqu'a un maximum de 4 nombres public decimal add(decimal nb1, decimal nb2) { //Declare le nombre qui va etre retourner et effectue l'addition decimal number = nb1 + nb2; //Retourne le resulat return number; } /// <summary> /// Recois 3 nombre et retourne le resultat de ces deux nombres additionnés /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <param name="nb3">Decimal</param> /// <returns>Decimal</returns> public decimal add(decimal nb1, decimal nb2, decimal nb3) { //Declare le nombre qui va etre retourner et effectue l'addition decimal number = nb1 + nb2 + nb3; //Retourne le resulat return number; } /// <summary> /// Recois 4 nombre et retourne le resultat de ces deux nombres additionnés /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <param name="nb3">Decimal</param> /// <param name="nb4">Decimal</param> /// <returns>Decimal</returns> public decimal add(decimal nb1, decimal nb2, decimal nb3, decimal nb4) { //Declare le nombre qui va etre retourner et effectue l'addition decimal number = nb1 + nb2 + nb3 + nb4; //Retourne le resulat return number; } /// <summary> /// Recois 2 nombre et retourne le resultat de ces deux nombres sustrais /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <returns>Decimal</returns> public decimal sustraction(decimal nb1, decimal nb2) { //Declare le nombre qui va etre retourner et effectue la sustraction decimal number = nb1 - nb2; //Retourne le resulat return number; } /// <summary> /// Recois 2 nombre et retourne le resultat de ces deux nombres sustrais /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <param name="nb3">Decimal</param> /// <returns>Decimal</returns> public decimal sustraction(decimal nb1, decimal nb2, decimal nb3) { //Declare le nombre qui va etre retourner et effectue la sustraction decimal number = nb1 - nb2 - nb3; //Retourne le resulat return number; } /// <summary> /// Recois 2 nombre et retourne le resultat de ces deux nombres sustrais /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <param name="nb3">Decimal</param> /// <param name="nb4">Decimal</param> /// <returns>Decimal</returns> public decimal sustraction(decimal nb1, decimal nb2, decimal nb3, decimal nb4) { //Declare le nombre qui va etre retourner et effectue la sustraction decimal number = nb1 - nb2 - nb3 - nb4; //Retourne le resulat return number; } /// <summary> /// Recois 2 nombre et retourne le resultat de ces deux nombres multiplier /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <returns>Decimal</returns> public decimal multi(decimal nb1, decimal nb2) { //Declare le nombre qui va etre retourner et effectue la multiplication decimal number = nb1 * nb2; //Retourne le resulat return number; } /// <summary> /// Recois 3 nombre et retourne le resultat de ces deux nombres multiplier /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <param name="nb3">Decimal</param> /// <returns>Decimal</returns> public decimal multi(decimal nb1, decimal nb2, decimal nb3) { //Declare le nombre qui va etre retourner et effectue la multiplication decimal number = nb1 * nb2 * nb3; //Retourne le resulat return number; } /// <summary> /// Recois 4 nombre et retourne le resultat de ces deux nombres multiplier /// </summary> /// <param name="nb1">Decimal</param> /// <param name="nb2">Decimal</param> /// <param name="nb3">Decimal</param> /// <param name="nb4">Decimal</param> /// <returns>Decimal</returns> public decimal multi(decimal nb1, decimal nb2, decimal nb3, decimal nb4) { //Declare le nombre qui va etre retourner et effectue la multiplication decimal number = nb1 * nb2 * nb3 * nb4; //Retourne le resulat return number; } //Créer un random pour le carathère bidon public static Random rnd = new Random(); /// <summary> /// Recois du texte et retourne le texte crypter /// </summary> /// <param name="textToCrypt">String</param> /// <returns>String</returns> public string cryptSimple(string textToCrypt) { //Decalare la variable qui va contenir le texte crypter c'est cette variable qui est returnée string textCrypt = ""; //Pour chaque caratère change le caratère pour un autre aléatoire foreach (char item in textToCrypt) { //Change le caratère pour le meme caratère avec un code ascii augmenter de 6 textCrypt += Convert.ToChar(item + 6); //Crée un code bidon textCrypt += Convert.ToChar(rnd.Next(43, 90)); } return textCrypt; } /// <summary> /// Recois du texte crypter et retoure le texte decryptés /// </summary> /// <param name="textToUnCrypt"></param> /// <returns></returns> public string unCryptSimple(string textToUnCrypt) { //L'index pour recuperer les bon caratère int index = 2; //Contien le texte décripter cette variable est retourner string textUnCrypt = ""; foreach (char item in textToUnCrypt) { //Quand l'index est paire (donc pas le caratere bidon) on l'ajoute au texte en diminuant de 6 son code ascii if (index % 2 == 0) { textUnCrypt += Convert.ToChar(item - 6);} //Augmente l'index a la main index++; } //retourne le texte décrypter return textUnCrypt; } } } <file_sep>/programme_Vierge/frmInterface.cs using System; using System.Windows.Forms; namespace programme_Vierge { public partial class frmInterface : Form { public frmInterface() { InitializeComponent(); } //Retourne au menu de choix private void button1_Click(object sender, EventArgs e) { frmAccueil frm = new frmAccueil(); frm.Show(); Close(); } //bouton qui Instensie l'interface et affiche le resultat private void btnBTN_Click(object sender, EventArgs e) { //Instensiation de l'interface Mot inter = new Mot(); //Affiche le retour de l'interface mot MessageBox.Show(inter.motInterface()); } private void btnBTN3_Click(object sender, EventArgs e) { //Instensiation de l'interface interFinal inter = new interFinal(); //Affiche le retour de l'interface mot MessageBox.Show(inter.motInterface()); //Affiche le retour de l'interface int MessageBox.Show(inter.intInterface().ToString()); //Affiche le retour de l'interface de validation MessageBox.Show(inter.valide().ToString()); } private void btnBTN2_Click(object sender, EventArgs e) { //Instensiation de l'interface nombre inter = new nombre(); //Affiche le retour de l'interface int MessageBox.Show(inter.intInterface().ToString()); } } } <file_sep>/programme_Vierge/cDog.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { class cDog: cAnimal { public cDog() : base(4) { } //Cette void override la void Talk pour donner une specificiter a comment un chat parle public override void Talk() { frmPoly2.affichageTotal += ("Woof! \r\n"); } public void Guard() { MessageBox.Show("The dog guards the house!"); } } } <file_sep>/programme_Vierge/frmPoly2.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace programme_Vierge { public partial class frmPoly2 : Form { public static string affichageTotal = ""; public frmPoly2() { InitializeComponent(); } private void btnExect_Click(object sender, EventArgs e) { //Creation d'une liste d'animals List<cAnimal> animals = new List<cAnimal>(); cCat monChat = new cCat(); //LE chat a un nom qui es envoiyer dans la classe animal dans name monChat.Name = "Roger"; //Ajouter dans la liste de forme animals.Add(monChat); cSnake monSerpent = new cSnake(); //LE Serpant a un nom qui es envoiyer dans la classe animal dans name monSerpent.Name = "<NAME>"; //Ajouter dans la liste de forme animals.Add(monSerpent); cDog monChien = new cDog(); //LE chien a un nom qui es envoiyer dans la classe animal dans name monChien.Name = "Rex"; //Console.WriteLine(monChien.CapitalizedName); cGermanShepard monChienPolicier = new cGermanShepard(); //LE GermanSherperd a un nom qui es envoiyer dans la classe animal dans name monChienPolicier.Name = "<NAME>"; //Ajouter dans la liste de forme animals.Add(monChienPolicier); //Ajouter dans la liste de forme animals.Add(monChien); //For each pour resortire le resultat de tout les animaux dans la liste avec l action que nous desirons decouvrire // dans ce cas ci c est juste eat et talk. foreach (var animal in animals) { animal.Eat(); animal.Talk(); } MessageBox.Show(affichageTotal); } private void button1_Click(object sender, EventArgs e) { cCat monChat = new cCat(); cSnake monSerpent = new cSnake(); cDog monChien = new cDog(); monChat.Name = "Roger"; monSerpent.Name = "<NAME>"; monChien.Name = "Rex"; //Ici on appelle la void MakeAnimalEat pis on lui envoiye l animal en parametre pour resortire le resultat MakeAnimalEat(monChien); MessageBox.Show(affichageTotal); affichageTotal = ""; MakeAnimalEat(monChat); MessageBox.Show(affichageTotal); affichageTotal = ""; MakeAnimalEat(monSerpent); MessageBox.Show(affichageTotal); affichageTotal = ""; } public void MakeAnimalEat(cAnimal animal) { //D'ici on ressort que ce qu on veux de animal dans ce cas ci c est eat animal.Eat(); } } } <file_sep>/programme_Vierge/cPolymorphismInfos.cs namespace programme_Vierge { class cPolymorphismInfos : cTemplateInfos { /// <summary> /// -- Variables publiques contenues dans la classe enfant uniquement. Leurs valeurs seront attribuées par les éléments /// hérités du parent /// </summary> public string nameChild = ""; public string contentChild = ""; public int dateEntryChild = 0; /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> string de nom</returns> public override string isAuthor() { nameChild = "Marie-Pier et Denis"; return nameChild; } /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> Contenu de l'article</returns> public override string isContent() { contentChild = "Polymorphisme"; return contentChild; } /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns>int représentant la date</returns> public override int isDate() { dateEntryChild = 20190408; return dateEntryChild; } /// <summary> /// -- Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais peut choisit /// de l'utiliser ou pas car il est virtual /// </summary> /// <returns> string de titre</returns> public override bool IsTitle(string titleEntry) { return base.IsTitle(titleEntry); } } }<file_sep>/programme_Vierge/cInterfaceAlex.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace programme_Vierge { //L'interface StringRand contiens une string interface StringRand { string motInterface(); } //L'interface IntRand contiens un int interface IntRand { int intInterface(); } //L'interface contiens plusieurs Variable interface MultipleVariable { string motInterface(); bool valide(); int intInterface(); } //La classe genere un string contenant les numeros 0 a 10 et les retourne dans la variable de l'interface class Mot : StringRand { public string motInterface() { string str = ""; for (int i = 0; i < 11; i++) { str += i.ToString() + Environment.NewLine; } return str; } } //La classe genere un int de 100 a 7000000 et le retourne dans le int de l'interface class nombre : IntRand { public int intInterface() { Random rnd = new Random(); int rtn = rnd.Next(100, 7000000); return rtn; } } //Une classe peux avoir plusieur interface tent que chaqu'une de variable se trouvant dans les interface recupère une valeur class interFinal : MultipleVariable, IntRand, StringRand { //cette string est dans l'interface MultipleVaraible et StringRand public string motInterface() { string str = ""; for (int i = 0; i < 11; i++) { str += i.ToString() + Environment.NewLine; } return str; } //Ce int est dans l'interface MultipleVaraible et intInterface public int intInterface() { Random rnd = new Random(); int rtn = rnd.Next(100, 7000000); return rtn; } //Ce bool est dans l'interface MultipleVaraible seulemeent public bool valide() { bool tst = true; tst = false; return tst; } } } <file_sep>/programme_Vierge/cInterface.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace programme_Vierge { class cInterface : cTemplateInfos { /// <summary> /// -- Variables publiques contenues dans la classe enfant uniquement. Leurs valeurs seront attribuées par les éléments /// hérités du parent /// </summary> public string nameChild = ""; public string contentChild = ""; public int dateEntryChild = 0; /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> string de nom</returns> public override string isAuthor() { nameChild = "Alexandre"; return nameChild; } /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> string de contenu</returns> public override string isContent() { contentChild = "Interface"; return contentChild; } /// <summary> /// --Hérite de la classe template qui est son parent. L'enfant pourra la modifier à sa guise mais doit l'avoir /// </summary> /// <returns> Int représentant la date</returns> public override int isDate() { dateEntryChild = 20190409; return dateEntryChild; } interface StringRand { string motInterface(); } //L'interface IntRand contiens un int interface IntRand { int intInterface(); } //L'interface contiens plusieurs Variable interface MultipleVariable { string motInterface(); bool valide(); int intInterface(); } } }
63755b067fd0d7d93a623f6ac003b292ba5fd382
[ "C#" ]
16
C#
Rayyz47/Prog_2019
a848f308fcc70c043a136f58884781a911064686
3610b96ad2249b1fd42a90779385526cc2d727ff
refs/heads/master
<file_sep>import sys import os import numpy as np import matplotlib.pyplot as plt alpha1,alpha2,alpha3 = np.loadtxt('ALPHA_AMP_values_V.txt',usecols=(1,2,3)).T kalpha1,kalpha2,kalpha3 = np.loadtxt('Kate_ALPHA_AMP_values_V.txt',usecols=(1,2,3)).T print '#Inf in Alpha 1: {}'.format(len(np.isnan(alpha1)==0)) print '#Inf in Alpha 2: {}'.format(len(np.isnan(alpha2)==0)) print '#Inf in Alpha 3: {}'.format(len(np.isnan(alpha3==0))) print '#Inf in Kate Alpha 1: {}'.format(len(np.isnan(kalpha1)==0)) print '#Inf in Kate Alpha 2: {}'.format(len(np.isnan(kalpha2)==0)) print '#Inf in Kate Alpha 3: {}'.format(len(np.isnan(kalpha3)==0)) print len(np.isnan(alpha2) ) #alpha1 = alpha1[~np.isnan(alpha2)] #alpha2 = alpha2[~np.isnan(alpha2)] #alpha3 = alpha3[~np.isnan(alpha2)] # xx=np.where(np.isnan(alpha2)) alpha1=np.delete(alpha1,xx) alpha2=np.delete(alpha2,xx) alpha3=np.delete(alpha3,xx) kalpha1=np.delete(kalpha1,xx) kalpha2=np.delete(kalpha2,xx) kalpha3=np.delete(kalpha3,xx) #kalpha1 = alpha1[~np.isnan(alpha2)] #kalpha2 = alpha2[~np.isnan(alpha2)] #kalpha3 = alpha3[~np.isnan(alpha2)] n_bins = 50 fig,(ax0,ax1,ax2) = plt.subplots(1,3,figsize=(15,8)) n1, bins1, patches1 = ax0.hist(kalpha1, n_bins,color='red', normed=0, histtype='step', label='Kate ALPHA') n, bins, patches = ax0.hist(alpha1, bins1,color='blue', normed=0, histtype='step', label='My ALPHA') nn1, nbins1, npatches1 = ax1.hist(kalpha2, n_bins,color='red', normed=0, histtype='step', label='Kate ALPHA') nn, nbins, npatches = ax1.hist(alpha2, nbins1,color='blue', normed=0, histtype='step', label='My ALPHA') nnn1, nnbins1, nnpatches1 = ax2.hist(kalpha3, n_bins,color='red', normed=0, histtype='step', label='Kate ALPHA') nnn, nnbins, nnpatches = ax2.hist(alpha3, nnbins1,color='blue', normed=0, histtype='step', label='My ALPHA') ax0.set_xlabel('ALPHA 1') ax1.set_xlabel('ALPHA 2') ax2.set_xlabel('ALPHA 3') ax0.set_ylabel('Histogram Density') ax1.set_ylabel('Histogram Density') ax2.set_ylabel('Histogram Density') ax0.legend(loc=2) ax0.set_title('Comparison of Kate\'s and Vivek\'s Continuum Fitting ') fig.tight_layout() fig.savefig('Continuumfitting_comparison_V.png') plt.show() <file_sep>import sys import os import numpy as np from astropy import io from astropy.io import fits from astropy.io import ascii from matplotlib import pyplot as plt from astropy import constants as const from astropy import units as U from astropy.coordinates import SkyCoord from dustmaps.sfd import SFDQuery from specutils import extinction import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from scipy.optimize import curve_fit from matplotlib.backends.backend_pdf import PdfPages from lmfit import minimize, Parameters from astropy.modeling.models import Voigt1D def dered_flux(Av,wave,flux): dered_flux = np.zeros(len(wave)) for i in range(len(wave)): ext_lambda= extinction.extinction_ccm89(wave[i] * U.angstrom, a_v= Av, r_v= 3.1) tau_lambda= ext_lambda/(1*1.086) dered_flux[i]= flux[i] * np.exp(tau_lambda) return dered_flux def myVoigt(x, amp, center, fwhm_l, fwhm_g, scale, alpha): v1= Voigt1D(x_0=center, amplitude_L=amp, fwhm_L=fwhm_l, fwhm_G=fwhm_g) powerlaw = scale*x**alpha voigt = v1(x) voigt_tot = (voigt+powerlaw) return voigt_tot def myGaussHermite(x, amp, center, sig, skew, kurt, scale, alpha): c1=-np.sqrt(3); c2=-np.sqrt(6); c3=2/np.sqrt(3); c4=np.sqrt(6)/3; c5=np.sqrt(6)/4 gausshermite = amp*np.exp(-.5*((x-center)/sig)**2)*(1+skew*(c1*((x-center)/sig)+c3*((x-center)/sig)**3)+kurt*(c5+c2*((x-center)/sig)**2+c4*((x-center)/sig)**4)) powerlaw = scale*x**alpha gaustot_gh = (gausshermite+powerlaw) return gaustot_gh def myDoubleGauss(x, amp1, center1, sig1, amp2, center2, sig2, scale, alpha): gaus1=amp1*np.exp(-.5*((x-center1)/sig1)**2) gaus2=amp2*np.exp(-.5*((x-center2)/sig2)**2) powerlaw = scale*x**alpha gaustot_2g= (gaus1+gaus2+powerlaw) return gaustot_2g def ext_coeff(lamb): inv_lamba=[0.45,0.61,0.8,1.82,2.27,2.7,3.22,3.34,3.46,3.6,3.75,3.92,4.09,4.28,4.50,4.73,5.00,5.24,5.38,5.52,5.70,5.88,6.07,6.27,6.48,6.72,6.98,7.23,7.52,7.84] smc_ext=[-2.61,-2.47,-2.12,0.0,1.0,1.67,2.29,2.65,3.0,3.15,3.49,3.91,4.24,4.53,5.3,5.85,6.38,6.76,6.9,7.17,7.71,8.01,8.49,9.06,9.28,9.84,10.8,11.51,12.52,13.54] xy=np.interp(1.0/(lamb*10**(-4)),inv_lamba,smc_ext) ext_lamb=(xy+2.98)/3.98 # Rv=2.98 #return(z,ext_lamb) return(ext_lamb) def myfunct(wave, a , b): return a*ext_coeff(wave)*wave**(b) def waveRange(wave): #wav_range=[[1300.,1350.],[1420.,1470.],[1700.,1800.],[2080.,2215],[2480.,2655],[3225.,3900.],[4200.,4230.],[4435.,4700.],[5200.,5700.]] wav_range= [(1400,1850)] mwav_range = [] for rr in wav_range: if ((np.min(wave) < rr[0]) & (np.max(wave) > rr[1])): nrr0 = rr[0] ; nrr1 = rr[1] elif ((np.min(wave) > rr[0]) & (np.min(wave) < rr[1])& (np.max(wave) < rr[1])): nrr0 = np.min(wave) ; nrr1 = rr[1] elif ((np.min(wave) < rr[0]) & (np.max(wave) > rr[0]) &(np.max(wave) < rr[1])): nrr0 = rr[0] ; nrr1 = np.max(wave) else : continue mwav_range.append([nrr0,nrr1]) return mwav_range def compute_alpha_voigt(wl, spec, ivar, wav_range, per_value=[1,99.5]): print ' Voigt Routine begins' spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 print ivar wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec #print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print 'voigt Debug',len(wavelength) pv0=[1.0, 1545., 50., 8.0,1.0,1.0] param_boundsv = ([0,1540,0.0,0.0,0.0,-np.inf],[np.inf,1550,np.inf,20,np.inf,np.inf]) try: #plt.plot(wavelength,spectra) #plt.show() poptv, pcovv = curve_fit(myVoigt, wavelength, spectra, pv0, sigma=1.0/np.sqrt(invar),bounds=param_boundsv) except (RuntimeError, TypeError): AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv, CHISQv, DOFv = np.nan, np.nan, np.nan, np.nan,np.nan, np.nan, np.nan, np.nan else: AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv = poptv[0], poptv[1], poptv[2], poptv[3], poptv[4], poptv[5] CHISQv = np.sum(invar * (spectra - myVoigt(wavelength, poptv[0], poptv[1], poptv[2], poptv[3], poptv[4], poptv[5]))**2) # DOF = N - n , n = 2 DOFv = len(spectra) - 6 print 'Voight Routine ends' print 'Compute Alpha:', AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv, CHISQv, DOFv return AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv, CHISQv, DOFv def compute_alpha_gh(wl, spec, ivar, wav_range, per_value=[1,99.5]): print ' GH Routine begins' spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 print ivar wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print '2H Debug',len(wavelength) pgh0=[1.0, 1545., 8., 0.2, 0.4,1.0,1.0] param_boundsgh = ([0,1540,-20,-np.inf,-np.inf,0,-np.inf],[np.inf,1555,20,np.inf,np.inf,np.inf,np.inf]) try: #plt.plot(wavelength,spectra) #plt.show() poptgh, pcovgh = curve_fit(myGaussHermite, wavelength, spectra, pgh0, sigma=1.0/np.sqrt(invar),bounds=param_boundsgh) except (RuntimeError, TypeError): AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh, SCALEgh, ALPHAgh, CHISQgh, DOFgh = np.nan, np.nan, np.nan, np.nan,np.nan, np.nan, np.nan, np.nan, np.nan else: AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh, SCALEgh, ALPHAgh = poptgh[0], poptgh[1], poptgh[2], poptgh[3], poptgh[4], poptgh[5], poptgh[6] CHISQgh = np.sum(invar * (spectra - myGaussHermite(wavelength, poptgh[0], poptgh[1], poptgh[2], poptgh[3], poptgh[4], poptgh[5], poptgh[6]))**2) # DOF = N - n , n = 2 DOFgh = len(spectra) - 7 print 'GH Routine ends' print 'Compute Alpha:', AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh,SCALEgh, ALPHAgh, CHISQgh, DOFgh return AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh,SCALEgh, ALPHAgh, CHISQgh, DOFgh def compute_alpha_2g(wl, spec, ivar, wav_range, per_value=[1,99.5]): print '2G Routine begins' spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print '2G Debug',len(wavelength) pg20=[1.0, 1545., 8., 1.0, 1550., 54.,1.0,1.0] param_bounds2g = ([0,1540,0,0,1540,-np.inf,-np.inf,-np.inf],[np.inf,1555,np.inf,np.inf,1555,np.inf,np.inf,np.inf]) try: #plt.plot(wavelength,spectra) #plt.show() popt2g, pcov2g = curve_fit(myDoubleGauss, wavelength, spectra, pg20, sigma=1.0/np.sqrt(invar),bounds=param_bounds2g) except (RuntimeError, TypeError): AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g, CHISQ2g, DOF2g = np.nan, np.nan, np.nan, np.nan,np.nan, np.nan, np.nan, np.nan, np.nan, np.nan else: AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g = popt2g[0], popt2g[1], popt2g[2], popt2g[3], popt2g[4], popt2g[5], popt2g[6], popt2g[7] CHISQ2g = np.sum(invar * (spectra - myDoubleGauss(wavelength, popt2g[0], popt2g[1], popt2g[2], popt2g[3], popt2g[4], popt2g[5], popt2g[6], popt2g[7]))**2) # DOF = N - n , n = 2 DOF2g = len(spectra) - 8 print '2G Routine ends' print 'Compute Alpha:' ,AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g, CHISQ2g, DOF2g return AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g, CHISQ2g, DOF2g def maskOutliers_v(wave, flux, weight, amp, center, sigmal, sigmag, scale, alpha): model = myVoigt(wave,amp, center, sigmal, sigmag, scale, alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model print 'Weights Before mask',weight #ww = np.where (np.abs(fluxdiff) > 3*std) ww = np.where (((np.abs(fluxdiff) > 2*std) & (flux <= np.median(flux))) | ((np.abs(fluxdiff) > 4*std) & (flux >= np.median(flux)))) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) print 'Weights After mask',weight return wave,flux,weight def maskOutliers_gh(wave, flux, weight, amp, center, sigma, skew, kurt, scale, alpha): model = myGaussHermite(wave,amp, center, sigma, skew, kurt, scale, alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model print 'Weights Before mask',weight #ww = np.where (np.abs(fluxdiff) > 3*std) ww = np.where (((np.abs(fluxdiff) > 2*std) & (flux <= np.median(flux))) | ((np.abs(fluxdiff) > 4*std) & (flux >= np.median(flux)))) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) print 'Weights After mask',weight return wave,flux,weight def maskOutliers_2g(wave,flux,weight,amp1,center1,sigma1,amp2,center2,sigma2,scale,alpha): model = myDoubleGauss(wave,amp1,center1,sigma1,amp2,center2,sigma2,scale,alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model #ww = np.where (np.abs(fluxdiff) > 3*std) ww = np.where (((np.abs(fluxdiff) > 2*std) & (flux <= np.median(flux))) | ((np.abs(fluxdiff) > 4*std) & (flux >= np.median(flux)))) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) return wave,flux,weight def minmax(vec): return min(vec),max(vec) #Version _ Tried small sigma values for both Gaussians in GausDouble and GausHermite #Version II Tried making one of the sigmas high, one 1 and two 54 GausDouble; Same as before for GausHermite #Version III Changing both the central wavelength to 1550 for GausDouble df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) wav_range= [(1280,1350),(1700,1800),(1950,2200),(2650,2710),(3010,3700),(3950,4050),(4140,4270)] pp = PdfPages('ContinuumNormalization_plus_EmissionLineFits_IV.pdf') #fx=open('ALPHA_AMP_values_V.txt','w') #fx1=open('Kate_ALPHA_AMP_values_V.txt','w') #for i in range(len(df['pmf1'])): for i in range(len(df)): #for i in range(12): print 'Norm_Spectra/Normspec_'+df['pmf1'][i]+'.txt' print 'Norm_Spectra/Normspec_'+df['pmf2'][i]+'.txt' print 'Norm_Spectra/Normspec_'+df['pmf3'][i]+'.txt' if ((not os.path.isfile('Norm_Spectra/Normspec_'+df['pmf1'][i]+'.txt')) | (not os.path.isfile('Norm_Spectra/Normspec_'+df['pmf2'][i]+'.txt')) | ( not os.path.isfile('Norm_Spectra/Normspec_'+df['pmf3'][i]+'.txt'))): continue else: data1 = np.loadtxt('Norm_Spectra/Normspec_'+df['pmf1'][i]+'.txt') data2 = np.loadtxt('Norm_Spectra/Normspec_'+df['pmf2'][i]+'.txt') data3 = np.loadtxt('Norm_Spectra/Normspec_'+df['pmf3'][i]+'.txt') wave1 = data1.T[0] ; flux1 = data1.T[1] ; weight1 = data1.T[2]; mask1 = data1.T[3] wave2 = data2.T[0] ; flux2 = data2.T[1] ; weight2 = data2.T[2]; mask2 = data2.T[3] wave3 = data3.T[0] ; flux3 = data3.T[1] ; weight3 = data3.T[2]; mask3 = data3.T[3] print len(wave1),len(flux1),len(weight1) #print weight1 #Initial Mask for broad absorptions cut1 = np.nanpercentile(flux1, 20) cut2 = np.nanpercentile(flux2, 20) cut3 = np.nanpercentile(flux3, 20) xx1 = np.where(flux1 < cut1)[0] xx2 = np.where(flux2 < cut2)[0] xx3 = np.where(flux3 < cut3)[0] print cut1 print flux1[xx1] weight1[xx1] = 0 weight2[xx2] = 0 weight3[xx3] = 0 #Fit powerlaw iterate and mask outliers iteration = 3 for j in range(iteration): if j == 0: print 'iteration 1 Begins' AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1, CHISQgh1, DOFgh1 = compute_alpha_gh(wave1, flux1, weight1, waveRange(wave1)) AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ,CHISQ2g1, DOF2g1 = compute_alpha_2g(wave1, flux1, weight1, waveRange(wave1)) AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1, CHISQv1, DOFv1 = compute_alpha_voigt(wave1, flux1, weight1, waveRange(wave1)) print 'Object 1 Done' AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2, CHISQgh2, DOFgh2 = compute_alpha_gh(wave2, flux2, weight2, waveRange(wave2)) AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ,CHISQ2g2, DOF2g2 = compute_alpha_2g(wave2, flux2, weight2, waveRange(wave2)) AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2, CHISQv2, DOFv2 = compute_alpha_voigt(wave2, flux2, weight2, waveRange(wave2)) print 'Object 2 Done' AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3, CHISQgh3, DOFgh3 = compute_alpha_gh(wave3, flux3, weight3, waveRange(wave3)) AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ,CHISQ2g3, DOF2g3 = compute_alpha_2g(wave3, flux3, weight3, waveRange(wave3)) AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3, CHISQv3, DOFv3 = compute_alpha_voigt(wave3, flux3, weight3, waveRange(wave3)) nwavegh1 = wave1; nfluxgh1=flux1;nweightgh1 = weight1 nwavegh2 = wave2; nfluxgh2=flux2;nweightgh2 = weight2 nwavegh3 = wave3; nfluxgh3=flux3;nweightgh3 = weight3 nwave2g1 = wave1; nflux2g1=flux1;nweight2g1 = weight1 nwave2g2 = wave2; nflux2g2=flux2;nweight2g2 = weight2 nwave2g3 = wave3; nflux2g3=flux3;nweight2g3 = weight3 nwavev1 = wave1; nfluxv1=flux1;nweightv1 = weight1 nwavev2 = wave2; nfluxv2=flux2;nweightv2 = weight2 nwavev3 = wave3; nfluxv3=flux3;nweightv3 = weight3 print 'iteration 1 Ends' continue else: nwavegh1,nfluxgh1,nweightgh1 = maskOutliers_gh(nwavegh1, nfluxgh1, nweightgh1, AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1) nwavegh2,nfluxgh2,nweightgh2 = maskOutliers_gh(nwavegh2, nfluxgh2, nweightgh2, AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2) nwavegh3,nfluxgh3,nweightgh3 = maskOutliers_gh(nwavegh3, nfluxgh3, nweightgh3, AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3) nwave2g1,nflux2g1,nweight2g1 = maskOutliers_2g(nwave2g1, nflux2g1, nweight2g1, AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1) nwave2g2,nflux2g2,nweight2g2 = maskOutliers_2g(nwave2g2, nflux2g2, nweight2g2, AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2) nwave2g3,nflux2g3,nweight2g3 = maskOutliers_2g(nwave2g3, nflux2g3, nweight2g3, AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3) nwavev1,nfluxv1,nweightv1 = maskOutliers_v(nwavev1, nfluxv1, nweightv1, AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1 ) nwavev2,nfluxv2,nweightv2 = maskOutliers_v(nwavev2, nfluxv2, nweightv2, AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2 ) nwavev3,nfluxv3,nweightv3 = maskOutliers_v(nwavev3, nfluxv3, nweightv3, AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3 ) AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1, CHISQgh1, DOFgh1 = compute_alpha_gh(nwavegh1, nfluxgh1, nweightgh1, waveRange(nwavegh1)) AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ,CHISQ2g1, DOF2g1 = compute_alpha_2g(nwave2g1, nflux2g1, nweight2g1, waveRange(nwave2g1)) AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1, CHISQv1, DOFv1 = compute_alpha_voigt(nwavev1, nfluxv1, nweightv1, waveRange(nwavev1)) AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2, CHISQgh2, DOFgh2 = compute_alpha_gh(nwavegh2, nfluxgh2, nweightgh2, waveRange(nwavegh2)) AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ,CHISQ2g2, DOF2g2 = compute_alpha_2g(nwave2g2, nflux2g2, nweight2g2, waveRange(nwave2g2)) AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2, CHISQv2, DOFv2 = compute_alpha_voigt(nwavev2, nfluxv2, nweightv2, waveRange(nwavev2)) AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3, CHISQgh3, DOFgh3 = compute_alpha_gh(nwavegh3, nfluxgh3, nweightgh3, waveRange(nwavegh3)) AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ,CHISQ2g3, DOF2g3 = compute_alpha_2g(nwave2g3, nflux2g3, nweight2g3, waveRange(nwave2g3)) AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3, CHISQv3, DOFv3 = compute_alpha_voigt(nwavev3, nfluxv3, nweightv3, waveRange(nwavev3)) fig,((ax1,rax1),(ax2,rax2),(ax3,rax3))=plt.subplots(3,2,figsize=(20,10)) ax1.plot(wave1,flux1,label=str(df['pmf1'][i])) ax1.plot(wave1,weight1,alpha=0.2) ax1.plot(wave1[weight1 > 0],flux1[weight1>0],'.') ax2.plot(wave2,flux2,label=str(df['pmf2'][i])) ax2.plot(wave2,weight2,alpha=0.2) ax2.plot(wave2[weight2 > 0],flux2[weight2>0],'.') ax3.plot(wave3,flux3,label=str(df['pmf3'][i])) ax3.plot(wave3,weight3,alpha=0.2) ax3.plot(wave3[weight3 > 0],flux3[weight3>0],'.') #ax1.plot(cwave1,cflux1,'--') pgh1=ax1.plot(wave1,myGaussHermite(wave1,AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1),':',color='red',lw=3,label='GaussHermite+Power law') pgh2=ax2.plot(wave2,myGaussHermite(wave2,AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2),':',color='red',lw=3,label='GaussHermite+Power law') pgh3=ax3.plot(wave3,myGaussHermite(wave3,AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3),':',color='red',lw=3,label='GaussHermite+Power law') p2g1=ax1.plot(wave1,myDoubleGauss(wave1,AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ),':',color='blue',lw=3,label='Double Gaussian + Power law') p2g2=ax2.plot(wave2,myDoubleGauss(wave2,AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ),':',color='blue',lw=3,label='Double Gaussian + Power law') p2g3=ax3.plot(wave1,myDoubleGauss(wave3,AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ),':',color='blue',lw=3,label='Double Gaussian + Power law') p2v1 = ax1.plot(wave1,myVoigt(wave1,AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1),':',color='orange',lw=3,label='Voigt+ Power law') p2v2 = ax2.plot(wave2,myVoigt(wave2,AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2),':',color='orange',lw=3,label='Voigt+ Power law') p2v3 = ax3.plot(wave3,myVoigt(wave3,AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3),':',color='orange',lw=3,label='Voigt+ Power law') ax1.axhline(cut1,ls=':') ax2.axhline(cut1,ls=':') ax3.axhline(cut1,ls=':') string1gh = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPgh1,CENTERgh1,(CHISQgh1/DOFgh1)) string12g = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPa2g1,CENTERa2g1,(CHISQ2g1/ DOF2g1)) string2gh = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPgh2,CENTERgh2,(CHISQgh2/ DOFgh2)) string22g = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPa2g2,CENTERa2g2,(CHISQ2g2/ DOF2g2)) string3gh = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPgh3,CENTERgh3,(CHISQgh3/ DOFgh3)) string32g = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPa2g3,CENTERa2g3,(CHISQ2g3/ DOF2g3)) ax1.set_xlim(np.min(wave1),np.max(wave1)) ax2.set_xlim(np.min(wave1),np.max(wave1)) ax3.set_xlim(np.min(wave1),np.max(wave1)) xlim=ax1.get_xlim() ylim1 = ax1.get_ylim() ylim2 = ax1.get_ylim() ylim3 = ax1.get_ylim() ax1.set_ylim(-0.05,4) ax2.set_ylim(-0.05,4) ax3.set_ylim(-0.05,4) ax1.text(xlim[1]-0.15*(xlim[1] - xlim[0]),ylim1[0] + 0.1*(ylim1[1] - ylim1[0]),str(df['pmf1'][i])) ax2.text(xlim[1]-0.15*(xlim[1] - xlim[0]),ylim1[0] + 0.1*(ylim1[1] - ylim1[0]),str(df['pmf2'][i])) ax3.text(xlim[1]-0.15*(xlim[1] - xlim[0]),ylim1[0] + 0.1*(ylim1[1] - ylim1[0]),str(df['pmf3'][i])) #ax1.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim1[1] - 0.2*(ylim1[1] - ylim1[0]),string12g) #ax2.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim2[1] - 0.1*(ylim1[1] - ylim2[0]),string2gh) #ax2.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim2[1] - 0.2*(ylim1[1] - ylim2[0]),string22g) #ax3.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim3[1] - 0.1*(ylim1[1] - ylim3[0]),string3gh) #ax3.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim3[1] - 0.2*(ylim1[1] - ylim2[0]),string32g) ax1.legend([pgh1,p2g1,p2v1],['Gaus-Hermite','2-Gaus','Voigt'],loc=3) ax1.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f' \ %(AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax1.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f' \ %(AMPa2g1, AMPb2g1, CENTERa2g1, CENTERb2g1, SIGMAa2g1, SIGMAb2g1),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax1.annotate('Voigt:\nAmp$_1$ = %.2f\nCenter = %.2f\n$\sigma_l$ = %.2f\n$\sigma_g$ = %.2f' \ %(AMPv1, CENTERv1, SIGMALv1, SIGMAGv1),xy=(.35,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.legend([pgh2,p2g2,p2v2],['Gaus-Hermite','2-Gaus','Voigt'],prop={'size':8},loc='center left') ax2.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f' \ %(AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f' \ %(AMPa2g2, AMPb2g2, CENTERa2g2, CENTERb2g2, SIGMAa2g2, SIGMAb2g2),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.annotate('Voigt:\nAmp$_1$ = %.2f\nCenter = %.2f\n$\sigma_l$ = %.2f\n$\sigma_g$ = %.2f' \ %(AMPv2, CENTERv2, SIGMALv2, SIGMAGv2),xy=(.35,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.legend([pgh3,p2g3,p2v3],['Gaus-Hermite','2-Gaus','Voigt'],prop={'size':8},loc='center left') ax3.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f' \ %(AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f' \ %(AMPa2g3, AMPb2g3, CENTERa2g3, CENTERb2g3, SIGMAa2g3, SIGMAb2g3),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.annotate('Voigt:\nAmp$_1$ = %.2f\nCenter = %.2f\n$\sigma_l$ = %.2f\n$\sigma_g$ = %.2f' \ %(AMPv3, CENTERv3, SIGMALv3, SIGMAGv3),xy=(.35,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) #Save the spectra filenamegh1 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf1'][i]+'_Em_gh.txt' filenamegh2 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf2'][i]+'_Em_gh.txt' filenamegh3 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf3'][i]+'_Em_gh.txt' filename2g1 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf1'][i]+'_Em_2g.txt' filename2g2 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf2'][i]+'_Em_2g.txt' filename2g3 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf3'][i]+'_Em_2g.txt' filenamev1 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf1'][i]+'_Em_v.txt' filenamev2 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf2'][i]+'_Em_v.txt' filenamev3 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf3'][i]+'_Em_v.txt' # Residuals & Weights resgh1 = flux1 / myGaussHermite(wave1,AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1) resgh2 = flux2 / myGaussHermite(wave2,AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2) resgh3 = flux3 / myGaussHermite(wave3,AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3) wresgh1 = weight1 / myGaussHermite(wave1,AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1) wresgh2 = weight2 / myGaussHermite(wave2,AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2) wresgh3 = weight3 / myGaussHermite(wave3,AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3) res2g1 = flux1 / myDoubleGauss(wave1,AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ) res2g2 = flux2 / myDoubleGauss(wave2,AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ) res2g3 = flux3 / myDoubleGauss(wave3,AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ) wres2g1 = weight1 / myDoubleGauss(wave1,AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ) wres2g2 = weight2 / myDoubleGauss(wave2,AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ) wres2g3 = weight3 / myDoubleGauss(wave3,AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ) resv1 = flux1 / myVoigt(wave1,AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1) resv2 = flux2 / myVoigt(wave2,AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2) resv3 = flux3 / myVoigt(wave3,AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3) wresv1 = weight1 / myVoigt(wave1,AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1) wresv2 = weight2 / myVoigt(wave2,AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2) wresv3 = weight3 / myVoigt(wave3,AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3) #Save Begins np.savetxt(filenamegh1,zip(wave1,resgh1,wresgh1,mask1), fmt='%10.5f') np.savetxt(filenamegh2,zip(wave2,resgh2,wresgh2,mask2), fmt='%10.5f') np.savetxt(filenamegh3,zip(wave3,resgh3,wresgh3,mask3), fmt='%10.5f') np.savetxt(filename2g1,zip(wave1,res2g1,wres2g1,mask1), fmt='%10.5f') np.savetxt(filename2g2,zip(wave2,res2g2,wres2g2,mask2), fmt='%10.5f') np.savetxt(filename2g3,zip(wave3,res2g3,wres2g3,mask3), fmt='%10.5f') np.savetxt(filenamev1,zip(wave1,resv1,wresv1,mask1), fmt='%10.5f') np.savetxt(filenamev2,zip(wave2,resv2,wresv2,mask2), fmt='%10.5f') np.savetxt(filenamev3,zip(wave3,resv3,wresv3,mask3), fmt='%10.5f') #Plot Begins presgh1,pres2g1,presv1,=rax1.plot(wave1,resgh1,'k--',wave1,res2g1,'r-',wave1,resv1,'b:',alpha=0.7) presgh2,pres2g2,presv2,=rax2.plot(wave2,resgh2,'k--',wave2,res2g2,'r-',wave2,resv2,'b:',alpha=0.7) presgh3,pres2g3,presv3,=rax3.plot(wave3,resgh3,'k--',wave3,res2g3,'r-',wave3,resv3,'b:',alpha=0.7) rax1.set_ylabel('Normalized Flux') rax1.set_xlabel('Wavelength ($\AA$)') rax1.legend([presgh1,pres2g1,presv1],['Gaus-Hermite','2-Gaus','Voigt'],numpoints=4,prop={'size':8},loc='lower right') rax2.set_ylabel('Normalized Flux') rax2.set_xlabel('Wavelength ($\AA$)') rax2.legend([presgh2,pres2g2,presv2],['Gaus-Hermite','2-Gaus','Voigt'],numpoints=4,prop={'size':8},loc='lower right') rax3.set_ylabel('Normalized Flux') rax3.set_xlabel('Wavelength ($\AA$)') rax3.legend([presgh3,pres2g3,presv3],['Gaus-Hermite','2-Gaus', 'Voigt'],numpoints=4,prop={'size':8},loc='lower right') rax1.axhline(1.0,ls=':',color='blue',alpha=0.5) rax2.axhline(1.0,ls=':',color='blue',alpha=0.5) rax3.axhline(1.0,ls=':',color='blue',alpha=0.5) rax1.set_ylim(0,2) rax2.set_ylim(0,2) rax3.set_ylim(0,2) fig.tight_layout() fig.savefig(pp,format='pdf') #plt.show() plt.clf() pp.close() <file_sep>import sys import os import numpy as np from astropy import io from astropy.io import fits from astropy.io import ascii from matplotlib import pyplot as plt from astropy import constants as const from astropy import units as U from astropy.coordinates import SkyCoord #from dustmaps.sfd import SFDQuery #from specutils import extinction import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from scipy.optimize import curve_fit from matplotlib.backends.backend_pdf import PdfPages #from lmfit import minimize, Parameters from astropy.modeling.models import Voigt1D from collections import Iterable def flatten(items): """Yield items from any nested iterable; see REF.""" for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): return flatten(x) else: return x def velocity(wave,ion_wave,z): #print wave #print z,ion_wave c = 299792.0# in km/s vel =np.zeros(len(wave)) zabs = np.zeros(len(wave)) for i in range(len(wave)): #print i,wave[i],zabs[i],vel[i] zabs[i] = (wave[i]/ion_wave) -1.0 vel[i] = -((((1+z)/(1+zabs[i]))**2-1.0)/(((1+z)/(1+zabs[i]))**2+1))*c return vel def balBounds(vel,flux,threshold=0.9,min_vel=2000): start = -1 contigous_segments = [] for idx,x in enumerate(zip(vel,flux)): if start < 0 and x[1] <= threshold: start = idx #print 'start', start elif start >= 0 and x[1] >= threshold: dur = idx-start veldiff = vel[idx] - vel[start] #print 'velocity difference: ',dur, veldiff #Multiply by -1 to take care of blueshifted velocities if veldiff >= min_vel: contigous_segments.append((vel[start],vel[start+dur])) start = -1 return contigous_segments def mergeVelocityBounds(bounds1,bounds2,bounds3): masterbounds = bounds1+bounds2+bounds3 sortedbounds = sorted(masterbounds, key=lambda t: t[0]) print 'MasterBounds',masterbounds print 'SortedBounds',sortedbounds merged = [] for higher in sortedbounds: print 'Higher',higher print 'M',merged if not merged: merged.append(higher) else: lower = merged[-1] #print 'To set the merging of adjacent BALs',higher[0] - lower[1] # this condition to merge close by BALs if higher[0] > lower[1]: if higher[0] - lower[1] <= 50: merged[-1] = (lower[0], higher[1]) # replace by merged interval else: merged.append(higher) elif higher[0] <= lower[1]: upper_bound = max(lower[1], higher[1]) merged[-1] = (lower[0], upper_bound) # replace by merged interval else: merged.append(higher) print 'Merged',merged return merged def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] <NAME>, <NAME>, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, <NAME>, <NAME>, <NAME> Cambridge University Press ISBN-13: 9780521880688 """ import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except (ValueError, msg): raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order+1) half_window = (window_size -1) // 2 # precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # pad the signal at the extremes with # values taken from the signal itself firstvals = np.asarray(y[0]) - np.abs( y[1:half_window+1][::-1] - np.asarray(y[0]) ) lastvals = np.asarray(y[-1]) + np.abs(y[-half_window-1:-1][::-1] - np.asarray(y[-1])) y = np.concatenate((firstvals, y, lastvals)) return np.convolve( m[::-1], y, mode='valid') def topHat(mvel1,merged): #Plot a top hat function mask1 = np.ones(len(mvel1))*(1==0) #print 'VelMerged',mvel1 indices = list() for m in merged: #print m[0],m[1] ix = np.where((mvel1 >= m[0]) & (mvel1 <=m[1]))[0] #print len(ix) if len(ix)>0: indices.append(ix) #print len(indices) indices = np.array(indices) findices = [y for x in indices for y in x] #print findices, #print len(findices) if len(findices) >0: mask1[findices] = True return mask1 c_light=299792.0 cw=1549.0 df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) pp = PdfPages('BALcomponents_search_I.pdf') fx=open('BALcomponents_output.txt','w') #for i in range(len(df['pmf1'])): for i in range(len(df)): #for i in range(5): filename1 = 'Normspec_'+df['pmf1'][i]+'_cEm_2g.txt' filename2 = 'Normspec_'+df['pmf2'][i]+'_cEm_2g.txt' filename3 = 'Normspec_'+df['pmf3'][i]+'_cEm_2g.txt' if ((not os.path.isfile('EmissionLines_Norm_Spectra/Normspec_'+df['pmf1'][i]+'_cEm_2g.txt')) | (not os.path.isfile('EmissionLines_Norm_Spectra/Normspec_'+df['pmf2'][i]+'_cEm_2g.txt')) | ( not os.path.isfile('EmissionLines_Norm_Spectra/Normspec_'+df['pmf3'][i]+'_cEm_2g.txt'))): continue else: data1 = np.loadtxt('EmissionLines_Norm_Spectra/Normspec_'+df['pmf1'][i]+'_cEm_2g.txt') data2 = np.loadtxt('EmissionLines_Norm_Spectra/Normspec_'+df['pmf2'][i]+'_cEm_2g.txt') data3 = np.loadtxt('EmissionLines_Norm_Spectra/Normspec_'+df['pmf3'][i]+'_cEm_2g.txt') wave1 = data1.T[0] ; bflux1 = data1.T[1] ; weight1 = data1.T[2]#; mask1 = data1.T[3] wave2 = data2.T[0] ; bflux2 = data2.T[1] ; weight2 = data2.T[2]#; mask2 = data2.T[3] wave3 = data3.T[0] ; bflux3 = data3.T[1] ; weight3 = data3.T[2]#; mask3 = data3.T[3] if ((len(bflux1[~np.isnan(bflux1)]) < 1) | (len(bflux2[~np.isnan(bflux2)]) < 1) | (len(bflux3[~np.isnan(bflux3)]) < 1) ) : filename1 = 'Normspec_'+df['pmf1'][i]+'_cEm_v.txt' filename2 = 'Normspec_'+df['pmf2'][i]+'_cEm_v.txt' filename3 = 'Normspec_'+df['pmf3'][i]+'_cEm_v.txt' data1 = np.loadtxt('EmissionLines_Norm_Spectra/Normspec_'+df['pmf1'][i]+'_cEm_v.txt') data2 = np.loadtxt('EmissionLines_Norm_Spectra/Normspec_'+df['pmf2'][i]+'_cEm_v.txt') data3 = np.loadtxt('EmissionLines_Norm_Spectra/Normspec_'+df['pmf3'][i]+'_cEm_v.txt') wave1 = data1.T[0] ; bflux1 = data1.T[1] ; weight1 = data1.T[2]#; mask1 = data1.T[3] wave2 = data2.T[0] ; bflux2 = data2.T[1] ; weight2 = data2.T[2]#; mask2 = data2.T[3] wave3 = data3.T[0] ; bflux3 = data3.T[1] ; weight3 = data3.T[2]#; mask3 = data3.T[3] #Work on smoothed spectrum to get rid og high frequency noise flux1 = savitzky_golay(bflux1, 5, 2) flux2 = savitzky_golay(bflux2, 5, 2) flux3 = savitzky_golay(bflux3, 5, 2) print len(wave1),len(flux1),len(weight1) #Convert wavelengths to velocities vel1 = velocity(wave1, cw, 0.0) ; vel2 = velocity(wave2, cw, 0.0) ; vel3 = velocity(wave3, cw, 0.0) bounds1 = balBounds(vel1,flux1) ; bounds2 = balBounds(vel2,flux2); bounds3 = balBounds(vel3, flux3) print 'bounds1', bounds1 print 'bounds2', bounds2 print 'bounds3', bounds3 #Merge the overlapping regions merged = mergeVelocityBounds(bounds1,bounds2,bounds3) ntroughs = len(merged) #Check if each component is present in atleast 2 epochs #topHat function returns a mask with ones inside the absorption mask1 = topHat(vel1,bounds1) ; mask2 = topHat(vel1,bounds2) ; mask3 = topHat(vel1,bounds3) for kk,mm in enumerate(merged): #print mm #print topHat(vel1,[mm]) #print mask1 track_absorption = 0 if np.sum( mask1.any() and topHat(vel1,[mm])) > 0: track_absorption += 1 if np.sum(mask2.any() and topHat(vel1,[mm])) > 0: track_absorption += 1 if np.sum(mask3.any() and topHat(vel1,[mm])) > 0: track_absorption += 1 if track_absorption < 2: merged.pop(kk) maskall = topHat(vel1,merged) #Get the min max of each bounds ubounds = [] if (len(bounds1) == len(bounds2) == len(bounds3)): for k in range(len(bounds1)): uboundsl,uboundsu = min(bounds1[k][0],bounds2[k][0],bounds3[k][0]),max(bounds1[k][1],bounds2[k][1],bounds3[k][1]) ubounds.append((uboundsl,uboundsu)) else: print 'Manually adjust ',df[i] #Plot the spectra and check the bounds fig, (ax1,ax2,ax3) = plt.subplots(3,1,sharex=True, sharey=True,figsize=(15,8)) ax1.plot(vel1,bflux1,color='black',alpha=0.3,label=str(df['pmf1'][i])) ax1.plot(vel1,flux1,color='magenta',alpha=0.3) ax1.plot(vel1,maskall*0.5,color='green') for bb in bounds1: ax1.axvline(bb[0],ls='--',color='blue',lw=1) ax1.axvline(bb[1],ls='--',color='red',lw=1) ax2.plot(vel2,bflux2,color='black',alpha=0.3,label=str(df['pmf2'][i])) ax2.plot(vel2,flux2,color='magenta',alpha=0.3) ax2.plot(vel1,maskall*0.5,color='green') for bb in bounds2: ax2.axvline(bb[0],ls='--',color='blue',lw=1) ax2.axvline(bb[1],ls='--',color='red',lw=1) ax3.plot(vel3,bflux3,color='black',alpha=0.3,label=str(df['pmf3'][i])) ax3.plot(vel3,flux3,color='magenta',alpha=0.3) ax3.plot(vel1,maskall*0.5,color='green') for bb in bounds3: ax3.axvline(bb[0],ls='--',color='blue',lw=1) ax3.axvline(bb[1],ls='--',color='red',lw=1) for ubb in ubounds: #print 'final bounds',ubounds ax1.axvline(ubb[0],ls='-',color='blue',lw=1) ax2.axvline(ubb[0],ls='-',color='blue',lw=1) ax3.axvline(ubb[0],ls='-',color='blue',lw=1) ax1.axvline(ubb[1],ls='-',color='red',lw=1) ax2.axvline(ubb[1],ls='-',color='red',lw=1) ax3.axvline(ubb[1],ls='-',color='red',lw=1) #ax1.set_xlabel(r'Velocity km s$^{-1}$') #ax2.set_xlabel(r'Velocity km s$^{-1}$') ax3.set_xlabel(r'Velocity km s$^{-1}$') ax1.axhline(1.0,ls='--',color='orange') ax2.axhline(1.0,ls='--',color='orange') ax3.axhline(1.0,ls='--',color='orange') ax1.axhline(0.9,ls='--',color='gold') ax2.axhline(0.9,ls='--',color='gold') ax3.axhline(0.9,ls='--',color='gold') ax1.axvspan(-30000,1000,color='grey',alpha=0.1) ax2.axvspan(-30000,1000,color='grey',alpha=0.1) ax3.axvspan(-30000,1000,color='grey',alpha=0.1) ax1.set_ylim(0,2) ax2.set_ylim(0,2) ax3.set_ylim(0,2) #ax1.set_ylabel(r'Normalized Flux') #ax2.set_ylabel(r'Normalized Flux') ax3.set_ylabel(r'Normalized Flux') ax1.legend(loc=1) ax2.legend(loc=1) ax3.legend(loc=1) for j in range(len(merged)): merge = merged[j] print>>fx,'{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(i,filename1,merge[1],merge[0],0,ntroughs, 2000.0000,2000.0000,10.0,10.0) print>>fx,'{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(i,filename2,merge[1],merge[0],0,ntroughs, 2000.0000,2000.0000,10.0,10.0) print>>fx,'{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(i,filename3,merge[1],merge[0],0,ntroughs, 2000.0000,2000.0000,10.0,10.0) #plt.show() #plt.clf() # Some book keeping fig.tight_layout() fig.savefig(pp,format='pdf') # sinp = raw_input('Type Some Key to Continue: ') pp.close() fx.close() <file_sep>#!/usr/bin/python #-*- coding: utf-8 -*- ''' Code for continuum normalization of SDSS spectra @author : <NAME> @date : 21-Jan-2018 @version : 1.0 ''' import sys import os import numpy as np from astropy import io from astropy.io import fits from astropy.io import ascii from matplotlib import pyplot as plt from astropy import constants as const from astropy import units as U from astropy.coordinates import SkyCoord from dustmaps.sfd import SFDQuery from specutils import extinction import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d import scipy.optimize as optimization from scipy import optimize from scipy.optimize import curve_fit def maskOutliers(wave,flux,weight,popt): model = powerlawFunc(wave,popt[0],popt[1],popt[2]) std =np.std(flux[weight > 0]) fluxdiff = flux - model ww = np.where (np.abs(fluxdiff) > 1*std) nwave = np.delete(wave,ww) nflux = np.delete(flux,ww) nweight = np.delete(weight,ww) return nwave,nflux,nweight def contWave(wave): linefree_regions = [(1250,1350),(1700,1800),(1950,2200),(2650,2710),(2950,3700),(3950,4050)] finalcond = False for lfr in linefree_regions: cond = ((wave >= lfr[0]) & (wave <= lfr[1])) finalcond = finalcond | cond indices = np.where(finalcond) return indices def powerlawFunc(xdata, amp,index): return amp*xdata**index def fitPowerlaw(wave,flux,sigma,p): p0 = p popt,pcov = optimization.curve_fit(powerlawFunc,wave,flux,p0,sigma) return popt,pcov def myfunct(wave, a , b): return a*wave**(b) def compute_alpha(wl, spec, ivar, wav_range, per_value): # print 'Routine begins' wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) for j in range(len(wav_range)): temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) try: popt, pcov = curve_fit(myfunct, wavelength, spectra, sigma=1.0/np.sqrt(invar)) except (RuntimeError, TypeError): AMP, ALPHA, CHISQ, DOF = np.nan, np.nan, np.nan, np.nan else: AMP, ALPHA = popt[0], popt[1] CHISQ = np.sum(invar * (spectra - myfunct(wavelength, popt[0], popt[1]))**2) # DOF = N - n , n = 2 DOF = len(spectra) - 2 # print 'Routine ends' return AMP, ALPHA, CHISQ, DOF per_value= 0.2 wav_range=[[1300.,1350.],[1420.,1470.],[1700.,1800.],[2080.,2215],[2480.,2655],[3225.,3900.],[4200.,4230.],[4435.,4700.],[5200.,5700.]] mwav_range = [] data = fits.open('Kate_Sources/spec-0389-51795-0332.fits')[1].data flux =data.flux wave = (10**data.loglam)/3.85 weight = (data.ivar*(data.and_mask == 0)) for rr in wav_range: if ((np.min(wave) < rr[0]) & (np.max(wave) > rr[1])): nrr0 = rr[0] ; nrr1 = rr[1] elif ((np.min(wave) > rr[0]) & (np.min(wave) < rr[1])& (np.max(wave) < rr[1])): nrr0 = np.min(wave) ; nrr1 = rr[1] elif ((np.min(wave) < rr[0]) & (np.max(wave) > rr[0]) &(np.max(wave) < rr[1])): nrr0 = rr[0] ; nrr1 = np.max(wave) else : continue mwav_range.append([nrr0,nrr1]) #print mwav_range AMP, ALPHA, CHISQ, DOF = compute_alpha(wave, flux, weight, mwav_range, per_value) cwave = wave[contWave(wave)] cflux = flux[contWave(wave)] cweight = weight[contWave(wave)] #sigma = cweight #p0=[1,1] #popt,pcov = optimization.curve_fit(powerlawFunc,cwave,cflux,p0,sigma) #print popt plt.plot(cwave,cflux) plt.plot(wave,AMP*wave**ALPHA,'--') plt.show() <file_sep>import numpy as np import os def velocity(wave,ion_wave,z): #print wave #print z,ion_wave c = 299792.0# in km/s vel =np.zeros(len(wave)) zabs = np.zeros(len(wave)) for i in range(len(wave)): #print i,wave[i],zabs[i],vel[i] zabs[i] = (wave[i]/ion_wave) -1.0 vel[i] = -((((1+z)/(1+zabs[i]))**2-1.0)/(((1+z)/(1+zabs[i]))**2+1))*c return vel cw=1549.0 pf = np.genfromtxt('BALcomponents_output.txt',names=('index','filename','vmin','vmax','nt','ntroughs','paddmin','paddmax','ew','ewerr'),dtype=(int,'|S35',float,float,float,float,float,float,float)) uindex = np.unique(pf['index']) for i in range(len(uindex)): match = np.where(pf['index'] == uindex[i])[0] mpf = pf[match] for k in range(len(mpf)): wave,flux,err = np.loadtxt('EmissionLines_Norm_Spectra/'+str(mpf['filename'][k])).T vel = velocity(wave, cw, 0.0)/1000. print 'Match', match, uindex[i] print mpf ntroughs = mpf['ntroughs'][0] print 'Ntroughs: ',ntroughs for ii in range(int(ntroughs)): print uindex[i] print 'index',ii,(mpf['vmax'][ii] - mpf['paddmin'][ii])/1000, (mpf['vmin'][ii] + mpf['paddmax'][ii])/1000. xx = np.where((vel >= (mpf['vmax'][ii] - mpf['paddmin'][ii])/1000.) & ( vel <= (mpf['vmin'][ii]+mpf['paddmax'][ii])/1000.))[0] nvel=vel[xx] ; nflux = flux[xx] ; nerr = err[xx] print 'Final',min(nvel),max(nvel) sfilename = 'spec-'+mpf['filename'][k].split('_')[1]+'_'+mpf['filename'][k].split('_')[2]+'_'+mpf['filename'][k].split('_')[3] savefilename = 'fivecol/'+sfilename+'.crop.5col'+'_'+str(ii) print savefilename np.savetxt(savefilename,zip(nvel,nflux,nerr,nflux,nerr), fmt='%10.5f') #fsdf=raw_input() <file_sep>#!/usr/bin/python #-*- coding: utf-8 -*- import sys import argparse import os import numpy as np from astropy import io from astropy.io import fits as pyfits from astropy.io import ascii from astropy.table import Table from matplotlib import pyplot as plt import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from scipy import optimize import matplotlib.cm as cm from matplotlib.backends.backend_pdf import PdfPages from matplotlib import rcParams #import crop_spectrum #not used in this version from Observation import Observation import CCF_interp as myccf from scipy import stats #Wavelengths of each species nv_0 = 1238.821 siiv_0 = 1393.755 civ_0 = 1548.202 aliii_0 = 1854.7164 mgii_0 = 2796.352 lightspeed = 2.99792458e5 nu_0 = civ_0 #crop = True #(False if I've already done cropping and just want to redo the lags). This is from an old version; not used here. #Convert wavelength to velocity def lam2vel(wavelength): zlambda = (wavelength-ion_0)/ion_0 R = 1./(1+zlambda) vel_ion = -lightspeed*(R**2-1)/(R**2+1) return vel_ion ################################################################################################### ## Directories and list of files to use ################################################################################################### tdssdatadir = 'EmissionLines_Norm_Spectra/' bossdatadir = 'EmissionLines_Norm_Spectra/' sdssdatadir = 'EmissionLines_Norm_Spectra/' #bi_file = '/Users/cjg235/balqsos/varbal/measurements/BI_out_multitrough.dat' bi_file = '/Users/vzm83/Acc_BALQSO/BALcomponents_output.txt' #'../../measurements/pyccf_tries_69kms_feb/trough_complexes.dat' datafile = '/Users/vzm83/Acc_BALQSO/tdss_allmatches_crop_edit.dat'#'../../sample_selection/tdss_allmatches_crop_edit.dat' #Read in file containing all plate-mjd-fibers of pairs of spectra I want to use targ_obs = list() with open(datafile) as file: for line in file: if line.startswith('#'): continue else: targ_obs.append(line.rstrip("\n")) num_obj = np.size(targ_obs) print 'Number of different targets: ', num_obj target_observations = [[] for _ in range(num_obj)] print target_observations #exit() #bi_info = np.genfromtxt(bi_file, dtype = None, names = ['files', 'num_troughs', 'BI', 'BI_err', 'BIround', 'Vmax', 'Verr', 'Vmaxround', 'Vmin', 'Verr2', 'Vminround', 'Chi2'], skiprows = 1) #num_bi = np.size(bi_info['num_troughs']) bi_info = np.genfromtxt(bi_file, dtype = None, names = ['speci', 'files', 'Vmin', 'Vmax', 'numt', 'num_troughs', 'highpad', 'lowpad', 'ew', 'ew_err']) num_bi = np.size(bi_info['num_troughs']) x = np.genfromtxt('linefits.txt', dtype = None, names = ['numobj', 'spec1', 'spec2', 'spec3', 'linefit']) linefit = x['linefit'] num_obj=119 for i in xrange(0, num_obj): values = targ_obs[i].split() print values ra = values[0] dec = values[1] redshift = values[2] valuesn = sorted(values[3:]) valuesize = np.size(valuesn) line_fit = linefit[i] if line_fit == 'gauss-hermite': file_suffix = '_cEm_gh.txt' elif line_fit == 'voigt': file_suffix = '_cEm_v.txt' else: file_suffix = '_cEm_2g.txt' #print valuesize, valuesn for j in xrange(0, valuesize): obs = Observation() platemjdfiber = valuesn[j] plate = platemjdfiber.split('-')[0] mjd = int(platemjdfiber.split('-')[1]) fiber = platemjdfiber.split('-')[2] if mjd < 55050: #print 'sdss' filename = sdssdatadir+'spec-'+valuesn[j]+file_suffix survey = 'SDSS' if np.logical_and(mjd >= 55100., mjd <= 56850.): #print 'boss' filename = bossdatadir+'spec-'+valuesn[j]+file_suffix survey = 'BOSS' if mjd > 56850.: #print 'tdss' filename = tdssdatadir+'spec-'+valuesn[j]+file_suffix survey = 'TDSS' spec_filename = 'NormSpec_'+valuesn[j]+file_suffix match = np.where(bi_info['files'] == spec_filename)[0] print 'Match' ,match, spec_filename if np.size(match) == 0: obs.filename = filename obs.spec_name = spec_filename obs.mjd = mjd obs.pmf = platemjdfiber obs.survey = survey obs.redshift = redshift obs.num_troughs = [0] obs.v_max = 0 obs.v_min = 0 print i, spec_filename else: obs.filename = filename obs.spec_name = spec_filename obs.mjd = mjd obs.pmf = platemjdfiber obs.survey = survey obs.redshift = redshift obs.num_troughs = bi_info['num_troughs'][match] obs.v_max = bi_info['Vmax'][match] obs.v_min = bi_info['Vmin'][match] target_observations[i].append(obs) print 'Carrying out CCF analysis' #Output files lagsout = open('shift_measurements.dat', 'w') lagsout.write('#Plot, Target-i, Spec1 Spec2 delta_t (years) Centroid UpErr Lowerr Peak UpErr Lowerr R_val Accel (cm/s^2) UpErr Lowerr Shift UpErr Lowerr vmin vmax \n') lagsout.close() lagsout3 = open('shift_measurements_3sigma.dat', 'w') lagsout3.write('#Plot, Target-i, Spec1 Spec2 delta_t (years) Centroid UpErr Lowerr Peak UpErr Lowerr R_val Accel (cm/s^2) UpErr Lowerr Shift UpErr Lowerr vmin vmax \n') lagsout3.close() pdf_pages = PdfPages('all_ccfs.pdf') numplot = 0 for i in xrange(0, num_obj): #num_obj target = target_observations[i] numrep = np.size(target) n_troughs = target[0].num_troughs[0] if n_troughs > 0: print n_troughs for z in xrange(0, n_troughs): suffix = str(z) for j in xrange(0, numrep-1): k = 0 while (j+k) < (numrep-1): k+=1 print k print 'Targetfilename',target[j].filename spec1 = 'fivecol/'+(target[j].filename).split('/')[1]+'.crop.5col_'+suffix spec2 = 'fivecol/'+(target[j+k].filename).split('/')[1]+'.crop.5col_'+suffix print spec1,spec2 prefix1 = ((target[j].filename).split('/')[1]).split('-')[1]+'-'+ ((target[j].filename).split('/')[1]).split('-')[2]+'-'+ ((target[j].filename).split('/')[1]).split('-')[3] prefix2 = ((target[j+k].filename).split('/')[1]).split('-')[1]+'-'+ ((target[j+k].filename).split('/')[1]).split('-')[2]+'-'+ ((target[j+k].filename).split('/')[1]).split('-')[3] prefix = prefix1+'-vs-'+prefix2+'-'+suffix print prefix print 'i = ', i, ' Cross correlating: ', prefix deltamjd = abs(int(target[j+k].mjd) - int(target[j].mjd)) deltamjd_rest = (deltamjd/(1+float(target[j].redshift)))/365. #Calculate lag with python CCF program nsim = 10000 wave1, flux1, err1 = np.loadtxt(spec1, unpack = True, usecols = [0, 1, 2]) wave2, flux2, err2 = np.loadtxt(spec2, unpack = True, usecols = [0, 1, 2]) print z print target[j].v_min vmin = target[j].v_min[z] vmax = target[j].v_max[z] #Run the CCF on the two spectra #Run the CCF from -2000 km/s to +2000 km/s and at 69 km/s interpolation tlag_peak, status_peak, tlag_centroid, status_centroid, ccf_pack, max_r, status_r,peak_r = myccf.peakcent(wave1, flux1, wave2, flux2, -2.001, 2.001, 0.069, imode = 0, sigmode = 0.2) tlags_peak, tlags_centroid, nsuccess_peak, nfail_peak, nsuccess_centroid, nfail_centroid, max_rvals, nfail_maxrvals,pvale = myccf.xcor_mc(wave1, flux1, abs(err1), wave2, flux2, abs(err2), -2.001, 2.001, 0.069, nsim = nsim, mcmode=2, sigmode = 0.2) #plt.plot(ccf_pack[1], ccf_pack[0]) #plt.show() #plt.hist(tlags_centroid, color = 'b') #plt.hist(tlags_peak, color = 'r') #plt.show() #Write out to file centfile = open('ccf_files/centdist_'+prefix, 'w') peakfile = open('ccf_files/peakdist_'+prefix, 'w') ccf_file = open('ccf_files/ccf_'+prefix, 'w') lag = ccf_pack[1] r = ccf_pack[0] for m in xrange(0, np.size(tlags_centroid)): centfile.write('%5.5f \n'%(tlags_centroid[m])) for m in xrange(0, np.size(tlags_peak)): peakfile.write('%5.5f \n'%(tlags_peak[m])) centfile.close() peakfile.close() for m in xrange(0, np.size(lag)): ccf_file.write('%5.5f %5.5f \n'%(lag[m], r[m])) ccf_file.close() #Calculate lag with python CCF program centfile = 'ccf_files/centdist_'+prefix peakfile = 'ccf_files/peakdist_'+prefix ccf_file = 'ccf_files/ccf_'+prefix lag, r = np.loadtxt(ccf_file, unpack = True) tlags_centroid = np.loadtxt(centfile, unpack = True) tlags_peak = np.loadtxt(peakfile, unpack = True) perclim = 84.1344746 perclim3sig = 99.8650102 #For non-Gaussian Distribution centau = stats.scoreatpercentile(tlags_centroid, 50) centau_uperr = (stats.scoreatpercentile(tlags_centroid, perclim))-centau centau_loerr = centau-(stats.scoreatpercentile(tlags_centroid, (100.-perclim))) centau_uperr3 = (stats.scoreatpercentile(tlags_centroid, perclim3sig))-centau centau_loerr3 = centau-(stats.scoreatpercentile(tlags_centroid, (100.-perclim3sig))) print 'Centroid, error: ', centau, centau_loerr, centau_uperr peaktau = stats.scoreatpercentile(tlags_peak, 50) peaktau_uperr = (stats.scoreatpercentile(tlags_peak, perclim))-centau peaktau_loerr = centau-(stats.scoreatpercentile(tlags_peak, (100.-perclim))) peaktau_uperr3 = (stats.scoreatpercentile(tlags_peak, perclim3sig))-centau peaktau_loerr3 = centau-(stats.scoreatpercentile(tlags_peak, (100.-perclim3sig))) print 'Peak, errors: ', peaktau, peaktau_uperr, peaktau_loerr #Convert the measured shift in velocity space to acceleration. rval = np.max(r) accel_meas = (centau*1000/deltamjd_rest)*(1.0e5)/(365.*24.*60.*60.) #in cm/s/s accel_uperr = (centau_uperr*1000./deltamjd_rest)*(1.0e5)/(365.*24.*60.*60.) accel_loerr = (centau_loerr*1000./deltamjd_rest)*(1.0e5)/(365.*24.*60.*60.) accel_uperr3 = (centau_uperr3*1000./deltamjd_rest)*(1.0e5)/(365.*24.*60.*60.) accel_loerr3 = (centau_loerr3*1000./deltamjd_rest)*(1.0e5)/(365.*24.*60.*60.) shift = centau shift_uperr = centau_uperr shift_loerr = centau_loerr shift_uperr3 = centau_uperr3 shift_loerr3 = centau_loerr3 print 'Shift Error ratio: ', shift_uperr/shift_loerr print 'Accel Error ratio: ', accel_uperr/accel_loerr print 'Shift3 Error ratio: ', shift_uperr3/shift_loerr3 print 'Accel3 Error ratio: ', accel_uperr3/accel_loerr3 #write all of this out to a file. lagsout = open('shift_measurements.dat', 'a') lagsout3 = open('shift_measurements_3sigma.dat', 'a') lagsout.write('%i %i %s %s %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f \n'%(numplot, \ i, spec1,spec2, deltamjd_rest, centau, centau_uperr, centau_loerr, peaktau, peaktau_uperr, peaktau_loerr, rval, accel_meas, accel_uperr, accel_loerr, shift, shift_uperr, shift_loerr, vmin/1000., vmax/1000.)) lagsout.close() lagsout3.write('%i %i %s %s %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f \n'%(numplot, \ i, spec1,spec2, deltamjd_rest, centau, centau_uperr3, centau_loerr3, peaktau, peaktau_uperr3, peaktau_loerr3, rval, accel_meas, accel_uperr3, accel_loerr3, shift, shift_uperr3, shift_loerr3, vmin/1000., vmax/1000.)) lagsout3.close() #Make plots of the spectra, CCF, CCCD, and CCPD, etc spec1w, spec1f, spec1er = np.loadtxt(spec1, unpack = True, usecols = [0, 1, 2]) spec2w, spec2f, spec2er = np.loadtxt(spec2, unpack = True, usecols = [0, 1, 2]) spec1w = -spec1w ; spec2w = - spec2w spec2wn = spec2w-shift fig = plt.figure() fig.subplots_adjust(hspace=0.2, wspace = 0.1) ax1 = fig.add_subplot(2, 1, 1) ax1.plot(spec1w, spec1f, color = 'k', label = 'First epoch') ax1.plot(spec2w, spec2f, color = 'r', label = 'Second epoch') try: ax1.plot(spec2wn, spec2f, color = 'b', linestyle = '--', label = 'Shifted') except: print 'No shift measured!' ax1.legend(loc = 'lower left', fontsize = 8) ax1.set_title('Spectrum i = %i, Trough %s/%i, $\Delta$t$_{\\rm rest}$ = %5.3f years'%(i, suffix, n_troughs-1, deltamjd_rest), fontsize = 20) ax1.text(0.05, 0.9, prefix, fontsize = 15, transform = ax1.transAxes) ax1.set_xlim(30, -2) ax1.set_ylabel('Normalized Flux') ax1.set_xlabel('Velocity (10$^3$) km/s)') xmin, xmax = -2,2 ax2 = fig.add_subplot(2, 3, 4) ax2.set_ylabel('Correlation coefficient') ax2.text(0.2, 0.85, 'CCF ', horizontalalignment = 'center', verticalalignment = 'center', transform = ax2.transAxes, fontsize = 16) ax2.set_xlim(xmin, xmax) ax2.set_ylim(0, 1.0) try: ax2.plot(lag, r, color = 'k') except: print 'No CCF data' ax3 = fig.add_subplot(2, 3, 5, sharex = ax2) #ax3.set_ylabel('N') ax3.set_xlim(xmin, xmax) ax3.axes.get_yaxis().set_ticks([]) ax3.set_xlabel('Shift: %5.1f + %5.1f - %5.1f km/s, Accel: %5.3f+ %5.3f - %5.3f cm s$^{-2}$'%(shift*1000, shift_uperr*1000, shift_loerr*1000, accel_meas, accel_uperr, accel_loerr), fontsize = 15) ax3.text(0.2, 0.85, 'CCCD ', horizontalalignment = 'center', verticalalignment = 'center', transform = ax3.transAxes, fontsize = 16) try: ax3.hist(tlags_centroid, color = 'k') except: print 'No centroid data' ax4 = fig.add_subplot(2, 3, 6, sharex = ax2) ax4.set_ylabel('N') ax4.yaxis.tick_right() ax4.yaxis.set_label_position('right') #ax4.set_xlabel('Lag (\AA)') ax4.set_xlim(xmin, xmax) ax4.text(0.2, 0.85, 'CCPD ', horizontalalignment = 'center', verticalalignment = 'center', transform = ax4.transAxes, fontsize = 16) try: ax4.hist(tlags_peak, color = 'k') except: print 'No peak data' pdf_pages.savefig(fig) plt.savefig('ccf_plots/ccfplot_'+prefix+'.png', format = 'png', bbox_inches = 'tight') plt.close(fig) #ttt = raw_input('After plot') pdf_pages.close() <file_sep>import sys import os import numpy as np from astropy import io from astropy.io import fits from astropy.io import ascii from matplotlib import pyplot as plt from astropy import constants as const from astropy import units as U from astropy.coordinates import SkyCoord from dustmaps.sfd import SFDQuery from specutils import extinction import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from scipy.optimize import curve_fit from matplotlib.backends.backend_pdf import PdfPages from lmfit import minimize, Parameters def gaussfunc_gh(paramsin,x): print paramsin amp=paramsin['amp'].value center=paramsin['center'].value sig=paramsin['sig'].value c1=-np.sqrt(3); c2=-np.sqrt(6); c3=2/np.sqrt(3); c4=np.sqrt(6)/3; c5=np.sqrt(6)/4 skew=paramsin['skew'].value kurt=paramsin['kurt'].value scale = paramsin['scale'].value ; alpha = paramsin['alpha'].value gaustot_gh=amp*np.exp(-.5*((x-center)/sig)**2)*(1+skew*(c1*((x-center)/sig)+c3*((x-center)/sig)**3)+kurt*(c5+c2*((x-center)/sig)**2+c4*((x-center)/sig)**4))+scale*x**alpha return gaustot_gh def gaussfunc_2g(paramsin,x): amp1=paramsin['amp1'].value; amp2=paramsin['amp2'].value; center1=paramsin['center1'].value; center2=paramsin['center2'].value; sig1=paramsin['sig1'].value; sig2=paramsin['sig2'].value; scale = paramsin['scale'].value ; alpha = paramsin['alpha'].value gaus1=amp1*np.exp(-.5*((x-center1)/sig1)**2) gaus2=amp2*np.exp(-.5*((x-center2)/sig2)**2) gaustot_2g=(gaus1+gaus2+scale*x**alpha) return gaustot_2g def PLot(vels,stackspec , fit_gh, fit_2g, pars_gh, pars_2g, resid_gh, resid_2g): fig3=plt.figure(3) f1=fig3.add_axes((.1,.3,.8,.6)) #xstart, ystart, xwidth, yheight --> units are fraction of the image from bottom left plt.plot(vels,stackspec,'k.') pgh,=plt.plot(vels,fit_gh,'b') p2g,=plt.plot(vels,fit_2g,'r') f1.set_xticklabels([]) #We will plot the residuals below, so no x-ticks on this plot plt.title('Multiple Gaussian Fit Example') plt.ylabel('Amplitude (Some Units)') f1.legend([pgh,p2g],['Gaus-Hermite','2-Gaus'],prop={'size':10},loc='center left') from matplotlib.ticker import MaxNLocator plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) #Removes lowest ytick label f1.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f' \ %(pars_gh[0],pars_gh[1],pars_gh[2],pars_gh[3],pars_gh[4]),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) f1.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f' \ %(pars_2g[0],pars_2g[3],pars_2g[1],pars_2g[4],pars_2g[2],pars_2g[5]),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) f2=fig3.add_axes((.1,.1,.8,.2)) resgh,res2g,=plt.plot(vels,resid_gh,'k--',vels,resid_2g,'k') plt.ylabel('Residuals') plt.xlabel('Velocity (km s$^{-1}$)') f2.legend([resgh,res2g],['Gaus-Hermite','2-Gaus'],numpoints=4,prop={'size':9},loc='upper left') plt.savefig(pp,format='pdf') plt.show() plt.clf() df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) wav_range= [(1280,1350),(1700,1800),(1950,2200),(2650,2710),(3010,3700),(3950,4050),(4140,4270)] pp = PdfPages('ContinuumNormalization_plus_EmissionLineFits.pdf') #fx=open('ALPHA_AMP_values_V.txt','w') #fx1=open('Kate_ALPHA_AMP_values_V.txt','w') #for i in range(len(df['pmf1'])): #for i in range(len(df)): for i in range(4): print 'Norm_Spectra/Normspec_'+df['pmf1'][i]+'.txt' print 'Norm_Spectra/Normspec_'+df['pmf2'][i]+'.txt' print 'Norm_Spectra/Normspec_'+df['pmf3'][i]+'.txt' if ((not os.path.isfile('Norm_Spectra/Normspec_'+df['pmf1'][i]+'.txt')) | (not os.path.isfile('Norm_Spectra/Normspec_'+df['pmf2'][i]+'.txt')) | ( not os.path.isfile('Norm_Spectra/Normspec_'+df['pmf3'][i]+'.txt'))): continue else: data1 = np.loadtxt('Norm_Spectra/Normspec_'+df['pmf1'][i]+'.txt') data2 = np.loadtxt('Norm_Spectra/Normspec_'+df['pmf2'][i]+'.txt') data3 = np.loadtxt('Norm_Spectra/Normspec_'+df['pmf3'][i]+'.txt') wave1 = data1.T[0] ; flux1 = data1.T[1] ; weight1 = data1.T[2] wave2 = data2.T[0] ; flux2 = data2.T[1] ; weight2 = data2.T[2] wave3 = data3.T[0] ; flux3 = data3.T[1] ; weight3 = data3.T[2] print len(wave1),len(flux1),len(weight1) print weight1 p_gh=Parameters() p_gh.add('amp',value=np.max(flux1),vary=True); p_gh.add('center',value=1550,min=1540,max=1560,vary=True); p_gh.add('sig',value=15,min=3,max=10,vary=True); p_gh.add('skew',value=0,vary=True,min=None,max=None); p_gh.add('kurt',value=0,vary=True,min=None,max=None); p_gh.add('scale',value=1,vary=True,min=None,max=None); p_gh.add('alpha',value=-1.5,vary=True,min=-3,max=3); p_2g=Parameters() p_2g.add('amp1',value=np.max(flux1)/2.,min=.1*np.max(flux1),max=np.max(flux1),vary=True); p_2g.add('center1',value=1550,min=1540,max=1560,vary=True); p_2g.add('sig1',value=15,min=3,max=10,vary=True); p_2g.add('amp2',value=np.max(flux1)/2.,min=.1*np.max(flux1),max=np.max(flux1),vary=True); p_2g.add('center2',value=1545,min=1540,max=1560,vary=True); p_2g.add('sig2',value=15,min=3,max=10,vary=True); p_2g.add('scale',value=1,vary=True,min=None,max=None); p_2g.add('alpha',value=-1.5,vary=True,min=-3,max=3); gausserr_gh = lambda p,x,y: gaussfunc_gh(p,x)-y gausserr_2g = lambda p,x,y: gaussfunc_2g(p,x)-y fitout_gh=minimize(gausserr_gh,p_gh,args=(wave1,flux1)) fitout_2g=minimize(gausserr_2g,p_2g,args=(wave1,flux1)) pars_gh=[p_gh['amp'].value,p_gh['center'].value,p_gh['sig'].value,p_gh['skew'].value,p_gh['kurt'].value] pars_2g=[p_2g['amp1'].value,p_2g['center1'].value,p_2g['sig1'].value,p_2g['amp2'].value,p_2g['center2'].value,p_2g['sig2'].value] fit_gh=gaussfunc_gh(p_gh,wave1) fit_2g=gaussfunc_2g(p_2g,wave1) resid_gh=fit_gh- flux1 resid_2g=fit_2g- flux1 print('Fitted Parameters (Gaus+Hermite):\nAmp = %.2f , Center = %.2f , Disp = %.2f\nSkew = %.2f , Kurt = %.2f' \ %(pars_gh[0],pars_gh[1],pars_gh[2],pars_gh[3],pars_gh[4])) print('Fitted Parameters (Double Gaussian):\nAmp1 = %.2f , Center1 = %.2f , Sig1 = %.2f\nAmp2 = %.2f , Center2 = %.2f , Sig2 = %.2f' \ %(pars_2g[0],pars_2g[1],pars_2g[2],pars_2g[3],pars_2g[4],pars_2g[5])) PLot(wave1,flux1,fit_gh, fit_2g, pars_gh, pars_2g, resid_gh, resid_2g) <file_sep>import numpy as np import os def velocity(wave,ion_wave,z): #print wave #print z,ion_wave c = 299792.0# in km/s vel =np.zeros(len(wave)) zabs = np.zeros(len(wave)) for i in range(len(wave)): #print i,wave[i],zabs[i],vel[i] zabs[i] = (wave[i]/ion_wave) -1.0 vel[i] = -((((1+z)/(1+zabs[i]))**2-1.0)/(((1+z)/(1+zabs[i]))**2+1))*c return vel cw=1549.0 pf = np.genfromtxt('BALcomponents_output.txt',names=('index','filename','vmin','vmax','nt','ntroughs','paddmin','paddmax','ew','ewerr'),dtype=(int,'|S35',float,float,float,float,float,float,float)) for i in range(len(pf)): wave,flux,err = np.loadtxt(pf['filename'][i]).T vel = velocity(wave1, cw, 0.0) xx = np.where((vel >= pf['vmin'][i] - pf['paddmin'][i]) & ( vel <= pf['vmax'][i]+pf['paddmax'][i]))[] nvel=vel[xx]/1000 ; nflux = flux[xx] ; nerr = 1.0/np.sqrt(err[xx]) sfilename = 'spec-'+pf['filename'][i].split(_)[1]+pf['filename'][i].split(_)[2]pf['filename'][i].split(_)[3] savefilename = 'fivecol/'+sfilename+'.crop.5col_0' print savefilename #np.savetxt(savefilename,zip(nvel,nflux,nerr,nflux,nerr)) <file_sep>import numpy as np import os df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) pf = np.genfromtxt('BALcomponents_output.txt',names=('index','filename','vmin','vmax','nt','ntroughs','paddmin','paddmax','ew','ewerr'),dtype=(int,'|S35',float,float,float,float,float,float,float)) print pf['filename'] fpmf = [] fittype =[] for k in range(len(pf['filename'])): fpmf.append(pf['filename'][k].strip().split('_')[1]) if (pf['filename'][k].strip().split('_')[3].split('.')[0] == 'v'): fittype.append('voigt') else: fittype.append('2guass') ab=open('linefits.txt','w') fpmf = np.array(fpmf) #print fpmf #print fittype[0] for i in range(len(df)): #print type(df['pmf1'][i]),type(fpmf) xx = np.where(fpmf == str(df['pmf1'][i]).strip())[0] print xx if len(xx)> 0: print>>ab,'{}\t{}\t{}\t{}\t{}'.format( i,df['pmf1'][i],df['pmf2'][i],df['pmf3'][i],fittype[xx[0]]) #dksh=raw_input() ab.close() <file_sep>#!/usr/bin/python #-*- coding: utf-8 -*- import scipy import numpy as np class Spectrum(object): ''' The Spectrum object ''' def __init__(self): ''' Initialize spectrum object ''' self._wavelengths= None self._flux = None self._flux_error = None self._c = None self._units = None @property def wavelengths(self): return self._wavelengths @wavelengths.setter def wavelengths(self, new_wave): self._wavelengths = new_wave @property def flux(self): return self._flux @flux.setter def flux(self, new_flux): self._flux = new_flux @property def flux_error(self): return self._flux_error @flux_error.setter def flux_error(self, new_ferr): self._flux_error = new_ferr @property def c(self): return self._c @c.setter def c(self, new_c): self._c = new_c @property def units(self): return self._units @units.setter def units(self, new_units): self._units = new_units @property def redshift(self): return self._redshift @units.setter def redshift(self, redshift): self._redshift = new_redshift @property def objname(self): return self._objname @units.setter def objname(self, objname): self._objname = new_objname <file_sep>#!/usr/bin/python #-*- coding: utf-8 -*- import sys import numpy as np from astropy import io from astropy.io import fits as pyfits from astropy.io import ascii from astropy.table import Table from matplotlib import pyplot as plt from Spectrum import Spectrum import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from pylab import * from scipy import optimize def runningMeanFast(x,N): return np.convolve(x, np.ones((N,))/N)[(N-1):] def SmoothBoxCar(x,N): boxcar=np.ones(N) return convolve(x, boxcar/boxcar.sum()) #Define the continuum power law function #reddening is E(B - V) def redpowerlaw(x, amp, index, reddening): w = x/10000 #convert wavelengths to microns a = [185, 27, 0.005, 0.010, 0.012, 0.030] l = [0.042, 0.08, 0.22, 9.7, 18, 25] b = [90, 5.50, -1.95, -1.95, -1.80, 0] n = [2, 4, 2, 2, 2, 2] K = [2.89, 0.91, 0.02, 1.55, 1.72, 1.89] R_V = 2.93 xi = 0 for i in xrange(0,6): xi+= a[i] / (np.power((w/l[i]), n[i]) + np.power((l[i]/w), n[i]) + b[i]) ElB = (xi*(1+R_V)-R_V)*reddening ##E(lambda - V) extinction = np.power(10, -0.4*ElB) ##10^(-0.4*E(lambda - V)) return (amp*(x/2000.)**(index))*np.power(10, (-0.4*(xi*(1+R_V)-R_V)*reddening)) ####Write a fitting program ################ def fit_three_params(x, y, errs): fittingx = x fittingy = y weights = errs #print x[0:10], y[0:10], weights[0:10] p_init = [8., -1.0, 0.05] out, var_matrix = optimize.curve_fit(redpowerlaw, fittingx, fittingy, p_init, maxfev = 10000) #print out #print var_matrix pfin = out #cov = out[1] redco = pfin[2] index = pfin[1] amp = pfin[0] #print amp, index, redco #errors = np.sqrt(np.diag(cov)) #indexErr = errors[0] #ampErr = errors[1] #redcoErr = errors[2] modelval = redpowerlaw(fittingx, amp, index, redco) return amp, index, redco def continuum_fit(wave, flux, error, redshift): ########################### spectrum = Spectrum() spectrum.wavelengths = wave spectrum.flux = flux spectrum.flux_error = error smooth=False N_kern=5 #pxl plotfit=True fitcon=True ############################################ ########################################### ####### Define line-free regions and calculate weighting scheme. This will need to ####### be updated to deal with different wavelength regions. maxwav = np.max(spectrum.wavelengths) minwav = np.min(spectrum.wavelengths) #RLF regions from Filiz ak et al., updated a bit, and also using a different one for low-z targets. if np.logical_and(redshift > 1.65, redshift < 1.85): index1=np.where(np.logical_and(spectrum.wavelengths>=1280.,spectrum.wavelengths<=1350.))[0] index2=np.where(np.logical_and(spectrum.wavelengths>=1425.,spectrum.wavelengths<=1450.))[0] index3=np.where(np.logical_and(spectrum.wavelengths>=1700.,spectrum.wavelengths<=1800.))[0] index4=np.where(np.logical_and(spectrum.wavelengths>=1950.,spectrum.wavelengths<=2200.))[0] index5=np.where(np.logical_and(spectrum.wavelengths>=2650.,spectrum.wavelengths<=2710.))[0] index6=np.where(np.logical_and(spectrum.wavelengths>=3010.,spectrum.wavelengths<=3700.))[0] index7=np.where(np.logical_and(spectrum.wavelengths>=3950.,spectrum.wavelengths<=4050.))[0] index8=np.where(np.logical_and(spectrum.wavelengths>=4140.,spectrum.wavelengths<=4270.))[0] index9=np.where(np.logical_and(spectrum.wavelengths>=4400.,spectrum.wavelengths<=4770.))[0] index10=np.where(np.logical_and(spectrum.wavelengths>=5100.,spectrum.wavelengths<=6400.))[0] if np.logical_or(redshift >= 1.85, redshift <= 1.65): index1=np.where(np.logical_and(spectrum.wavelengths>=1280.,spectrum.wavelengths<=1350.))[0] index2=np.where(np.logical_and(spectrum.wavelengths>=1700.,spectrum.wavelengths<=1800.))[0] index3=np.where(np.logical_and(spectrum.wavelengths>=1950.,spectrum.wavelengths<=2200.))[0] index4=np.where(np.logical_and(spectrum.wavelengths>=2650.,spectrum.wavelengths<=2710.))[0] index5=np.where(np.logical_and(spectrum.wavelengths>=3010.,spectrum.wavelengths<=3700.))[0] index6=np.where(np.logical_and(spectrum.wavelengths>=3950.,spectrum.wavelengths<=4050.))[0] index7=np.where(np.logical_and(spectrum.wavelengths>=4140.,spectrum.wavelengths<=4270.))[0] index8=np.where(np.logical_and(spectrum.wavelengths>=4400.,spectrum.wavelengths<=4770.))[0] index9=np.where(np.logical_and(spectrum.wavelengths>=5100.,spectrum.wavelengths<=6400.))[0] index10=np.where(spectrum.wavelengths>=6900.)[0] #print 'made it to here!' indexes=np.concatenate((index1, index2, index3, index4, index5, index6, index7, index8, index9, index10)) #Calculate weights for each pixel n1, n2, n3, n4, n5, n6, n7, n8, n9, n10 = np.size(index1), np.size(index2), np.size(index3), \ np.size(index4), np.size(index5), np.size(index6), np.size(index7), np.size(index8), np.size(index9), np.size(index10) ntot = n1+n2+n3+n4+n5+n6+n7+n8+n9+n10 w1 = list() w2 = list() w3 = list() w4 = list() w5 = list() w6 = list() w7 = list() w8 = list() w9 = list() w10 = list() for j in xrange(0, n1): w1.append(ntot/float(n1)) for j in xrange(0, n2): w2.append(ntot/float(n2)) for j in xrange(0, n3): w3.append(ntot/float(n3)) for j in xrange(0, n4): w4.append(ntot/float(n4)) for j in xrange(0, n5): w5.append(ntot/float(n5)) for j in xrange(0, n6): w6.append(ntot/float(n6)) for j in xrange(0, n7): w7.append(ntot/float(n7)) for j in xrange(0, n8): w8.append(ntot/float(n8)) for j in xrange(0, n9): w9.append(ntot/float(n9)) for j in xrange(0, n10): w10.append(ntot/float(n10)) allweights = concatenate((w1, w2, w3, w4, w5, w6, w7, w8, w9, w10)) ############################################ ########################################### ##Fit the spectrum to get the actual fit first. spec_to_fit1 = Spectrum() spec_to_fit1.wavelengths = spectrum.wavelengths[indexes] spec_to_fit1.flux =spectrum.flux[indexes] spec_to_fit1.flux_error = spectrum.flux_error[indexes] num_wavs_fit = np.size(spec_to_fit1.wavelengths) toweight = True if toweight: weights_specfit = allweights else: weights_specfit = spec_to_fit1.flux_error #weights_specfit = ones(num_wavs_fit) #Iteratively fit continuum and drop 3sigma outliers with 10 iterations. newregions = spec_to_fit1.wavelengths newflux = spec_to_fit1.flux newweights = weights_specfit newfluxerr = spec_to_fit1.flux_error checksize = 10 while checksize > 0: amp, index, redco = fit_three_params(newregions, newflux, newweights) first_continuum_fit = redpowerlaw(spectrum.wavelengths, amp, index, redco) ###iterate and remove pixels that deviate from too con_fit_fitreg = redpowerlaw(newregions, amp, index, redco) diff = con_fit_fitreg - newflux sigma = np.std(diff) toolarge = np.where(diff >= 3*sigma) justright = np.where(diff <= 3*sigma) #print np.size(newregions) #print np.size(toolarge) checksize = np.size(toolarge) newregions = newregions[justright] newflux = newflux[justright] newweights = newweights[justright] newfluxerr = newfluxerr[justright] finalspecfitwave, finalspecfitflux, finalweights_specfit = newregions, newflux, newweights #final continuum fit amp, index, redco = fit_three_params(finalspecfitwave, finalspecfitflux, finalweights_specfit) continuum_fit = redpowerlaw(spectrum.wavelengths, amp, index, redco) #print 'Amplitude, Index, Reddening', amp, index, redco spec_to_fit = Spectrum() spec_to_fit.wavelengths = finalspecfitwave spec_to_fit.flux = finalspecfitflux spec_to_fit.flux_error = newfluxerr num_wavs_fit = np.size(spec_to_fit.wavelengths) toweight = True if toweight: weights_specfit = allweights else: weights_specfit = spec_to_fit.flux_error #weights_specfit = ones(num_wavs_fit) ############################################ ########################################### ##### Now do Monte Carlo simulations to get the uncertainties. num_samples = 100 num_wavelengths_fit = np.size(spec_to_fit.wavelengths) num_wavelengths_tot = np.size(spectrum.wavelengths) if toweight: weights = allweights else: #weights = ones(num_wavelengths_fit) weights = ones(num_wavelengths_fit) consamples = zeros((num_samples, num_wavelengths_tot)) ampsamples = zeros(num_samples) indexsamples = zeros(num_samples) meancon = zeros(num_wavelengths_tot) errcon = zeros(num_wavelengths_tot) #Monte carlo iterations for uncertainties for j in xrange(0, num_samples): specfit = zeros(num_wavelengths_fit) for k in xrange(0, num_wavelengths_fit): specfit[k] = spec_to_fit.flux[k]+randn()*spec_to_fit.flux_error[k] plot2 = False if plot2: figure2, ax3 = plt.subplots(1, figsize=(12,4)) ax3.errorbar(spectrum.wavelengths, spectrum.flux, yerr = spectrum.flux_error, color = 'b', label = 'Spec') ax3.plot(spectrum.wavelengths, spectrum.flux, color = 'k', label = 'Spec') ax3.plot(spec_to_fit.wavelengths, specfit, color = 'r', label = 'Fitting flux') ymin = min(0, np.percentile(spectrum.flux, 1)) ymax = 1.25*np.percentile(spectrum.flux, 99) ax3.set_xlim(min(spectrum.wavelengths), max(spectrum.wavelengths)) ax3.set_ylim(ymin, ymax) ax3.set_xlabel('Rest-frame Wavelength (\AA)', fontsize = 20) ax3.set_ylabel('Flux $(10^{-17} erg/cm^2/s/\AA)$', fontsize = 20) #ax2.set_title('SDSS '+str(object_info['name'][i])+ ', $z$ = '+str(object_info['z'][i]), fontsize = 22) ax3.tick_params(axis='x', labelsize=19) ax3.tick_params(axis='y', labelsize=19) ax3.legend() ax3.grid() plt.show() plt.close(figure2) ampout, indexout, redout = fit_three_params(spec_to_fit.wavelengths, specfit, weights) contflux = redpowerlaw(spectrum.wavelengths, ampout, indexout, redout) ampsamples[j] = ampout indexsamples[j] = indexout for m in xrange(0, num_wavelengths_tot): consamples[j,m] += contflux[m] for j in xrange(0, num_wavelengths_tot): meancon[j] = mean(consamples[:,j]) errcon[j] = std(consamples[:,j]) conflux = continuum_fit confluxerr = errcon mean_amp = amp err_amp = np.std(ampsamples) mean_index = index err_index = np.std(indexsamples) plotfit = False if plotfit: figure, ax2 = plt.subplots(1, figsize=(12,4)) ax2.plot(spectrum.wavelengths, spectrum.flux, color = 'k', label = 'Spec') ax2.plot(spectrum.wavelengths, conflux, color = 'b', label = 'Continuum', linewidth = 2) ymin = min(0, np.percentile(spectrum.flux, 1)) ymax = 1.25*np.percentile(spectrum.flux, 99) ax2.set_xlim(min(spectrum.wavelengths), max(spectrum.wavelengths)) ax2.set_ylim(ymin, ymax) ax2.set_xlabel('Rest-frame Wavelength (\AA)', fontsize = 20) ax2.set_ylabel('Flux $(10^{-17} erg/cm^2/s/\AA)$', fontsize = 20) #ax2.set_title('SDSS '+str(object_info['name'][i])+ ', $z$ = '+str(object_info['z'][i]), fontsize = 22) ax2.tick_params(axis='x', labelsize=19) ax2.tick_params(axis='y', labelsize=19) ax2.legend() ax2.grid() plt.show() #Return the continuum fit, flux, uncertainty associated with the Monte Carlo iterations, and fitting regions. return spectrum.wavelengths, conflux, confluxerr, mean_amp, mean_index, redco, spec_to_fit.wavelengths, spec_to_fit.flux <file_sep>import numpy as np import os df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) def download_spectra(plate, mjd, fiber, dirname='.'): ''' Downloads SDSS spectra from DR14 and puts it in dirname Change the SDSS URL to download from a different location ''' FITS_FILENAME = 'spec-%(plate)04i-%(mjd)05i-%(fiber)04i.fits' SDSS_URL = ('https://data.sdss.org/sas/dr14/eboss/spectro/redux/v5_10_0/spectra/%(plate)04i/' 'spec-%(plate)04i-%(mjd)05i-%(fiber)04i.fits') SDSS_URL = ('https://data.sdss.org/sas/dr8/sdss/spectro/redux/26/spectra/%(plate)04i/' 'spec-%(plate)04i-%(mjd)05i-%(fiber)04i.fits') # print SDSS_URL % dict(plate=plate,mjd=mjd,fiber=fiber) download_url = 'wget '+SDSS_URL % dict(plate=plate,mjd=mjd,fiber=fiber) print download_url os.system(download_url) mv_cmd='mv '+FITS_FILENAME % dict(plate=plate,mjd=mjd,fiber=fiber) + ' '+dirname+'/.' #print mv_cmd os.system(mv_cmd) for i in range(len(df['pmf1'])): print df['pmf1'][i] plate = int(df['pmf1'][i].split('-')[0]) mjd = int(df['pmf1'][i].split('-')[1]) fiber = int(df['pmf1'][i].split('-')[2]) print plate,mjd,fiber download_spectra(int(df['pmf1'][i].split('-')[0]),int(df['pmf1'][i].split('-')[1]),int(df['pmf1'][i].split('-')[2]),'Kate_Sources') download_spectra(int(df['pmf2'][i].split('-')[0]),int(df['pmf2'][i].split('-')[1]),int(df['pmf2'][i].split('-')[2]),'Kate_Sources') download_spectra(int(df['pmf3'][i].split('-')[0]),int(df['pmf3'][i].split('-')[1]),int(df['pmf3'][i].split('-')[2]),'Kate_Sources') <file_sep>import sys import os import numpy as np from astropy import io from astropy.io import fits from astropy.io import ascii from matplotlib import pyplot as plt from astropy import constants as const from astropy import units as U from astropy.coordinates import SkyCoord from dustmaps.sfd import SFDQuery from specutils import extinction import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from scipy.optimize import curve_fit from matplotlib.backends.backend_pdf import PdfPages from lmfit import minimize, Parameters from astropy.modeling.models import Voigt1D def dered_flux(Av,wave,flux): dered_flux = np.zeros(len(wave)) for i in range(len(wave)): ext_lambda= extinction.extinction_ccm89(wave[i] * U.angstrom, a_v= Av, r_v= 3.1) tau_lambda= ext_lambda/(1*1.086) dered_flux[i]= flux[i] * np.exp(tau_lambda) return dered_flux def myVoigt(x, amp, center, fwhm_l, fwhm_g, scale, alpha): v1= Voigt1D(x_0=center, amplitude_L=amp, fwhm_L=fwhm_l, fwhm_G=fwhm_g) powerlaw = scale*x**alpha voigt = v1(x) voigt_tot = (voigt+powerlaw) return voigt_tot def myGaussHermite(x, amp, center, sig, skew, kurt, scale, alpha): c1=-np.sqrt(3); c2=-np.sqrt(6); c3=2/np.sqrt(3); c4=np.sqrt(6)/3; c5=np.sqrt(6)/4 gausshermite = amp*np.exp(-.5*((x-center)/sig)**2)*(1+skew*(c1*((x-center)/sig)+c3*((x-center)/sig)**3)+kurt*(c5+c2*((x-center)/sig)**2+c4*((x-center)/sig)**4)) powerlaw = scale*x**alpha gaustot_gh = (gausshermite+powerlaw) return gaustot_gh def myDoubleGauss(x, amp1, center1, sig1, amp2, center2, sig2, scale, alpha): gaus1=amp1*np.exp(-.5*((x-center1)/sig1)**2) gaus2=amp2*np.exp(-.5*((x-center2)/sig2)**2) powerlaw = scale*x**alpha gaustot_2g= (gaus1+gaus2+powerlaw) return gaustot_2g def ext_coeff(lamb): inv_lamba=[0.45,0.61,0.8,1.82,2.27,2.7,3.22,3.34,3.46,3.6,3.75,3.92,4.09,4.28,4.50,4.73,5.00,5.24,5.38,5.52,5.70,5.88,6.07,6.27,6.48,6.72,6.98,7.23,7.52,7.84] smc_ext=[-2.61,-2.47,-2.12,0.0,1.0,1.67,2.29,2.65,3.0,3.15,3.49,3.91,4.24,4.53,5.3,5.85,6.38,6.76,6.9,7.17,7.71,8.01,8.49,9.06,9.28,9.84,10.8,11.51,12.52,13.54] xy=np.interp(1.0/(lamb*10**(-4)),inv_lamba,smc_ext) ext_lamb=(xy+2.98)/3.98 # Rv=2.98 #return(z,ext_lamb) return(ext_lamb) def myfunct(wave, a , b): return a*ext_coeff(wave)*wave**(b) def waveRange(wave): #wav_range=[[1300.,1350.],[1420.,1470.],[1700.,1800.],[2080.,2215],[2480.,2655],[3225.,3900.],[4200.,4230.],[4435.,4700.],[5200.,5700.]] wav_range= [(1400,1850)] mwav_range = [] for rr in wav_range: if ((np.min(wave) < rr[0]) & (np.max(wave) > rr[1])): nrr0 = rr[0] ; nrr1 = rr[1] elif ((np.min(wave) > rr[0]) & (np.min(wave) < rr[1])& (np.max(wave) < rr[1])): nrr0 = np.min(wave) ; nrr1 = rr[1] elif ((np.min(wave) < rr[0]) & (np.max(wave) > rr[0]) &(np.max(wave) < rr[1])): nrr0 = rr[0] ; nrr1 = np.max(wave) else : continue mwav_range.append([nrr0,nrr1]) return mwav_range def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] <NAME>, <NAME>, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, <NAME>, <NAME>, <NAME> Cambridge University Press ISBN-13: 9780521880688 """ import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except (ValueError, msg): raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order+1) half_window = (window_size -1) // 2 # precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # pad the signal at the extremes with # values taken from the signal itself firstvals = np.asarray(y[0]) - np.abs( y[1:half_window+1][::-1] - np.asarray(y[0]) ) lastvals = np.asarray(y[-1]) + np.abs(y[-half_window-1:-1][::-1] - np.asarray(y[-1])) y = np.concatenate((firstvals, y, lastvals)) return np.convolve( m[::-1], y, mode='valid') def compute_alpha_voigt(wl, spec, ivar, wav_range, per_value=[1,99.5]): print ' Voigt Routine begins' spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 print ivar wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec #print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print 'voigt Debug',len(wavelength) pv0=[20.0, 1545., 50., 8.0,1.0,-1.0] param_boundsv = ([0,1540,0.0,0.0,0.0,-np.inf],[np.inf,1550,np.inf,20,np.inf,np.inf]) try: #plt.plot(wavelength,spectra) #plt.show() poptv, pcovv = curve_fit(myVoigt, wavelength, spectra, pv0, sigma=1.0/np.sqrt(invar),bounds=param_boundsv) except (RuntimeError,TypeError): AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv, CHISQv, DOFv = np.nan, np.nan, np.nan, np.nan,np.nan, np.nan, np.nan, np.nan else: AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv = poptv[0], poptv[1], poptv[2], poptv[3], poptv[4], poptv[5] CHISQv = np.sum(invar * (spectra - myVoigt(wavelength, poptv[0], poptv[1], poptv[2], poptv[3], poptv[4], poptv[5]))**2) # DOF = N - n , n = 2 DOFv = len(spectra) - 6 print 'Voight Routine ends' print 'Compute Alpha:', AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv, CHISQv, DOFv return AMPv, CENTERv, SIGMALv, SIGMAGv, SCALEv, ALPHAv, CHISQv, DOFv def compute_alpha_gh(wl, spec, ivar, wav_range, per_value=[1,99.5]): print ' GH Routine begins' print ivar spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 print ivar wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print '2H Debug',len(wavelength) pgh0=[20.0, 1545., 8., 0.2, 0.4,21.0,-1.0] param_boundsgh = ([0,1540,-20,-1,-np.inf,0,-np.inf],[np.inf,1555,20,1,np.inf,np.inf,np.inf]) try: #plt.plot(wavelength,spectra) #plt.show() poptgh, pcovgh = curve_fit(myGaussHermite, wavelength, spectra, pgh0, sigma=1.0/np.sqrt(invar),bounds=param_boundsgh) except (RuntimeError, TypeError): AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh, SCALEgh, ALPHAgh, CHISQgh, DOFgh = np.nan, np.nan, np.nan, np.nan,np.nan, np.nan, np.nan, np.nan, np.nan else: AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh, SCALEgh, ALPHAgh = poptgh[0], poptgh[1], poptgh[2], poptgh[3], poptgh[4], poptgh[5], poptgh[6] CHISQgh = np.sum(invar * (spectra - myGaussHermite(wavelength, poptgh[0], poptgh[1], poptgh[2], poptgh[3], poptgh[4], poptgh[5], poptgh[6]))**2) # DOF = N - n , n = 2 DOFgh = len(spectra) - 7 print 'GH Routine ends' print 'Compute Alpha:', AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh,SCALEgh, ALPHAgh, CHISQgh, DOFgh return AMPgh, CENTERgh, SIGMAgh, SKEWgh, KURTgh,SCALEgh, ALPHAgh, CHISQgh, DOFgh def compute_alpha_2g(wl, spec, ivar, wav_range, per_value=[1,99.5]): print '2G Routine begins' spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print '2G Debug',len(wavelength) pg20=[10.0, 1545., 9., 10.0, 1550., 18.,20.0,1] param_bounds2g = ([0,1540,5,0,1540,0,0,-np.inf],[np.inf,1555,np.inf,np.inf,1555,1000,np.inf,np.inf]) try: #plt.plot(wavelength,spectra) #plt.show() popt2g, pcov2g = curve_fit(myDoubleGauss, wavelength, spectra, pg20, sigma=1.0/np.sqrt(invar),bounds=param_bounds2g) except (RuntimeError, TypeError): AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g, CHISQ2g, DOF2g = np.nan, np.nan, np.nan, np.nan,np.nan, np.nan, np.nan, np.nan, np.nan, np.nan else: AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g = popt2g[0], popt2g[1], popt2g[2], popt2g[3], popt2g[4], popt2g[5], popt2g[6], popt2g[7] CHISQ2g = np.sum(invar * (spectra - myDoubleGauss(wavelength, popt2g[0], popt2g[1], popt2g[2], popt2g[3], popt2g[4], popt2g[5], popt2g[6], popt2g[7]))**2) # DOF = N - n , n = 2 DOF2g = len(spectra) - 8 print '2G Routine ends' print 'Compute Alpha:' ,AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g, CHISQ2g, DOF2g return AMPa2g, CENTERa2g, SIGMAa2g, AMPb2g, CENTERb2g, SIGMAb2g, SCALE2g, ALPHA2g, CHISQ2g, DOF2g def maskOutliers_v(wave, flux, weight, amp, center, sigmal, sigmag, scale, alpha): model = myVoigt(wave,amp, center, sigmal, sigmag, scale, alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model print 'Weights Before mask',weight #ww = np.where (np.abs(fluxdiff) > 3*std) ww = np.where (((np.abs(fluxdiff) > 2*std) & (flux <= np.median(flux))) | ((np.abs(fluxdiff) > 4*std) & (flux >= np.median(flux)))) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) print 'Weights After mask',weight return wave,flux,weight def maskOutliers_gh(wave, flux, weight, amp, center, sigma, skew, kurt, scale, alpha): model = myGaussHermite(wave,amp, center, sigma, skew, kurt, scale, alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model print 'Weights Before mask',weight #ww = np.where (np.abs(fluxdiff) > 3*std) ww = np.where (((np.abs(fluxdiff) > 2*std) & (flux <= np.median(flux))) | ((np.abs(fluxdiff) > 4*std) & (flux >= np.median(flux)))) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) print 'Weights After mask',weight return wave,flux,weight def maskOutliers_2g(wave,flux,weight,amp1,center1,sigma1,amp2,center2,sigma2,scale,alpha): model = myDoubleGauss(wave,amp1,center1,sigma1,amp2,center2,sigma2,scale,alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model #ww = np.where (np.abs(fluxdiff) > 3*std) ww = np.where (((np.abs(fluxdiff) > 2*std) & (flux <= np.median(flux))) | ((np.abs(fluxdiff) > 4*std) & (flux >= np.median(flux)))) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) return wave,flux,weight def minmax(vec): return min(vec),max(vec) #Version _ Tried small sigma values for both Gaussians in GausDouble and GausHermite #Version II Tried making one of the sigmas high, one 1 and two 54 GausDouble; Same as before for GausHermite #Version III Changing both the central wavelength to 1550 for GausDouble df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) wav_range= [(1280,1350),(1700,1800),(1950,2200),(2650,2710),(3010,3700),(3950,4050),(4140,4270)] pp = PdfPages('ContinuumNormalization_plus_EmissionLineFits_V.pdf') #fx=open('ALPHA_AMP_values_V.txt','w') #fx1=open('Kate_ALPHA_AMP_values_V.txt','w') #for i in range(len(df['pmf1'])): for i in range(len(df)): #for i in range(12): print 'Kate_Sources/spec-'+df['pmf1'][i]+'.fits' print 'Kate_Sources/spec-'+df['pmf2'][i]+'.fits' print 'Kate_Sources/spec-'+df['pmf3'][i]+'.fits' data1 = fits.open('Kate_Sources/spec-'+df['pmf1'][i]+'.fits')[1].data data2 = fits.open('Kate_Sources/spec-'+df['pmf2'][i]+'.fits')[1].data data3 = fits.open('Kate_Sources/spec-'+df['pmf3'][i]+'.fits')[1].data wave1 = 10**data1.loglam.copy() flux1 = data1.flux.copy() weight1 = (data1.ivar).copy() sigma1 = 1.0/np.sqrt((data1.ivar).copy()) wave2 = 10**data2.loglam.copy() flux2 = data2.flux.copy() weight2 = (data2.ivar).copy() sigma2 = 1.0/np.sqrt((data2.ivar).copy()) wave3 = 10**data3.loglam.copy() flux3 = data3.flux.copy() weight3 = (data3.ivar).copy() sigma3 = 1.0/np.sqrt((data3.ivar).copy()) print len(wave1),len(flux1),len(weight1) print weight1 print data1.and_mask #clean QSO #sn1= flux1*np.sqrt(weight1) ; sn2= flux2*np.sqrt(weight2); sn3= flux3*np.sqrt(weight3) #w1 = (weight1>0)&((sn1<-10)|(sn1>80)); w2 = (weight2>0)&((sn2<-10)|(sn2>80)) ; w3 = (weight3>0)&((sn3<-10)|(sn3>80)) #print w1,w2,w3 #weight1[w1] = 0; flux1[w1] = 0 #weight2[w2] = 0; flux2[w2] = 0 #weight3[w3] = 0; flux3[w3] = 0 #de-redden the flux info = fits.open('Kate_Sources/spec-'+df['pmf1'][i]+'.fits')[2].data coords = SkyCoord(info['RA'],info['DEC'],unit='degree',frame='icrs') sfd = SFDQuery() eb_v = sfd(coords) dered_flux1 = dered_flux(3.1*eb_v,wave1,flux1) dered_flux2 = dered_flux(3.1*eb_v,wave2,flux2) dered_flux3 = dered_flux(3.1*eb_v,wave3,flux3) # Change wavelengths to rest wavellegths rwave1 = wave1/(1.0+df['z'][i]) rwave2 = wave2/(1.0+df['z'][i]) rwave3 = wave3/(1.0+df['z'][i]) #Clip all the spectra to same wavelength bounds Necessary to capture variation in alpha wmin1,wmax1 = minmax(rwave1) wmin2,wmax2 = minmax(rwave2) wmin3,wmax3 = minmax(rwave3) wlim1,wlim2 = max([wmin1,wmin2,wmin3]),min([wmax1,wmax2,wmax3]) l1 = np.where((rwave1 >= 1410) & (rwave1 <= 1650))[0] l2 = np.where((rwave2 >= 1410) & (rwave2 <= 1650))[0] l3 = np.where((rwave3 >= 1410) & (rwave3 <= 1650))[0] crwave1 = rwave1[l1];cdered_flux1 = dered_flux1[l1];cweight1 = weight1[l1];csigma1= sigma1[l1] crwave2 = rwave2[l2];cdered_flux2 = dered_flux2[l2];cweight2 = weight2[l2];csigma2 = sigma2[l2] crwave3 = rwave3[l3];cdered_flux3 = dered_flux3[l3];cweight3 = weight3[l3];csigma3 = sigma3[l3] #Initial Mask for broad absorptions cut1 = np.nanpercentile(cdered_flux1, 20) cut2 = np.nanpercentile(cdered_flux2, 20) cut3 = np.nanpercentile(cdered_flux3, 20) xx1 = np.where(cdered_flux1 < cut1)[0] xx2 = np.where(cdered_flux2 < cut2)[0] xx3 = np.where(cdered_flux3 < cut3)[0] print cut1 print dered_flux1[xx1] cweight1[xx1] = 0 cweight2[xx2] = 0 cweight3[xx3] = 0 #Fit powerlaw iterate and mask outliers iteration = 3 for j in range(iteration): if j == 0: print 'iteration 1 Begins' print j,'GH',df['pmf1'][i] AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1, CHISQgh1, DOFgh1 = compute_alpha_gh(crwave1, cdered_flux1, cweight1, waveRange(crwave1)) print j,'2G',df['pmf1'][i] AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ,CHISQ2g1, DOF2g1 = compute_alpha_2g(crwave1, cdered_flux1, cweight1, waveRange(crwave1)) print j,'V',df['pmf1'][i] AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1, CHISQv1, DOFv1 = compute_alpha_voigt(crwave1, cdered_flux1, cweight1, waveRange(crwave1)) print 'Object 1 Done' print j,'GH',df['pmf2'][i] AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2, CHISQgh2, DOFgh2 = compute_alpha_gh(crwave2, cdered_flux2, cweight2, waveRange(crwave2)) print j,'2G',df['pmf2'][i] AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ,CHISQ2g2, DOF2g2 = compute_alpha_2g(crwave2, cdered_flux2, cweight2, waveRange(crwave2)) print j,'V',df['pmf2'][i] AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2, CHISQv2, DOFv2 = compute_alpha_voigt(crwave2, cdered_flux2, cweight2, waveRange(crwave2)) print 'Object 2 Done' print j,'GH',df['pmf3'][i] AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3, CHISQgh3, DOFgh3 = compute_alpha_gh(crwave3, cdered_flux3, cweight3, waveRange(crwave3)) print j,'2G',df['pmf3'][i] AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ,CHISQ2g3, DOF2g3 = compute_alpha_2g(crwave3, cdered_flux3, cweight3, waveRange(crwave3)) print j,'V',df['pmf3'][i] AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3, CHISQv3, DOFv3 = compute_alpha_voigt(crwave3, cdered_flux3, cweight3, waveRange(crwave3)) print 'Object 3 Done' nwavegh1 = crwave1; nfluxgh1=cdered_flux1;nweightgh1 = cweight1 nwavegh2 = crwave2; nfluxgh2=cdered_flux2;nweightgh2 = cweight2 nwavegh3 = crwave3; nfluxgh3=cdered_flux3;nweightgh3 = cweight3 nwave2g1 = crwave1; nflux2g1=cdered_flux1;nweight2g1 = cweight1 nwave2g2 = crwave2; nflux2g2=cdered_flux2;nweight2g2 = cweight2 nwave2g3 = crwave3; nflux2g3=cdered_flux3;nweight2g3 = cweight3 nwavev1 = crwave1; nfluxv1=cdered_flux1;nweightv1 = cweight1 nwavev2 = crwave2; nfluxv2=cdered_flux2;nweightv2 = cweight2 nwavev3 = crwave3; nfluxv3=cdered_flux3;nweightv3 = cweight3 print 'iteration 1 Ends' continue else: nwavegh1,nfluxgh1,nweightgh1 = maskOutliers_gh(nwavegh1, nfluxgh1, nweightgh1, AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1) nwavegh2,nfluxgh2,nweightgh2 = maskOutliers_gh(nwavegh2, nfluxgh2, nweightgh2, AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2) nwavegh3,nfluxgh3,nweightgh3 = maskOutliers_gh(nwavegh3, nfluxgh3, nweightgh3, AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3) nwave2g1,nflux2g1,nweight2g1 = maskOutliers_2g(nwave2g1, nflux2g1, nweight2g1, AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1) nwave2g2,nflux2g2,nweight2g2 = maskOutliers_2g(nwave2g2, nflux2g2, nweight2g2, AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2) nwave2g3,nflux2g3,nweight2g3 = maskOutliers_2g(nwave2g3, nflux2g3, nweight2g3, AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3) nwavev1,nfluxv1,nweightv1 = maskOutliers_v(nwavev1, nfluxv1, nweightv1, AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1 ) nwavev2,nfluxv2,nweightv2 = maskOutliers_v(nwavev2, nfluxv2, nweightv2, AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2 ) nwavev3,nfluxv3,nweightv3 = maskOutliers_v(nwavev3, nfluxv3, nweightv3, AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3 ) print j,'GH',df['pmf1'][i] AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1, CHISQgh1, DOFgh1 = compute_alpha_gh(nwavegh1, nfluxgh1, nweightgh1, waveRange(nwavegh1)) print j,'2G',df['pmf1'][i] AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ,CHISQ2g1, DOF2g1 = compute_alpha_2g(nwave2g1, nflux2g1, nweight2g1, waveRange(nwave2g1)) print j,'V',df['pmf1'][i] AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1, CHISQv1, DOFv1 = compute_alpha_voigt(nwavev1, nfluxv1, nweightv1, waveRange(nwavev1)) print j,'GH',df['pmf2'][i] AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2, CHISQgh2, DOFgh2 = compute_alpha_gh(nwavegh2, nfluxgh2, nweightgh2, waveRange(nwavegh2)) print j,'2G',df['pmf2'][i] AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ,CHISQ2g2, DOF2g2 = compute_alpha_2g(nwave2g2, nflux2g2, nweight2g2, waveRange(nwave2g2)) print j,'V',df['pmf2'][i] AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2, CHISQv2, DOFv2 = compute_alpha_voigt(nwavev2, nfluxv2, nweightv2, waveRange(nwavev2)) print j,'GH',df['pmf3'][i] AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3, CHISQgh3, DOFgh3 = compute_alpha_gh(nwavegh3, nfluxgh3, nweightgh3, waveRange(nwavegh3)) print j,'2G',df['pmf3'][i] AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ,CHISQ2g3, DOF2g3 = compute_alpha_2g(nwave2g3, nflux2g3, nweight2g3, waveRange(nwave2g3)) print j,'V',df['pmf3'][i] AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3, CHISQv3, DOFv3 = compute_alpha_voigt(nwavev3, nfluxv3, nweightv3, waveRange(nwavev3)) fig,((ax1,rax1),(ax2,rax2),(ax3,rax3))=plt.subplots(3,2,figsize=(20,10)) ax1.plot(crwave1,cdered_flux1) ax1.plot(crwave1,cweight1,alpha=0.2) ax1.plot(crwave1[cweight1 > 0],cdered_flux1[cweight1>0],'.') ax2.plot(crwave2,cdered_flux2) ax2.plot(crwave2,cweight2,alpha=0.2) ax2.plot(crwave2[cweight2 > 0],cdered_flux2[cweight2>0],'.') ax3.plot(crwave3,cdered_flux3) ax3.plot(crwave3,cweight3,alpha=0.2) ax3.plot(crwave3[cweight3 > 0],cdered_flux3[cweight3>0],'.') #ax1.plot(cwave1,cflux1,'--') pgh1=ax1.plot(crwave1,myGaussHermite(crwave1,AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1),':',color='red',lw=3,label='Gauss-Hermite') pgh2=ax2.plot(crwave2,myGaussHermite(crwave2,AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2),':',color='red',lw=3,label='Gauss-Hermite') pgh3=ax3.plot(crwave3,myGaussHermite(crwave3,AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3),':',color='red',lw=3,label='Gauss-Hermite') p2g1=ax1.plot(crwave1,myDoubleGauss(crwave1,AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ),':',color='blue',lw=3,label='2-Gaussian') p2g2=ax2.plot(crwave2,myDoubleGauss(crwave2,AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ),':',color='blue',lw=3,label='2-Gaussian') p2g3=ax3.plot(crwave1,myDoubleGauss(crwave3,AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ),':',color='blue',lw=3,label='2-Gaussian') p2v1 = ax1.plot(crwave1,myVoigt(crwave1,AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1),':',color='orange',lw=3,label='Voigt') p2v2 = ax2.plot(crwave2,myVoigt(crwave2,AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2),':',color='orange',lw=3,label='Voigt') p2v3 = ax3.plot(crwave3,myVoigt(crwave3,AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3),':',color='orange',lw=3,label='Voigt') ax1.axhline(cut1,ls=':') ax2.axhline(cut1,ls=':') ax3.axhline(cut1,ls=':') string1gh = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPgh1,CENTERgh1,(CHISQgh1/DOFgh1)) string12g = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPa2g1,CENTERa2g1,(CHISQ2g1/ DOF2g1)) string2gh = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPgh2,CENTERgh2,(CHISQgh2/ DOFgh2)) string22g = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPa2g2,CENTERa2g2,(CHISQ2g2/ DOF2g2)) string3gh = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPgh3,CENTERgh3,(CHISQgh3/ DOFgh3)) string32g = 'AMP: {0:4.3f} CENTER: {1:4.3f} RCHIS:{2:4.3f}'.format(AMPa2g3,CENTERa2g3,(CHISQ2g3/ DOF2g3)) ax1.set_xlim(np.min(crwave1),np.max(crwave1)) ax2.set_xlim(np.min(crwave1),np.max(crwave1)) ax3.set_xlim(np.min(crwave1),np.max(crwave1)) xlim=ax1.get_xlim() ylim1 = ax1.get_ylim() ylim2 = ax1.get_ylim() ylim3 = ax1.get_ylim() ax1.set_ylim(min(savitzky_golay(cdered_flux1,101,2))-3*np.std(cdered_flux1),max(savitzky_golay(cdered_flux1,101,2))+5*np.std(cdered_flux1)) ax2.set_ylim(min(savitzky_golay(cdered_flux2,101,2))-3*np.std(cdered_flux2),max(savitzky_golay(cdered_flux2,101,2))+5*np.std(cdered_flux2)) ax3.set_ylim(min(savitzky_golay(cdered_flux3,101,2))-3*np.std(cdered_flux3),max(savitzky_golay(cdered_flux3,101,2))+5*np.std(cdered_flux3)) ax1.annotate(str(df['pmf1'][i]) ,xy=(.95,.15), xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.annotate(str(df['pmf2'][i]),xy=(.95,.15), xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.annotate(str(df['pmf3'][i]),xy=(.95,.15), xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) #ax1.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim1[1] - 0.2*(ylim1[1] - ylim1[0]),string12g) #ax2.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim2[1] - 0.1*(ylim1[1] - ylim2[0]),string2gh) #ax2.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim2[1] - 0.2*(ylim1[1] - ylim2[0]),string22g) #ax3.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim3[1] - 0.1*(ylim1[1] - ylim3[0]),string3gh) #ax3.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim3[1] - 0.2*(ylim1[1] - ylim2[0]),string32g) #ax1.legend([pgh1,p2g1,p2v1],['Gaus-Hermite','2-Gaus','Voigt'],loc=3) ax1.legend(loc=3) ax1.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f\nrChi2 = %.3f' \ %(AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1,(CHISQgh1/ DOFgh1)),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax1.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f\nrChi2 = %.3f' \ %(AMPa2g1, AMPb2g1, CENTERa2g1, CENTERb2g1, SIGMAa2g1, SIGMAb2g1,(CHISQ2g1/ DOF2g1)),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax1.annotate('Voigt:\nAmp$_1$ = %.2f\nCenter = %.2f\n$\sigma_l$ = %.2f\n$\sigma_g$ = %.2f\nrChi2 = %.3f' \ %(AMPv1, CENTERv1, SIGMALv1, SIGMAGv1,(CHISQv1/ DOFv1)),xy=(.35,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.legend(loc=3) #ax2.legend([pgh2,p2g2,p2v2],['Gaus-Hermite','2-Gaus','Voigt'],prop={'size':8},loc='center left') ax2.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f\nrChi2 = %.3f'\ %(AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2,(CHISQgh2/ DOFgh2)),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f\nrChi2 = %.3f' \ %(AMPa2g2, AMPb2g2, CENTERa2g2, CENTERb2g2, SIGMAa2g2, SIGMAb2g2,(CHISQ2g2/ DOF2g2)),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax2.annotate('Voigt:\nAmp$_1$ = %.2f\nCenter = %.2f\n$\sigma_l$ = %.2f\n$\sigma_g$ = %.2f\nrChi2 = %.3f' \ %(AMPv2, CENTERv2, SIGMALv2, SIGMAGv2,(CHISQv2/ DOFv2)),xy=(.35,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.legend(loc=3) #ax3.legend([pgh3,p2g3,p2v3],['Gaus-Hermite','2-Gaus','Voigt'],prop={'size':8},loc='center left') ax3.annotate('Gauss-Hermite:\nAmp = %.2f\nCenter = %.2f\n$\sigma$ = %.2f\nH3 = %.2f\nH4 = %.2f\nrChi2 = %.3f' \ %(AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3,(CHISQgh3/ DOFgh3)),xy=(.05,.95), \ xycoords='axes fraction',ha="left", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.annotate('Double Gaussian:\nAmp$_1$ = %.2f\nAmp$_2$ = %.2f\nCenter$_1$ = %.2f\nCenter$_2$ = %.2f\n$\sigma_1$ = %.2f\n$\sigma_2$ = %.2f\nrChi2 = %.3f' \ %(AMPa2g3, AMPb2g3, CENTERa2g3, CENTERb2g3, SIGMAa2g3, SIGMAb2g3,(CHISQ2g3/ DOF2g3)),xy=(.95,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax3.annotate('Voigt:\nAmp$_1$ = %.2f\nCenter = %.2f\n$\sigma_l$ = %.2f\n$\sigma_g$ = %.2f\nrChi2 = %.3f' \ %(AMPv3, CENTERv3, SIGMALv3, SIGMAGv3,(CHISQv3/ DOFv3)),xy=(.35,.95), \ xycoords='axes fraction',ha="right", va="top", \ bbox=dict(boxstyle="round", fc='1'),fontsize=10) ax1.set_ylabel('Flux') ax1.set_xlabel('Wavelength ($\AA$)') ax2.set_ylabel('Flux') ax2.set_xlabel('Wavelength ($\AA$)') ax3.set_ylabel('Flux') ax3.set_xlabel('Wavelength ($\AA$)') #Save the spectra filenamegh1 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf1'][i]+'_cEm_gh.txt' filenamegh2 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf2'][i]+'_cEm_gh.txt' filenamegh3 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf3'][i]+'_cEm_gh.txt' filename2g1 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf1'][i]+'_cEm_2g.txt' filename2g2 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf2'][i]+'_cEm_2g.txt' filename2g3 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf3'][i]+'_cEm_2g.txt' filenamev1 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf1'][i]+'_cEm_v.txt' filenamev2 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf2'][i]+'_cEm_v.txt' filenamev3 = 'EmissionLines_Norm_Spectra/NormSpec_'+df['pmf3'][i]+'_cEm_v.txt' # Residuals & Weights resgh1 = cdered_flux1 / myGaussHermite(crwave1,AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1) resgh2 = cdered_flux2 / myGaussHermite(crwave2,AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2) resgh3 = cdered_flux3 / myGaussHermite(crwave3,AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3) wresgh1 = csigma1 / myGaussHermite(crwave1,AMPgh1, CENTERgh1, SIGMAgh1, SKEWgh1, KURTgh1, SCALEgh1, ALPHAgh1) wresgh2 = csigma2 / myGaussHermite(crwave2,AMPgh2, CENTERgh2, SIGMAgh2, SKEWgh2, KURTgh2, SCALEgh2, ALPHAgh2) wresgh3 = csigma3 / myGaussHermite(crwave3,AMPgh3, CENTERgh3, SIGMAgh3, SKEWgh3, KURTgh3, SCALEgh3, ALPHAgh3) res2g1 = cdered_flux1 / myDoubleGauss(crwave1,AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ) res2g2 = cdered_flux2 / myDoubleGauss(crwave2,AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ) res2g3 = cdered_flux3 / myDoubleGauss(crwave3,AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ) wres2g1 = csigma1 / myDoubleGauss(crwave1,AMPa2g1, CENTERa2g1, SIGMAa2g1, AMPb2g1, CENTERb2g1, SIGMAb2g1, SCALE2g1, ALPHA2g1 ) wres2g2 = csigma2 / myDoubleGauss(crwave2,AMPa2g2, CENTERa2g2, SIGMAa2g2, AMPb2g2, CENTERb2g2, SIGMAb2g2, SCALE2g2, ALPHA2g2 ) wres2g3 = csigma3 / myDoubleGauss(crwave3,AMPa2g3, CENTERa2g3, SIGMAa2g3, AMPb2g3, CENTERb2g3, SIGMAb2g3, SCALE2g3, ALPHA2g3 ) resv1 = cdered_flux1 / myVoigt(crwave1,AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1) resv2 = cdered_flux2 / myVoigt(crwave2,AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2) resv3 = cdered_flux3 / myVoigt(crwave3,AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3) wresv1 = csigma1 / myVoigt(crwave1,AMPv1, CENTERv1, SIGMALv1, SIGMAGv1, SCALEv1, ALPHAv1) wresv2 = csigma2 / myVoigt(crwave2,AMPv2, CENTERv2, SIGMALv2, SIGMAGv2, SCALEv2, ALPHAv2) wresv3 = csigma3 / myVoigt(crwave3,AMPv3, CENTERv3, SIGMALv3, SIGMAGv3, SCALEv3, ALPHAv3) #Save Begins np.savetxt(filenamegh1,zip(crwave1,resgh1,wresgh1), fmt='%10.5f') np.savetxt(filenamegh2,zip(crwave2,resgh2,wresgh2), fmt='%10.5f') np.savetxt(filenamegh3,zip(crwave3,resgh3,wresgh3), fmt='%10.5f') np.savetxt(filename2g1,zip(crwave1,res2g1,wres2g1), fmt='%10.5f') np.savetxt(filename2g2,zip(crwave2,res2g2,wres2g2), fmt='%10.5f') np.savetxt(filename2g3,zip(crwave3,res2g3,wres2g3), fmt='%10.5f') np.savetxt(filenamev1,zip(crwave1,resv1,wresv1), fmt='%10.5f') np.savetxt(filenamev2,zip(crwave2,resv2,wresv2), fmt='%10.5f') np.savetxt(filenamev3,zip(crwave3,resv3,wresv3), fmt='%10.5f') #Plot Begins presgh1,pres2g1,presv1,=rax1.plot(crwave1,resgh1,'k--',crwave1,res2g1,'r-',crwave1,resv1,'b:',alpha=0.7) presgh2,pres2g2,presv2,=rax2.plot(crwave2,resgh2,'k--',crwave2,res2g2,'r-',crwave2,resv2,'b:',alpha=0.7) presgh3,pres2g3,presv3,=rax3.plot(crwave3,resgh3,'k--',crwave3,res2g3,'r-',crwave3,resv3,'b:',alpha=0.7) rax1.set_ylabel('Normalized Flux') rax1.set_xlabel('Wavelength ($\AA$)') rax1.legend([presgh1,pres2g1,presv1],['Gaus-Hermite','2-Gaus','Voigt'],numpoints=4,prop={'size':8},loc='lower right') rax2.set_ylabel('Normalized Flux') rax2.set_xlabel('Wavelength ($\AA$)') rax2.legend([presgh2,pres2g2,presv2],['Gaus-Hermite','2-Gaus','Voigt'],numpoints=4,prop={'size':8},loc='lower right') rax3.set_ylabel('Normalized Flux') rax3.set_xlabel('Wavelength ($\AA$)') rax3.legend([presgh3,pres2g3,presv3],['Gaus-Hermite','2-Gaus', 'Voigt'],numpoints=4,prop={'size':8},loc='lower right') rax1.axhline(1.0,ls=':',color='blue',alpha=0.5) rax2.axhline(1.0,ls=':',color='blue',alpha=0.5) rax3.axhline(1.0,ls=':',color='blue',alpha=0.5) rax1.set_ylim(0,2) rax2.set_ylim(0,2) rax3.set_ylim(0,2) fig.tight_layout() fig.savefig(pp,format='pdf') #plt.show() plt.clf() pp.close() <file_sep>#!/usr/bin/python #-*- coding: utf-8 -*- ''' Code for continuum normalization of SDSS spectra @author : <NAME> @date : 21-Jan-2018 @version : 1.0 ''' import sys import os import numpy as np from astropy import io from astropy.io import fits from astropy.io import ascii from matplotlib import pyplot as plt from astropy import constants as const from astropy import units as U from astropy.coordinates import SkyCoord from dustmaps.sfd import SFDQuery from specutils import extinction import scipy from scipy.ndimage.filters import convolve from scipy import interpolate from scipy.interpolate import interp1d from scipy.optimize import curve_fit from matplotlib.backends.backend_pdf import PdfPages from con_fit_iterative import * def lam2vel(wavelength,ion_w): zlambda = (wavelength-ion_w)/ion_w R = 1./(1+zlambda) vel_ion = -const.c.to('km/s').value*(R**2-1)/(R**2+1) return vel_ion def dered_flux(Av,wave,flux): dered_flux = np.zeros(len(wave)) for i in range(len(wave)): ext_lambda= extinction.extinction_ccm89(wave[i] * U.angstrom, a_v= Av, r_v= 3.1) tau_lambda= ext_lambda/(1*1.086) dered_flux[i]= flux[i] * np.exp(tau_lambda) return dered_flux def ext_coeff(lamb): inv_lamba=[0.45,0.61,0.8,1.82,2.27,2.7,3.22,3.34,3.46,3.6,3.75,3.92,4.09,4.28,4.50,4.73,5.00,5.24,5.38,5.52,5.70,5.88,6.07,6.27,6.48,6.72,6.98,7.23,7.52,7.84] smc_ext=[-2.61,-2.47,-2.12,0.0,1.0,1.67,2.29,2.65,3.0,3.15,3.49,3.91,4.24,4.53,5.3,5.85,6.38,6.76,6.9,7.17,7.71,8.01,8.49,9.06,9.28,9.84,10.8,11.51,12.52,13.54] xy=np.interp(1.0/(lamb*10**(-4)),inv_lamba,smc_ext) ext_lamb=(xy+2.98)/3.98 # Rv=2.98 #return(z,ext_lamb) return(ext_lamb) def myfunct(wave, a , b): return a*ext_coeff(wave)*wave**(b) def compute_alpha(wl, spec, ivar, wav_range, per_value=[10,90]): # print 'Routine begins' spec[np.isnan(spec)] = 0 ivar[np.isnan(ivar)] = 0 wavelength, spectra, invar = np.array([]), np.array([]), np.array([]) #plt.plot(wl,spec) for j in range(len(wav_range)): #print wav_range[j] #print min(wl),max(wl) temp = np.where((wl > wav_range[j][0]) & (wl < wav_range[j][1]))[0] #print wl[temp],len(spec),len(wl),spec[temp],ivar[temp] tempspec, tempivar = spec[temp], ivar[temp] #print tempspec print len(tempspec) #Mask out metal absorption lines cut = np.percentile(tempspec, per_value) #print 'cut',cut blah = np.where((tempspec > cut[0]) & (tempspec < cut[1]) & (tempivar > 0))[0] wave = wl[temp][blah] wavelength = np.concatenate((wavelength, wave)) spectra = np.concatenate((spectra, tempspec[blah])) invar = np.concatenate((invar, tempivar[blah])) print 'Debug',len(wavelength) p0=[1.0,1.0] try: #plt.plot(wavelength,spectra) #plt.show() popt, pcov = curve_fit(myfunct, wavelength, spectra, p0, sigma=1.0/np.sqrt(invar)) except (RuntimeError, TypeError): AMP, ALPHA, CHISQ, DOF = np.nan, np.nan, np.nan, np.nan else: AMP, ALPHA = popt[0], popt[1] CHISQ = np.sum(invar * (spectra - myfunct(wavelength, popt[0], popt[1]))**2) # DOF = N - n , n = 2 DOF = len(spectra) - 2 # print 'Routine ends' print 'Compute Alpha:', AMP,ALPHA,CHISQ,DOF return AMP, ALPHA, CHISQ, DOF def waveRange(wave): #wav_range=[[1300.,1350.],[1420.,1470.],[1700.,1800.],[2080.,2215],[2480.,2655],[3225.,3900.],[4200.,4230.],[4435.,4700.],[5200.,5700.]] wav_range= [(1250,1350),(1700,1800),(1950,2200),(2650,2710),(2950,3700),(3950,4050)] mwav_range = [] for rr in wav_range: if ((np.min(wave) < rr[0]) & (np.max(wave) > rr[1])): nrr0 = rr[0] ; nrr1 = rr[1] elif ((np.min(wave) > rr[0]) & (np.min(wave) < rr[1])& (np.max(wave) < rr[1])): nrr0 = np.min(wave) ; nrr1 = rr[1] elif ((np.min(wave) < rr[0]) & (np.max(wave) > rr[0]) &(np.max(wave) < rr[1])): nrr0 = rr[0] ; nrr1 = np.max(wave) else : continue mwav_range.append([nrr0,nrr1]) return mwav_range def powerlawFunc(xdata, scale, amp,index): return scale + amp*ext_coeff(xdata)*np.power(xdata,index) def fitPowerlaw(wave,flux,weight,scale = 1, amp=1,index=1): from lmfit import minimize, Parameters, fit_report, Minimizer import numpy as np import scipy.optimize as optimization x0= [scale, amp,index] xdata=np.asarray(wave) ydata=np.asarray(flux) sigma=np.asarray(weight) print len(xdata),len(ydata),len(sigma) popt, pcov = optimization.curve_fit(powerlawFunc, xdata, ydata, x0, sigma) print popt #popt, pcov = optimization.curve_fit(func, xdata, ydata, x0) model = powerlawFunc(wave,popt[0],popt[1],popt[2]) chi2 = ((flux - model)*np.sqrt(weight))**2 rchi2 = np.sum(chi2)/(len(xdata) - 2) print 'Reduced Chi Square : {0} Number of points: {1}'.format(rchi2,len(xdata)) return (popt,pcov) def maskOutliers(wave,flux,weight,amp,alpha): model = myfunct(wave,amp,alpha) std =np.std(flux[weight > 0]) fluxdiff = flux - model ww = np.where (np.abs(fluxdiff) > 3*std) #nwave = np.delete(wave,ww) #nflux = np.delete(flux,ww) weight[ww] = 0#np.delete(weight,ww) return wave,flux,weight def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] <NAME>, <NAME>, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, <NAME>, <NAME>, <NAME> Cambridge University Press ISBN-13: 9780521880688 """ import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except (ValueError, msg): raise ValueError("window_size and order have to be of type int") if window_size % 2 != 1 or window_size < 1: raise TypeError("window_size size must be a positive odd number") if window_size < order + 2: raise TypeError("window_size is too small for the polynomials order") order_range = range(order+1) half_window = (window_size -1) // 2 # precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # pad the signal at the extremes with # values taken from the signal itself firstvals = np.asarray(y[0]) - np.abs( y[1:half_window+1][::-1] - np.asarray(y[0]) ) lastvals = np.asarray(y[-1]) + np.abs(y[-half_window-1:-1][::-1] - np.asarray(y[-1])) y = np.concatenate((firstvals, y, lastvals)) return np.convolve( m[::-1], y, mode='valid') def contWave(wave): linefree_regions = [(1280,1350),(1700,1800),(1950,2200),(2650,2710),(2950,3700),(3950,4050)] finalcond = False for lfr in linefree_regions: cond = ((wave >= lfr[0]) & (wave <= lfr[1])) finalcond = finalcond | cond indices = np.where(finalcond) return indices def minmax(vec): return min(vec),max(vec) #version I = no maskOutliers percentile 25 75 #version II = with maskOutliers percentile 10 90 #version III = clipped wavelengths to same bounds; to deal with the difference in spectral indices #version IV = Kate model included, ALPHA_AMP_values file is not different from III #version V =Reddened power law df = np.genfromtxt('tdss_allmatches_crop_edit.dat',names=['ra','dec','z','pmf1','pmf2','pmf3'],dtype=(float,float,float,'|S15','|S15','|S15')) wav_range= [(1280,1350),(1700,1800),(1950,2200),(2650,2710),(3010,3700),(3950,4050),(4140,4270)] pp = PdfPages('ContinuumNormalization_plots_V.pdf') fx=open('ALPHA_AMP_values_V.txt','w') fx1=open('Kate_ALPHA_AMP_values_V.txt','w') #for i in range(len(df['pmf1'])): for i in range(len(df)): #for i in range(10): print 'Kate_Sources/spec-'+df['pmf1'][i]+'.fits' print 'Kate_Sources/spec-'+df['pmf2'][i]+'.fits' print 'Kate_Sources/spec-'+df['pmf3'][i]+'.fits' data1 = fits.open('Kate_Sources/spec-'+df['pmf1'][i]+'.fits')[1].data data2 = fits.open('Kate_Sources/spec-'+df['pmf2'][i]+'.fits')[1].data data3 = fits.open('Kate_Sources/spec-'+df['pmf3'][i]+'.fits')[1].data wave1 = 10**data1.loglam.copy() flux1 = data1.flux.copy() weight1 = (data1.ivar*(data1.and_mask == 0)).copy() wave2 = 10**data2.loglam.copy() flux2 = data2.flux.copy() weight2 = (data2.ivar*(data2.and_mask == 0)).copy() wave3 = 10**data3.loglam.copy() flux3 = data3.flux.copy() weight3 = (data3.ivar*(data3.and_mask == 0)).copy() print len(wave1),len(flux1),len(weight1) print weight1 print data1.and_mask #clean QSO sn1= flux1*np.sqrt(weight1) ; sn2= flux2*np.sqrt(weight2); sn3= flux3*np.sqrt(weight3) w1 = (weight1>0)&((sn1<-10)|(sn1>80)); w2 = (weight2>0)&((sn2<-10)|(sn2>80)) ; w3 = (weight3>0)&((sn3<-10)|(sn3>80)) print w1,w2,w3 weight1[w1] = 0; flux1[w1] = 0 weight2[w2] = 0; flux2[w2] = 0 weight3[w3] = 0; flux3[w3] = 0 #de-redden the flux info = fits.open('Kate_Sources/spec-'+df['pmf1'][i]+'.fits')[2].data coords = SkyCoord(info['RA'],info['DEC'],unit='degree',frame='icrs') sfd = SFDQuery() eb_v = sfd(coords) dered_flux1 = dered_flux(3.1*eb_v,wave1,flux1) dered_flux2 = dered_flux(3.1*eb_v,wave2,flux2) dered_flux3 = dered_flux(3.1*eb_v,wave3,flux3) # Change wavelengths to rest wavellegths rwave1 = wave1/(1.0+df['z'][i]) rwave2 = wave2/(1.0+df['z'][i]) rwave3 = wave3/(1.0+df['z'][i]) #Clip all the spectra to same wavelength bounds Necessary to capture variation in alpha wmin1,wmax1 = minmax(rwave1) wmin2,wmax2 = minmax(rwave2) wmin3,wmax3 = minmax(rwave3) wlim1,wlim2 = max([wmin1,wmin2,wmin3]),min([wmax1,wmax2,wmax3]) l1 = np.where((rwave1 >= wlim1) & (rwave1 <= wlim2))[0] l2 = np.where((rwave2 >= wlim1) & (rwave2 <= wlim2))[0] l3 = np.where((rwave3 >= wlim1) & (rwave3 <= wlim2))[0] crwave1 = rwave1[l1];cdered_flux1 = dered_flux1[l1];cweight1 = weight1[l1] crwave2 = rwave2[l2];cdered_flux2 = dered_flux2[l2];cweight2 = weight2[l2] crwave3 = rwave3[l3];cdered_flux3 = dered_flux3[l3];cweight3 = weight3[l3] # Choose line free region #cwave1 = rwave1[contWave(rwave1)];cflux1 = flux1[contWave(rwave1)] ; cweight1 = weight1[contWave(rwave1)] #cwave2 = rwave2[contWave(rwave2)];cflux2 = flux2[contWave(rwave2)] ; cweight2 = weight2[contWave(rwave2)] #cwave3 = rwave3[contWave(rwave3)];cflux3 = flux3[contWave(rwave3)] ; cweight3 = weight3[contWave(rwave3)] #Fit powerlaw iterate and mask outliers iteration = 3 for j in range(iteration): if j == 0: AMP1, ALPHA1, CHISQ1, DOF1 = compute_alpha(crwave1, cdered_flux1, cweight1, waveRange(crwave1)) AMP2, ALPHA2, CHISQ2, DOF2 = compute_alpha(crwave2, cdered_flux2, cweight2, waveRange(crwave2)) AMP3, ALPHA3, CHISQ3, DOF3 = compute_alpha(crwave3, cdered_flux3, cweight3, waveRange(crwave3)) print AMP1,ALPHA1 nwave1 = crwave1; nflux1=cdered_flux1;nweight1 = cweight1 nwave2 = crwave2; nflux2=cdered_flux2;nweight2 = cweight2 nwave3 = crwave3; nflux3=cdered_flux3;nweight3 = cweight3 print 'iteration number',j+1#,popt1[0],popt1[1],popt1[2] print 'iteration 1 completed' continue else: nwave1,nflux1,nweight1 = maskOutliers(nwave1,nflux1,nweight1,AMP1,ALPHA1) AMP1, ALPHA1, CHISQ1, DOF1 = compute_alpha(nwave1, nflux1, nweight1, waveRange(nwave1)) nwave2,nflux2,nweight2 = maskOutliers(nwave2,nflux2,nweight2,AMP2,ALPHA2) AMP2, ALPHA2, CHISQ2, DOF2 = compute_alpha(nwave2, nflux2, nweight2, waveRange(nwave2)) nwave3,nflux3,nweight3 = maskOutliers(nwave3,nflux3,nweight3,AMP3,ALPHA3) AMP3, ALPHA3, CHISQ3, DOF3 = compute_alpha(nwave3, nflux3, nweight3, waveRange(nwave3)) # print 'iteration number',j+1,popt1[0],popt1[1],popt1[2] # nwave1,nflux1,nweight1 = maskOutliers(cwave1,cflux1*1e15,cweight1,popt1) # popt1,pcov1 = fitPowerlaw(nwave1,nflux1,nweight1,popt1[0],popt1[1],popt1[2]) # nwave2,nflux2,nweight2 = maskOutliers(cwave2,cflux2*1e15,cweight2,popt2) # popt2,pcov2 = fitPowerlaw(nwave2,nflux2,nweight2,popt2[0].popt2[1],popt2[2]) # nwave3,nflux3,nweight3 = maskOutliers(cwave3,cflux3*1e15,cweight3,popt3) # popt3,pcov3 = fitPowerlaw(nwave3,nflux3,nweight3,popt3[0],popt3[1],popt3[2]) print>>fx,'{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}'.format(df['pmf1'][i],ALPHA1,ALPHA2,ALPHA3,AMP1,AMP2,AMP3) #Try Kate's continuum normalization fit kcwave1,kcflux1,kcfluxerr1,kmean_amp1,kmean_index1,kredco1,kwave1,kflux1=continuum_fit(wave1,flux1,weight1,df['z'][i]) kcwave2,kcflux2,kcfluxerr2,kmean_amp2,kmean_index2,kredco2,kwave2,kflux2=continuum_fit(wave2,flux2,weight2,df['z'][i]) kcwave3,kcflux3,kcfluxerr3,kmean_amp3,kmean_index3,kredco3,kwave3,kflux3=continuum_fit(wave3,flux3,weight3,df['z'][i]) print>>fx1,'{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}'.format(df['pmf1'][i],kmean_index1,kmean_index2,kmean_index3,kmean_amp1,kmean_amp2,kmean_amp3) # #Plot for testing fig,(ax1,ax2,ax3)=plt.subplots(3,1,figsize=(15,8)) ax1.plot(crwave1,cdered_flux1,label=str(df['pmf1'][i])) #ax1.plot(cwave1,cflux1,'--') ax1.plot(crwave1,myfunct(crwave1,AMP1,ALPHA1),':',color='red',lw=3,label='my model') ax1.plot(kcwave1/(1.0+df['z'][i]),kcflux1,'--',color='cyan',lw=3,label='Kate model') #ax1.plot(rwave1,dered_flux1,'--') #ax1.plot(rwave1,weight1,':',label='weight') #ax1.plot(rwave1,data1.flux,label='Clipped') string1 = 'AMP: {0:4.3f} ALPHA: {1:4.3f} rCHISQ: {2:4.3f}'.format(AMP1,ALPHA1,CHISQ1/DOF1) for ll in wav_range : ax1.axvspan(ll[0], ll[1], alpha=0.25, color='cyan') ax2.axvspan(ll[0], ll[1], alpha=0.25, color='cyan') ax3.axvspan(ll[0], ll[1], alpha=0.25, color='cyan') ax2.plot(crwave2,cdered_flux2,label=str(df['pmf2'][i])) #ax2.plot(cwave2,cflux2,'--') ax2.plot(crwave2,myfunct(crwave2,AMP2,ALPHA2),':',color='red',lw=3,label='my model') ax2.plot(kcwave2/(1.0+df['z'][i]),kcflux2,'--',color='cyan',lw=3,label='Kate model') #ax2.plot(rwave2,dered_flux2,'--') #ax2.plot(rwave2,weight2,':',label='weight') #ax2.plot(rwave2,data2.flux,'--',label='Clipped') string2 = 'AMP: {0:4.3f} ALPHA: {1:4.3f} rCHISQ: {2:4.3f}'.format(AMP2,ALPHA2,CHISQ2/DOF2) ax3.plot(crwave3,cdered_flux3,label=str(df['pmf3'][i])) #ax3.plot(cwave3,cflux3,'--') ax3.plot(crwave3,myfunct(crwave3,AMP3,ALPHA3),':',color='red',lw=3,label='my model') ax3.plot(kcwave3/(1.0+df['z'][i]),kcflux3,'--',color='cyan',lw=3,label='Kate model') #ax3.plot(rwave3,dered_flux3,'--') #ax3.plot(rwave3,weight3,':',label='weight') #ax3.plot(rwave3,data3.flux,'--',label='Clipped') string3 = 'AMP: {0:4.3f} ALPHA: {1:4.3f} rCHISQ: {2:4.3f}'.format(AMP3,ALPHA3,CHISQ3/DOF3) ax1.set_xlim(np.min(crwave1),np.max(crwave1)) ax2.set_xlim(np.min(crwave1),np.max(crwave1)) ax3.set_xlim(np.min(crwave1),np.max(crwave1)) xlim=ax1.get_xlim() ylim1 = ax1.get_ylim() ylim2 = ax2.get_ylim() ylim3 = ax3.get_ylim() ax1.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim1[1] - 0.1*(ylim1[1] - ylim1[0]),string1) ax2.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim2[1] - 0.1*(ylim2[1] - ylim2[0]),string2) ax3.text(xlim[0]+0.1*(xlim[1] - xlim[0]),ylim3[1] - 0.1*(ylim3[1] - ylim3[0]),string3) ax1.legend(loc=1) ax2.legend(loc=1) ax3.legend(loc=1) fig.tight_layout() fig.savefig(pp,format='pdf') #plt.show() fx.close() fx1.close() pp.close() <file_sep>#!/usr/bin/python #-*- coding: utf-8 -*- import scipy import numpy as np class Observation(object): ''' The Observation object ''' def __init__(self): ''' Initialize Observation object ''' self._pmf= None self._snr = None self._survey = None self._filename = None @property def pmf(self): return self._pmf @pmf.setter def pmf(self, new_pmf): self._pmf = new_pmf @property def snr(self): return self._snr @snr.setter def snr(self, new_snr): self._snr = new_snr @property def survey(self): return self._survey @survey.setter def survey(self, new_survey): self._survey = new_survey @property def filename(self): return self._filename @filename.setter def filename(self, new_filename): self._filename = new_filename @property def redshift(self): return self._redshift @redshift.setter def redshift(self, new_redshift): self._redshift = new_redshift @property def bi(self): return self._bi @bi.setter def bi(self, new_bi): self._bi = new_bi @property def bi_err(self): return self._bi_err @bi_err.setter def bi_err(self, new_bi_err): self._bi_err = new_bi_err @property def v_max(self): return self._v_max @v_max.setter def v_max(self, new_v_max): self._v_max = new_v_max @property def v_min(self): return self._v_min @v_min.setter def v_min(self, new_v_min): self._v_min = new_v_min @property def mjd(self): return self._mjd @mjd.setter def mjd(self, new_mjd): self._mjd = new_mjd @property def spec_name(self): return self._spec_name @spec_name.setter def spec_name(self, new_spec_name): self._spec_name = new_spec_name @property def num_troughs(self): return self._num_troughs @num_troughs.setter def num_troughs(self, new_num_troughs): self._num_troughs = new_num_troughs @property def ew(self): return self._ew @ew.setter def ew(self, new_ew): self._ew = new_ew @property def ew_err(self): return self._ew_err @ew_err.setter def ew_err(self, new_err_ew_err): self._ew_err = new_err_ew_err
2236e5d1b4bae751126318aff56d2f8eb4453644
[ "Python" ]
15
Python
vivekastro/Acceleration_BALs
676a849b9dbea0c24377bf4fc1022471a1011aa9
d8edfc6823cf4819a4a66e4b355913c2436d191d
refs/heads/master
<repo_name>hasannasrul/breaking-bad-project<file_sep>/script.js const character = document.getElementById('character-Api'); fetch('https://www.breakingbadapi.com/api/characters') .then(res => res.json()) .then(data => { const dataStore = data; let output = ''; dataStore.forEach(element => { output += ` <div class="flip-card"> <div class="flip-card-inner"> <div class="flip-card-front"> <img src="${element.img}" alt="Avatar" style="width:200px"> </div> <div class="flip-card-back"> <h1>Name: ${element.name}</h1> <p>Status: ${element.status}</p> <p>Portrayed by: ${element.portrayed}</p> </div> </div> </div>` }); character.innerHTML = output; }) //Tracing the API const search = document.getElementById('searchBox'); search.addEventListener('keyup', trace); function trace() { fetch('https://www.breakingbadapi.com/api/characters') .then(res => res.json()) .then(data => { let matches = data.filter(character => { const regex = new RegExp(`^${search.value}`, 'gi'); return character.name.match(regex); }); let output = ''; matches.forEach(element => { output += `<div class="flip-card"> <div class="flip-card-inner"> <div class="flip-card-front"> <img src="${element.img}" alt="Avatar" style="width:200px"> </div> <div class="flip-card-back"> <h1>Name: ${element.name}</h1> <p>Status: ${element.status}</p> <p>Portrayed by: ${element.portrayed}</p> </div> </div> </div> ` }); character.innerHTML = output; }) }
ba32882ecf315d75a815a5c4750c3e88a8f8e9eb
[ "JavaScript" ]
1
JavaScript
hasannasrul/breaking-bad-project
0977db8ada628883233a53d4419db5d99ddf00ef
d29d2ea497b9fc30e0b1eb8de5b2ebf47466765e
refs/heads/master
<repo_name>Howww/url-shortener<file_sep>/src/main/java/org/santel/url/ServletInitializer.java package org.santel.url; import org.springframework.boot.builder.*; import org.springframework.boot.context.web.*; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { System.setProperty("spring.profiles.active", "production"); return application.sources(ShorteningService.class, ShorteningService.ProductionShorteningConfiguration.class); } } <file_sep>/src/main/java/org/santel/url/dao/DynamoDbBroker.java package org.santel.url.dao; import com.amazonaws.regions.*; import com.amazonaws.services.dynamodbv2.*; import com.amazonaws.services.dynamodbv2.document.*; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.internal.*; import com.amazonaws.services.dynamodbv2.document.spec.*; import com.amazonaws.services.dynamodbv2.document.utils.*; import com.amazonaws.services.dynamodbv2.model.*; import com.google.common.base.*; import com.google.common.collect.*; import org.slf4j.*; import java.util.*; public class DynamoDbBroker { private static final Logger LOG = LoggerFactory.getLogger(DynamoDbMappingDao.class); private static final String VALUE_ATTRIBUTE_NAME = "longUrl"; public static final String KEY_ATTRIBUTE_NAME = "shortUrl"; private final DynamoDB dynamoDB; private final String tableName; public DynamoDbBroker(String dynamoDbUrl, String tableName) { AmazonDynamoDBClient client = selectDynamoDbClient(dynamoDbUrl); this.dynamoDB = new DynamoDB(client); this.tableName = tableName; } private AmazonDynamoDBClient selectDynamoDbClient(String dynamoDbUrl) { return System.getProperty("santel.url.local") == null? new AmazonDynamoDBClient().withRegion(Regions.US_WEST_2) : new AmazonDynamoDBClient().withEndpoint(dynamoDbUrl); } public boolean createTable() { try { ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput(10L, 10L); CreateTableRequest createTableRequest = getCreateTableRequest(provisionedThroughput); Table table = dynamoDB.createTable(createTableRequest); table.waitForActive(); LOG.info("Successfully created table"); return true; } catch (Exception e) { LOG.error("Failed to create table", e); return false; } } private CreateTableRequest getCreateTableRequest(ProvisionedThroughput provisionedThroughput) { GlobalSecondaryIndex globalSecondaryIndex = getGlobalSecondaryIndex(provisionedThroughput); return new CreateTableRequest( ImmutableList.of(new AttributeDefinition(KEY_ATTRIBUTE_NAME, ScalarAttributeType.S), new AttributeDefinition(VALUE_ATTRIBUTE_NAME, ScalarAttributeType.S)), tableName, ImmutableList.of(new KeySchemaElement(KEY_ATTRIBUTE_NAME, KeyType.HASH)), provisionedThroughput) .withGlobalSecondaryIndexes(ImmutableList.of(globalSecondaryIndex)); } private GlobalSecondaryIndex getGlobalSecondaryIndex(ProvisionedThroughput provisionedThroughput) { return new GlobalSecondaryIndex() .withIndexName(VALUE_ATTRIBUTE_NAME) .withKeySchema(ImmutableList.of(new KeySchemaElement(VALUE_ATTRIBUTE_NAME, KeyType.HASH))) .withProvisionedThroughput(provisionedThroughput) .withProjection(new Projection() .withProjectionType(ProjectionType.ALL)); } public boolean deleteTable() { try { Table table = dynamoDB.getTable(tableName); table.delete(); table.waitForDelete(); LOG.info("Successfully deleted table"); return true; } catch (Exception e) { LOG.error("Failed to delete table", e); return false; } } public boolean insertEntry(String key, String value) { try { Table table = dynamoDB.getTable(tableName); PutItemSpec putItemSpec = new PutItemSpec() .withItem(new Item() .withPrimaryKey(KEY_ATTRIBUTE_NAME, key) .with(VALUE_ATTRIBUTE_NAME, value)) .withConditionExpression("attribute_not_exists(" + KEY_ATTRIBUTE_NAME + ") AND attribute_not_exists(" + VALUE_ATTRIBUTE_NAME + ")"); table.putItem(putItemSpec); LOG.info("Successfully inserted entry {} -> {}", key, value); return true; } catch (Exception e) { LOG.error(String.format("Failed to insert entry %s -> %s", key, value), e); return false; } } public String queryValue(String key) { Table table = dynamoDB.getTable(tableName); ItemCollection<QueryOutcome> items = table.query(new KeyAttribute(KEY_ATTRIBUTE_NAME, key)); IteratorSupport<Item, QueryOutcome> itemIterator = items.iterator(); if (!itemIterator.hasNext()) { return null; } Item item = itemIterator.next(); Preconditions.checkState(!itemIterator.hasNext()); for (Map.Entry<String, Object> entry : item.attributes()) { if (entry.getKey().equals(VALUE_ATTRIBUTE_NAME)) { return String.class.cast(entry.getValue()); } Preconditions.checkState(entry.getKey().equals(KEY_ATTRIBUTE_NAME)); } throw new IllegalStateException("Shouldn't get here"); } public String queryKey(String value) { Table table = dynamoDB.getTable(tableName); Index index = table.getIndex(VALUE_ATTRIBUTE_NAME); QuerySpec querySpec = new QuerySpec() .withKeyConditionExpression("#v = :value") .withNameMap(new NameMap().with("#v", VALUE_ATTRIBUTE_NAME)) .withValueMap(new ValueMap().withString(":value", value)); ItemCollection<QueryOutcome> items = index.query(querySpec); IteratorSupport<Item, QueryOutcome> itemIterator = items.iterator(); if (!itemIterator.hasNext()) { return null; } Item item = itemIterator.next(); //Preconditions.checkState(!itemIterator.hasNext()); // there might be more than one key for this indexed value for (Map.Entry<String, Object> entry : item.attributes()) { if (entry.getKey().equals(KEY_ATTRIBUTE_NAME)) { return String.class.cast(entry.getValue()); } Preconditions.checkState(entry.getKey().equals(VALUE_ATTRIBUTE_NAME)); } throw new IllegalStateException("Shouldn't get here"); } } <file_sep>/src/test/java/org/santel/url/dao/DynamoDbBrokerTest.java package org.santel.url.dao; import org.testng.*; import org.testng.annotations.*; /** Tests will pass only if a DynamoDB instance is located in the given or default url */ @Test public class DynamoDbBrokerTest { public static final String TEST_KEY = "a key"; public static final String TEST_VALUE = "some value"; private DynamoDbBroker dynamoDbBroker; @BeforeMethod void beforeDynamoDbBrokerMethod() { String dynamoDbUrl = System.getProperty("dynamodb.url", "http://localhost:8000"); //TODO add to Spring property system? dynamoDbBroker = new DynamoDbBroker(dynamoDbUrl, "TestTableDynamoDbBrokerTest"); dynamoDbBroker.deleteTable(); // make sure test table starts clean } @AfterMethod void afterDynamoDbBrokerMethod() { dynamoDbBroker.deleteTable(); // clean up test table after test } @Test void canCreateAndDestroyTestTable() { AssertJUnit.assertTrue("Table creation should succeed", dynamoDbBroker.createTable()); AssertJUnit.assertTrue("Table deletion should succeed", dynamoDbBroker.deleteTable()); } @Test void canStoreAndReadUrlEntryByKey() { AssertJUnit.assertTrue("Table creation should succeed", dynamoDbBroker.createTable()); AssertJUnit.assertTrue("First insertion should succeed", dynamoDbBroker.insertEntry(TEST_KEY, TEST_VALUE)); // first insertion succeeds AssertJUnit.assertEquals("Value for key should be what we inserted", TEST_VALUE, dynamoDbBroker.queryValue(TEST_KEY)); } @Test void canStoreAndReadUrlEntryByValue() { AssertJUnit.assertTrue("Table creation should succeed", dynamoDbBroker.createTable()); AssertJUnit.assertTrue("First insertion should succeed", dynamoDbBroker.insertEntry(TEST_KEY, TEST_VALUE)); // first insertion succeeds AssertJUnit.assertEquals("Key for value should be what we inserted", TEST_KEY, dynamoDbBroker.queryKey(TEST_VALUE)); } @Test void doubleInsertionFails() { AssertJUnit.assertTrue("Table creation should succeed", dynamoDbBroker.createTable()); AssertJUnit.assertTrue("First insertion should succeed", dynamoDbBroker.insertEntry(TEST_KEY, TEST_VALUE)); // first insertion succeeds AssertJUnit.assertFalse("Repeated insertion should fail", dynamoDbBroker.insertEntry(TEST_KEY, TEST_VALUE)); // second insertion fails } } <file_sep>/README.md # url-shortener ## Goals * A URL shortening RESTful service which produces short urls from “long” (any) urls and redirects requests for short urls to the original urls * Basic availability via data persistence * Scalability: single instance for this demo but ready to add load balancer and more instances * Validation of URL well-formedness * Security: it should be hard for strangers to discover existing short urls whose expansions might be sensitive for the other users who created them ## Non-goals For demo purposes, the focus is on the core service, not on a full-blown production- level web app. Therefore, the service does not offer: * A UI * Scalability beyond a single instance (but ready to add load balancer and multiple instances) * High availability (e.g. redundancy) beyond data persistence * Validation that a service exists and is up on the “long” URL * Security: blacklist or slow down users who are trying to repeatedly guess short urls <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.santel</groupId> <artifactId>url-shortener</artifactId> <packaging>war</packaging> <version>0.1.0</version> <name>url-shortener</name> <description>An example URL shortener using Spring Boot that can run on a single machine or AWS</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <start-class>org.santel.url.ShorteningService</start-class> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-bom</artifactId> <version>1.10.43</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- Compile dependencies --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-dynamodb</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-ec2</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-remote-shell</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Test dependencies --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.9.10</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <dependencies> <!--<dependency>--> <!--<groupId>org.apache.maven.surefire</groupId>--> <!--<artifactId>surefire-junit47</artifactId>--> <!--<version>2.19.1</version>--> <!--</dependency>--> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-testng</artifactId> <version>2.19.1</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project><file_sep>/src/main/java/org/santel/url/model/MappingModel.java package org.santel.url.model; import com.google.common.base.*; import org.santel.exception.*; import org.santel.net.*; import org.santel.url.dao.*; import org.slf4j.*; import org.springframework.stereotype.*; import javax.inject.*; import java.net.*; @Component public class MappingModel { private static final Logger LOG = LoggerFactory.getLogger(MappingModel.class); private static final String SHORT_URL_PROTOCOL = "http"; //TODO make more secure with https @Inject private MappingDao mappingDao; @Inject private AlphanumericEncoder alphanumericEncoder; public URL shortenUrl(URL longUrl) { Preconditions.checkNotNull(longUrl); // first, check store for existence of entry for long url URL shortUrl = mappingDao.getShortUrl(longUrl); if (shortUrl != null) { LOG.info("Long url {} has already been shortened to {}", longUrl, shortUrl); return shortUrl; } // create short url, trying multiple times in case of collisions int tries = 100; while (tries-- > 0) { // encode long url as an alphanumeric-base string String shortCode = alphanumericEncoder.encodeAlphanumeric(longUrl.toString()); shortUrl = getShortUrlFromCode(shortCode); // check for entry in data store; store and return it if it doesn't exist (i.e. no collision) if (mappingDao.addUrlEntry(shortUrl, longUrl)) { LOG.info("Shortened {} to {}", longUrl, shortUrl); return shortUrl; } // long URL might have been added by another thread or instance in the meantime URL anotherShortUrl = mappingDao.getShortUrl(longUrl); if (anotherShortUrl != null) { LOG.info("Long url {} was shortened in the meantime to {}", longUrl, anotherShortUrl); return anotherShortUrl; } URL storedLongUrl = mappingDao.getLongUrl(shortUrl); Preconditions.checkState(storedLongUrl != null && !storedLongUrl.equals(longUrl)); // it must be a collision } String errorMessage = "Exhausted tries to generate a non-colliding short url"; LOG.error(errorMessage); throw new RuntimeException(errorMessage); } public URL expandUrl(String shortCode) { URL shortUrl = getShortUrlFromCode(shortCode); URL longUrl = mappingDao.getLongUrl(shortUrl); if (longUrl == null) { Exceptions.logAndThrow(LOG, String.format("Short url %s not found in store", shortUrl)); } LOG.info("Expanded {} to {}", shortUrl, longUrl); return longUrl; } private URL getShortUrlFromCode(String shortCode) { URL shortUrl; String hostName = Network.getLocalHostName(); try { shortUrl = new URL(SHORT_URL_PROTOCOL, hostName, "/" + shortCode); } catch (MalformedURLException e) { LOG.error("Exception trying to form URL from protocol {}, local host name {}, and code {}: {}", SHORT_URL_PROTOCOL, hostName, shortCode, e); throw new RuntimeException("Can't form short URL from original url, local host name, and code", e); } return shortUrl; } }
54b49de857d16c360e5285ab0bf6d36dba35bdb2
[ "Markdown", "Java", "Maven POM" ]
6
Java
Howww/url-shortener
c3ec672109c470f5c617cedb3eef5f03088ba53e
305eed253b8efb4a836fd8aebdd08e1f7293b9f3
refs/heads/master
<repo_name>saranzz/Per-vekala<file_sep>/src/main/java/pages/CreateLead.java package pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import wdMethods.ProjectMethods; public class CreateLead extends ProjectMethods{ public CreateLead() { PageFactory.initElements(driver,this); } @FindBy(how=How.ID, using ="createLeadForm_companyName") private WebElement eleCName ; public CreateLead cName(String data) { type(eleCName, data); return this; } @FindBy(how=How.ID,using= "createLeadForm_firstName") private WebElement elefName ; public CreateLead fName(String data) { type(elefName, data); return this; } @FindBy(how=How.ID,using= "createLeadForm_lastName") private WebElement elelName ; public CreateLead lName(String data) { type(elelName, data); return this; } @FindBy(how=How.CLASS_NAME,using ="smallSubmit") private WebElement eleCleadButton ; public ViewLead clickcleadButton(){ click(eleCleadButton); return new ViewLead(); } }
7143a71894d1d39dcbf1966f180ac536dc569c61
[ "Java" ]
1
Java
saranzz/Per-vekala
9c8233f84d787b7135f3df79f32b1d98ab7a2d0a
62f657daef6157d65ba6f883fc66e33b0c732cb1
refs/heads/master
<repo_name>KortneyField/Guess-the-Number<file_sep>/guessnumber.py import random guessNum = 0 guessLimit = 3 low = 0 high = 20 num = random.randint(low,high) #low = int(input("Enter low number: ")) #high = int(input("Enter high number: ")) print(" ") print(" ***Welcome to the Great Number Guessing Game***") print(" ") while guessNum < guessLimit: try: guess = int(input("guess number between {} and {}: ". format(low, high))) print(" ") except ValueError: print("Not at valid number. Try again") continue if guess > high or guess < low: print("Your guess is out of range. Please pick a number betwee {} and {}".format(low,high)) print(" ") else: guessNum = guessNum + 1 if guess > num: print("too high") if guess < num: print("too low") print("You have {} guesses left".format(guessNum)) print(" ") pass while True: var = print("Would you like to play again? (y/n): ") if var == "n" or "N": break if guess == num: print("CONGRATS!! You guess the number! ") print(" ") if guessNum == guessLimit: print("You have guessed too many times. Goodbye") print("The secret number was ** {} **".format(num)) print(" ")
fd6fbf6ab1d495c42f7908ce30bbf7a427795f13
[ "Python" ]
1
Python
KortneyField/Guess-the-Number
fc2a4d797051c63ada3325f6a7d25912276e857a
ed4881e6705ebcf4412f18ebc332042a8594bf3e
refs/heads/master
<file_sep>\[**Note**: this file _should not_ be distributed with the prcs2hg package.\] This repository contains the source code for prcs2hg, which is a command to convert a [PRCS][] project to [Mercurial][] revisions. It would help you publish the revision history of an obsolete project whose changes were maintained with [PRCS][]. prcs2hg is free software: you can redistribute it and/or modify it under the conditions specified in each file. The main part of prcs2hg is licensed with the [OSI-approved MIT License][]. For more information about prcs2hg, visit the prcs2hg project at <http://www.vx68k.org/prcs2hg>. [PRCS]: <http://prcs.sourceforge.net/> [Mercurial]: <http://mercurial.selenic.com/> [OSI-approved MIT License]: <http://opensource.org/licenses/MIT> ## Third-party components The file 'prcs/sexpdata.py' was copied from the [sexpdata][] package and modified not to parse numbers so that we can handle version numbers correctly. [sexpdata]: <https://github.com/tkf/sexpdata> <file_sep>#!/usr/bin/env python # # Copyright (C) 2012-2015 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from distutils.core import setup setup(name = 'prcs2hg', version = '2.0', author = '<NAME>', author_email = '<EMAIL>', url = 'http://www.vx68k.org/prcs2hg', packages = ['prcs2hg', 'prcslib'], scripts = ['scripts/prcs2hg']) <file_sep># # Copyright (C) 2012-2014 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # """convert PRCS revisions to Mercurial changesets """ import sys import re import os import hglib from string import join from prcslib import PrcsProject class Converter(object): def __init__(self, name, verbose = False): """Construct a Converter object.""" self.name = name self.verbose = verbose self.revisionmap = {} self.symlink_warned = {} self.prcs = PrcsProject(self.name) self.revisions = self.prcs.revisions() self.hgclient = hglib.open(".") def convert(self): """Convert all revisions in a project.""" list = sorted(self.revisions, key = lambda id: self.revisions[id]["date"]) for i in list: self.convertrevision(i) def convertrevision(self, version): version = str(version) if self.revisions[version].get("deleted"): sys.stderr.write("Ignored deleted version {0}\n".format(version)) return if self.verbose: sys.stderr.write("Converting version {0}\n".format(version)) descriptor = self.prcs.descriptor(version) parent = descriptor.parentversion() if parent is None: # It is a root revision. self.hgclient.update("null") parent_filemap = {} else: while self.revisions[str(parent)].get("deleted"): parent.minor -= 1 parent = str(parent) if self.revisionmap.get(parent) is None: self.convertrevision(parent) # TODO: If the parent is not converted, do it here. sys.exit("Parent revision {0} not converted" .format(parent)) self.hgclient.update(self.revisionmap[parent]) parent_filemap = self.revisions[parent].get("filemap") if parent_filemap is None: sys.exit("No parent filemap") parent_descriptor = self.prcs.descriptor(parent) parent_filemap = _makefilemap(parent_descriptor.files()) # Handles merges. mergeparents = descriptor.mergeparents() if mergeparents: self._handlemerge(mergeparents) # Makes the working directory clean. for i in self.hgclient.status(): if i[0] == "?": os.unlink(i[1]) self.hgclient.revert([], "null", all = True) self.prcs.checkout(version) files = descriptor.files() filemap = _makefilemap(files) self.revisions[version]["filemap"] = filemap # Checks for files. addlist = [] for name, file in files.iteritems(): # We cannot include symbolic links in Mercurial repositories. if "symlink" in file: if not self.symlink_warned.get(name, False): sys.stderr.write("{0}: warning: symbolic link\n" .format(name)) self.symlink_warned[name] = True else: file_id = file.get("id") if file_id is None: sys.exit("{0}: Missing file identity".format(name)) parent_name = parent_filemap.get(file_id) if parent_name is not None and parent_name != name: if self.verbose: sys.stderr.write("{0}: renamed from {1}\n" .format(name, parent_name)) self.hgclient.copy(parent_name, name, after = True) else: addlist.append(name) if addlist: self.hgclient.add(addlist) # Sets the branch for the following commit. version = descriptor.version() branch = "default" if not re.match("[0-9]+$", version.major): branch = version.major self.hgclient.branch(branch, force = True) version = str(version) message = descriptor.message() if not message: message = "(empty commit message)" revision = self.hgclient.commit(message = message, date = self.revisions[version]["date"], user = self.revisions[version]["author"]) self.revisionmap[version] = revision[1] # Keeps the revision identifier as a local tag for convenience. self.hgclient.tag([version], local = True, force = True) def _handlemerge(self, mergeparents): """Handle merges.""" if len(mergeparents) > 1: sys.stderr.write("warning: multiple merge parents: {0}\n" .format(join(mergeparents, ", "))) sys.stderr.write("warning: picked {0} on record\n" .format(mergeparents[-1])) self.hgclient.merge(self.revisionmap[mergeparents[-1]], tool = "internal:local", cb = hglib.merge.handlers.noninteractive) def _makefilemap(files): filemap = {} for name, file in files.iteritems(): id = file.get("id") if id is not None: if filemap.get(id) is not None: sys.stderr.write( "warning: Duplicate file identifier in a revision\n") filemap[id] = name return filemap def convert(name, verbose = False): """convert revisions.""" converter = Converter(name, verbose = verbose) converter.convert() <file_sep># # prcslib/__init__.py - command interface package for PRCS # Copyright (C) 2012-2015 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # """provide command line interface to PRCS """ import sys import re import os from datetime import datetime from email.utils import parsedate from subprocess import Popen, PIPE import prcslib.sexpdata as sexpdata # Regular expression pattern for splitting versions. _VERSION_RE = re.compile(r"^(.*)\.(\d+)$") class PrcsError(Exception): """Base exception for this module.""" pass class PrcsCommandError(PrcsError): """Error from the PRCS command.""" def __init__(self, error_message): """Construct a command error with an error message from PRCS.""" super(PrcsCommandError, self).__init__(self) self.error_message = error_message class PrcsVersion(object): """Version identifier of PRCS.""" def __init__(self, major, minor=None): if minor is None: m = _VERSION_RE.match(major) major, minor = m.groups() self.major = major self.minor = int(minor) def __str__(self): return self.major + "." + str(self.minor) class PrcsProject(object): def __init__(self, name): """construct a Project object.""" self.name = name self.info_re = re.compile( "^([^ ]+) ([^ ]+) (.+) by ([^ ]+)( \*DELETED\*|)") def revisions(self): out, err = self._run_prcs(["info", "-f", self.name]); revisions = {} if (not err): # We use iteration over lines so that we can detect parse errors. for line in out.splitlines(): m = self.info_re.search(line) if (m): # The prcs info command always returns the local time. date = parsedate(m.group(3)) revisions[m.group(2)] = { "project": m.group(1), "id": m.group(2), "date": datetime(*date[0:6]), "author": m.group(4), "deleted": bool(m.group(5)) } else: raise PrcsCommandError(err) return revisions def descriptor(self, id = None): return PrcsDescriptor(self, id) def checkout(self, revision = None, files = []): args = ["checkout", "-fqu"] if not files: args.append("-P") if revision is not None: args.extend(["-r", revision]) args.append(self.name) args.extend(files) out, err = self._run_prcs(args) if err: sys.stderr.write(err) def _run_prcs(self, args, input = None): """run a PRCS subprocess.""" prcs = Popen(["prcs"] + args, stdin = PIPE, stdout = PIPE, stderr = PIPE) return prcs.communicate(input) class PrcsDescriptor(object): def __init__(self, project, id = None): prj_name = project.name + ".prj" project.checkout(id, [prj_name]) self.properties = _readdescriptor(prj_name) os.unlink(prj_name) def version(self): """Return the version in this descriptor.""" v = self.properties["Project-Version"] return PrcsVersion(v[1].value(), v[2].value()) def parentversion(self): """Return the major and minor parent versions.""" v = self.properties["Parent-Version"] major = v[1].value() minor = v[2].value() if v[0].value() == "-*-" and major == "-*-" and minor == "-*-": return None return PrcsVersion(major, minor) def mergeparents(self): """Return the list of merge parents.""" p = [] for i in self.properties["Merge-Parents"]: if i[1].value() == "complete": p.append(i[0].value()) return p def message(self): """Return the log message.""" return self.properties["Version-Log"][0] def files(self): """Return the file information as a dictionary.""" files = {} for i in self.properties["Files"]: name = i[0].value() symlink = False for j in i[2:]: if j.value() == ":symlink": symlink = True if symlink: files[name] = { "symlink": i[1][0].value(), } else: files[name] = { "id": i[1][0].value(), "revision": i[1][1].value(), "mode": int(i[1][2].value(), 8), } return files def _readdescriptor(name): with open(name, "r") as f: string = f.read() descriptor = {} # Encloses the project descriptor in a single list. for i in sexpdata.loads("(\n" + string + "\n)"): if isinstance(i, list) and isinstance(i[0], sexpdata.Symbol): descriptor[i[0].value()] = i[1:] return descriptor
09465c02a3f7e034780a567b4ae5c62c15848b84
[ "Markdown", "Python" ]
4
Markdown
vx68k/prcs2hg
640890247047f0067f0ba822981d8fbdc3c77896
d2bf79657aba7dba9f869cf3d2669824f17bdf46
refs/heads/master
<repo_name>GayriNizami/Marabeyn<file_sep>/README.md # Marabeyn Hub'a girilirkende çıkılırkende marabeyn denir. <file_sep>/marabayn.c #include <stdio.h> main () { printf("<NAME> olsun tekrar marabayn \n"); }
d483fb22389928081ccc29519e5c5943bba0465f
[ "Markdown", "C" ]
2
Markdown
GayriNizami/Marabeyn
825e767b82887bae4916cca290a5bdbf0b1232ae
f8866f60a7ffd43837cb8bef54dcc61ced1d5e91
refs/heads/master
<repo_name>schurakov/selenium-page-object-exersice<file_sep>/pages/basket_page.py from .base_page import BasePage from .locators import BasketPageLocators class BasketPage(BasePage): def should_not_be_product_in_basket(self): assert self.is_not_element_present(*BasketPageLocators.SOME_PRODUCT_IN_BASKET), \ "Some product in basket, but should not be" def should_be_text_about_empty_basket(self): expected_text = "Your basket is empty. Continue shopping" actual_text = self.browser.find_element(*BasketPageLocators.EMPTY_BASKET_TEXT) assert actual_text.text == expected_text, f"Unexpected empty basket text: {actual_text.text}. Expected: {expected_text}" <file_sep>/pages/locators.py from selenium.webdriver.common.by import By class MainPageLocators: LOGIN_LINK = (By.CSS_SELECTOR, "#login_link") class LoginPageLocators: LOGIN_FORM = (By.CSS_SELECTOR, "#login_form") REGISTRATION_FORM = (By.CSS_SELECTOR, "#register_form") REGISTRATION_FORM_EMAIL = (By.CSS_SELECTOR, "[name='registration-email']") REGISTRATION_FORM_PASS = (By.CSS_SELECTOR, "[name='registration-password1']") REGISTRATION_FORM_CONFIRM_PASS = (By.CSS_SELECTOR, "[name='registration-password2']") LOGIN_FORM_EMAIL = (By.CSS_SELECTOR, "[name='login-username']") LOGIN_FORM_PASS = (By.CSS_SELECTOR, "[name='login-password']") REGISTRATION_SUBMIT_BUTTON = (By.CSS_SELECTOR, "[name='registration_submit']") class ProductPageLocators: ADD_TO_BASKET_BUTTON = (By.CSS_SELECTOR, ".btn-add-to-basket") ADDED_TO_BASKET_ALERT = (By.CSS_SELECTOR, ".alert:first-child .alertinner ") BASKET_BLOCK_IN_RIGHT_CORNER = (By.CSS_SELECTOR, ".basket-mini") PRODUCT_MAIN_PRISE = (By.CSS_SELECTOR, ".product_main .price_color") PRODUCT_MAIN_NAME = (By.CSS_SELECTOR, ".product_main h1") class BasePageLocators: LOGIN_LINK = (By.CSS_SELECTOR, "#login_link") LOGIN_LINK_INVALID = (By.CSS_SELECTOR, "#login_link_inc") BASKET_BUTTON = (By.CSS_SELECTOR, ".basket-mini .btn") USER_ICON = (By.CSS_SELECTOR, ".icon-user") class BasketPageLocators: EMPTY_BASKET_TEXT = (By.CSS_SELECTOR, "[id='content_inner'] > p") # TODO: придумать селектор получше SOME_PRODUCT_IN_BASKET = (By.CSS_SELECTOR, ".basket-items") <file_sep>/pytest.ini [pytest] markers = login_guest: guest go to login page need_review: test for review<file_sep>/pages/product_page.py from .base_page import BasePage from .locators import ProductPageLocators class ProductPage(BasePage): def add_product_to_basket(self): add_to_basket_button = self.browser.find_element(*ProductPageLocators.ADD_TO_BASKET_BUTTON) add_to_basket_button.click() def should_be_correct_price_in_basket(self): expected_price = self.get_product_price() price_in_basket = self.browser.find_element(*ProductPageLocators.BASKET_BLOCK_IN_RIGHT_CORNER) assert expected_price in price_in_basket.text, "Unexpected price in basket" def should_be_correct_add_to_basket_notification(self): expected_notification = self.get_product_name() + " has been added to your basket." notification = self.browser.find_element(*ProductPageLocators.ADDED_TO_BASKET_ALERT) assert expected_notification == notification.text, "Unexpected product name in add to basket notification" def get_product_price(self): product_price = self.browser.find_element(*ProductPageLocators.PRODUCT_MAIN_PRISE) return product_price.text def get_product_name(self): product_name = self.browser.find_element(*ProductPageLocators.PRODUCT_MAIN_NAME) return product_name.text def should_not_be_success_message(self): assert self.is_not_element_present(*ProductPageLocators.ADDED_TO_BASKET_ALERT), \ "Success message is presented, but should not be" def should_disappear_success_message(self): assert self.is_disappeared(*ProductPageLocators.ADDED_TO_BASKET_ALERT), \ "Success message is not disappeared, but should be"
e33f49333321b7dd7028c31883316a2784bb0354
[ "Python", "INI" ]
4
Python
schurakov/selenium-page-object-exersice
277a485e86f30f3b476d2cb3aac160e2f2766859
e4c643d93d12cb059b177a2540e889f9c649de97
refs/heads/master
<repo_name>pszaflarski/image_downloader<file_sep>/image_downloader.py import os import csv import tkinter as tk from tkinter import filedialog # import openpyxl from urllib import request from urllib import error import datetime import requests def download_image(link, filename): headers = {'user-agent': 'Mozilla/5.0'} p = requests.get( link, headers=headers, stream=True) if p.status_code != 200: return p.status_code while True: try: with open('./downloads/' + filename, 'wb') as f: for chunk in p.iter_content(1024): f.write(chunk) break except FileNotFoundError: os.makedirs('./downloads/') return p.status_code def csv_work(filename): f = open(filename, 'r', encoding='windows-1252', errors='ignore') reader = csv.reader(f) return reader def write_audit(file, row): try: csv.writer(open(file, mode='a', encoding='utf-8', errors='ignore'), lineterminator='\n').writerow(row) except FileNotFoundError: csv.writer(open(file, mode='w', encoding='utf-8', errors='ignore'), lineterminator='\n').writerow(row) if __name__ == '__main__': has_headers = True # get a file dialogue box root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() folder = file_path.split('.')[0].split('\\')[-1].split('/')[-1] audit_file = 'audit_' + str(datetime.datetime.today()).replace('-', '').replace(':', '').replace('.', '').replace( ' ', '') + '.csv' # quit if you hit cancel if file_path == '': audit = ["cancelled by user"] print(audit) write_audit(audit_file, audit) quit() # convert the file to an iterator reader = csv_work(file_path) # loop through and and build dict d = {} while True: try: row = next(reader) except StopIteration: break if has_headers: has_headers = False continue key = row[0] links = row[1:] if key not in d: d[key] = ([], set()) for index, full_link in enumerate(links): link = full_link.split("?")[0] link = link.strip() if link == '': continue if link not in d[key][1]: d[key][0].append(link) for key in d: for index, link in enumerate(d[key][0]): ext = link.split('.')[-1] name = key + '_' + str(index) + '.' + ext code = 400 # assume things fail unless they don't try: code = download_image(link, name) if code != 200: raise Exception audit = ["successfully downloaded", name, link] except error.HTTPError: audit = ["error downloading", name, link] except (error.URLError, ValueError): audit = ["invalid link", name, link] except Exception: audit = ["unknown error, code:" + str(code), name, link] print(audit) write_audit(audit_file, audit)
9388dddb33ecab43fc57f8cb6d34e9429f48c102
[ "Python" ]
1
Python
pszaflarski/image_downloader
479ca4fef3575849dee36c6fe1817959db2ed0e8
87251acaacdd251f6ab0a052a13f277535f76ef7
refs/heads/master
<file_sep><?php # Script 3.7 - index.php #2 // This function outputs theoretical HTML // for adding ads to a Web page. function create_ad() { echo '<div class="alert alert-info" role="alert"><p>This is an add for Assignment 2! This is an add for Assignment 2! This is an add for Assignment 2!</p></div>'; } // End of the function definition. $page_title = 'Welcome to Assignment 2!'; include('includes/header.html'); // Call the function: create_ad(); ?> <div class="page-header"><h1>Assignment 2 Homepage</h1></div> <p>This is the first paragraph for Assignment 2. </p> <p> Use your example files from the book. There is a sql.sql file in the root folder. Read through it and find where the DB called banking is created. </p> <p>Run phpMyAdmin. Using the sql.sql SQL script from the book, import the banking database, its table(s), and insert data into table(s).</p> <p>In Cloud9 BASH: navigate to the folder that contains the local repo you created previously for all assignments. Hint: check that you see a prompt similar to</p> <p>Your username:~/workspace/yourAssignments (master) $</p> <p>Recall that without the (master) you don’t have a repo.</p> <p>Use git status and git remote –v to make sure everything is set up correctly.</p> </p> <?php // Call the function again: create_ad(); include('includes/footer.html'); ?><file_sep><?php # Script 3.7 - index.php #2 // This function outputs theoretical HTML // for adding ads to a Web page. function create_ad() { echo '<div class="alert alert-info" role="alert"><p>This is an add for Assignment 1! This is an add for Assignment 1! This is an add for Assignment 1!</p></div>'; } // End of the function definition. $page_title = 'Welcome to Assignment 1!'; include('includes/header.html'); // Call the function: create_ad(); ?> <div class="page-header"><h1>Assignment 1 Homepage</h1></div> <p>This is the first paragraph for Assignment 1. </p> <p> In your Cloud9 folder structure, create one folder to hold all of our assignments. Use BASH shell: navigate to the folder for all assignments you just created (cd folder name). Here are the steps to use the local and remote repos. Repeat as necessary. </p> <p>1. Initialize a git repo for assignments (do this only once)</p> <p>2. Remember to check status, add pages to the stage, commit locally</p> <p>3. Check to see if you are connected to a remote repo</p> <p>4. If not connected, run “git remote add origin …” command</p> <p>5. Push local commit to remote rep</p> </p> <?php // Call the function again: create_ad(); include('includes/footer.html'); ?>
f42c7c6a6dbebdc3950a43e29648548145c83d27
[ "PHP" ]
2
PHP
josiereynolds/Fall2018Assignments
17c9c6a1af1de8cbacd30c6d56397e8524a307e3
3bfc2047e012a56ab4dadc5c2087d326c7a5372c
refs/heads/master
<repo_name>MichiganCliffy/chef<file_sep>/cookbooks/mono/attributes/default.rb default['mono']['install_method'] = "packages" case platform when "debian","ubuntu" default['mono']['prefix'] = "/usr/local" default['mono']['branch'] = "mono-3.0.12" end <file_sep>/roles/java.rb name "java" description "Java Stack" override_attributes({ "java" => { "jdk_version" => "7" } }) run_list "recipe[java]","recipe[maven]" <file_sep>/roles/tomcat7.rb name "tomcat7" description "Tomcat Stack" override_attributes({ "java" => { "jdk_version" => "7" }, "tomcat" => { "base_version" => "7" } }) run_list "recipe[java]","recipe[maven]","recipe[openssl]","recipe[tomcat]"
3f601d488ea5d11a9698e29d6aa9ec4cb3520c92
[ "Ruby" ]
3
Ruby
MichiganCliffy/chef
14d7deae63c03c5f4b6d81d5e399a04fa0a5052f
d41ee9bd938ba0da292f28eb517d5e426650924e
refs/heads/master
<file_sep>#! /bin/sh # make symlink of reveal.js ln -s $revealJsPath$/css \$(pwd)/css ln -s $revealJsPath$/js \$(pwd)/js ln -s $revealJsPath$/lib \$(pwd)/lib ln -s $revealJsPath$/plugin \$(pwd)/plugin ln -s $revealJsPath$/node_modules \$(pwd)/node_modules ln -s $revealJsPath$/Gruntfile.js \$(pwd)/Gruntfile.js ln -s $revealJsPath$/package.json \$(pwd)/package.json # make directories mkdir code mkdir image mkdir graphviz # add permission to scripts chmod u+x \$(dirname \$0)/* <file_sep>name=presentation description=Create a presentation slide using reveal.js. title=Title author=Author date=\\today revealJsPath= <file_sep>#! /bin/sh find ./\$1 -type f <file_sep>% $title$ % $author$ % $date$ # Title1 ## Sub Section <file_sep>#! /bin/sh scriptDir=\$(dirname \$0) srcDir=\$1 mainFile=\$2 target=\$3 pandocCmd=\$4 shift 4 pandocFlag=\$@ # join # pre-compile # compile # post-compile \${scriptDir}/join.scala \$srcDir \$mainFile \${scriptDir} | \ \${scriptDir}/precompile.sh | \ \${pandocCmd} \${pandocFlag} | \ \${scriptDir}/postcompile.sh > \${target}
a3887878f73853a12a85d6c4668c1e2d67cc0947
[ "Markdown", "INI", "Shell" ]
5
Shell
HiroakiMikami/Reveal.js.g8
78d2a271b28826b5766e390eaf1ce925ce0cb8b6
d5ba0868e37c9450c65129aac83e0967e7bf72da
refs/heads/master
<repo_name>joaozuchinali/semanaoministak11<file_sep>/backend/src/index.js const express = require('express'); const cors = require('cors'); const routes = require('./routes'); const app = express(); app.use(cors()); app.use(express.json()); app.use(routes); app.listen('3333'); // get busca informações do back end // post, criar uma nova informação // put altera // delete deleta // tipos de parâmetros // Query: parâmetros nomeados e enviados na rota após o símbolo de interrogação (filtros paginação) // app.get('/users?evento=testa...', (request,response) => { // const params = request.params; // console.log(params); // return response.json({ // evento: 'testa da semana oministek', // aluno: '<NAME>' // }); // }); // Route Params: parametros utilizados para indentificar recursos // app.get('/users/id:1', (request,response) => { // return response.json({ // evento: 'testa da semana oministek', // aluno: '<NAME>' // }); // }); // // Request Body: corpo da requisição utilizado para criar ou modificar recursos // SQL's da vida: MySQL, SQLite, etc.. // NoSQL: MongoDB, CounchDB, etc.. // isse define o caminho do arquivo
0840ee7e5ab7b3bcd3d9fbbbb9c808371715829e
[ "JavaScript" ]
1
JavaScript
joaozuchinali/semanaoministak11
4202a501d78f2a2cd7ecf783235a04b436b5b177
01da7f226e52a12e3ca294c3b8e39ced492c86aa
refs/heads/master
<file_sep>// // File.swift // LongPratice // // Created by god、long on 15/9/16. // Copyright (c) 2015年 ___GL___. All rights reserved. // import Foundation import UIKit // 当前系统版本 let version = (UIDevice.currentDevice().systemVersion as NSString).floatValue // 屏幕宽度 let ScreenHeight : CGFloat = UIScreen.mainScreen().bounds.height // 屏幕高度 let ScreenWidth : CGFloat = UIScreen.mainScreen().bounds.width // 默认图片 let defaultImg = UIImage(named: "photo_define") // NSUserDefault let userDefault = NSUserDefaults.standardUserDefaults() // 通知中心 let notice = NSNotificationCenter.defaultCenter() //判断是不是plus let currentModeSize = UIScreen.mainScreen().currentMode?.size let isPlus = UIScreen.instancesRespondToSelector("currentMode") ? CGSizeEqualToSize(CGSizeMake(1242, 2208), currentModeSize!) : false //判断字符串是否为空 func trimString(#str:String)->String{ var nowStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()); return nowStr } //去除空格和回车 func trimLineString(#str:String)->String{ var nowStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) return nowStr } //根据键盘监控 获取键盘高度 func getKeyBoardHeight(#aNotification:NSNotification)->CGFloat{ var uInfo = aNotification.userInfo as NSDictionary! let avalue = uInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue let keyrect : CGRect = avalue.CGRectValue() let keyheight : CGFloat = keyrect.size.height; return keyheight } //获取目录下存储的json文件并解析为集合 func getNativeJson(#filename : String,#fileext : String)->AnyObject{ let pathsBun = NSBundle.mainBundle() let paths = pathsBun.pathForResource(filename, ofType : fileext) var errors:NSError? var content : NSData = NSData(contentsOfFile: paths!, options : .DataReadingMappedIfSafe, error: nil)! var returneddata: AnyObject? = NSJSONSerialization.JSONObjectWithData(content as NSData, options:NSJSONReadingOptions.MutableContainers, error:&errors) return returneddata! } //消息提醒 func showAlertView(#title:String,#message:String){ var alert = UIAlertView() alert.title = title alert.message = message alert.addButtonWithTitle("好") alert.show() } //获取本地存储数据 func get_userDefaults(#key : String)->AnyObject?{ var saveStr : AnyObject! = userDefault.objectForKey(key) saveStr = (saveStr == nil) ? "" : saveStr return saveStr } //存储数据 func save_userDefaults(#key : String,#value:AnyObject?){ userDefault.setObject(value!, forKey:key) } //字符串转数组 func stringToArray(#str:String)->NSArray{ var dataArray:[String] = [] for items in str{ dataArray.append("/(items)") } return dataArray }
65f31e5d1ce2afd52d5b63460b583895e877b1c8
[ "Swift" ]
1
Swift
dennishappy/GLSegmentSlideView
506c01cdeb8f9ddc22a0fc38e5e5b3998afeba87
c4d8d83713e58a7998826d60eb19637a0a25c99d
refs/heads/master
<repo_name>lowi-yeah/puppet-rethinkdb<file_sep>/README.md # puppet-rethinkdb <!-- [![Build Status](https://travis-ci.org/lowi-yeah/puppet-mpsquitto.png?branch=master)](https://travis-ci.org/lowi-yeah/puppet-mpsquitto) --> [Wirbelsturm](https://github.com/miguno/wirbelsturm)-compatible [Puppet](http://puppetlabs.com/) module to deploy [RethinkDB](https://rethinkdb.com/). You can use this Puppet module to deploy RethinkDB to physical and virtual machines, for instance via your existing internal or cloud-based Puppet infrastructure and via a tool such as [Vagrant](http://www.vagrantup.com/) for local and remote deployments. --- Table of Contents * <a href="#quickstart">Quick start</a> * <a href="#features">Features</a> * <a href="#requirements">Requirements and assumptions</a> * <a href="#installation">Installation</a> * <a href="#configuration">Configuration</a> * <a href="#usage">Usage</a> * <a href="#configuration-examples">Configuration examples</a> * <a href="#hiera">Using Hiera</a> * <a href="#manifests">Using Puppet manifests</a> * <a href="#service-management">Service management</a> * <a href="#log-files">Log files</a> * <a href="#custom-zk-root">Custom ZooKeeper chroot (experimental)</a> * <a href="#development">Development</a> * <a href="#todo">TODO</a> * <a href="#changelog">Change log</a> * <a href="#contributing">Contributing</a> * <a href="#license">License</a> * <a href="#references">References</a> --- <a name="quickstart"></a> # Quick start See section [Usage](#usage) below. <a name="features"></a> # Features * Decouples code (Puppet manifests) from configuration data ([Hiera](http://docs.puppetlabs.com/hiera/1/)) through the use of Puppet parameterized classes, i.e. class parameters. Hence you should use Hiera to control how Kafka is deployed and to which machines. * Supports RHEL OS family (e.g. RHEL 6, CentOS 6, Amazon Linux). * Code contributions to support additional OS families are welcome! * Supports tuning of system-level configuration such as the maximum number of open files (cf. `/etc/security/limits.conf`) to optimize the performance of your Mosquitto deployments. * Mosquitto is run under process supervision via [supervisord](http://www.supervisord.org/) version 3.0+. <a name="requirements"></a> # Requirements and assumptions * This module requires that the target machines to which you are deploying Mosquitto have **yum repositories configured** for pulling the Mosquitto package (i.e. RPM). * Because we run Mosquitto via supervisord through [puppet-supervisor](https://github.com/miguno/puppet-supervisor), the supervisord RPM must be available, too. See [puppet-supervisor](https://github.com/miguno/puppet-supervisor) for details. * This module requires the following **additional Puppet modules**: * [puppetlabs/stdlib](https://github.com/puppetlabs/puppetlabs-stdlib) * [puppet-limits](https://github.com/miguno/puppet-limits) * [puppet-supervisor](https://github.com/miguno/puppet-supervisor) It is recommended that you add these modules to your Puppet setup via [librarian-puppet](https://github.com/rodjek/librarian-puppet). See the `Puppetfile` snippet in section _Installation_ below for a starting example. * **When using Vagrant**: Depending on your Vagrant box (image) you may need to manually configure/disable firewall settings -- otherwise machines may not be able to talk to each other. One option to manage firewall settings is via [puppetlabs-firewall](https://github.com/puppetlabs/puppetlabs-firewall). <a name="installation"></a> # Installation It is recommended to use [librarian-puppet](https://github.com/rodjek/librarian-puppet) to add this module to your Puppet setup. Add the following lines to your `Puppetfile`: ``` # Add the stdlib dependency as hosted on public Puppet Forge. # # We intentionally do not include the stdlib dependency in our Modulefile to make it easier for users who decided to # use internal copies of stdlib so that their deployments are not coupled to the availability of PuppetForge. While # there are tools such as puppet-library for hosting internal forges or for proxying to the public forge, not everyone # is actually using those tools. mod 'puppetlabs/stdlib', '>= 4.1.0' # Add the puppet-kafka module mod 'mosquitto', :git => 'https://github.com/lowi-yeah/puppet-mosquitto.git' # Add the puppet-limits and puppet-supervisor module dependencies mod 'limits', :git => 'https://github.com/miguno/puppet-limits.git' mod 'supervisor', :git => 'https://github.com/miguno/puppet-supervisor.git' ``` Then use librarian-puppet to install (or update) the Puppet modules. <a name="configuration"></a> # Configuration * See [init.pp](manifests/init.pp) for the list of currently supported configuration parameters. These should be self-explanatory. * See [params.pp](manifests/params.pp) for the default values of those configuration parameters. <a name="usage"></a> # Usage **IMPORTANT: Make sure you read and follow the [Requirements and assumptions](#requirements) section above.** **Otherwise the examples below will of course not work.** <a name="configuration-examples"></a> ## Configuration examples <a name="hiera"></a> ### Using Hiera A "full" single-node example that includes the deployment of [supervisord](http://www.supervisord.org/) via [puppet-supervisor](https://github.com/miguno/puppet-supervisor). The Mosquitto broker will listen on port `1883/tcp`. ```yaml --- classes: - mosquitto::service - supervisor ``` <a name="manifests"></a> ### Using Puppet manifests _Note: It is recommended to use Hiera to control deployments instead of using this module in your Puppet manifests_ _directly._ TBD <a name="service-management"></a> ## Service management To manually start, stop, restart, or check the status of the Kafka broker service, respectively: $ sudo supervisorctl [start|stop|restart|status] mosquitto Example: $ sudo supervisorctl status mosquitto RUNNING pid 16461, uptime 3 days, 09:22:38 <a name="log-files"></a> ## Log files _Note: The locations below may be different depending on the Kafka RPM you are actually using._ * Kafka log files: `/var/log/mosquitto/*.log` * Supervisord log files related to Kafka processes: * `/var/log/supervisor/mosquitto/mosquitto.out` * `/var/log/supervisor/kafka-broker/kafka-broker.err` * Supervisord main log file: `/var/log/supervisor/supervisord.log` <a name="custom-zk-root"></a> <a name="development"></a> # Development It is recommended run the `bootstrap` script after a fresh checkout: $ ./bootstrap You have access to a bunch of rake commands to help you with module development and testing: $ bundle exec rake -T rake acceptance # Run acceptance tests rake build # Build puppet module package rake clean # Clean a built module package rake coverage # Generate code coverage information rake help # Display the list of available rake tasks rake lint # Check puppet manifests with puppet-lint / Run puppet-lint rake module:bump # Bump module version to the next minor rake module:bump_commit # Bump version and git commit rake module:clean # Runs clean again rake module:push # Push module to the Puppet Forge rake module:release # Release the Puppet module, doing a clean, build, tag, push, bump_commit and git push rake module:tag # Git tag with the current module version rake spec # Run spec tests in a clean fixtures directory rake spec_clean # Clean up the fixtures directory rake spec_prep # Create the fixtures directory rake spec_standalone # Run spec tests on an existing fixtures directory rake syntax # Syntax check Puppet manifests and templates rake syntax:hiera # Syntax check Hiera config files rake syntax:manifests # Syntax check Puppet manifests rake syntax:templates # Syntax check Puppet templates rake test # Run syntax, lint, and spec tests Of particular interest are: * `rake test` -- run syntax, lint, and spec tests * `rake syntax` -- to check you have valid Puppet and Ruby ERB syntax * `rake lint` -- checks against the [Puppet Style Guide](http://docs.puppetlabs.com/guides/style_guide.html) * `rake spec` -- run unit tests <a name="todo"></a> TBD <a name="changelog"></a> # Change log See [CHANGELOG](CHANGELOG.md). <a name="contributing"></a> # Contributing to puppet-mosquitto Code contributions, bug reports, feature requests etc. are all welcome. If you are new to GitHub please read [Contributing to a project](https://help.github.com/articles/fork-a-repo) for how to send patches and pull requests to puppet-kafka. <a name="license"></a> # License Copyright © 2014 <NAME> See [LICENSE](LICENSE) for licensing information. <a name="references"></a> # References This Puppet module is basically just an adaption of [miguno/puppet-kafka](https://github.com/miguno/puppet-kafka) <file_sep>/spec/classes/rethinkdb_spec.rb require 'spec_helper' describe 'rethinkdb' do context 'supported operating systems' do ['RedHat'].each do |osfamily| ['CentOS'].each do |operatingsystem| let(:facts) {{ :osfamily => 'RedHat', :operatingsystem => 'CentOS', }} default_broker_configuration_file = '/opt/rethinkdb/rethinkdb.conf' context "with explicit data (no Hiera)" do describe "rethinkdb with default settings on CentOS" do let(:params) {{ }} # We must mock $::operatingsystem because otherwise this test will # fail when you run the tests on e.g. Mac OS X. it { should compile.with_all_deps } it { should contain_class('rethinkdb::params') } it { should contain_class('rethinkdb') } it { should contain_class('rethinkdb::users').that_comes_before('rethinkdb::install') } it { should contain_class('rethinkdb::install').that_comes_before('rethinkdb::config') } it { should contain_class('rethinkdb::config') } it { should contain_class('rethinkdb::service').that_subscribes_to('rethinkdb::config') } it { should contain_package('rethinkdb').with_ensure('present') } it { should contain_group('rethinkdb').with({ 'ensure' => 'present', 'gid' => 53076, })} it { should contain_user('rethinkdb').with({ 'ensure' => 'present', 'home' => '/home/rethinkdb', 'shell' => '/bin/bash', 'uid' => 53046, 'comment' => 'RethinkDB system account', 'gid' => 'rethinkdb', 'managehome' => true })} it { should contain_file(default_broker_configuration_file).with({ 'ensure' => 'file', 'owner' => 'root', 'group' => 'root', 'mode' => '0644', }). with_content(/\sdriver-port=28015\s/) } it { should_not contain_file('/tmpfs') } it { should_not contain_mount('/tmpfs') } it { should contain_supervisor__service('rethinkdb').with({ 'ensure' => 'present', 'enable' => true, 'command' => 'rethinkdb --config-file /opt/rethinkdb/rethinkdb.conf', 'user' => 'rethinkuser', 'group' => 'rethinkgroup', 'autorestart' => true, 'startsecs' => 10, 'retries' => 999, 'stopsignal' => 'INT', 'stopasgroup' => true, 'stopwait' => 10, 'stdout_logfile_maxsize' => '20MB', 'stdout_logfile_keep' => 5, 'stderr_logfile_maxsize' => '20MB', 'stderr_logfile_keep' => 10, })} end describe "rethinkdb with disabled user management on #{osfamily}" do let(:params) {{ :user_manage => false, }} it { should_not contain_group('rethinkdb') } it { should_not contain_user('rethinkdb') } end describe "rethinkdb with custom user and group on #{osfamily}" do let(:params) {{ :user_manage => true, :gid => 456, :group => 'rethinkgroup', :uid => 123, :user => 'rethinkuser', :user_description => 'RethinkDB system account', :user_home => '/home/rethinkuser', }} it { should_not contain_group('rethinkdb') } it { should_not contain_user('rethinkdb') } it { should contain_user('rethinkuser').with({ 'ensure' => 'present', 'home' => '/home/rethinkuser', 'shell' => '/bin/bash', 'uid' => 123, 'comment' => 'RethinkDB system account', 'gid' => 'rethinkgroup', 'managehome' => true, })} it { should contain_group('rethinkgroup').with({ 'ensure' => 'present', 'gid' => 456, })} end describe "rethinkdb with a custom port on #{osfamily}" do let(:params) {{ :driver_port => 28055, }} it { should contain_file(default_broker_configuration_file).with_content(/\driver_port=28055\s/) } end end end end end # context 'unsupported operating system' do # describe 'kafka without any parameters on Debian' do # let(:facts) {{ # :osfamily => 'Debian', # }} # it { expect { should contain_class('kafka') }.to raise_error(Puppet::Error, # /The kafka module is not supported on a Debian based system./) } # end # end end
b462ff424128e868f224614ff3ee25ae6d530c82
[ "Markdown", "Ruby" ]
2
Markdown
lowi-yeah/puppet-rethinkdb
71cf25ba9402d67d1ec06d3fb80a051275f11dba
d4eceac807e99bb4106fa6a050c5f21263f27ea6
refs/heads/master
<file_sep>//You are given an array of integers of size N. Can you find the sum of the elements in the array? #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int a,b,d; long long int c=0; scanf("%d",&a); int m[a]; for(b=0;b<a;b++) { scanf("%d",&m[b]); } for(b=0;b<a;b++) { c=c+m[b]; } printf("%lli",c); /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
e2c40e4d01b41bbe80a156505c45818145e0640b
[ "C" ]
1
C
prince-pratik7/HackerRank_Problems
6fde624c2c4ab64fd6d5478d0280f325841019a4
67f6fcac2a8c3c754c7083ed36967a77d95f87e3
refs/heads/main
<repo_name>pimvh/simpleenigma<file_sep>/parts/__init__.py from .rotor import Rotor, StaticRotor from .stekkerbrett import StekkerBrett<file_sep>/parts/stekkerbrett.py from collections import OrderedDict import itertools import random from .alphabetmapping import AlphabetMapping class StekkerBrett(AlphabetMapping): def __init__(self): super().__init__() n_of_stekkers = random.randint(1, 9) self.mapping = OrderedDict(itertools.islice(self.mapping.items(), n_of_stekkers)) self.reverse_mapping = OrderedDict(itertools.islice(self.reverse_mapping.items(), n_of_stekkers)) def get_encoded_char(self, key) -> str: if not key in self.mapping: return key return self.mapping.get(key) def get_decoded_char(self, key) -> str: if not key in self.reverse_mapping: return key return self.reverse_mapping.get(key) <file_sep>/parts/rotor.py from collections import OrderedDict from itertools import islice, cycle from .alphabetmapping import AlphabetMapping class Rotor(AlphabetMapping): """ defines a rotor of an enigma machine """ def __init__(self) -> None: super().__init__() self.rotorsize = len(self.mapping) self.state = 0 self.full_turns = 0 self.shift = 1 self.initial_state = next(iter(self.mapping)) def get_encoded_char(self, key) -> str: return self.mapping.get(key) def get_decoded_char(self, key) -> str: return self.reverse_mapping.get(key) def get_initial_state(self) -> str: return self.initial_state def turn(self) -> bool: ''' turn the rotor 1 spot, return True when the rotor is fully turned ''' self.state += self.shift self.mapping = OrderedDict( (k, v) for k, v in zip(self.mapping.keys(), islice(cycle(self.mapping.values()), 1, None)) ) self.reverse_mapping = OrderedDict((v, k) for k, v in self.mapping.items()) encoded = self.mapping.get('a') # print(self.mapping.get('a')) decoded = self.reverse_mapping.get(encoded) # print(self.reverse_mapping.get('n')) assert decoded == 'a' if self.state > self.rotorsize: self.state = 0 self.full_turns += 1 return True return False def dump_settings(self): return self.mapping def set_settings(self, mapping): self.mapping = mapping class StaticRotor(Rotor): """ defines a static rotor of an enigma machine """ def __init__(self) -> None: super().__init__() def turn(self) -> bool: return False <file_sep>/main.py #!/usr/bin/env python3 from collections import OrderedDict import copy from typing import Text import string import time from parts import Rotor, StaticRotor, StekkerBrett class Enigma(): def __init__(self, rotors : list[Rotor], stekkerbret : StekkerBrett): self.rotors = rotors self.stekkerbret = stekkerbret def get_state(self) -> list[OrderedDict]: return [rotor.dump_settings() for rotor in self.rotors] def set_state(self, settings) -> None: for rotor, setting in zip(self.rotors, settings): rotor.set_settings(setting) def encode(self, text_to_encode : Text) -> Text: print('encoding text...') result = '' char_map = {' ' : 'x', '?' : 'qq', '.' : 'dot', '/' : 'slash', ',' : 'comma',} for c, char in enumerate(text_to_encode): if c % 4 == 0 and not c == 0: result += ' ' if char in char_map: chars = char_map.get(char, '') for ch in chars: result += self.encode_character(ch) continue char = char.lower() if not char in string.ascii_lowercase: continue result += self.encode_character(char) return result def decode(self, text_to_decode : Text) -> Text: print('decoding text...') result = '' for c, char in enumerate(text_to_decode.replace(' ', '')): result += self.decode_character(char) return result def encode_character(self, char : str): ''' parse a single character ''' turn_next = True for i, current_rotor in enumerate(self.rotors): if turn_next: # print(f'rotor {i} turned') turn_next = current_rotor.turn() char = current_rotor.get_encoded_char(char) char = self.stekkerbret.get_encoded_char(char) return char def decode_character(self, char : str): ''' parse a single character ''' char = self.stekkerbret.get_decoded_char(char) turn_next = True for i, current_rotor in enumerate(self.rotors): if turn_next: # print(f'rotor {i} turned') turn_next = current_rotor.turn() for i, current_rotor in enumerate(reversed(self.rotors)): char = current_rotor.get_decoded_char(char) return char def show_settings(self): pass def main() -> None: rotors = [] stekkerbrett = StekkerBrett() for i in range(10): rotors.append(Rotor()) print(rotors[0]) rotors.append(StaticRotor()) decoder_rotors = [copy.deepcopy(x) for x in rotors] decoder_stekkerbrett = copy.deepcopy(stekkerbrett) enigma = Enigma(rotors, stekkerbrett) enigma_decoder = Enigma(decoder_rotors, decoder_stekkerbrett) plaintext = '''Hoi dit is enigma''' print(f'{plaintext=}') encoded = enigma.encode(plaintext) print(f'{encoded=}') decoded = enigma_decoder.decode(encoded) print(f'{decoded=}') if __name__ == "__main__": main() <file_sep>/parts/alphabetmapping.py from collections import OrderedDict import random import string class AlphabetMapping(): ''' implements a mapping of the alphabet for one letter to another ''' def __init__(self) -> None: input_alpabet = [x for x in string.ascii_lowercase] random.shuffle(input_alpabet) output_alphabet = [x for x in string.ascii_lowercase] random.shuffle(output_alphabet) self.mapping : OrderedDict = OrderedDict() self.reverse_mapping : OrderedDict = OrderedDict() for key, value in zip(input_alpabet, output_alphabet): self.mapping.update({key : value}) self.reverse_mapping.update({value : key}) encoded = self.mapping.get('a') decoded = self.reverse_mapping.get(encoded) assert decoded == 'a' def show(self) -> None: ''' display the alphabet mapping of this wheel ''' print(self) def __str__(self) -> str: out = '' for key, value in self.mapping.items(): out += str(key) + ' --> ' + str(value) + '\n' return out
7bbf3fad714bf425457ab1a9472d3184da3c34e3
[ "Python" ]
5
Python
pimvh/simpleenigma
bed6cfbdb2f6764753bd242ef80a4c6458d1a84d
6351d9f607c9103e59d1c8044b1911a08953e189
refs/heads/master
<repo_name>louissobel/github-repo-recommender<file_sep>/algo.py """ the repo reccommender """ import requests import repowalker from repowalker import Repo MAX_API_CALLS = 50 def get_user(username): USERS_URL = "https://api.github.com/users/%s" r = requests.get(USERS_URL % username) api_calls = 1 return r.json, 1 def get_repos(username): REPOS_URL = "https://api.github.com/users/%s/repos" r = requests.get(REPOS_URL % username) api_calls = 1 return [Repo.from_json(repo_object) for repo_object in r.json], api_calls def get_language_distribution(username): """ returns a distribtution of users language """ users_repos, api_calls = get_repos(username) language_count = {} for repo in users_repos: language_count[repo.language] = language_count.get(repo.language, 0) + 1 return language_count, api_calls def get_repo_key_function(user_object): """ besides language, each possible repo has 2 features right now:s - watcher count (a sign of popularity) - forker count (roughly) other features that I would like to work in are: - age - activity (last commit? commit frequency?) - number of contributors? - size (in terms of code) anyway, what this function does is: given a user_object, returns weighted sort function. what im trying to capture is that the way that i sort repos is going to be different for a given user. a user that forks a lot will prefer a repo with high forks a user that hasn't contributed to a project will prefer something with a lot of contributors a vertern github user maybe wants a new repo (or the opposite, or vice versa) but right now, its not going to use the userobject, instead returning a function that returns 10 * forkers + 3 * watchers. (arbitrarily) """ def key_function(repo): return repo.forks * 10 + repo.watchers * 3 return key_function def repo_reccommender_by_language(username): """ returns repos sorted by a function specific to the user """ # get a BFS of 100 repos or all of their second-degree repos (rate-limiting ourselves along the way) # we have to get their language # ideally i would get all of their repos, then get the full byte distribution of all the repos, # but unfortunately that's a lot of calls. # better to just get a list of their repos (1 call) # and then make a whole number distribution. print "Geting user..." user_object, api_calls = get_user(username) # users_language_distribution, api_calls = get_language_distribution(username) # the bfs... using list() to turn it from un-sortable set to a list print "Getting nearby repos for user..." close_repos_set, api_calls = repowalker.do_bfs_from_username(username, 100, MAX_API_CALLS) close_repos = list(close_repos_set) # we need to sort them somehow repo_key_function = get_repo_key_function(user_object) # ok, now we sort them! possibly slow print "Sorting repos" sorted_repos = sorted(close_repos, key=repo_key_function, reverse=True) # lets go through and separate them by language language_sorted_repos_hash = {} for repo in sorted_repos: language_sorted_repos_hash.setdefault(repo.language, []).append(repo) # ok lets return that return language_sorted_repos_hash def repo_reccommender(): """ gets a user as input from the user gets the users top languages gets the reccomended repos by language outputs information to the user """ username = raw_input('Enter a username > ') language_sorted_repos = repo_reccommender_by_language(username) print "getting language distribution..." language_distribution, api_calls = get_language_distribution(username) top_languages = sorted(language_distribution.keys(), key=lambda l : language_distribution[l], reverse=True)[:3] print "Your top languages, with top up to 5 repo reccommendations are:" for i, l in enumerate(top_languages): print "%d : %s" % (i, l) for repo in language_sorted_repos[l][:5]: print "\t%s" % str(repo) if __name__ == "__main__": repo_reccommender() <file_sep>/repowalker.py """ MOdule for finding a bunch of github repo names through a random walk """ import random import requests # datastructure for a repo is ('user', 'reposlug') pair BASE_REPO = ('django', 'django') FALLBACK_REPO = BASE_REPO BASE_USER = 'louissobel' # so we get the watchers of a repo. # then we pick one of them randomly, and get the list of repos that they watch # we hold on to some amount of users (lets cap it at say, N), ????? maybe # so that if we ever come to a dead end we can backtrack. # i gotta watch my rate limit class Repo: @classmethod def from_json(cls, repo_object): return cls( repo_object['owner']['login'], repo_object['name'], repo_object['watchers'], repo_object['forks'], repo_object['language'], ) def __init__(self, user, name, watchers, forks, language): self.user = user self.name = name self.watchers = watchers self.forks = forks self.language = language def __str__(self): return "%s/%s" % (self.user, self.name) def __repr__(self): return "<%s w:%d f:%d l:%s>" % (str(self), self.watchers, self.forks, self.language) def __hash__(self): return str(self).__hash__() def __eq__(self, other): return str(self) == str(other) def apicalltrack(howmany): def decorator(function): function.api_calls = howmany return function return decorator @apicalltrack(1) def get_stargazers(repo): """ returns a list of usernames that starred the repo with (user, reposlug) given """ STARGAZERS_URL = "https://api.github.com/repos/%s/stargazers" r = requests.get(STARGAZERS_URL % str(repo)) api_calls = 1 return [user_object['login'] for user_object in r.json], api_calls def get_starred_repos(username): """ returns a list of repos that the given username has starred """ STARGAZING_URL = "https://api.github.com/users/%s/starred" r = requests.get(STARGAZING_URL % username) api_calls = 1 return [Repo.from_json(repo_object) for repo_object in r.json], api_calls def get_neighbors(repo): """ gets the set of repos that are connected to a repo by a follower in common """ neighbor_set = set() api_call_count = 0 stargazers, api_calls = get_stargazers(repo) #due to pagination, this will never be too high api_call_count += api_calls print "stargazers for %s: %s" % (str(repo), str(stargazers)) for stargazer in stargazers: print "getting %s wathced repos" % stargazer stargazers_watched_repos, api_calls = get_starred_repos(stargazer) api_call_count += api_calls for repo in stargazers_watched_repos: neighbor_set.add(repo) return neighbor_set, api_call_count def do_random_walk_from_repo(repo, target_repo_count, max_api_calls, repo_set=None): """ will attempt to get target_repo_count repos by walking around githubs graph. will short-circuit if more than max_api_calls take place """ if repo_set is None: repo_set = set() current_repo = repo api_call_count = 0 while len(repo_set) < target_repo_count and api_call_count < max_api_calls: #print "Getting stargazers for %s" % str(current_repo) repo_stargazers, api_calls = get_stargazers(current_repo) # pick random stargazer random.shuffle(repo_stargazers) found_repo = None while not found_repo and repo_stargazers: chosen_one = repo_stargazers.pop() # get their starred repos #print "Getting starred repos for %s" % chosen_one his_starred_repos, api_calls = get_starred_repos(chosen_one) # now we have to randomally go through his_starred_repos random.shuffle(his_starred_repos) next_repo = his_starred_repos.pop() # we know it is at least one, so this is safe next_is_new = next_repo not in repo_set while not next_is_new and his_starred_repos: next_repo = his_starred_repos.pop() next_is_new = next_repo not in repo_set if next_is_new: found_repo = next_repo if found_repo: repo_set.add(found_repo) current_repo = found_repo else: print "Dead end, found %d repos using %d api_calls" % (len(repo_set), api_call_count) return repo_set, api_call_count print "Found %d repos using %d api calls." % (len(repo_set), api_call_count) return repo_set, api_call_count def do_bfs_from_username(username, target_repo_count, max_api_calls): """ will get repos that are 1, 2 degrees connected to this user """ api_call_count = 0 users_starred_repos, api_calls = get_starred_repos(username) api_call_count += api_calls print users_starred_repos # we have to filter out the ones that are the users users_starred_repos = [repo for repo in users_starred_repos if not repo.user==username] #I want to do bfs through it repo_set = set() frontier = users_starred_repos print "initial frontier: %s" % str(frontier) # we want to make sure we go through all of the initial frontier? # yes, but still bounded by our api_call constraint initial_frontier_length = len(frontier) iteration_count = 0 while (len(repo_set) < target_repo_count or iteration_count < initial_frontier_length) and api_call_count < max_api_calls: iteration_count += 1 if frontier: check_repo = frontier.pop(0) print "getting neighbors for %s" % str(check_repo) check_repo_neighbors, api_calls = get_neighbors(check_repo) api_call_count += api_calls for repo in check_repo_neighbors: if repo.user != username: # we don't want to go back to ourselves if repo not in repo_set: repo_set.add(repo) frontier.append(repo) # put in on the back for BFS else: # we've run out of places to check, but we still need some want more repos # and have more API calls to spend! so lets do random walk from django repo_set, api_calls = do_random_walk_from_repo( FALLBACK_REPO, target_repo_count - len(repo_set), max_api_calls - api_call_count, repo_set ) api_call_count += api_calls # ok,,, so we've done as much as we can return repo_set, api_call_count if __name__ == "__main__": repos, api_calls = do_bfs_from_username(BASE_USER, 10, 100) print "using bfs from %s found %d repos using %d api calls" % (BASE_USER, len(repos), api_calls) for repo in repos: print repr(repo)
4e38a08c939e1aa6d78362192fa4d034d4a8007b
[ "Python" ]
2
Python
louissobel/github-repo-recommender
ecdc8176ef2d59943544f519f27f95d4ba17c6bb
264c0afd4f6c3db07de9e2ed1b59b7d7fa8613e5
refs/heads/master
<repo_name>mrmoment/heyegg<file_sep>/action/userquit.php <?php include_once("lib/head.php"); session_start(); unset($_SESSION['email']); unset($_SESSION['nickname']); session_destroy(); print "<code>success</code>"; ?> <file_sep>/codelist.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>黑蛋 | 新用户注册邀请码</title> <link href="res/style.css" rel="stylesheet" type="text/css" /> <style> .codeline{ padding:6px 0; font-size:1.1em; font-weight:bold; margin:auto 10px; } .codeline:hover{ background: #fff; } #view h4{ margin:5px; } </style> </head> <body> <div id="topbar"> <div id="btm_border"></div> <div id="logo" onclick="window.open('index.php');"></div> </div> <div id="main"> <div id="view" style="background:#eaeaea; font-size:14px;"> <div style="font-family:'Microsoft YaHei'; background:rgba(255,255,255,0.8); padding:10px; margin:10px;"> <h4>为什么要邀请码</h4>黑蛋"&nbsp;目前处于测试阶段,用户注册需要通过邀请码进行。<br /> <h4>如何获取邀请码</h4><li>每天我们会定时更新一批邀请码(见下方)。</li><li>活跃用户还将不定期得到发送邀请码的机会,可以分享给您的好友。</li> <h4>需要注意什么</h4><li>每天定期更新的邀请码数量有限,如果列表为空请您稍后再试。</li><li>对于已注册用户发送给您的邀请码,请注意保管,不要随意透露给他人。</li><li>当然,您应当及时使用该邀请码进行注册。</li> </div> <div style="font-family:'Courier New', Courier, monospace; min-height:400px;" align="center" id="codelist"> <div onclick="document.location=document.location;" style="cursor:pointer; background:#00CCFF; border:1px solid #333; width:60px;">刷新</div> <?php sleep(1); include_once("action/lib/head.php"); $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); $sql="select * from reginvite where used=0 limit 30"; $query=mysql_query($sql); while($myrow=mysql_fetch_array($query)){ $code=$myrow['code']; print "<div class='codeline'>".$code."</div>"; } ?> </div> <script language="javascript"> if(document.getElementById('codelist').childNodes.length<4){ var d=document.createElement('div'); d.className="codeline"; d.innerHTML="暂无更多邀请码"; document.getElementById('codelist').appendChild(d); } </script> </div> </div> </body> </html> <file_sep>/action/lib/head.php <?php $URL_PREFIX="../p"; $URL_SUFFIX=".html"; $CMT_SUFFIX=".xml"; $LIST_SIZE=15;//how many lists per page $mysqlpw=""; $ADMIN_PASSWD="<PASSWORD>"; function seg($tag, $val){ return "<".$tag.">".$val."</".$tag.">"; } function mkdirs($dir) { if(!is_dir($dir)){ if(!mkdirs(dirname($dir))){ return false; } if(!mkdir($dir,0777)){ return false; } } return true; } function randomkeys($length) { $pattern='<KEY>'; for($i=0;$i<$length;$i++) { $key .= $pattern{mt_rand(0,35)}; } return $key; } /* @param string $string 原文或者密文 * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE * @param string $key 密钥 * @param int $expiry 密文有效期, 加密时候有效, 单位 秒,0 为永久有效 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文 * 可以在指定时间内加密还原字符串,超时无法还原 可做单点登录的token加密传输,临时密码等 * @example * * $a = authcode('abc', 'ENCODE', 'key'); * $b = authcode($a, 'DECODE', 'key'); // $b(abc) * * $a = authcode('abc', 'ENCODE', 'key', 3600); * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内,$b(abc),否则 $b 为空 */ function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) { $ckey_length = 4; // 随机密钥长度 取值 0-32; // 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。 // 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方 // 当此值为 0 时,则不产生随机密钥 $key = md5($key ? $key : 'default_key'); //这里可以填写默认key值 $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } if($operation == 'DECODE') { if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyc.str_replace('=', '', base64_encode($result)); } } /* * Add score for a user */ function addScore($email,$incre){ $sql="select * from userscores where user_email=\"$email\" limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $score=$myrow['score']; $sql="update userscores set score=($score+$incre) where user_email='$email'";//each post makes 5 scores $query=mysql_query($sql); } } ?> <file_sep>/action/adduser.php <?php if( !isset($_POST['p']) || !isset($_POST['m']) || !isset($_POST['n']) || !isset($_POST['c']) ){ return; } include_once("lib/head.php"); $email=$_POST['m']; $nick=$_POST['n']; $passwd=$_POST['p'];//encrypted $code=$_POST['c']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error()); mysql_select_db('eggsys',$conn); //check invite code first $sql="select * from reginvite where code='$code' and used=0 limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $sql="select * from uauth where email='$email' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)) { print "<code>existing_email</code>"; return; }else{ $sql="select * from uauth where nickname='$nick' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ print "<code>existing_nick</code>"; return; }else{ //forbid sensitive nicknames $postFile=$dir."/".$timestr.$URL_SUFFIX; $kwFile="../cfg/nickkeywords.txt"; if(file_exists($kwFile)){ $handler= fopen($kwFile, "r"); $fileContent=fread($handler,fileSize($kwFile)); $words=explode(",",$fileContent); for($i=0; $i<count($words); $i++){ if(strpos($nick,$words[$i])!==false){ print "<code>bad_nick</code>"; return; } } } date_default_timezone_set("PRC"); $createtime=date("YmdHis"); $sql="insert into uauth (email, nickname, passwd, create_time) values ('$email','$nick','$passwd','$createtime')"; $query=mysql_query($sql); $sql="update reginvite set used=1 where code='$code'"; $query=mysql_query($sql); } } }else{ print "<code>invite_code_error</code>"; return; } $sql="insert into userscores (user_email, score, items) values ('$email',200,',0001,')"; $query=mysql_query($sql); print "<code>register_ok</code>"; ?><file_sep>/action/loadnearbypost.php <?php include_once("lib/head.php"); ////TODO: update post view stat if(!isset($_GET['id']) || !isset($_GET['tp']) || !isset($_GET['m']) || !isset($_GET['o']) ){ return; } $id=$_GET['id']; $type=$_GET['tp']; $mode=$_GET['m']; $orient=$_GET['o']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); if($orient<0){ $sql="select * from posts where id<$id and type='$type' and public='$mode' order by id desc limit 1"; }else{ $sql="select * from posts where id>$id and type='$type' and public='$mode' order by id limit 1"; } $query=mysql_query($sql); ////TODO: this is same segment to loadpost.php, change it to function if($myrow=mysql_fetch_array($query)){ print $myrow['id'].'<>'.$myrow['title']."<>".$myrow['create_time']."<>"; $dir=$URL_PREFIX."/".$myrow['author_email']; $timestr=str_replace(":","",$myrow['create_time']); $timestr=str_replace("-","",$timestr); $timestr=str_replace(" ","",$timestr); $postFile=$dir."/".$timestr.$URL_SUFFIX; if(file_exists($postFile)){ $handler= fopen($postFile, "r"); $fileContent=fread($handler,fileSize($postFile)); }else{ $fileContent="原文已丢失";///TODO: add a link for user to report this } print $fileContent."<>"; $email=$myrow['author_email']; }else{ print "<code>no_post</code>"; return; } //get current user nickname $sql="select * from uauth where email='$email'"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ print $myrow['nickname']; }else{ print "未知"; } ?><file_sep>/index.php <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>黑蛋 | 品质新闻阅读</title> <link rel="stylesheet" type="text/css" href="jsMessage/codebase/themes/message_growl_dark.css"> <link href="res/style.css" rel="stylesheet" type="text/css" /> <link href="res/effect.css" rel="stylesheet" type="text/css" /> <script language="javascript" src="res/jquery-1.6.2.min.js"></script> <script language="javascript" src="res/extool.js?v=0.1"></script> <script language="javascript" src="res/md5-min.js"></script> <script language="javascript" src="res/hey.js"></script> <script type="text/javascript" src='jsMessage/codebase/message.js'></script> <script language="javascript"> $(document).ready(function(){ scrHgt=screen.availHeight; $('#post_text').css('min-height',(scrHgt-370)+"px"); $('#comment_view').css('min-height',(scrHgt-216)+"px"); setToolTop(); initUser(); var pid="<?php if( isset($_GET['pid']) ){ print $_GET['pid']; }else{ print ""; } ?>"; if(pid==""){ quickEgg(); }else{ loadEggById(pid); } }); function initUser(){ tmpemail="<?php if(isset($_SESSION['email'])) { print $_SESSION['email']; }else{ print ""; } ?>"; tmpnickname="<?php if(isset($_SESSION['nickname'])) { print $_SESSION['nickname']; }else{ print ""; } ?>"; if(tmpemail==""){ tmpemail=getCookie("email"); if(tmpemail!=null){ tmppassword=getCookie("password"); $.post("./action/verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);}); //todo: show a loading circle nearby "login" span } }else{ email=tmpemail; nickname=tmpnickname; showTopbar(nickname); } } </script> </head> <body> <div id="topbar"> <div id="btm_border"></div> <div id="left_panel"></div> <div id="right_panel"> <div id="anony"><span onclick="login()">登录</span><span onclick="window.open('register.html');">注册</span></div> <div id="identity" style="display:none"><span>欢迎,&nbsp;<a id="nickname"></a>!</span><span onclick="logout()">退出</span></div> </div> <div id="logo"></div> </div> <div id="main"> <div id="view"> <div id="post_view" onmouseup="doSelect()"> <div id="post_title">加载中...</div> <div id="post_avatar"><!--img src="img/default_avatar_64.gif" width="32" height="32"/--></div> <div id="post_author">作者:&nbsp;<a id="post_author_name" target="_blank">加载中...</a></div> <div id="post_time">时间:&nbsp;加载中...</div> <div id="post_text">正在载入...</div> </div> <div id="comment_view"> <div id="new_cmt"> <h3 id="comment_to"></h3> <textarea id="cmt_content" wrap="soft"></textarea> <button id="submit" onclick="doComment()" style="top:10px;margin-bottom:20px;">发表</button> </div> <div id="cmt_list"> </div> </div> </div> <div id="footer"> <div style="width:330px; margin:auto; font-size:12px; font-family:sans-serif">All rights reserved&copy;2012&nbsp;黑蛋网&nbsp;京ICP备11034032号</div> </div> </div> <div id="tool"> <div id="tool_main"> <div id="left_tool" class="toolpanel"> <div class="leftbtn"> <div class="ltoolname" onclick="browseType(0);"> <div style="float:left">科技</div> <div class="type_icon"></div> </div> </div> <div class="leftbtn"> <div class="ltoolname" onclick="browseType(1);"> <div style="float:left">社会</div> <div class="type_icon"></div> </div> </div> <div class="leftbtn"> <div class="ltoolname" onclick="browseType(2);"> <div style="float:left">奇趣</div> <div class="type_icon"></div> </div> </div> <div class="leftbtn"> <div class="ltoolname" onclick="browseType(3);"> <div style="float:left">娱乐</div> <div class="type_icon"></div> </div> </div> </div><!--eof left_tool--> <div id="right_tool" class="toolpanel"> <div id="tl_list" class="rightbtn tran-9" onclick="openList()"> <div class="rtoolname"> <div style="float:left">列表</div> <div class="tl_icon" style="float:right"></div> </div> </div> <div id="tl_review" class="rightbtn tran-9" onclick="window.open('review.php')"> <div class="rtoolname"> <div style="float:left">审稿</div> <div class="tl_icon" style="float:right"></div> </div> </div> <div id="tl_submit" class="rightbtn tran-9" onclick="window.open('ueditor/_examples/post.php');" style="margin-bottom:10px;"> <div class="rtoolname"> <div style="float:left">投递</div> <div class="tl_icon" style="float:right"></div> </div> </div> <div id="tl_cmt" class="rightbtn tran-9" onclick="triggerComment()"> <div class="rtoolname"> <div id="cmt_btn" style="float:left">评论</div> <div id="cmt_icon" style="float:right"></div> </div> </div> <div id="tl_score" class="rightbtn tran-9"> <div class="rtoolname"> <div style="float:left">打分</div> <div id="rate_box" style="float:right"> <div class="star active" onmousemove="lightStars(1)" onmouseover="lightStars(1)" onclick="votePost(1)"></div> <div class="star active" onmousemove="lightStars(2)" onmouseover="lightStars(2)" onclick="votePost(2)"></div> <div class="star active" onmousemove="lightStars(3)" onmouseover="lightStars(3)" onclick="votePost(3)"></div> <div class="star" onmousemove="lightStars(4)" onmouseover="lightStars(4)" onclick="votePost(4)"></div> <div class="star" onmousemove="lightStars(5)" onmouseover="lightStars(5)" onclick="votePost(5)"></div> </div> </div> </div> <div id="tl_fav" class="rightbtn tran-9" onclick="checkFav()"> <div class="rtoolname"> <div style="float:left">收藏</div> <div style="float:right"> <div id="check_fav" class="unchecked" style="float:right"></div> </div> </div> </div> </div><!--eof right_tool--> <div id="page_tool"> <div class="pager" id="prev_post" onclick="nearbyEgg(-1)" title="较早的文章"></div> <div class="pager" id="next_post" onclick="nearbyEgg(1)" title="较新的文章"></div> </div> </div> </div> <div id="list"> <div id="close_list" onclick="closeList()"><div></div></div> <div id="list_rows"> </div> <div id="list_pager"> <div id="prev_list" onclick="prevList();"></div> <div id="list_now" align="center">1&nbsp;/&nbsp;14&nbsp;页</div> <div id="list_goto"><input id="jumpNum" /><a onclick="gotoList()">跳至</a></div> <div id="next_list" onclick="nextList();"></div> </div> </div> <div id="login_wrapper" style="display:none"> <div id="login"> <div id="close_login" onclick="$('#login_wrapper').hide();"></div> <input type="text" value="Email" id="email" onfocus="this.className='selected';this.style.border='none';if(this.value=='Email') this.value='';" onblur="this.className='';if(this.value.trim()=='') this.value='Email';" /> <input type="text" value="密码" id="password" onfocus="this.className='selected'; this.type='password';if(this.value=='密码') this.value='';" onblur="this.className='';if(this.value=='') {this.value='密码';this.type='text';};"/> <button id="submit" onclick="doLogin()" style="top:80px;left:-37px;float:right;">登录</button> </div> </div> </body> </html> <file_sep>/user.php <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="jsMessage/codebase/themes/message_growl_dark.css"> <link href="res/style.css" rel="stylesheet" type="text/css" /> <script language="javascript" src="res/jquery-1.6.2.min.js"></script> <script language="javascript" src="res/extool.js?v=0.1"></script> <script language="javascript" src="res/md5-min.js"></script> <script language="javascript" src="res/hey.js"></script> <script type="text/javascript" src='jsMessage/codebase/message.js'></script> <title>黑蛋 | 查看用户</title> <script language="javascript"> $(document).ready(function(){ scrHgt=screen.availHeight; $('#user_view').css('min-height',(scrHgt-216)+"px"); initUser(); loadUserInfo(); }); function initUser(){ tmpemail="<?php if(isset($_SESSION['email'])) { print $_SESSION['email']; }else{ print ""; } ?>"; tmpnickname="<?php if(isset($_SESSION['nickname'])) { print $_SESSION['nickname']; }else{ print ""; } ?>"; if(tmpemail==""){ tmpemail=getCookie("email"); if(tmpemail!=null){ tmppassword=getCookie("password"); $.post("./action/verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);}); //todo: show a loading circle nearby "login" span } }else{ email=tmpemail; nickname=tmpnickname; showTopbar(nickname); } } function loadUserInfo(){ var tmpid="<?php if(isset($_GET['uid'])) { print $_GET['uid']; }else{ print ""; } ?>"; if(tmpid==""){ dhtmlx.alert({ text:"错误的调用,将跳转到主页", callback: function(){ document.location="index.php"; } }); }else{ $.get(phpDir+"loaduserinfo.php",{uid: tmpid}, function(resp){handleUserInfo(resp)}); } } function handleUserInfo(resp){ var code=getRespCode(resp); if(code=="user_id_error"){ dhtmlx.alert({ text:"被查询的用户信息错误,将跳转到主页", callback: function(){ document.location="index.php"; } }); return; }else if(code=="user_info_ok"){ var data=getRespData(resp); var userinfo=my_substr(data, "user"); var nick=my_substr(userinfo, "nick"); var score=my_substr(userinfo, "score"); var group=my_substr(userinfo, "group"); $('#nick').html(nick); $('#point').html(score); $('#group').html(group); var posts=my_substr(data, "post"); var pcs=posts.split("<|>"); var list=document.getElementById('user_post_list'); if(pcs.length==1){ list.childNodes[0].innerHTML="暂无投递"; }else{ list.innerHTML=""; for(i=0; i<pcs.length-1; i++){ var post=pcs[i]; var items=post.split("<>"); var public=items[3]; var a=document.createElement('a'); if(public==0){ a.innerHTML=unescape(decodeURI(items[1]))+"<a class='inreview'>(审核中)</a>"; a.href="review.php?pid="+items[0]; }else if(public==-1){ a.innerHTML=unescape(decodeURI(items[1]))+"<a class='reject'>(未通过)</a>"; }else{ a.innerHTML=unescape(decodeURI(items[1])); a.href="index.php?pid="+items[0]; } a.title=items[2]; a.target="_blank"; a.className="list_item"; list.appendChild(a); } } var favs=my_substr(data, "fav"); pcs2=favs.split("<|>"); var list2=document.getElementById('user_fav_list'); if(pcs2.length==1){ list2.childNodes[0].innerHTML="暂无收藏"; }else{ list2.innerHTML=""; for(j=0; j<pcs2.length-1; j++){ var fav=pcs2[j]; var items2=fav.split("<>"); var a2=document.createElement('a'); a2.innerHTML=unescape(decodeURI(items2[1])); a2.href="index.php?pid="+items2[0]; a2.title=items2[2]; a2.target="_blank"; a2.className="list_item"; list2.appendChild(a2); } } }else{ dhtmlx.alert("抱歉,出现未知错误!"); } } </script> <style> #user_view{ margin-top:40px; border:0px dashed #ccc; padding:0 60px; font-size:14px; } #user_view i{ color:#999; } #avatar{ width:64px; height:64px; float:left; background:#fff url(img/default_avatar_64.gif) no-repeat; border-radius:4px; box-shadow:0 0 4px #ccc; } #name{ width:440px; height:64px; float:right; } #info{ margin-top:20px; margin-bottom:10px; border-top: 6px solid #39c; } .record{ width:240px; border:1px solid #eee; min-height:400px; background:#fbfbfb; padding:5px; word-break:break-all; } #post_rec{ float:left; } #fav_rec{ float:right; } .record span:first-child{ display:block; font-weight:bold; margin-bottom:8px; } .list_item{ display:block; margin:5px 0; cursor:pointer; } .list_item:hover{ background:#fdfdfd; } #main a, #main a:visited, #main a:active{ text-decoration:underlined; color:#000; } a.inreview{ color:green !important; font-style:italic; } a.reject{ color:blue !important; font-style:italic; } </style> </head> <body> <div id="topbar"> <div id="btm_border"></div> <div id="left_panel"></div> <div id="right_panel"> <div id="anony"><span onclick="login()">登录</span><span onclick="window.open('register.html');">注册</span></div> <div id="identity" style="display:none"><span>欢迎,&nbsp;<a id="nickname"></a>!</span><span onclick="logout()">退出</span></div> </div> <div id="logo" onclick="window.open('index.php')"></div> </div> <div id="main"> <div id="view"> <div id="user_view"> <div id="avatar"> </div> <div id="name"> <div id="nick" style="margin-bottom:10px; font-size:18px; font-weight:bold;"><i>用户页面正在载入...</i></div> <div>身份:&nbsp;<a id="group"><i>加载中...</i></a></div> <div> <span>积分:&nbsp;<a id="point"><i>加载中...</i></a></span>&nbsp;<!--span>邮箱:&nbsp;<a id="mail"><i>加载中...</i></a></span--> </div> </div> <br style="clear:both" /> <div id="info"> </div> <div id="post_rec" class="record"> <span>投稿列表</span> <div id="user_post_list"><i>加载中...</i></div> </div> <div id="fav_rec" class="record"> <span>收藏列表</span> <div id="user_fav_list"><i>加载中...</i></div> </div> </div> </div> </div> <div id="login_wrapper" style="display:none"> <div id="login"> <div id="close_login" onClick="$('#login_wrapper').hide();"></div> <input type="text" value="Email" id="email" onFocus="this.className='selected';this.style.border='none';if(this.value=='Email') this.value='';" onBlur="this.className='';if(this.value.trim()=='') this.value='Email';" /> <input type="text" value="密码" id="password" onFocus="this.className='selected'; this.type='password';if(this.value=='密码') this.value='';" onBlur="this.className='';if(this.value=='') {this.value='密码';this.type='text';};"/> <button id="submit" onclick="doLogin()" style="top:80px;left:-37px;float:right;">登录</button> </div> </div> </body> </html> <file_sep>/action/loadcomment.php <?php if( !isset($_GET['id']) ){ return; } $COMMENTS_READ_AT_ONCE=10; $id=$_GET['id']; if( isset($_GET['all']) ){ $readall=$_GET['all']; } include_once("lib/head.php"); $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); $sql="select * from posts where id=$id limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $dir=$URL_PREFIX."/".$myrow['author_email']; $timestr=str_replace(":","",$myrow['create_time']); $timestr=str_replace("-","",$timestr); $timestr=str_replace(" ","",$timestr); $cmtDir=$dir."/".$timestr."-cmt"; if(!file_exists($cmtDir)){ print "<code>no_comment</code>"; return; } $files=glob($cmtDir."/*".$CMT_SUFFIX); if(isset($readall) && $readall=1){ $count=count($files); }else{ $count=min(count($files),$COMMENTS_READ_AT_ONCE); } print $count; if($count!=0){ print "<data>"; } for($idx=count($files)-1; $idx>=(count($files)-$count); $idx--){ $handle=fopen($files[$idx],"r"); $cmt=fread($handle, fileSize($files[$idx])); $start=strpos($cmt,"<u>")+3; $end=strpos($cmt,"</u>"); $email=substr($cmt,$start,($end-$start)); $tmpsql="select * from uauth where email='$email' limit 1"; $tmpquery=mysql_query($tmpsql); if($tmprow=mysql_fetch_array($tmpquery)){ $nick=$tmprow['nickname']; }else{ $nick="未知用户"; } $cmt=str_replace($email,$nick,$cmt); print $cmt."<>"; } if($count!=0){ print "</data>"; } }else{ print "<code>no_such_post</code>"; return; } print "<code>load_comment_ok</code>"; ///TODO: load comment num for users to reference ?><file_sep>/action/addpost.php <?php session_start(); if( !isset($_SESSION['email']) || !isset($_POST['tp']) || !isset($_POST['tl']) || !isset($_POST['ct']) ){ return; } include_once('lib/head.php'); $email=$_SESSION['email']; $type=$_POST['tp']; $title=$_POST['tl']; $content=$_POST['ct']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); date_default_timezone_set("PRC"); $createtime=date("YmdHis"); $title=urlencode($title); $sql="insert into posts (type, title, author_email, create_time) values ('$type', '$title', '$email', '$createtime')"; $query=mysql_query($sql) or die ("<code>insert_error</code>".mysql_error()); $dir=$URL_PREFIX."/".$email; $postFile=$dir."/".$createtime.$URL_SUFFIX; mkdirs($dir); $handle=fopen($postFile,"w"); fwrite($handle, $content); /////TODO: write a single html file (for seo?) fclose($handle); $cmtDir=$dir."/".$createtime."-cmt"; mkdirs($cmtDir); /*$commentFile=$cmtDir."/".$createtime."-cmt".$CMT_SUFFIX; $handle=fopen($commentFile,"w"); fclose($handle);*/ addScore($email, 5); print "<code>post_ok</code>"; ?><file_sep>/action/votepost.php <?php session_start(); if( !isset($_GET['id']) || !isset($_GET['s']) || !isset($_SESSION['email']) ){ return; } include_once("lib/head.php"); $MIN_VOTE_USERS=5; $MIN_VOTE_SCORE=3; $MIN_REJECT_SCORE=2; $id=$_GET['id']; $score=$_GET['s']; $email=$_SESSION['email']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); $sql="select count(*) from postvote where post_id=$id limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){//TODO: this count process can be rewritten, see loadpostbyid.php; also change favpost.php if($myrow[0]==0){ //add a new record $sql="insert into postvote (post_id, voted, score, vote_users) values ($id, 1, $score, ',$email,')"; $query=mysql_query($sql); print '<code>vote_ok</code>'; }else{ $sql="select * from postvote where post_id=$id limit 1"; $query=mysql_query($sql); $myrow=mysql_fetch_array($query); $users=$myrow['vote_users']; if(strpos($users,','.$email.',')!==false){ print "<code>already_voted</code>"; return; }else{ $curScore=$myrow['score']; $curPeople=$myrow['voted']; $newScore=($curScore*$curPeople+$score)/($curPeople+1); $newUsers=$users.$email.','; $sql="update postvote set voted=($curPeople+1), score=$newScore, vote_users='$newUsers' where post_id=$id"; $query=mysql_query($sql); print '<code>vote_ok</code>'; } //check if publicize this post if( ($curPeople+1)>=$MIN_VOTE_USERS && $newScore>=$MIN_VOTE_SCORE ){ $sql="update posts set public=1 where id=$id"; $query=mysql_query($sql); }else if( ($curPeople+1)>=$MIN_VOTE_USERS && $newScore<=$MIN_REFJECT_SCORE ){//check if reject this post $sql="update posts set public=-1 where id=$id"; $query=mysql_query($sql); } } //check if publicize this post by admin if( isset($_SESSION['admin']) && $_SESSION['admin']==true ){ if( $score>=$MIN_VOTE_SCORE ){ $sql="update posts set public=1 where id=$id"; $query=mysql_query($sql); }else if($score<=$MIN_REJECT_SCORE){ $sql="update posts set public=-1 where id=$id"; $query=mysql_query($sql); } } } ?> <file_sep>/action/loadpost.php <?php session_start(); include_once("lib/head.php"); ////TODO: update post view stat if( !isset($_GET['id']) || !isset($_GET['tp']) || !isset($_GET['m']) ){ return; } $idx=$_GET['id']; $type=$_GET['tp']; $mode=$_GET['m']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); $pid=0; $sql="select * from posts where type='$type' and public='$mode' order by id desc limit $idx, 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $pid=$myrow['id']; print $pid.'<>'.$myrow['title']."<>".$myrow['create_time']."<>"; $dir=$URL_PREFIX."/".$myrow['author_email']; $timestr=str_replace(":","",$myrow['create_time']); $timestr=str_replace("-","",$timestr); $timestr=str_replace(" ","",$timestr); $postFile=$dir."/".$timestr.$URL_SUFFIX; if(file_exists($postFile)){ $handler= fopen($postFile, "r"); $fileContent=fread($handler,fileSize($postFile)); }else{ $fileContent="原文已丢失";///TODO: add a link for user to report this } print $fileContent."<>"; $email=$myrow['author_email']; }else{ print "<code>no_post</code>"; return; } //get current user nickname $sql="select * from uauth where email='$email'"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ print $myrow['nickname']."<>".$myrow['id']; } //get fav status if($mode==1){//1:view mode if( isset($_SESSION['email']) ){ $myemail=$_SESSION['email']; $sql="select * from userlike where user_email='$myemail' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $likes=$myrow['liked_posts']; if(strpos($likes,",".$pid.",")!==false){ print "<>1"; }else{ print "<>0"; } } }else{ print "<>0"; } }else{ print "<>0"; } ?><file_sep>/action/loadlist.php <?php include_once("lib/head.php"); if(!isset($_GET['n']) || !isset($_GET['tp']) || !isset($_GET['m']) ){ return; } $idx=$_GET['n']; $type=$_GET['tp']; $mode=$_GET['m']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); $offset=$idx*$LIST_SIZE; $sql="select * from posts where type='$type' and public=$mode order by id desc limit $offset, $LIST_SIZE"; $query=mysql_query($sql); while($myrow=mysql_fetch_array($query)){ $id=$myrow['id']; $title=$myrow['title']; $time=$myrow['create_time']; //print_r($myrow); $author=$myrow['author_email']; print $id."<>".$title."<>".$time."<>".$author; print "<|>"; } $sql="select count(*) from posts where type='$type' and public=$mode"; $query=mysql_query($sql); $myrow=mysql_fetch_array($query); print $myrow[0];//total posts in this type ?><file_sep>/action/verifyuser.php <?php session_start(); include_once("lib/head.php"); if( !isset($_POST['p']) || !isset($_POST['u']) ){ return; } $email=$_POST['u']; $enpasswd=$_POST['p'];//encrypted $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error()); mysql_select_db('eggsys',$conn); $sql="select * from uauth where email='$email' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)) { if(strcasecmp($myrow['passwd'], $enpasswd)==0){ print '<code>verify_ok</code><data>'.$myrow['nickname'].'</data>'; $_SESSION['email']=$email; $_SESSION['nickname']=$myrow['nickname']; if($myrow['group']==0){//0 admin; 1 user $_SESSION['admin']=true; } return; } } print '<code>verify_error</code>'; ?><file_sep>/action/postcomment.php <?php session_start(); if( !isset($_POST['id']) || !isset($_POST['c']) || !isset($_SESSION['email']) ){ return; } include_once("lib/head.php"); $id=$_POST['id']; $comment=$_POST['c']; $email=$_SESSION['email']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); $sql="select * from posts where id=$id limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $dir=$URL_PREFIX."/".$myrow['author_email']; $timestr=str_replace(":","",$myrow['create_time']); $timestr=str_replace("-","",$timestr); $timestr=str_replace(" ","",$timestr); $cmtDir=$dir."/".$timestr."-cmt"; if(!file_exists($cmtDir)){//comment dir is deleted (in development case) mkdirs($cmtDir); } $files=glob($cmtDir."/*".$CMT_SUFFIX); //$cmtIdx=count($files)+1; $createtime=date("YmdHis"); $cmtFile=$cmtDir."/".$createtime.$CMT_SUFFIX; $handle=fopen($cmtFile,"w"); date_default_timezone_set("PRC"); $createtime=date("Y-m-d H:i:s"); $content="<u>".$email."</u><t>".$createtime."</t><c>".$comment."</c>"; fwrite($handle, $content); fclose($handle); $newComments=$myrow['comments']+1; $sql="update posts set comments=$newComments where id=$id"; $query=mysql_query($sql); }else{ print "<code>no_such_post</code>"; return; } addScore($email, 2); print "<code>comment_ok</code>"; ?><file_sep>/action/addcodes.php <?php session_start(); include_once("lib/head.php"); if( !isset($_SESSION['admin']) || !isset($_POST['u']) || !isset($_POST['p']) || !isset($_POST['n']) ){ return; } $uname=strtolower($_POST['u']); $passwd=$_POST['p']; if( strcmp($uname,"maxadmin")!=0 || strcmp($passwd,"<PASSWORD>")!=0 ){ sleep(10); return; } print "<p>Start...</p>"; $num=$_POST['n']; $CODE_LEN=12; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("Could not connect: " . mysql_error()); mysql_select_db('eggsys',$conn); for($i=0; $i<$num; $i++){ $code=randomkeys($CODE_LEN); $sql="select * from reginvite where code='$code' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ $i--;//duplicate code doesn't count }else{ print "New Code:&nbsp;"; $nsql="insert into reginvite (code, used) values ('$code', 0)" or die(mysql_error()); $query=mysql_query($nsql); print $code."<br />"; } } odbc_close($conn); print "<p>Done...</p>"; ?> <file_sep>/action/loaduserinfo.php <?php if( !isset($_GET['uid']) ){ return; } include_once("lib/head.php"); $userid=$_GET['uid']; print $userid; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error()); mysql_select_db('eggsys',$conn); $sql="select * from uauth where id='$userid' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ print "<data>"; $email=$myrow['email'];//TODO: now no email info to display $group=$myrow['group']; if($group==0){ $group='管理员'; }else{ $group='用户'; } $nick=$myrow['nickname']; $score=0;//TODO: add score table in db... $sql="select * from userscores where user_email='$email' limit 1"; $query=mysql_query($sql); if($scorerow=mysql_fetch_array($query)){ $score=$scorerow['score']; } print "<user><nick>".$nick."</nick><score>".$score."</score><group>".$group."</group></user>"; $sql="select * from posts where author_email='$email' order by id desc limit 30";//30 posts at most to display at once if( isset($_SESSION['email']) && strncmp($_SESSION['email'], $email)==0 ){ $sql="select * from posts where author_email='$email' order by id desc";//fetch all for himself } $query=mysql_query($sql); print "<post>"; while($newrow=mysql_fetch_array($query)){ $id=$newrow['id']; $title=$newrow['title']; $time=$newrow['create_time']; $public=$newrow['public']; print $id."<>".$title."<>".$time."<>".$public; print "<|>"; } print "</post>"; $sql="select * from userlike where user_email='$email' limit 1"; $query=mysql_query($sql); print "<fav>"; if($newrow=mysql_fetch_array($query)){ $str=$newrow['like_posts']; $pcs=explode(",",$str); for($idx=1; $idx<count($pcs)-1; $idx++){ $id=$pcs[$idx]; $sql="select * from posts where id=$id limit 1"; $query=mysql_query($sql); if($xrow=mysql_fetch_array($query)){ print $id."<>".$xrow['title']."<>".$xrow['create_time']; } print "<|>"; } } print "</fav>"; print "</data>"; }else{ print "<code>user_id_error</code>"; } print "<code>user_info_ok</code>"; ?> <file_sep>/res/hey.js var scrHgt; var nickname, email, password, tmpemail, tmppassword, tmpnickname; var phpDir="./action/"; var postId=0; var commentToId=0;//which post now commenting to var viewMode=1;//1 for view, 0 for review var TYPES=new Array('tech', 'news', 'fun', 'ent'); var heyType=TYPES[0]; var listIdx=0, totalLists=0; var LIST_SIZE=15; var MSG_NO_MORE_POST="<b>没有更多文章...</b><br /><li>过会儿更新试试</li><li>点击\"审稿\"审批新文章</li><li>点击\"投递\"发表一篇</li><button style=\"border:none; font-size:11px; margin-left:120px;\" onclick=\"closeHint('no_more_post')\">关闭建议</button>"; function setToolTop(){ $('#page_tool').css('top',Math.max((scrHgt*0.5-$('#tool')[0].offsetHeight), 240)+"px"); } function lightStars(idx){ var box=document.getElementById('rate_box').children; for(i=0; i<idx; i++){ box[i].className="star active"; } for(i=idx;i<5; i++){ box[i].className="star"; } } function checkFav(){ if(email){ if(postId==0){ dhtmlx.message({type:"error", text:"当前没有可收藏的文章" }); return; } $('#tl_fav')[0].onclick=null; var check=$('#check_fav')[0]; var like; if(check.className=="unchecked"){ check.className="checked"; like=1; }else{ check.className="unchecked"; like=-1; } $.get(phpDir+"favpost.php", { id: postId, f: like }, function(resp){handleFavPost(resp);} ); }else{ dhtmlx.message({type:"error", text:"请先登录" }); } } function handleFavPost(resp){ var code=getRespCode(resp); if(code=="fav_ok"){ dhtmlx.message("收藏成功!"); }else if(code=="unfav_ok"){ dhtmlx.message("取消收藏!"); }else{ dhtmlx.alert("抱歉,出现未知错误!"); } $('#tl_fav')[0].onclick=checkFav; } function triggerComment(force){//force=force_to_close if(!$('#comment_view')[0]){//this is null in review.php return; } if(postId==0){ return; } var postHgt=$('#post_view')[0].offsetHeight; var commentHgt=$('#comment_view')[0].offsetHeight; if(commentHgt==0){ if(!force){ $('#post_view').hide(); $('#comment_view').fadeIn(); $('#comment_to').html("关于&nbsp;\""+$('#post_title').html()+"\"&nbsp;的评论"); if(commentToId!=postId && postId!=0){ $.get(phpDir+"loadcomment.php", { id: postId }, function(resp){handleLoadComment(resp);}); commentToId=postId; } } }else{ $('#comment_view').hide(); $('#post_view').fadeIn(); } } function handleLoadComment(resp){ var code=getRespCode(resp); var list=$('#cmt_list')[0]; list.innerHTML=""; if(code=="no_comment"){ dhtmlx.message("本文暂无评论,赶紧抢沙发啦~"); }else if(code=="load_comment_ok"){ var data=getRespData(resp); var pcs=data.split("<>"); for(i=0; i<pcs.length-1; i++){ var user=my_substr(pcs[i],"u");//later use it to load avartar var time=my_substr(pcs[i],"t"); var comment=my_substr(pcs[i],"c"); addAComment(list, user, time, comment); } }else{ dhtmlx.alert("抱歉,出现未知错误!"); } } function addAComment(list, user, time, comment, head){ var avtDiv=document.createElement('div'); avtDiv.className="cmt_avatar"; var cmtDiv=document.createElement('div'); cmtDiv.className="cmt_text"; cmtDiv.innerHTML="<i><b>"+user+"</b></i>&nbsp;("+time+")&nbsp;说:<br />"+comment; var pDiv=document.createElement('div'); pDiv.className="cmtbox"; pDiv.appendChild(avtDiv); pDiv.appendChild(cmtDiv); var hr=document.createElement('hr'); hr.className="clear"; if(head==1){//insert to head list.insertBefore(hr,list.childNodes[0]); list.insertBefore(pDiv,list.childNodes[0]); }else{ list.appendChild(pDiv); list.appendChild(hr); } } function doComment(){ if(!email){ dhtmlx.alert("您尚未登录,无法评论。请先登录或注册后再试!"); return; } var text=$('#cmt_content')[0].value; if(text==null || text==""){ dhtmlx.message({ type:"error", text:"请输入评论内容!" }); return; } $.post(phpDir+"postcomment.php", { id: commentToId, c:text }, function(resp){handleComment(resp);}); //immediately add new comment locally addAComment($('#cmt_list')[0],nickname,"",text,1); $('#cmt_content')[0].value=""; } function handleComment(resp){ var code=getRespCode(resp); if(code=="no_such_post"){ dhtmlx.message({ type:"error", text:"原帖已删除,无法评论,请更新网页" }); }else if(code=="comment_ok"){ dhtmlx.message("成功添加评论!"); }else{ dhtmlx.message({ type:"error", text:"抱歉,出现未知错误!" }); } } function login(){ $('#login_wrapper').show(); } function showTopbar(nick){ if(nick){ $('#anony').hide() $('#identity').fadeIn(); $('#nickname')[0].innerHTML=nick; }else{ $('#identity').hide() $('#anony').fadeIn(); $('#nickname')[0].innerHTML=""; } } function handleUAuth(resp){ if(getRespCode(resp)=="verify_ok"){ email=tmpemail; password=<PASSWORD>; $('#login_wrapper').hide(); showTopbar(getRespData(resp)); }else{ dhtmlx.alert("抱歉,出现未知错误!"); } } function getRespCode(resp){ return resp.substring(resp.indexOf("<code>")+6, resp.indexOf("</code>")); } function getRespData(resp){ return resp.substring(resp.indexOf("<data>")+6, resp.indexOf("</data>")); } function logout(path){ delCookie("email"); delCookie("password"); if(path==undefined){ path=""; } $.post(path+phpDir+"userquit.php", {}, function(resp){handleUserQuit(resp);}); } function handleUserQuit(resp){ email=null; password=null; showTopbar(); } function doLogin(path){ tmpemail=$('#email')[0].value; tmppassword=$('#password')[0].value; if(tmpemail!="test"||tmppassword!="<PASSWORD>"){ tmppassword=hex_md5(tmppassword); } if(path==undefined){ path=""; } $.post(path+phpDir+"verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);}); //todo: hint circle } function quickEgg(id,type){ if(!id){ id=0; } if(!type){ type=heyType; } $.get(phpDir+"loadpost.php", { tp: type, id: id, m: viewMode }, function(resp){handleLoadEgg(resp);}); } function handleLoadEgg(resp){ var code=getRespCode(resp); if(code=="no_post"){ dhtmlx.message(MSG_NO_MORE_POST); var title=$('#post_title')[0]; if(title.innerHTML=="加载中..." && postId==0){ title.innerHTML="暂无文章"; $('#post_author_name').html("-"); $('#post_time').html("时间:&nbsp;-"); $('#post_text').html(""); } }else if(code=="no_such_post"){ dhtmlx.alert("文章找不到了,看看别的吧" ); }else{ resp=decodeURIComponent(resp); var pcs=resp.split("<>"); postId=Number(pcs[0]); $('#post_title').html(pcs[1]); $('#post_time').html("时间:&nbsp;"+pcs[2]); $('#post_text').html(pcs[3]); $('#post_author_name').html(pcs[4]); $('#post_author_name')[0].href="user.php?uid="+pcs[5]; //check other components if($('#tl_fav')[0]){//in review.php, it's null $('#tl_fav')[0].onclick=checkFav; if(pcs[6]==0){ $('#check_fav')[0].className="unchecked"; }else{ $('#check_fav')[0].className="checked"; } } closeList(); triggerComment(true); } } function nearbyEgg(orient,id){ if(!id){ id=postId; } $.get(phpDir+"loadnearbypost.php", { tp: heyType, id: id, m: viewMode, o: orient }, function(resp){handleLoadEgg(resp);}); triggerComment(true); } function openList(){ $('#list').show(); $('#list').animate({ width:"420px" },300,function(){ if(!$('#list_rows')[0].childNodes[0] || $('#list_rows')[0].childNodes[0].className!="rows"){ loadList(); } } ); } function closeList(){ $('#list').animate({ width:"0" },300,function(){ $('#list').hide(); } ); } function prevList(){ if(listIdx==0){ dhtmlx.message(MSG_NO_MORE_POST); return; } listIdx--; loadList(); } function nextList(){ if(listIdx==totalLists-1 || totalLists==0){ dhtmlx.message(MSG_NO_MORE_POST); return; } listIdx++; loadList(); } function loadList(){ $.get(phpDir+'loadlist.php', { n: listIdx, tp: heyType, m: viewMode }, function(resp){handleLoadList(resp);}); } function handleLoadList(resp){ $('#list_rows').html('');//reset resp=decodeURIComponent(resp.trim()); var mbrs=resp.split("<|>"); var list=$('#list_rows')[0]; for(i=0; i<mbrs.length-1; i++){ var blks=mbrs[i].split("<>"); var pDiv=document.createElement('div'); pDiv.className="row"; pDiv.innerHTML=blks[1];//title pDiv.title=blks[1]; pDiv.onclick=function(v){return function(){loadEggById(v);}}(blks[0])//blks[0]=id, note the grammar list.appendChild(pDiv); } postsInType=Number(mbrs[mbrs.length-1]);//last piece is total lists totalLists=Math.ceil(postsInType/LIST_SIZE); if(isNaN(totalLists)){ totalLists=0; } showListNow(); } function showListNow(){ $('#list_now').html((listIdx+1)+"&nbsp;/&nbsp;"+totalLists+"页"); } function gotoList(){ var target=$('#jumpNum')[0].value; if(target!=null && !isNaN(target) && target.indexOf(".")<0){ target=Number(target); if(target>0 && target<=totalLists){ listIdx=target-1; loadList(); }else{ dhtmlx.message( {type:"error", text:"页码超过范围"} ); } }else{ dhtmlx.message( {type:"error", text:"请输入要跳转的页码数字"} ); } } function votePost(score){ if(postId==0){ dhtmlx.message({type:"error", text:"当前没有可打分的文章"}); return; } if(email){ $.get(phpDir+"votepost.php", { id: postId, s: score }, function(resp){handleVotePost(resp);} ); } } function handleVotePost(resp){ //alert(resp); var code=getRespCode(resp); if(code=="vote_ok"){ dhtmlx.message("打分成功!"); }else if(code=="already_voted"){ dhtmlx.message("已经打过分了!"); }else{ dhtmlx.alert("抱歉,出现未知错误!"); } } function loadEggById(id){ if(!id){ id=postId; } $.get(phpDir+"loadpostbyid.php", { id: id }, function(resp){handleLoadEgg(resp);}); } function checkEmail(){ var r_email=document.getElementById('mail').value; if(r_email==""){ dhtmlx.alert("邮箱地址必须填写!"); return false; }else{ var at=r_email.indexOf("@"); var dot=r_email.lastIndexOf("."); if(at<1 || dot<3 || dot<at || at!=r_email.lastIndexOf('@') || dot==r_email.length-1){ dhtmlx.alert("邮箱格式不正确,请检查!"); return false; } } return true; } function checkNick(){ var nick=document.getElementById('nick').value; if(nick.length<2){ dhtmlx.alert("昵称不能少于2个字符"); return false; } return true; } function checkPass(){ var pw=document.getElementById('passwd').value; if(pw.length<6 || pw.length>18){ dhtmlx.alert("密码由6至18个字符组成"); return false; } var pw2=document.getElementById('passwd2').value; if(pw!=pw2){ dhtmlx.alert("确认密码不一致,请检查"); return false; } return true; } function checkCode(){ var code=document.getElementById('regcode').value; if(code.length!=12){ dhtmlx.alert("邀请码不正确"); return false; } return true; } function doReg(){ var email=document.getElementById('mail').value; var pw=document.getElementById('passwd').value; var nick=document.getElementById('nick').value; var code=document.getElementById('regcode').value; if( checkEmail() && checkPass() && checkNick() && checkCode() ){ dhtmlx.message("注册中,请稍候..."); //document.getElementById('submit').onclick=""; $.post(phpDir+"adduser.php", { m: email, p: hex_md5(pw), n: nick, c: code}, function(resp){handleReg(resp);}); } } function handleReg(resp){ var code=getRespCode(resp); if(code=="register_ok"){ dhtmlx.message("恭喜,注册成功!"); }else if(code=="existing_email"){ dhtmlx.alert("该邮箱已被注册!请直接登录或用其它邮箱注册"); }else if(code=="existing_nick"){ dhtmlx.alert("该昵称已经存在了,请尝试其它名字吧"); }else if(code=="invite_code_error"){ dhtmlx.alert("邀请码不OK哦"); }else if(code=="bad_nick"){ dhtmlx.alert("不适当的昵称,保护黑蛋,人人有责"); }else{ dhtmlx.alert("抱歉,出现未知错误!"); } $('#submit')[0].onclick=doReg; } function browseType(idx){ if(heyType!=TYPES[idx]){ heyType=TYPES[idx]; postId=0; commentToId=0; listIdx=0; totalLists=0; closeList(); triggerComment(true); quickEgg(); } } function closeHint(cmd){ if(cmd=="no_more_post"){ MSG_NO_MORE_POST="<b>暂时没有更多文章.</b>"; } } function doSelect(){ //TODO }<file_sep>/todo.txt * post/post-under-review db -need to evaluate design tradeoff (two table or one?) -done. ONE db for both posts. * postnew function -done without the writing seperate post.html file. -need disable local upload for image in editor page * load default function -"no-type-parameter" loading is done for view mode. -need do with type parameter -done. -review mode -done. * page function -done. * list view design -container and closer done. -need to paginate -done. -need to list rows -done. -consider loading abstract together with title, and reduce list_size to 5 * list function -loadEggsById not done -done. -handle empty list case -done. don't handle. -others done. * list page function -done. % -list pager overflow case -done. * review function -consider add reviewers to give feedbacks to poster -others done. % -review page tool button rotate -done. * user favourate function % -need to init like/unlike status on the icon when load a post //-need to rebuild the mechanism (show two buttons, not one) to make it simpler -done. -others done. * comment view -rough layout done. * comment function -post new comment done. -need to consider comment id (so for future deletion) -partly done with timestamp. -comment load mechanism (not all at a time, or firstly all, refine later) -need to do small files - one comment one file in a dir -done. * register page -design / ui done. -need to do registration process -need to check invitation mechanism first -done. -others done. * user info view and link updates in other related pages -view and load function done. -need to handle parameter input for index.php and review.php -done. -no information yet % -links should be added at all proper places (topbar, post author, comment author) * user info edit -no yet * messaging -integrated jsMessage. % -check out all alert places, and unify the style -error: red, info: black % -define alert strings as constant ------------------- -> Masking (especially in post.php) ------------------- * selection pop-up view * selection comment function * selection user-focus function* * user credit function* * add post view counts (design the method & rule first) ------------------- * score mechanism ------------------- * allow anonymous post submission? * all masking effect for loading (load post/list/paging, login, logout, like, comment, score, submit, review) ---------------------------------- * Check all similar pages are with same frame ui and functions * TEST logics that i can think... (remember the test script written down) * TEST on the deployed environment... ---------------------------------- * check SQL injection (add keyword judgement for input parameters) * data & code backup mechanism<file_sep>/action/favpost.php <?php session_start(); if( !isset($_SESSION['email']) || !isset($_GET['id']) || !isset($_GET['f']) ){ return; } include_once("lib/head.php"); $email=$_SESSION['email']; $id=$_GET['id']; $like=$_GET['f']; $conn= mysql_connect("localhost", "root", "$mysqlpw") or die("<code>connect_err</code>".mysql_error()); mysql_select_db('eggsys',$conn); $sql="select count(*) from postlike where post_id=$id limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ if($myrow[0]==0){ if($like==1){ $sql="insert into postlike values ($id, 1, ',$email,')"; $query=mysql_query($sql); } }else{ $sql="select * from postlike where post_id=$id limit 1"; $query=mysql_query($sql); $myrow=mysql_fetch_array($query); $users=$myrow['like_users']; if(strpos($users,','.$email.',')!==false){ if($like==-1){//cancel favourate $users=str_replace(",".$email.",",",",$users); $liked=$myrow['liked']-1; $sql="update postlike set like_users='$users', liked=$liked where post_id=$id"; $query=mysql_query($sql); } }else{ if($like==1){ $users=$users.$email.","; $liked=$myrow['liked']+1; $sql="update postlike set like_users='$users', liked=$liked where post_id=$id"; $query=mysql_query($sql); } } } } //update user's like list $sql="select count(*) from userlike where user_email='$email' limit 1"; $query=mysql_query($sql); if($myrow=mysql_fetch_array($query)){ if($myrow[0]==0){//first time for this user to like a post if($like==1){ $sql="insert into userlike values ('$email', 1, ',$id,')"; $query=mysql_query($sql); print "<code>fav_ok</code>"; } }else{ $sql="select * from userlike where user_email='$email' limit 1"; $query=mysql_query($sql); $myrow=mysql_fetch_array($query); $posts=$myrow['like_posts']; if(strpos($posts,','.$id.',')!==false){ if($like==-1){//cancel favourate $posts=str_replace(",".$id.",", ",", $posts); $liked=$myrow['liked']-1; $sql="update userlike set like_posts='$posts', liked=$liked where user_email='$email'"; $query=mysql_query($sql); print "<code>unfav_ok</code>"; } }else{ if($like==1){ $posts=$posts.$id.","; $liked=$myrow['liked']+1; $sql="update userlike set like_posts='$posts', liked=$liked where user_email='$email'"; $query=mysql_query($sql); print "<code>fav_ok</code>"; } } } } ?> <file_sep>/README.md heyegg ====== Heyegg is a Digg-like yet reading friendly news service. It allows users to submit and evaluate news posts. Posts with recommendations will be public accessible. Heyegg is built upon jQuery, PHP, and MySQL. A sample site is available at http://www.heyegg.com (closed now). <file_sep>/res/extool.js /*firefox's event*/ function __firefox(){ HTMLElement.prototype.__defineGetter__("runtimeStyle", __element_style); window.constructor.prototype.__defineGetter__("event", __window_event); Event.prototype.__defineGetter__("srcElement", __event_srcElement); } function __element_style(){ return this.style; } function __window_event(){ return __window_event_constructor(); } function __event_srcElement(){ return this.target; } function __window_event_constructor(){ if(document.all){ return window.event; } var _caller = __window_event_constructor.caller; while(_caller!=null){ var _argument = _caller.arguments[0]; if(_argument){ var _temp = _argument.constructor; if(_temp.toString().indexOf("Event")!=-1){ return _argument; } } _caller = _caller.caller; } return null; } if(window.addEventListener){ __firefox(); } /*Browser detection*/ var Browser = { init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data) { for (var i=0;i<data.length;i++) { var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity; } else if (dataProp) return data[i].identity; } }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) return; return parseFloat(dataString.substring(index+this.versionSearchString.length+1)); }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },{ string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" },{ string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" },{ prop: window.opera, identity: "Opera" },{ string: navigator.vendor, subString: "iCab", identity: "iCab" },{ string: navigator.vendor, subString: "KDE", identity: "Konqueror" },{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },{ string: navigator.vendor, subString: "Camino", identity: "Camino" },{ // for newer Netscapes (6+) string: navigator.userAgent, subString: "Netscape", identity: "Netscape" },{ string: navigator.userAgent, subString: "MSIE", identity: "IE", versionSearch: "MSIE" },{ string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" },{ // for older Netscapes (4-) string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows" },{ string: navigator.platform, subString: "Mac", identity: "Mac" },{ string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" },{ string: navigator.platform, subString: "Linux", identity: "Linux" } ] }; /*Cookie management*/ function setCookie(name,value){ var days = 30; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } function getCookie(name){ var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); if(arr != null) return unescape(arr[2]); return null; } function delCookie(name){ var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString(); } /*String prototype*/ String.prototype.trim= function(){ return this.replace(/(^\s*)|(\s*$)/g, ""); } /*Misc*/ function my_substr(origin, tag){//parse xml like strings var fromstr="<"+tag+">"; var tostr="</"+tag+">"; if(origin.indexOf(fromstr)>=0 && origin.indexOf(tostr)>=0){ return origin.substring(origin.indexOf(fromstr)+fromstr.length, origin.indexOf(tostr)); }else{ return null; } } function getSelectedText() { if (window.getSelection) { // This technique is the most likely to be standardized. // getSelection() returns a Selection object, which we do not document. return window.getSelection().toString(); } else if (document.getSelection) { // This is an older, simpler technique that returns a string return document.getSelection(); } else if (document.selection) { // This is the IE-specific technique. // We do not document the IE selection property or TextRange objects. return document.selection.createRange().text; } } <file_sep>/ueditor/_examples/post.php <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>黑蛋 | 投递新稿件</title> <link rel="stylesheet" type="text/css" href="../../jsMessage/codebase/themes/message_growl_dark.css"> <link href="../../res/style.css" rel="stylesheet" type="text/css" /> <link href="../../res/effect.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="../themes/default/ueditor.css"/> <script language="javascript" src="../../res/jquery-1.6.2.min.js"></script> <script language="javascript" src="../../res/extool.js"></script> <script language="javascript" src="../../res/md5-min.js"></script> <script language="javascript" src="../../res/hey.js?v=0.2"></script> <script type="text/javascript" src='../../jsMessage/codebase/message.js?v=0.2'></script> <script type="text/javascript" charset="utf-8" src="../editor_config.js"></script> <script type="text/javascript" charset="utf-8" src="../editor_all_min.js"></script> <style> #view{ font-size:14px; font-family:'Microsoft YaHei'; padding:40px 10px; } #ptitle{ width:100%; } label{ display:block; margin:25px 0px 2px 0; } </style> <script language="javascript"> $(document).ready(function(){ initUser(); }); function initUser(){ tmpemail="<?php if(isset($_SESSION['email'])) { print $_SESSION['email']; }else{ print ""; } ?>"; tmpnickname="<?php if(isset($_SESSION['nickname'])) { print $_SESSION['nickname']; }else{ print ""; } ?>"; if(tmpemail==""){ tmpemail=getCookie("email"); if(tmpemail!=null){ tmppassword=getCookie("password"); $.post("../../action/verifyuser.php", {u: tmpemail, p: tmppassword}, function(resp){handleUAuth(resp);}); //todo: show a loading circle nearby "login" span } }else{ email=tmpemail; nickname=tmpnickname; showTopbar(nickname); } } function doPost(){ var type=$('#type')[0].value; var title=$('#ptitle')[0].value; var content=editor_a.getContent(); if(email){ if(title==""){ dhtmlx.alert("请输入文章标题!"); }else if(!editor_a.hasContents()){ dhtmlx.alert("请输入文章内容!"); }else{ editor_a.sync(); $.post("../../action/addpost.php", { tp: type, tl: title, ct: content}, function(resp){handlePost(resp);}); } }else{ dhtmlx.alert("请先登录!"); } } function handlePost(resp){ var code=getRespCode(resp); if(code=="post_ok"){ dhtmlx.message("投递成功!"); $('#ptitle')[0].value=""; }else if(code=="identity_error"){ dhtmlx.alert("登录信息错误,请重新登录!"); }else{ dhtmlx.alert("抱歉,出现未知错误!"); } } </script> </head> <body> <div id="topbar"> <div id="btm_border"></div> <div id="left_panel"></div> <div id="right_panel"> <div id="anony"><span onclick="login()">登录</span><span onclick="window.open('register.html');">注册</span></div> <div id="identity" style="display:none"><span>欢迎,&nbsp;<a id="nickname"></a>!</span><span onclick="logout('../../')">退出</span></div> </div> <div id="logo" onclick="window.open('../../index.php');"></div> </div> <div id="main"> <div id="view"> <div> <label>文章标题</label> <input type="text" id="ptitle" maxlength="50" /> </div> <div> <label>类别:</label> <select id="type"> <option value="tech">科技</option> <option value="news">社会</option> <option value="fun">奇趣</option> <option value="ent">娱乐</option> </select> </div> <div> <label>正文内容</label> <script type="text/plain" id="myEditor" class="myEditor"></script> <script type="text/javascript"> var editor_a = new baidu.editor.ui.Editor(); editor_a.render('myEditor'); //remove unused tools var unused=Array(3,6,7,8,15,16,18,19,20,21,50,57,88,89,90,122,133,138,143,144,149,166,167,168,169,170,171,172,173,174,175,176,177,184,186); //alert(unused+";"+unused.length); var i=0; for(; i<unused.length; i++){ hideTool('edui'+unused[i]); } function hideTool(tid){ var tobj=document.getElementById(tid); if(tobj){ /*var tparent=tobj.parentNode; tparent.removeChild(tobj); *///we don't remove it as warnings in console, so just hide it tobj.style.display="none !important"; } } </script> </div> <div> <button id="submit" style="top:10px" onclick="doPost()" style="top:90px; right:-270px;">投递</button> </div> </div> </div> <div id="login_wrapper" style="display:none"> <div id="login"> <div id="close_login" onClick="$('#login_wrapper').hide();"></div> <input type="text" value="Email" id="email" onFocus="this.className='selected';this.style.border='none';if(this.value=='Email') this.value='';" onBlur="this.className='';if(this.value.trim()=='') this.value='Email';" /> <input type="text" value="密码" id="password" onFocus="this.className='selected'; this.type='password';if(this.value=='密码') this.value='';" onBlur="this.className='';if(this.value=='') {this.value='密码';this.type='text';};"/> <button id="submit" onclick="doLogin('../../');" style="top:80px;left:-37px;float:right;">登录</button> </div> </div> </body> </html>
8e129d51e1196f3d3523781cbe36c291cad8324e
[ "JavaScript", "Markdown", "Text", "PHP" ]
22
PHP
mrmoment/heyegg
d3cca3272c726a5f67c6d0a1d14749f77616c88f
200c4a864a2b1a646f7daa00403ab7dbc23db994
refs/heads/master
<repo_name>vollmerr/spo-react<file_sep>/src/webparts/demo/constants/status.ts export enum STATUS { ERROR, READY, LOADING, SUBMITTING, } <file_sep>/src/webparts/demo/actions/listActions.ts import { actionTypes, Action } from './actionTypes'; import { SPHttpClient, ISPHttpClientOptions, SPHttpClientResponse } from '@microsoft/sp-http'; import { IODataList } from '@microsoft/sp-odata-types'; const addListRequest = (): Action => ({ type: actionTypes.ADD_LIST_REQUEST }); const addListSuccess = (list: string): Action => ({ type: actionTypes.ADD_LIST_SUCCESS, payload: list }); const addListError = (error: Error): Action => ({ type: actionTypes.ADD_LIST_FAILURE, payload: error.message }); const getListsRequest = (): Action => ({ type: actionTypes.GET_LISTS_REQUEST }); const getListsSuccess = (title: string, lists: IListItems[]): Action => ({ type: actionTypes.GET_LISTS_SUCCESS, payload: { title, lists } }); const getListsError = (error: Error): Action => ({ type: actionTypes.GET_LISTS_FAILURE, payload: error.message }); export function addList(spHttpClient: SPHttpClient, currentWebUrl: string, title: string) { return async (dispatch: any) => { //Fire the 'request' action if you want to update the state to specify that an ajax request is being made. //This can be used to show a loading screen or a spinner. dispatch(addListRequest()); const spOpts: ISPHttpClientOptions = { body: `{ Title: '${title}', BaseTemplate: 100 }` }; try { const response: SPHttpClientResponse = await spHttpClient.post(`${currentWebUrl}/_api/web/lists`, SPHttpClient.configurations.v1, spOpts); const list: IODataList = await response.json(); //Fire the 'success' action when you want to update the state based on a successfull request. dispatch(addListSuccess(list.Title)); } catch (error) { //Fire the 'error' action when you want to update the state based on an error request. dispatch(addListError(error)); } }; } export function getLists(spHttpClient: SPHttpClient, currentWebUrl: string, listTitle: string, title: string) { return (dispatch) => { dispatch(getListsRequest()); // return spHttpClient.get(`${currentWebUrl}/_api/web/lists/getbytitle(${listTitle})/items(1)`, SPHttpClient.configurations.v1) // .then(response => response.json()) // .then(json => console.log("NUMERO UNO: ", json)) // .then( // () => { return spHttpClient.get(`${currentWebUrl}/_api/web/lists/getByTitle('${listTitle}')/items`, SPHttpClient.configurations.v1) .then(response => response.json()) .then(json => json.value) .then(lists => dispatch(getListsSuccess(title, lists))) .catch(error => dispatch(getListsError(error))); // } // ); }; } <file_sep>/src/webparts/demo/IDemoWebPartProps.ts export interface IDemoWebPartProps { id: number; } <file_sep>/src/webparts/demo/reducers/loadingReducer.ts import { Action } from '../actions/actionTypes'; import { Reducer } from 'redux'; import { LoadingState } from '../state/LoadingState'; export const actionTypeEndsInRequest = type => type.substring(type.length - 8) === '_REQUEST'; export const actionTypeEndsInSuccess = type => type.substring(type.length - 8) === '_SUCCESS'; export const actionTypeEndsInFailure = type => type.substring(type.length - 8) === '_FAILURE'; const initState = new LoadingState(); // Reducer determines how the state should change after every action. const loadingReducer: Reducer<LoadingState> = (state: LoadingState = initState, action: Action): LoadingState => { if (actionTypeEndsInRequest(action.type)) { return state.increaseLoading(); } else if (actionTypeEndsInSuccess(action.type)) { return state.decreaseLoading(); } else if (actionTypeEndsInFailure(action.type)) { return state.decreaseLoading(); } return state; }; export default loadingReducer; <file_sep>/src/webparts/demo/store/configureStore.ts import { createStore, applyMiddleware, compose } from 'redux'; import thunkMiddleware from 'redux-thunk'; import { createLogger } from 'redux-logger'; import { RootState } from '../state'; import rootReducer from '../reducers'; const loggerMiddleware = createLogger(); const composeEnhancers = window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] || compose; export default function configureStore(initialState?) { const middleWares = [ thunkMiddleware, // loggerMiddleware, ]; const enhancer = composeEnhancers(applyMiddleware(...middleWares)); return createStore<RootState>(rootReducer, initialState, enhancer); } <file_sep>/src/webparts/demo/reducers/index.ts import { Reducer, combineReducers } from 'redux'; import { reducer as form } from 'redux-form'; import lists from './listsReducer'; import loading from './loadingReducer'; import error from './errorReducer'; import { RootState } from '../state'; // ALL reducers must got through this reducer const rootReducer = combineReducers<RootState>({ form, lists, error, loading, }); export default rootReducer; <file_sep>/src/webparts/demo/state/index.ts import { ListState } from './ListState'; import { LoadingState } from './LoadingState'; import { ErrorState } from './ErrorState'; export interface RootState { form: any; lists: ListState; error: ErrorState; loading: LoadingState; } <file_sep>/src/webparts/demo/state/ListState.ts import * as Immutable from 'immutable'; export interface IListState { agencyCodes: any[]; stage1: any[]; } export const initialState: IListState = { agencyCodes: [], stage1: [], }; // Immutable State. export class ListState extends Immutable.Record(initialState) implements IListState { // Getters public readonly agencyCodes: IListItems[]; public readonly stage1: IListItems[]; // Setters public addList(payload): ListState { const { title, item } = payload; return this.update(title, (lists: any[]) => { return lists.concat(item); }) as ListState; } public setLists(payload): ListState { const { title, lists } = payload; return this.set(title, lists) as ListState; } } <file_sep>/src/webparts/demo/state/ErrorState.ts import * as Immutable from 'immutable'; export interface IErrorState { error: string | null; } export const initialState: IErrorState = { error: null, }; // Immutable State. export class ErrorState extends Immutable.Record(initialState) implements IErrorState { // Getters public readonly error: string | null; public setError(error) { return this.set('error', error) as ErrorState; } public clearError() { return this.set('error', null) as ErrorState; } } <file_sep>/src/webparts/demo/loc/mystrings.d.ts declare interface IDemoStrings { PropertyPaneDescription: string; BasicGroupName: string; DescriptionFieldLabel: string; } declare module 'demoStrings' { const strings: IDemoStrings; export = strings; } declare interface IListItems { Id?: number; Title?: string; firstName?: string; lastName?: string; phoneNumber?: string; testRequired?: string; } <file_sep>/src/webparts/demo/reducers/errorReducer.ts import { Action } from '../actions/actionTypes'; import { Reducer } from 'redux'; import { ErrorState } from '../state/ErrorState'; export const actionTypeEndsInRequest = type => type.substring(type.length - 8) === '_REQUEST'; export const actionTypeEndsInSuccess = type => type.substring(type.length - 8) === '_SUCCESS'; export const actionTypeEndsInFailure = type => type.substring(type.length - 8) === '_FAILURE'; const initState = new ErrorState(); // Reducer determines how the state should change after every action. const errorReducer: Reducer<ErrorState> = (state: ErrorState = initState, action: Action): ErrorState => { if (actionTypeEndsInRequest(action.type)) { return state.clearError(); } else if (actionTypeEndsInFailure(action.type)) { return state.setError(action.payload); } return state; }; export default errorReducer; <file_sep>/src/webparts/demo/state/LoadingState.ts import * as Immutable from 'immutable'; export interface ILoadingState { loading: number; } export const initialState: ILoadingState = { loading: 0, }; // Immutable State. export class LoadingState extends Immutable.Record(initialState) implements ILoadingState { // Getters public readonly loading: number; public increaseLoading() { return this.set('loading', this.loading + 1) as LoadingState; } public decreaseLoading() { return this.set('loading', this.loading - 1) as LoadingState; } } <file_sep>/src/webparts/demo/actions/actionTypes.ts export const actionTypes = { ADD_LIST_REQUEST: 'ADD_LIST_REQUEST', ADD_LIST_SUCCESS: 'ADD_LIST_SUCCESS', ADD_LIST_FAILURE: 'ADD_LIST_FAILURE', GET_LISTS_REQUEST: 'GET_LISTS_REQUEST', GET_LISTS_SUCCESS: 'GET_LISTS_SUCCESS', GET_LISTS_FAILURE: 'GET_LISTS_FAILURE', }; export type Action = { type: string, payload?: any };
ec290d84ea26c59808f3b1f06257f8196f84d834
[ "TypeScript" ]
13
TypeScript
vollmerr/spo-react
bb795abc7c1c3fb1d855a4d26dd442a697004017
9700505d1a3bc3f421e04f9af2c65f67a6469180
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace OCLogInterpreter { class LogFile { public List<Entry> m_entryList = new List<Entry>(); public List<string> m_listOfPriorities = new List<string>(); public void populatePriorities() { m_listOfPriorities.Clear(); m_listOfPriorities.Add(""); foreach (Entry e in m_entryList) { if (!m_listOfPriorities.Contains(e.m_priority)) { m_listOfPriorities.Add(e.m_priority); } } } public List<Entry> findEntriesByTimeDate(string filterTimeDate) { List<Entry> retList = new List<Entry>(); foreach (Entry e in m_entryList) { if (e.m_dateTime.Contains(filterTimeDate)) { retList.Add(e); } } return retList; } public List<Entry> findEntriesByPriority(string filterPriority) { List<Entry> retList = new List<Entry>(); foreach (Entry e in m_entryList) { if (e.m_priority.Contains(filterPriority)) { retList.Add(e); } } return retList; } public List<Entry> filterEntries(string filterPriority, string filterDateTime) { List<Entry> retList = new List<Entry>(); foreach (Entry e in m_entryList) { if (e.m_priority.Contains(filterPriority) && e.m_dateTime.Contains(filterDateTime) ) { retList.Add(e); } } return retList; } public void loadFromFile(string path) { m_entryList.Clear(); m_listOfPriorities.Clear(); StreamReader sr = new StreamReader(path); try { while (!sr.EndOfStream) { m_entryList.Add(Entry.unSerialize(sr.ReadLine())); } populatePriorities(); } finally { sr.Close(); } } public void exportAsCSV(string path) { StreamWriter sw = new StreamWriter(path); try { sw.WriteLine("Date/Time,Log Information,Priority"); foreach (Entry e in m_entryList) { sw.WriteLine(e.toCSVFormat()); } } finally { sw.Close(); } } } class Entry { public string m_dateTime = ""; public string m_info = ""; public string m_priority = ""; public override string ToString() { return m_dateTime + ": " + m_priority; } public static Entry unSerialize(string data) { Entry newEntry = new Entry(); int part = 0; char[] charrdata = data.ToCharArray(); foreach (char c in charrdata) { if (c == '|') { part++; } else { switch (part) { case 1: newEntry.m_dateTime += c; break; case 2: newEntry.m_info += c; break; case 3: newEntry.m_priority += c; break; } } } return newEntry; } public string toCSVFormat() { string retString = "\"" + m_dateTime + "\",\"" + m_info + "\",\"" + m_priority + "\""; return retString; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace OCLogInterpreter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { LogFile lf; Microsoft.Win32.OpenFileDialog ofd; Microsoft.Win32.SaveFileDialog sfd; public MainWindow() { InitializeComponent(); lf = new LogFile(); ofd = new Microsoft.Win32.OpenFileDialog(); sfd = new Microsoft.Win32.SaveFileDialog(); EntriesView.ItemsSource = lf.m_entryList; PriorityFilterDD.ItemsSource = lf.m_listOfPriorities; } private void OpenLogFile(object sender, RoutedEventArgs e) { ofd.DefaultExt = ".log"; ofd.Filter = "OpenComputers Log Files (.log)|*.log"; bool? result = ofd.ShowDialog(); if ( result == true ) { lf.loadFromFile(ofd.FileName); } else { MessageBox.Show("Error opening file!"); } refreshAllItems(); } private void refreshAllItems() { EntriesView.Items.Refresh(); PriorityFilterDD.Items.Refresh(); } private void EntriesView_SelectionChanged(object sender, SelectionChangedEventArgs e) { Entry selectedEntry = (Entry) EntriesView.SelectedItem; if (selectedEntry != null) { SelTimeDateLab.Content = "Date/Time: " + selectedEntry.m_dateTime; SelPriorityLab.Content = "Priority: " + selectedEntry.m_priority; SelInfoTB.Text = selectedEntry.m_info; } } private void RenewFilter(object sender, RoutedEventArgs e) { if (FilterCB != null) { if (FilterCB.IsChecked == true) { EntriesView.ItemsSource = lf.filterEntries(PriorityFilterDD.Text, DateFilterTB.Text); } else { EntriesView.ItemsSource = lf.m_entryList; } refreshAllItems(); } } private void PriorityFilterDD_DropDownClosed(object sender, EventArgs e) { RenewFilter( sender, null ); } private void ExportLogFile(object sender, RoutedEventArgs e) { sfd.DefaultExt = ".csv"; sfd.Filter = "Comma Seperated Values (.csv)|*.csv"; bool? result = sfd.ShowDialog(); if (result == true) { lf.exportAsCSV(sfd.FileName); } else { MessageBox.Show("Error saving file!"); } } } } <file_sep># OCLOGAPI Creates log files in opencomputers Included: The API An interpreter for log files ( allows filtration and views in a nice little table ) An example program for creation ( test.lua ) An example program for reading ( testr.lua ) Documentation is included inside the logapi.lua file. WPF interpreter executable located at: \OCLOGAPI\OCLogInterpreter\OCLogInterpreter\bin\Debug\OCLogInterpreter.exe<file_sep>local fs = require( "filesystem" ) local term = require( "term" ) --Container local logContainerMeta = { } logContainerMeta.__index = logContainerMeta function logContainer( inPath ) -- Creates a log container ( sort of a massive list for entries ). slc = { path = inPath, entries = { } } setmetatable( slc, logContainerMeta ) if ( fs.exists( inPath ) ) then slc:loadFrom( inPath ) end return slc end function logContainerMeta:addEntry( newEntry, append ) -- Adds an entry "object" to the specified container. table.insert( self.entries, newEntry ) if ( append ) then file = io.open( self.path, "a" ) file:write( newEntry:serialize( ), "\n" ) file:flush( ) file:close( ) end end -- Looks through container and returns a new table of entries that are matching the filter. function logContainerMeta:findEntriesByPriority( filterPriority ) retTable = { } for k, v in ipairs( self.entries ) do if ( v.priority == tostring( filterPriority ) ) then table.insert( retTable, v ) end end return retTable end -- Looks through container and returns a new table of entries that are matching the filter. -- Note that the filter can be either dd/mm/yy, hh/mm/ss, or dd/mm/yy hh/mm/ss. function logContainerMeta:removeEntry( entry ) -- Duplicates not taken into account for k, v in ipairs( self.entries ) do if ( v:entryUnserialize() == entry:entryUnserialize() ) then table.remove( self.entries, k ) break end end end function logContainerMeta:findEntriesByDateTime( filtertd ) retTable = { } for k, v in ipairs( self.entries ) do if ( v.timedatestamp == filtertd or string.sub( v.timedatestamp, 1, 8 ) == filtertd or string.sub( v.timedatestamp, 10, 18 ) == filtertd ) then table.insert( retTable, v ) end end return retTable end function logContainerMeta:loadFrom( path ) -- Loads an entry list from the specified path io.input( path ) allLines = { } for l in io.lines( ) do table.insert( allLines, l ) end io.close( ) for k, v in ipairs( allLines ) do self:addEntry( entryUnserialize( v ), false ) end end function logContainerMeta:save( path ) -- Saves the entry list to the specified path io.output( path ) for k, v in ipairs( self.entries ) do io.write( v:serialize( ), "\n" ) end io.flush( ) io.close( ) end function logContainerMeta:exportCSV( path ) io.output( path ) io.write( "Date/Time,Log Info,Priority\n" ) for k, v in ipairs( self.entries ) do io.write( v:serializeCSV( ), "\n" ) end io.flush( ) io.close( ) end --Entry local entryMeta = { } entryMeta.__index = entryMeta function entry( intds, inInfo, inPriority ) -- Create new entry "object", intds can be either nil ( get current time ) or you can specify a time, make sure it's in the correct format e = { timedatestamp = "", info = tostring( inInfo ), priority = tostring( inPriority ) } if ( intds == nil ) then e.timedatestamp = tostring( os.date( ) ) else e.timedatestamp = tostring( intds ) end setmetatable( e, entryMeta ) return e end function entryUnserialize( entrystring ) -- Takes a string and creates an entry from it part = 0 tds = "" inf = "" pri = "" for i = 1, #entrystring do cchar = string.sub( entrystring, i, i ) if ( cchar == "|" ) then part = part + 1 else if ( cchar ~= "\t" ) then if ( part == 1 ) then tds = tds .. cchar elseif ( part == 2 ) then inf = inf .. cchar elseif ( part == 3 ) then pri = pri .. cchar end end end end return entry( tds, inf, pri ) end function entryMeta:serialize( ) -- Serializes entry for transmission or storage return "|" .. self.timedatestamp .. "|" .. self.info .. "|" .. self.priority .. "|" end function entryMeta:serializeCSV( ) -- Serializes entry for transmission or storage return "\"" .. self.timedatestamp .. "\",\"" .. self.info .. "\",\"" .. self.priority .. "\"" end <file_sep>require( "logapi" ) term = require( "term" ) newlog = logContainer( ) newlog:loadFrom("testser.log") for k, v in ipairs ( newlog.entries ) do term.write( v.timedatestamp .. "#" .. v.info .. "#" .. v.priority .. "\n") end for k, v in ipairs ( newlog:findEntriesByPriority( "5" ) ) do term.write( v:serialize() ) end<file_sep>require( "logapi" ) local comp = require( "component" ) local gpu = comp.gpu local fs = require( "filesystem" ) local term = require( "term" ) local event = require( "event" ) local tdl = 17 local infl = 60 local pril = 16 local display_amount = 5 local curdisplay = 1 local whitecol = 0xFFFFFF local blackcol = 0x000000 local selcol = 0x00AA55 local logfilecol = 0x00FFFF path = "/" local clog = logContainer( ) gpu.setForeground( whitecol ) gpu.setBackground( blackcol ) function pad( str, lenpad ) return str .. string.rep( " ", lenpad - #str ) end function drawHeader( ) term.write( "|" .. string.rep( "=", tdl ) .. "|" .. string.rep( "=", infl ) .. "|" .. string.rep( "=", pril ) .. "|\n" ) term.write( "|----Date/Time----|----------------------------Info----------------------------|----Priority----|\n" ) end function drawEntry( entry ) i = 1 while true do term.write( "|" .. pad( string.sub( entry.timedatestamp, (i*tdl)-(tdl-1), i*tdl ), tdl ) .. "|" .. pad( string.sub( entry.info, (i*infl)-(infl-1), i*infl ), infl ) .. "|" .. pad( string.sub( entry.priority, (i*pril)-(pril-1), i*pril ), pril ) .. "|\n") i = i + 1 if ( ( #entry.timedatestamp < i*tdl ) and ( #entry.info < i*infl ) and ( #entry.priority < i*pril ) ) then term.write( "|" .. string.rep( "-", tdl ) .. "|" .. string.rep( "-", infl ) .. "|" .. string.rep( "-", pril ) .. "|\n" ) break end end end function interpretelogFile( path ) clog:loadFrom( path ) shownEntries = clog.entries while true do term.clear( ) drawHeader( ) for i = curdisplay, curdisplay + display_amount do if ( i > #shownEntries ) then break end drawEntry( shownEntries[ i ] ) end term.write( "|" .. string.rep( "=", tdl ) .. "|" .. string.rep( "=", infl ) .. "|" .. string.rep( "=", pril ) .. "|\n" ) term.write( "Use arrow keyes for navigation\nQ to (Q)uit\nF to (F)ind\nR to (R)eset\nE to (E)xport CSV" ) -- q 16 f 33 d 32 p 25 r 19 ev, addr, ch, co, pl = event.pull( "key_down" ) if ( co == 200 and curdisplay > 1 ) then curdisplay = curdisplay - 1 elseif ( co == 208 and curdisplay < #shownEntries - display_amount ) then curdisplay = curdisplay + 1 elseif ( co == 16 ) then term.clear( ) break elseif ( co == 18 ) then term.clear( ) term.write( "Path to export: " ) expPath = term.read( ) clog:exportCSV( "/" .. string.sub( expPath, 1, #expPath-1 ) ) elseif ( co == 19 ) then shownEntries = clog.entries elseif ( co == 33 ) then curdisplay = 1 while true do term.clear() term.write( "By (D)ate or by (P)riority?\nQ to (Q)uit\n" ) ev, addr, ch, co, pl = event.pull( "key_down" ) if ( co == 16 ) then break elseif ( co == 32 ) then term.write( "Date to filter: " ) dtf = term.read( ) shownEntries = clog:findEntriesByDateTime( string.sub( dtf, 1, #dtf-1 ) ) break elseif ( co == 25 ) then term.write( "Priority to filter: " ) ptf = term.read( ) shownEntries = clog:findEntriesByPriority( string.sub( ptf, 1, #ptf-1 ) ) break end end end end end function choose( options ) local sel = 1 while true do term.clear( ) for k, v in ipairs( options ) do if ( k == sel ) then gpu.setForeground( selcol ) term.write( v .. " <--\n" ) gpu.setForeground( whitecol ) else if ( string.sub( v, #v - 3, #v ) == ".log" ) then gpu.setForeground( logfilecol ) end term.write( v .. "\n" ) gpu.setForeground( whitecol ) end end ev, addr, ch, co, pl = event.pull( "key_down" ) if ( co == 200 ) then -- 200 208 28 if ( sel > 1 ) then sel = sel - 1 else sel = #options end elseif ( co == 208 ) then if ( sel < #options ) then sel = sel + 1 else sel = 1 end elseif ( co == 28 ) then return options[sel] end end end while true do dirs = { } table.insert( dirs, "<<exit>>" ) table.insert( dirs, "<<root>>" ) for dir in fs.list( path ) do table.insert( dirs, dir ) end choice = choose( dirs ) if ( choice == "<<root>>" ) then path = "/" elseif ( choice == "<<exit>>" ) then term.clear( ) break else newpath = path .. "/" .. choice term.write( string.sub( newpath, #newpath-4, #newpath ) ) if ( fs.isDirectory( newpath ) ) then path = newpath elseif ( string.sub( newpath, #newpath-3, #newpath ) == ".log" ) then interpretelogFile( newpath ) end end end<file_sep>require("logapi") term = require("term") newlog = logContainer( ) for i = 1, 10 do newlog:addEntry( entry( nil,string.rep( "test" .. i, 20), i + 1 ) ) end newlog:save("testser.log")
19a81b020f1458d4ac9998705517dda0abe4273d
[ "Markdown", "C#", "Lua" ]
7
C#
sirdabalot/OCLOGAPI
522ba92c1279f0bf8d284fdaa8f115934c82d784
e93ca13cee71878c51d829611d78753c2f67628e
refs/heads/main
<file_sep>const capitalizer = (func) => { const innerFunc = (arg) => { return func(arg.toUpperCase()); } return innerFunc; } const after = (num, func) => { let count = 0 const innerFunc = (arg) => { count++ if (count > num) { return func(arg) } } return innerFunc } module.exports = {capitalizer, after}<file_sep>const {capitalizer, after} = require('../testinghofs') describe('test capitalizer function', () => { test('returns a function', () => { expect(typeof capitalizer()).toEqual('function') }) test('returns a _new_ function', () => { expect(capitalizer()).not.toBe(capitalizer()) }) test('takes a function as an argument and returns a function that returns the string', () => { function returnString(string) { return string } const changedString = capitalizer(returnString) expect(typeof changedString('string')).toEqual('string') }) test('takes a function as an argument and returns a function that returns a capitalized string', () => { function upperCase(string) { return string.toUpperCase() } const changedString = capitalizer(upperCase) expect(changedString('string')).toEqual('STRING') expect(changedString('eli')).toEqual('ELI') }) test('takes a function and returns a function that can capitalize the argument its invoked with', () => { const sayHello = (person) => { return `hello ${person}`; }; const shoutGreeting = capitalizer(sayHello) expect(shoutGreeting('eli')).toEqual('hello ELI') }) }) describe('test after function', () => { test('returns a function when invoked with nothing', () => { expect(typeof after()).toEqual('function') }); test('takes the number 0 and a function and returns the function', () => { const someFunc = (someStr) => { return someStr } expect(typeof after(0, someFunc)).toEqual('function') }); test('takes the number 0 and a function and when returned function is invoked gives the return value of the original function', () => { const someFunc = (someStr) => { return someStr } const returnedFunc = after(0, someFunc) expect(returnedFunc('Hello')).toEqual('Hello') }); test('takes the number 1 and a function and returned function returns undefined when invoked once', () => { const someFunc = (someStr) => { return someStr } const returnedFunc = after(1, someFunc) expect(returnedFunc('Poonam')).toEqual(undefined) }) test('takes the number 1 and a function and invoked function returns value after more than one invocation', () => { const someFunc = (someStr) => { return someStr } const returnedFunc = after(1, someFunc) returnedFunc('Christian') expect(returnedFunc('Christian')).toEqual('Christian') }) });<file_sep># Testing Higher Order Functions Your task is to write the functions below using full TDD. ## Challenges ### 1. capitalizer `capitalizer` should accept a function as an argument and return a _new_ function. That returned function should take a string as an argument, _CAPITALISE_ the string, and invoke the originally passed function with the _capitalised_ string. **Examples** ```js // Example 1 const createPDF = (file) => { return `${file}.pdf`; }; createPDF('super_secret_file'); // 'super_secret_file.pdf' const createCapitalizedPDF = capitalizer(createPDF); createCapitalizedPDF('super_secret_file'); // 'SUPER_SECRET_FILE.pdf' createCapitalizedPDF('northcoders_curriculum'); // 'NORTHCODERS_CURRICULUM.pdf' // Example 2 const sayHello = (person) => { return `hello ${person}`; }; sayHello('Paul'); // 'hello Paul' const shoutHello = capitalizer(sayHello); shoutHello('Paul'); // 'hello PAUL' shoutHello('Haz'); // 'hello HAZ' ``` ### 2. after `after` should be able to accept two arguments (a number and a function) and it should return another function. That returned function should invoke the _original_ passed `func` when invoked `n` or more times: - Before and including `n` number of calls is reached, it should return `undefined` - After being invoked `n` times it should behave _exactly_ as the original `func` would - It should be able to accept any number of arguments to account for the unknown amount of arguments `func` will need to accept ```js // Example 1 function doubleNum(num) { return num * 2; } const doubleAfterTwoCalls = after(2, doubleNum); doubleAfterTwoCalls(5); // undefined doubleAfterTwoCalls(5); // undefined doubleAfterTwoCalls(5); // 10 doubleAfterTwoCalls(7); // 14 // Example 2 - multiple arguments function sumFourNumbers(a, b, c, d) { return a + b + c + d; } const sumFourNumbersAfter3Calls = after(3, sumFourNumbers); sumFourNumbersAfter3Calls(1, 2, 3, 4); // undefined sumFourNumbersAfter3Calls(1, 2, 3, 4); // undefined sumFourNumbersAfter3Calls(1, 2, 3, 4); // undefined sumFourNumbersAfter3Calls(1, 2, 3, 4); // 10 sumFourNumbersAfter3Calls(10, 32, 6, 12); // 60 ``` ### 3. before This function should essentially exhibit the _opposite_ behaviour to `after` but with a twist. - `before` should accept two arguments - `n` - a number - `func` - a function - This function should return another function - That returned function should invoke the _original_ passed `func` when invoked _UP TO_ `n` times - Before `n` number of calls is reached, it should behave _exactly_ as the original `func` would - **After being invoked `n` times it should always provide the same return value** - This return value should be the same provided by the _last_ invocation _before_ reaching `n` regardless of the arguments provided to subsequent calls. **Examples:** ```js // Example 1 function capitaliseString(str) { return str.toUpperCase(); } const capitaliseBeforeThreeCalls = before(3, capitaliseString); capitaliseBeforeThreeCalls('hello'); // HELLO capitaliseBeforeThreeCalls('northcoders'); // NORTHCODERS // upon reaching `n` number of calls - it should always return the most recent return value capitaliseBeforeThreeCalls('hello'); // NORTHCODERS capitaliseBeforeThreeCalls(''); // NORTHCODERS capitaliseBeforeThreeCalls('not northcoders please'); // NORTHCODERS // Example 2 function sum(a, b, c) { return a + b + c; } const sumBeforeFourCalls = before(4, sum); sumBeforeFiveCalls(1, 2, 3); // 6 sumBeforeFiveCalls(10, 11, 12); // 33 sumBeforeFiveCalls(4, 1, 9); // 14 // `n` number of calls is reached sumBeforeFiveCalls(100, 200, 300); // 14 sumBeforeFiveCalls(10); // 14 sumBeforeFiveCalls(93, 4, 7.2); // 14 ``` ## More Challenges If you have managed to implement the above using full TDD, bravo! Remember [lodash](https://lodash.com/docs/4.17.15)? Now it is time to try and implement some functions from another library... _Ramda_! Here are the [Docs](https://ramdajs.com/docs/) & the [NPM](https://www.npmjs.com/package/ramda) page. Ramda is another popular utility library in JavaScript. It strives for purity and is designed to facilitate the composition of functions in nice functional patterns. Reimplement the following Rambda functions using TDD: - once - nthArg - juxt
19980bd23ce06a7f02888a942ceb53128ee203d6
[ "JavaScript", "Markdown" ]
3
JavaScript
Dutton1990/fun-testing-hofs-nc
88077775e32cf2796bd57f7a3261797fa397dafe
c158275c62d28b91e543520e8536209b96230d6b
refs/heads/master
<repo_name>Rafasystec/genius-core<file_sep>/genius-core/src/main/java/br/com/barcadero/genius/core/exceptions/ExceptionErroMsg.java package br.com.barcadero.genius.core.exceptions; public class ExceptionErroMsg extends Exception{ } <file_sep>/genius-core/src/main/java/br/com/barcadero/genius/core/role/RoleClient.java package br.com.barcadero.genius.core.role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.barcadero.genius.core.dao.DAOClient; import br.com.barcadero.genius.core.exceptions.ValidationException; import br.com.barcadero.genius.persistence.model.Client; @Service public class RoleClient extends RoleSuperClass<Client> { public RoleClient() { System.out.println(this.getClass().getName()); } @Autowired private DAOClient daoClient; @Override public Client insert(Client entidade) throws ValidationException { return daoClient.insert(entidade); } @Override public void delete(long codigo) throws ValidationException { daoClient.delete(codigo); } @Override public Client update(Client entidade) throws ValidationException { return daoClient.update(entidade); } @Override public Client find(long codigo) throws ValidationException { return daoClient.find(codigo); } } <file_sep>/genius-core/src/main/java/br/com/barcadero/genius/core/dao/DAOClient.java package br.com.barcadero.genius.core.dao; import javax.persistence.NoResultException; import org.springframework.stereotype.Repository; import br.com.barcadero.genius.persistence.model.Client; @Repository public class DAOClient extends SuperClassDAO<Client> { public DAOClient() { } @Override public Client find(long codigo) { try{ return getManager().find(Client.class, codigo); }catch(NoResultException e){ return null; } } public void exempleHowToManuallyRemoveInstancesFromPersistenceContext() { Client exemplo = find(1l); //You don't have to wait for the persistence context to close. //You can evict entity instances manually getManager().detach(exemplo); if(getManager().contains(exemplo)){ //It will never enter here because the entity was removed } //Any changes has no effect } }
6d28b58edf7640ccde5f1a1c1848203701c2e814
[ "Java" ]
3
Java
Rafasystec/genius-core
e05dff32d3752e8514de7f9383a0542ea8f68333
091ce5188485967280ca46c0c9036067884c5a44
refs/heads/master
<repo_name>Pipeliners6/Lifestyle<file_sep>/VraagReactie.java package org.module.system.pojos.hack; public class VraagReactie { private String vraag; private String reactie; private Boolean isValid; /** * @param vraag * @param reactie * @param isValid */ public VraagReactie(String vraag, String reactie, Boolean isValid) { super(); this.vraag = vraag; this.reactie = reactie; this.isValid = isValid; } public String getVraag() { return vraag; } public void setVraag(String vraag) { this.vraag = vraag; } public String getReactie() { return reactie; } public void setReactie(String reactie) { this.reactie = reactie; } public Boolean getIsValid() { return isValid; } public void setIsValid(Boolean isValid) { this.isValid = isValid; } } <file_sep>/Reacties.java package org.module.system.pojos.hack; public class Reacties { public static final String REACTIE1 = "1"; public static final String REACTIE2 = "2"; public static final String REACTIE3 = "3"; } <file_sep>/Topics.java package org.module.system.pojos.hack; public class Topics { public static final String TOPIC_HIV = "HIV"; public static final String TOPIC_2 = "2"; private String topic; private SubTopics subTopic; /** * */ public Topics(String topic) { this.topic = topic; if (topic.equalsIgnoreCase(TOPIC_HIV)) { subTopic = new SubTopics(TOPIC_HIV); } } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public SubTopics getSubTopic() { return subTopic; } public void setSubTopic(SubTopics subTopic) { this.subTopic = subTopic; } } <file_sep>/Vragen.java package org.module.system.pojos.hack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Vragen { private Map<String, List<VraagReactie>> vragen; public Vragen(List<String> subTopics) { if (subTopics != null) { vragen = new HashMap<>(); for (String subTopic : subTopics) { if (subTopic.equalsIgnoreCase(SubTopics.INFO_PROMOTIE)) { List<VraagReactie> list = new ArrayList<>(); list.add(new VraagReactie(VRAAG1, Reacties.REACTIE1, false)); list.add(new VraagReactie(VRAAG2, Reacties.REACTIE2, true)); list.add(new VraagReactie(VRAAG3, Reacties.REACTIE3, false)); vragen.put(subTopic, list); } else if (subTopic.equalsIgnoreCase(SubTopics.OMGANG_OCCUPATIE)) { } } } } private static final String VRAAG1 = "1"; private static final String VRAAG2 = "2"; private static final String VRAAG3 = "3"; private static final String VRAAG4 = "4"; }
a421f399bfa428a539a486e3025e602569847575
[ "Java" ]
4
Java
Pipeliners6/Lifestyle
b47090f759371d88d366b1faf34e8ff8b6df31c5
f3340ef376950551acbe2a0d4f3f4500ba02db1f
refs/heads/master
<repo_name>kevinortizfis/collections_practice-online-web-sp-000<file_sep>/collections_practice.rb def sort_array_asc(array) array.sort end def sort_array_desc(array) array.sort.reverse end def sort_array_char_count(array) array.sort do |a,b| a.length<=>b.length end end def swap_elements(array) array.sort do |a,b| a[-1]<=>b end end def reverse_array(array) array.reverse end def kesha_maker(array) array.each do |name| name[2] = "$" end end def find_a(array) a = "a" || "A" array.select{|word| word[0] == a} end def sum_array(array) array.sum end def add_s(array) i = 0 dos = %w() while i < array.length if i != 1 dos << "#{array[i]}" + "s" i += 1 else dos << "#{array[i]}" i += 1 end end dos end
ce815a9e70e96ea5efe8bb27720bb8826e08a2aa
[ "Ruby" ]
1
Ruby
kevinortizfis/collections_practice-online-web-sp-000
be1ec9f4ee62a3d9df8e9932611d416bafa71938
0bd7c7237bd3e2746d23d7709c977903d3c01e31
refs/heads/master
<repo_name>csamuelr/web-atividade3<file_sep>/README.md # web-atividade3 <file_sep>/parcelador.js $(document).ready(function(){ $('.resultado').fadeOut(0); $('#calc_parcelas').click(function(e){ e.preventDefault(); var valor_inicial = $('#val').val(); var parcelas = $('#parcela').val(); var juros = 0; var valor; valor_inicial = parseFloat(valor_inicial); parcelas = parseFloat(parcelas); if(parcelas > 5){ alert('O parcelamento em mais de 5 vezes tem acrescido ao seu valor juros de 10%.'); juros = (valor_inicial * 0.10); valor = valor_inicial + juros; } else{ valor = valor_inicial } var valor_parcela = Number(valor/parcelas).toFixed(2); $('.resultado').fadeIn('slow'); tab = '<tr>' + '<th>Valor</th>' + '<th>Juro</th>' + '<th>Valor Final</th>' + '</th>'; $('#thead-info').html(tab); tab = '<td>' + valor_inicial + '</td>' + '<td>' + juros + '</td>' + '<td>' + valor + '</td>' $('#tbody-info').html(tab); var html = '<tr>'; for (var i = 0; i < parcelas; i++) { html = html + '<th>Parcela ' + (i + 1) + ' </th>\n'; } html = html + ' </tr>'; $('#thead').html(html); html = '<tr>'; for (var i = 0; i < parcelas; i++) { html = html + '<td> ' + valor_parcela + ' </td>\n'; } html = html + '</tr>'; $('#tbody').html(html); }); })
de4ed48977a7e126f8fa5dd37fdef18e3cc4a6d1
[ "Markdown", "JavaScript" ]
2
Markdown
csamuelr/web-atividade3
0bb06cdb51bab2c73e5a55d67b2e9934b1c46095
e4a5c2354da98eab18be4819bc80a6b4fe2c36c4
refs/heads/master
<repo_name>hydium/project1<file_sep>/.bash_history ls cd .. ls cd team17b cd team17a cd team16a cd team18b ls cd .. cd team18a ls cp /shared/pintos . -r ls cd pintos ls cd src ls vim Makefile cd threads ls make ../utils/pintos run alarm-multiple echo 'export PATH=$PATH:~/pintos/src/utils/' >> ~/.bashrc source ~/.bashrc echo 'export PATH=$PATH:~/pintos/src/utils/' >> ~/.bashrc source ~/.bashrc pintos -v ---q run alarm-multiple pintos -v -- -q run alarm-multiple make check make grade cd build/grade cd /build/grade cd ../build/grade cd build ls vim grade cd .. make clean ls vim Make.tests ls cd .. cd tests cd threads ls vim Make.tests ls cd .. cd threads ls cd build ls make check ls make grade ls cd build ls cd .. cd test cd tests cd threads ls vim Make.tests vim Grading make grade cd .. cd threads make grade cd .. cd tests cd threads vim Grading make grade make clean vim Grading cd .. cd threads make grade make clean make grade>result ls vim result make clean rm -rf build ls make clean make grade>result ls cd build ls :q cd .. ls vim result make check make grade cd build vim grade vim tests cd .. cd tests cd threads ls :q cd .. cd threads ls cd .. cd tests cd threads vim Make.tests echo What the fuck? vim Make.tests echo What the fuck? ls echo What the fuck? cd .. cd threads cd build ls vim grade cd .. vim results vim result ls cd pintos ls s ls cd .. ls wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate cd pintos wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate cd .. wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate ls cd .. ls cd team18a ls cd pintos ls cd src ls cd .. ls cd pintos cd src ls rm adi_zver.txt ls cd pintos ls cd srcs cd src ls cd threads ls make clean ls rm result ls make cd build pintos run alarm-multiple pintos -v -- run alarm-multiple pintos ls cd pintos cd src ls cd threads ls cd build macke check make check FAIL tests/threads/priority-condvar ls cd tests ls cd threads ls :q cd .. ls FAIL tests/threads/priority-condvar make ls make cd .. ls make grade ls make clean make ls cd build ls make make check ls cd .. ls cd build make make check ls rm results make check ls rm results ls make check ls cd .. ls cd pintos cd src ls cd threads ls cd build ls cd .. ls cd built cd .. cd src cd tests ls cd threads ls cd Makes.tests vim Make.tests cd .. cd threads ls make clean ls make ls make clean make check ls cd build sl ls cd .. make clean make cd build ls cd .. make clean make grade ls cd build ls make make grade make check cd .. make make clean ls make cd build ls make make check ls make grade ls pintos pintos run alarm-multiple make grade make check make grade make check ls cd .. make clean make cd build cd .. ls vim init.c cd build pintos run alarm-multiple cd .. cd build pintos run alarm-multiple cd .. make clean make cd build pintos run alarm-multiple cd .. make make clean ls cd pintos cd src cd threads ls make cd build ls pintos run alarm-multiple ls cd tests ls cd threads ls cd .. cd pintod cd pintos cd src cd threads ls cd build pintos run alarm-multipl cd tests ls cd threads ls vim tests.c cd .. pintos run alarm-single ls cd pintos git init git clone https://github.com/hydium/Operating-Systems-and-Lab-Project-1.git ls cd Operating-Systems-and-Lab-Project-1 ls cd src ls cd .. rm -rf Operating-Systems-and-Lab-Project-1 ls cd .. ls cd pintos cd pintos cd src ls cs thread cd threads cd build pintos run alarm-priority make check pintos run alarm-priority cd .. make clean make cd build pintos run alarm-multiple make check pintos run alarm-multiple cd .. make clean make cd build ls pintos run alarm-multiple pintos run alarm-priority cd .. make clean make cd build ls pintos run alarm-multiple cd .. make clean make cd build ls cd .. make make clean make cd build ls pintos run alarm-multiple ls cd .. make clean make cd pintos cd src cd threads cd build pintos-gdb kernel.o cd ls cd pintos ls git init git clone https://github.com/hydium/Operating-Systems-and-Lab-Project-1.git ls cd Operating-Systems-and-Lab-Project-1/ ls cd .. ls cd ls rm -rf pintos git init git clone https://github.com/hydium/Operating-Systems-and-Lab-Project-1.git cd Operating-Systems-and-Lab-Project-1/ ls cd .. ls cd Operating-Systems-and-Lab-Project-1/ cd src ls cd threads make check ls cd build make check ls make make grade cd .. make clean make cd build make check ls make check make cd .. make check make checl make check pintos run alaem-single pintos run alarm-single cd .. ls cd .. ls cd .. ls cd team18a ls cd .. ls cd team18a cd team18b cd .. cd team18b ls cp -r /home/team18a cp -r /home/team18a/ cp -r /home/team18a/ . ls cd .. cd team18a ls rm -rf Operating-Systems-and-Lab-Project-1/ ls cd .. cd team18a ls -a rm -rf .git git init git clone https://github.com/hydium/project1 ls cd project1 cd pintos cd src cd threads make clean make make check make checl make check pintos cd .. ls ls -a cd pintos cd src cd threads make check ls cd .. ls vim Makefile.kernel cd threads ls make clean make make check cd build make checl make check make grade cd .. ls cd .. cd team18a ls cd project1 ls cd pintos ls cd src ls cd threads ls cd .. cp -r /home/team18a cp -r /home/team18a . ls cd .. ls cd project1 ls cd team18a ls cd .. rm -rf team18a cd .. cp -r /home/project1/pintos . ls cp -r /home/project1/pintos ls cp -r /home/team18a/project1/pintos /home/team18a/ ls rm -rf project1 ls cd pintos cd src ls cd .. ls ls -a cd pinto cd pintos cd src cd threads make clean make check cd .. ls cd .. cd team18a ls -a cd src ls cd pintoa cd pintos cd src cd threads make clean make make check vim threads.c vim thread.c make clean make make check cd .. ls cd .. ls cd team18a ls ls -a rm -rf .git git init git remote add origin https://github.com/hydium/project1 ls git pull https://github.com/hydium/project1 ls git pull https://github.com/hydium/project1 cd pintos cd src cd threads ls cd build cd .. vim thread.c make clean make check cd build pintos run alarm-single cd .. make clean make cd build cd .. pintos run alarm-single gdb make clean make pintos run alarm-single cd .. cd ,, cd .. cd cd pintos cd src cd threads make clean make pintos run alarm-single pintos run alarm-priority make clean make pintos run alarm-single make check make make clean make mak make make clean make make check make grade make clean make make check make clean make make check pintos run alarm-single pintos run alarm-simultaneous make check make clean make make check make claen make clean make check make clean make make check make clean make checl make check make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single gdb make clean make make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make cleab make clean make pintos run alarm-single mke make pintos run alarm-single cd .. cd utilsof the Pintos documentation for more information. of the Pintos documentation for more information. cd threads pintos --gdb -- run alarm-single make clean make pintos run alarm-single pintos --gdb -- run alarm-single cd pitnos cd pintos cd src cd threads pintos --gdb -- run alarm-single cd pintos/src/threads/buikd cd pintos/src/threads/build pintos-gdb kernel.o ls cd pintos cd src cd threads make make clean make make make check make clean make make check make clean make make make check make clean make make check make clean make make check pintos run alarm-single make clean make pintos run alarm-single make check make clean make make checl make check make clean make make check make clean make make checl make check pintos run priority-fifo cd pintos pintos-gdb kernel.o cd pintos cd src cd threads make clean make make check pintos run alarm-simultaneous make clean make make check pintos run priority-sema make check make clean make make check make clean make make check make clean make pintos run priority-sema make make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make make check pintos run priority-sema make make clean make pintos run priority-sema make clean make pintos run priority-sema make clean ls make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make make clean make make clean make pintos run priority-sema make clean make make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make make clean make make clean make make clean make pintos run priority-sema pintos --gdb -- run priority-sema cd pintos/src/threads/build pintos-gdb kernel.o echo idi nahui suka echo rabotai blyat pintos-gdb kernel.o cd pintos/src/threads pintos --gdb -- run priority-sema make clean make pintos run priority-sema pintos --gdb -- run priority-sema cd pintos cd src cd threads pintos --gdb -- run priority-sema cd pintos/src/threads/build pintos-gdb kernel.o ls cd pintos cd src cd threads make cleab make clean mak make make check pintos run priority-sema make clean nake make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make checl make check pintos run alarm-single make clean make pintos run alarm-sing make check make clean make pintos run priority-sema make make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make clean make pintos run priority-sema make check pintos run priority-sema make clean make check pintos run priority-sema make clean make make check cd .. git add . git commit -m "priority-sema done" git config user.name "<EMAIL>" git push origin master ls -a git push origin master git remote git remote origin git remote origin https://github.com/hydium/project1 git remote origin "https://github.com/hydium/project1" git remote origin git remote add https://github.com/hydium/project1 git remote add origin https://github.com/hydium/project1 git remove remote git push -u origin master git show-ref rm -rf git git init git add . git remote add origin 'https://github.com/hydium/project1' git remote set-url origin 'https://github.com/hydium/project1' git commit -m "priority-sema done" git config user.email "<EMAIL>" git commit -m "priority-sema done" git push origin master git remote set-url origin https://github.com/hydium/project1 git config user.email "<EMAIL>" git commit -m "priority-sema done" git push origin master git remote -v git push origin master git push -f origin master cd pintos/src/threads ls make check make clean make make check make clean make check make clean make check make clean make make check make clean make check make clean make make check pintos run priority-preempt make check make clean make make check make clean make make check cd .. git add . git commit -m "priority-fifo and alarm-simultaneous done" git push origin master cd pintos/src.threads cd pintos/src/threads make clean make check make clean make make check cd .. git add . git commit -m "Some redundant code is removed" git push origin master cd pintos/src/threads pintos run priority-donate-one make check make clean make check ls cd pintos/src/threads make clean make make clean make make clean make make celna make clean make make check make make clean make make clean make make clean make make check make clean make make check make clean make make check pintos run alarm-single make clean make make check make clean make make clean make make clean make ../../threads/thread.c:592: error: incompatible types in assignment make clean make ../../threads/synch.c:321: error: incompatible type for argument 1 of ‘list_end’ make clean make make check make clean make make check make clean make make check make clean make check cd pintos/src/threasd cd pintos/src/threads make clean make make chcek make check pintos run alarm-single make clean make pintos run alarm-single make clean make check make clean make check make cleab make clean make make check pintos --gdb -- run pintos --gdb -- run alarm-single pintos --gdb -- run cd pintos/src/threads/build ls ls -a git remote git remote origin git remote -v git pull https://github.com/hydium/project1.git ls git checkout donation-attempt git branch donation-attempt git checkout donation-attempt git pull https://github.com/hydium/project1.git donation-attempt git pull https://github.com/hydium/project1.git donation_attempt git branch git branch -d donation-attempt git checkout master git branch -d donation-attempt git branch donation_attempt git checkout donation_attempt git pull https://github.com/hydium/project1.git donation_attempt git fetch https://github.com/hydium/project1.git donation_attempt ls cd pintos git fetch https://github.com/hydium/project1.git donation_attempt git merge git fetch -all git fetch --all git reset --hard origin/donation_attempt git branch make cleam make clean cd src/ cd threads/ make clean make check make clean make check make clean make check make clean make pintos run alarm-single make clean make check make clean make check pintos run alarm-simultaneous make clean make make clean make make clean make make clean make make check make clean make check make clean make check make clean make make check make clean make make check make clean make make check make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single make check pintos run alarm-single pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make make clean make make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean pintos run alarm-simultaneous make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous make clean make pintos run alarm-simultaneous cd pintos/ cd s cd src/ cd threads/ ls make clean make check make clean make check make clean make check make clean make make check make clean make make clean make make clean make make check ls cd pintos/ cd src/ cd threads/ make clean make pintos run priority-fifo make clean make pintos run priority-fifo make clean make pintos run priority-fifo make clean make pintos run priority-fifo make clean make pintos run alarm-single make clean make pintos run alarm-single make clean make pintos run alarm-single pintos run alarm-simultaneous make clean make pintos --gdb -- run alarm-simultaneous cd pintos/ cd src/ cd threads/ cd build/ pintos-gdb kernel.o cd pintos/ cd s cd src/ cd threads/ pintos --gdb -- run alarm-simultaneous make clean make make check cd s cd pintos/ cd src/ cd threads/ cd build/ ls pintos-gdb kernel.o cd pintos/ cd src/ cd threads/ make clean make pintos run alarm-single cd pintos/src/threads/ cd build cd .. cd build pintos-gdb kernel.o cd pintos/ cd src/ cd threads/ make clean make make clean make pintos --gdb -- run alarm-simultaneous cd pintos/ cd s cd src/ cd threads/ pintos --gdb -- run alarm-simultaneous make clean make pintos --gdb -- run alarm-simultaneous cd pintos/src/threads/build pintos-gdb kernel.o cd pintos/src/ cd threads/ pintos --gdb -- run alarm-simultaneous make clean make pintos run alarm-single make clean make pintos run alarm-single make check pintos run alarm-simultaneous pintos --gdb -- run pintos --gdb -- run alarm-simultaneous cd pintos/src/threads/build/ pintos-gdb kernel.o cd pintos/src/threads/build/ pintos-gdb kernel.o cd pintos/src/threads/ pintos --gdb -- run alarm-simultaneous make clean make make check pintos run alarm-single make clean make make clean make make clean make make clean make make celean  make clean make make clean make make check pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one make clean make pintos run priority-donate-one cd pintos/src/threads/ make clean make make clean make make check pintos run alarm-single make clean make pintos run alarm-single make check make clean make make check make clean make check make clean make check make clean make check make clean make make check make clean make make check make clean make make check make clean make check make clean make check make clean make check cd .. git branch git add . git commit -m "Everything is done except condvar" git config user.name "hydium" git commit -m "Everything is done except condvar" git push origin master git push -f origin master cd pintos/ tar –czvf [team18].tar.gz src document tar –czvf team18.tar.gz src document tar –czvf team18.tar.gz src tar -czvf team18.tar.gz src tar -czvf team18.tar.gz src document tar -czvf team18.tar.gz src src/document tar -czvf team18.tar.gz src pintos/src/document tar -czvf team18.tar.gz src document.docx tar -czvf team18.tar.gz src team18.docx cd pintos/src/threads/build/ pintos-gdb kernel.o cd pintos/src/threads/ make clean make check cd .. git add . git commit -m "Everything is done except condvar" git push -f origin master git checkout master git add . git commit -m "Everything is done except condvar" git push origin master git push -f origin master cd pintos/src/threads make clean make cd .. git checkout donation_attempt git stash git checkout master git checkout donation_attempt make clean cd pintos/src/threads make clean make check make clean make check make clean make check make clean make check make clean make check make clean make check pintos run priority-condvar make clean make pintos run priority-condvar make clean make pintos run priority-condvar make check pintos run priority-condvar make clean make check make clean make check make clean make check make clean make pintos run priority-condvar make clean make pintos run priority-condvar pintos --gdb -- run priority-condvar make clean make make clean make pintos run priority-condvar make check make clean make check make grade
2aaa026befdf3f17bd2aa61fafce1314868eeb40
[ "Shell" ]
1
Shell
hydium/project1
be4a8aa65dcb202227d18521c2bd16aa943954c2
a737fe07bf8a85770dd5e910bcae54b30df65948
refs/heads/master
<repo_name>zszqwe/dp2<file_sep>/DigitalPlatform.CirculationClient/ClientInfo.cs using System; using System.Deployment.Application; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Windows.Forms; using log4net; // using DigitalPlatform; using DigitalPlatform.IO; using DigitalPlatform.LibraryClient; using DigitalPlatform.Text; using DigitalPlatform.Core; namespace DigitalPlatform.CirculationClient { /// <summary> /// 存储各种程序信息的全局类 /// </summary> public static class ClientInfo { public static string ProgramName { get; set; } public static Form MainForm { get; set; } /// <summary> /// 前端,的版本号 /// </summary> public static string ClientVersion { get; set; } public static Type TypeOfProgram { get; set; } /// <summary> /// 数据目录 /// </summary> public static string DataDir = ""; /// <summary> /// 用户目录 /// </summary> public static string UserDir = ""; /// <summary> /// 错误日志目录 /// </summary> public static string UserLogDir = ""; /// <summary> /// 临时文件目录 /// </summary> public static string UserTempDir = ""; // 附加的一些文件名非法字符。比如 XP 下 Path.GetInvalidPathChars() 不知何故会遗漏 '*' static string spec_invalid_chars = "*?:"; public static string GetValidPathString(string strText, string strReplaceChar = "_") { if (string.IsNullOrEmpty(strText) == true) return ""; char[] invalid_chars = Path.GetInvalidPathChars(); StringBuilder result = new StringBuilder(); foreach (char c in strText) { if (c == ' ') continue; if (IndexOf(invalid_chars, c) != -1 || spec_invalid_chars.IndexOf(c) != -1) result.Append(strReplaceChar); else result.Append(c); } return result.ToString(); } static int IndexOf(char[] chars, char c) { int i = 0; foreach (char c1 in chars) { if (c1 == c) return i; i++; } return -1; } /// <summary> /// 指纹本地缓存目录 /// </summary> public static string FingerPrintCacheDir(string strUrl) { string strServerUrl = GetValidPathString(strUrl.Replace("/", "_")); return Path.Combine(UserDir, "fingerprintcache\\" + strServerUrl); } public static string Lang = "zh"; // parameters: // product_name 例如 "fingerprintcenter" public static void Initial(string product_name) { ClientVersion = Assembly.GetAssembly(TypeOfProgram).GetName().Version.ToString(); if (ApplicationDeployment.IsNetworkDeployed == true) { // MessageBox.Show(this, "network"); DataDir = Application.LocalUserAppDataPath; } else { DataDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } UserDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), product_name); PathUtil.TryCreateDir(UserDir); UserTempDir = Path.Combine(UserDir, "temp"); PathUtil.TryCreateDir(UserTempDir); UserLogDir = Path.Combine(UserDir, "log"); PathUtil.TryCreateDir(UserLogDir); InitialConfig(); var repository = log4net.LogManager.CreateRepository("main"); log4net.GlobalContext.Properties["LogFileName"] = Path.Combine(UserLogDir, "log_"); log4net.Config.XmlConfigurator.Configure(repository); LibraryChannelManager.Log = LogManager.GetLogger("main", "channellib"); _log = LogManager.GetLogger("main", "fingerprintcenter"); // 启动时在日志中记载当前 .exe 版本号 // 此举也能尽早发现日志目录无法写入的问题,会抛出异常 WriteInfoLog(Assembly.GetAssembly(typeof(ClientInfo)).FullName); } public static void Finish() { SaveConfig(); } #region Log static ILog _log = null; public static ILog Log { get { return _log; } } // 写入错误日志文件 public static void WriteErrorLog(string strText) { WriteLog("error", strText); } public static void WriteInfoLog(string strText) { WriteLog("info", strText); } // 写入错误日志文件 // parameters: // level info/error // Exception: // 可能会抛出异常 public static void WriteLog(string level, string strText) { // Console.WriteLine(strText); if (_log == null) // 先前写入实例的日志文件发生过错误,所以改为写入 Windows 日志。会加上实例名前缀字符串 WriteWindowsLog(strText, EventLogEntryType.Error); else { // 注意,这里不捕获异常 if (level == "info") _log.Info(strText); else _log.Error(strText); } } // 写入 Windows 日志 public static void WriteWindowsLog(string strText) { WriteWindowsLog(strText, EventLogEntryType.Error); } #endregion #region 未捕获的异常处理 // 准备接管未捕获的异常 public static void PrepareCatchException() { Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } static bool _bExiting = false; // 是否处在 正在退出 的状态 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (_bExiting == true) return; Exception ex = (Exception)e.ExceptionObject; string strError = GetExceptionText(ex, ""); // TODO: 把信息提供给数字平台的开发人员,以便纠错 // TODO: 显示为红色窗口,表示警告的意思 bool bSendReport = true; DialogResult result = MessageDlg.Show(MainForm, $"{ProgramName} 发生未知的异常:\r\n\r\n" + strError + "\r\n---\r\n\r\n点“关闭”即关闭程序", $"{ProgramName} 发生未知的异常", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1, ref bSendReport, new string[] { "关闭" }, "将信息发送给开发者"); // 发送异常报告 if (bSendReport) CrashReport(strError); } static string GetExceptionText(Exception ex, string strType) { // Exception ex = (Exception)e.Exception; string strError = "发生未捕获的" + strType + "异常: \r\n" + ExceptionUtil.GetDebugText(ex); Assembly myAssembly = Assembly.GetAssembly(TypeOfProgram); strError += $"\r\n{ProgramName} 版本: " + myAssembly.FullName; strError += "\r\n操作系统:" + Environment.OSVersion.ToString(); strError += "\r\n本机 MAC 地址: " + StringUtil.MakePathList(SerialCodeForm.GetMacAddress()); // TODO: 给出操作系统的一般信息 // MainForm.WriteErrorLog(strError); return strError; } static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { if (_bExiting == true) return; Exception ex = (Exception)e.Exception; string strError = GetExceptionText(ex, "界面线程"); bool bSendReport = true; DialogResult result = MessageDlg.Show(MainForm, $"{ProgramName} 发生未知的异常:\r\n\r\n" + strError + "\r\n---\r\n\r\n是否关闭程序?", $"{ProgramName} 发生未知的异常", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2, ref bSendReport, new string[] { "关闭", "继续" }, "将信息发送给开发者"); { if (bSendReport) CrashReport(strError); } if (result == DialogResult.Yes) { _bExiting = true; Application.Exit(); } } static void CrashReport(string strText) { MessageBar _messageBar = null; _messageBar = new MessageBar { TopMost = false, Text = $"{ProgramName} 出现异常", MessageText = "正在向 dp2003.com 发送异常报告 ...", StartPosition = FormStartPosition.CenterScreen }; _messageBar.Show(MainForm); _messageBar.Update(); int nRet = 0; string strError = ""; try { string strSender = ""; //if (MainForm != null) // strSender = MainForm.GetCurrentUserName() + "@" + MainForm.ServerUID; // 崩溃报告 nRet = LibraryChannel.CrashReport( strSender, $"{ProgramName}", strText, out strError); } catch (Exception ex) { strError = "CrashReport() 过程出现异常: " + ExceptionUtil.GetDebugText(ex); nRet = -1; } finally { _messageBar.Close(); _messageBar = null; } if (nRet == -1) { strError = "向 dp2003.com 发送异常报告时出错,未能发送成功。详细情况: " + strError; MessageBox.Show(MainForm, strError); // 写入错误日志 WriteErrorLog(strError); } } // 写入 Windows 系统日志 public static void WriteWindowsLog(string strText, EventLogEntryType type) { try { EventLog Log = new EventLog("Application"); Log.Source = $"{ProgramName}"; Log.WriteEntry(strText, type); } catch { } } #endregion static ConfigSetting _config = null; public static ConfigSetting Config { get { return _config; } } public static void InitialConfig() { if (string.IsNullOrEmpty(UserDir)) throw new ArgumentException("UserDir 尚未初始化"); string filename = Path.Combine(UserDir, "settings.xml"); _config = ConfigSetting.Open(filename, true); } public static void SaveConfig() { // Save the configuration file. if (_config != null) { _config.Save(); _config = null; } } public static void AddShortcutToStartupGroup(string strProductName) { if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment != null && ApplicationDeployment.CurrentDeployment.IsFirstRun) { string strTargetPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); strTargetPath = Path.Combine(strTargetPath, strProductName) + ".appref-ms"; string strSourcePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); strSourcePath = Path.Combine(strSourcePath, strProductName) + ".appref-ms"; File.Copy(strSourcePath, strTargetPath, true); } } public static void RemoveShortcutFromStartupGroup(string strProductName) { if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment != null && ApplicationDeployment.CurrentDeployment.IsFirstRun) { string strTargetPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); strTargetPath = Path.Combine(strTargetPath, strProductName) + ".appref-ms"; try { File.Delete(strTargetPath); } catch { } } } public static NormalResult InstallUpdateSync() { if (ApplicationDeployment.IsNetworkDeployed) { Boolean updateAvailable = false; ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment; try { updateAvailable = ad.CheckForUpdate(); } catch (DeploymentDownloadException dde) { // This exception occurs if a network error or disk error occurs // when downloading the deployment. return new NormalResult { Value = -1, ErrorInfo = "The application cannt check for the existence of a new version at this time. \n\nPlease check your network connection, or try again later. Error: " + dde }; } catch (InvalidDeploymentException ide) { return new NormalResult { Value = -1, ErrorInfo = "The application cannot check for an update. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message }; } catch (InvalidOperationException ioe) { return new NormalResult { Value = -1, ErrorInfo = "This application cannot check for an update. This most often happens if the application is already in the process of updating. Error: " + ioe.Message }; } catch (Exception ex) { return new NormalResult { Value = -1, ErrorInfo = "检查更新出现异常: " + ExceptionUtil.GetDebugText(ex) }; } if (updateAvailable == false) return new NormalResult { Value = 0, ErrorInfo = "没有发现更新" }; try { ad.Update(); return new NormalResult { Value = 1, ErrorInfo = "自动更新完成。重启可使用新版本" }; // Application.Restart(); } catch (DeploymentDownloadException dde) { return new NormalResult { Value = -1, ErrorInfo = "Cannot install the latest version of the application. Either the deployment server is unavailable, or your network connection is down. \n\nPlease check your network connection, or try again later. Error: " + dde.Message }; } catch (TrustNotGrantedException tnge) { return new NormalResult { Value = -1, ErrorInfo = "The application cannot be updated. The system did not grant the application the appropriate level of trust. Please contact your system administrator or help desk for further troubleshooting. Error: " + tnge.Message }; } catch (Exception ex) { return new NormalResult { Value = -1, ErrorInfo = "自动更新出现异常: " + ExceptionUtil.GetDebugText(ex) }; } } return new NormalResult(); } } }
51e18a7b04b4ef9cf8a51172b10d9eb20be3d89b
[ "C#" ]
1
C#
zszqwe/dp2
ef859b2ba0fbf347165dcf6fcddce3fda6b8bb29
571e6ddd4f2c2e2b6578a11e831974176aa2713c
refs/heads/master
<file_sep>package model; public class UserBeans { private int id; private String loginId; private String name; private String birthDate; private String password; private String createDate; private String updateDate; public UserBeans(String loginId, String name) { this.loginId = loginId; this.name = name; } public UserBeans(int id) { this.id = id; } public UserBeans (int id, String loginId, String name,String birthDate, String password, String createDate, String updateDate) { this.id = id; this.loginId = loginId; this.name = name; this.birthDate = birthDate; this.password = <PASSWORD>; this.createDate = createDate; this.updateDate = updateDate; } public UserBeans (String password,String name,String birthDate) { this.password = <PASSWORD>; this.name = name; this.birthDate = birthDate; } public UserBeans (String loginId, String name,String birthDate, String password) { this.loginId = loginId; this.name = name; this.birthDate = birthDate; this.password = <PASSWORD>; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLoginId() { return loginId; } public void setLoginId(String loginId) { this.loginId = loginId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getUpdateDate() { return updateDate; } public void setUpdateDate(String updateDate) { this.updateDate = updateDate; } } <file_sep>package controller; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.DatatypeConverter; import dao.UserDao; import model.UserBeans; /** * Servlet implementation class NewUsersServlet */ @WebServlet("/NewUsersServlet") public class NewUsersServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public NewUsersServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String id = request.getParameter("id"); UserDao infoDao = new UserDao(); UserBeans user = infoDao.UserInfo(id); request.setAttribute("user", user); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/NewUser.jsp"); dispatcher.forward(request, response ); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); UserDao loginDao = new UserDao(); List<UserBeans> userList =loginDao.findAll(); String loginId = request.getParameter("loginId"); String password = request.getParameter("password"); String re_password = request.getParameter("re_password"); String name = request.getParameter("name"); String birthDate = request.getParameter("birth_date"); UserDao infoDao = new UserDao(); UserBeans user = infoDao.LoginInfo(loginId, password); Charset charset = StandardCharsets.UTF_8; String algorithm = "MD5"; byte[] bytes = null; try { bytes = MessageDigest.getInstance(algorithm).digest(password.getBytes(charset)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String result = DatatypeConverter.printHexBinary(bytes); if (!password.equals(re_password )|| loginId == "" || name == "" || birthDate == "" || password == "" ) { request.setAttribute("errMsg","入力された内容は正しくありません。"); UserBeans ub = new UserBeans(loginId,name,birthDate,password); request.setAttribute("ub", ub); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/NewUser.jsp"); dispatcher.forward(request, response); return ; } UserDao NewUserDao = new UserDao(); try { NewUserDao.NewUser(loginId, name, birthDate, result); } catch (SQLException e) { request.setAttribute("errmSg", "そのログインIDは既に使用されています。"); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/NewUser.jsp"); dispatcher.forward(request, response); return; } String passwordP = <PASSWORD>; String id = request.getParameter("id"); response.sendRedirect("LoginListServlet"); } } <file_sep>package controller; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.DatatypeConverter; import dao.UserDao; import model.UserBeans; /** * Servlet implementation class UsersUpdateServlet */ @WebServlet("/UsersUpdateServlet") public class UsersUpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UsersUpdateServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ request.setCharacterEncoding("UTF-8"); String id = request.getParameter("id"); UserDao infoDao = new UserDao(); UserBeans user = infoDao.UserInfo(id); request.setAttribute("user", user); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/UsersUpdate.jsp"); dispatcher.forward(request, response ); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String password = request.getParameter("password"); String re_password = request.getParameter("re_password"); String name = request.getParameter("name"); String birthDate = request.getParameter("birthDate"); String id = request.getParameter("id"); String loginId = request.getParameter("loginId"); Charset charset = StandardCharsets.UTF_8; String algorithm = "MD5"; byte[] bytes = null; try { bytes = MessageDigest.getInstance(algorithm).digest(password.getBytes(charset)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String result = DatatypeConverter.printHexBinary(bytes); if(!password.equals(re_password)|| name == "" || birthDate == ""){ request.setAttribute("errMsg","入力された内容は正しくありません。" ); UserBeans ub = new UserBeans(loginId,name,birthDate,password); request.setAttribute("user", ub); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/UsersUpdate.jsp"); dispatcher.forward(request,response ); return; } UserDao userUpdateDao = new UserDao(); userUpdateDao.UsersUpdate(name, result, birthDate, id); response.sendRedirect("LoginListServlet"); } }
30bc969645d74e18e408ea0461b6c63cec901a2c
[ "Java" ]
3
Java
YoshiyukiYamaguchi/WebProgramming
e68731dde00f1ef21e6d1962c02a45159dd698c9
67023c20f666161c394e6b9634cc4c199cdd2688
refs/heads/master
<repo_name>daya-prac/web_spider_lagou<file_sep>/job.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 16-7-11 下午7:51 # @Author : leon # @Site : # @File : test1.py # @Software: PyCharm import requests from bs4 import BeautifulSoup origin = 'http://www.lagou.com' cookie = 'Cookie: user_trace_token=<PASSWORD>-0<PASSWORD>; LGMOID=20160710094357-447236C62C36EDA1D297A38266ACC1C3; LGUID=20160710094359-c5cb0e3b-463f-11e6-a4ae-5254005c3644; index_location_city=%E6%9D%AD%E5%B7%9E; LGRID=20160710094631-208fc272-4640-11e6-955d-525400f775ce; _ga=GA1.2.954770427.1465959000; ctk=1468117465; JSESSIONID=F827D8AB3ACD05553D0CC9634A5B6096; SEARCH_ID=5c0a948f7c02452f9532b4d2dde92762; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1465958999,1468115038; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1468117466' user_agent = 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36' headers = {'cookie':cookie, 'origin':origin, 'User-Agent':user_agent, } url = 'http://www.lagou.com' r = requests.get(url=url, headers=headers) page = r.content.decode('utf-8') soup = BeautifulSoup(page, 'lxml') date = [] jobnames = soup.select('#sidebar > div.mainNavs > div > div.menu_sub.dn > dl > dd > a') for i in jobnames: jobname = i.get_text().replace('/','+') date.append(jobname) with open('jobnames', 'w') as f: for i in date: f.write(i + '\n')
d2ad647accd62e920761130d4e78ef551900e076
[ "Python" ]
1
Python
daya-prac/web_spider_lagou
ef4780a988ebf0bd5538010689c89973b3739cbb
9f559e9a6812e3da76191623552de27dc6f1bf0e
refs/heads/master
<file_sep>#ifndef DeltaHIDINTERFACE_H #define DeltaHIDINTERFACE_H #include <stdio.h> #include <wchar.h> #include <string.h> #include <stdlib.h> #include "hidapi.h" // Headers needed for sleeping. #include <unistd.h> #define hidDataLength 64 //hid data receive callback function typedef void (*DataArriveCallBackFunc)(unsigned char *recData,unsigned char length); DataArriveCallBackFunc hidDataArriveCallBack; hid_device *handle; unsigned char isOpen; int hidApi_Init(DataArriveCallBackFunc DataArriveCallBack); int hidApi_Write(unsigned char *data, unsigned char length); //when data arrived, the function will be called void hidApi_DataReceive(unsigned char *recData,unsigned char length); int hidApi_Close(void); #endif // HIDINTERFACE_H <file_sep>/******************************************************* Windows HID simplification <NAME> Signal 11 Software 8/22/2009 Copyright 2009, All Rights Reserved. This contents of this file may be used by anyone for any reason without any conditions and may be used as a starting point for your own applications which use HIDAPI. ********************************************************/ #include "hidinterface.h" #include <pthread.h> void hidRead_thread(void); int hidApi_Init(DataArriveCallBackFunc DataArriveCallBack) { hidDataArriveCallBack = NULL; // Open the device using the VID, PID, // and optionally the Serial number. ////handle = hid_open(0x4d8, 0x3f, L"12345"); handle = hid_open(0x4d8, 0x3f, NULL); if (!handle) { printf("unable to open device\n"); isOpen = 0; return -1; } printf("open device success\n"); isOpen = 1; hidDataArriveCallBack = DataArriveCallBack; hidRead_thread(); // Set the hid_read() function to be non-blocking. hid_set_nonblocking(handle, 1); return 0; } int hidApi_Write(unsigned char *data, unsigned char length) { int res; unsigned char realData[length+1]; realData[0]=length; int i; for(i=0;i<length;i++) { realData[i+1]=data[i]; } res = hid_write(handle, realData, length+1); if (res < 0) { printf("Unable to write()\n"); printf("Error: %ls\n", hid_error(handle)); return -1; } printf("write success\n"); return 0; } void hidApi_DataReceive(unsigned char *recData,unsigned char length) { if(hidDataArriveCallBack==NULL) return; hidDataArriveCallBack(recData,length); } void hidApi_Read() { unsigned char recData[hidDataLength]; int res; while (isOpen==1) { res = hid_read(handle, recData, hidDataLength); if (res == 0) ;//printf("waiting...\n"); else if (res < 0) { printf("Unable to read()\n"); return -1; } else { int i; // printf("Data read:\n "); // // Print out the returned buffer. // // for (i = 0; i < res; i++) // printf("%02hhx ", recData[i]); // printf("\n"); unsigned char length = recData[0]; unsigned char datas[length]; for(i=0;i<length;i++) { datas[i]=recData[i+1]; } hidApi_DataReceive(datas,length); } usleep(50*1000); } } void hidRead_thread(void) { pthread_t id; int ret, i; ret=pthread_create(&id,NULL,(void *) hidApi_Read,NULL); // 成功返回0,错误返回错误编号 if(ret!=0) { printf ("Create pthread error!\n"); exit (1); } //pthread_join(id,NULL); printf ("Create pthread success!\n"); } int hidApi_Close(void) { hid_close(handle); isOpen = 0; /* Free static HIDAPI objects. */ hid_exit(); return 0; } <file_sep>#include <hidlib/hidinterface.h> // down 50000 50 : FA 00 00 04 03 01 00 00 00 50 C3 00 00 32 00 00 00 A7 A5 unsigned char bufferDown50[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x01, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0xA7, 0xA5}; // down 50000 10 : FA 00 00 04 03 01 00 00 00 50 C3 00 00 0A 00 00 00 9F A5 unsigned char bufferDown10[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x01, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x9F, 0xA5}; // up 50000 50 : FA 00 00 04 03 00 00 00 00 50 C3 00 00 32 00 00 00 A6 A5 unsigned char bufferUp50[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0xA6, 0xA5}; // up 50000 10 : FA 00 00 04 03 00 00 00 00 50 C3 00 00 0A 00 00 00 9E A5 unsigned char bufferUp10[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x9E, 0xA5}; // go home FA 00 02 04 03 00 00 00 00 00 00 00 00 0A 00 00 00 0D A5 unsigned char bufferGoHome[] = { 0xFA, 0x00, 0x02, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0xA5}; char isReponse = 0; void datarec(unsigned char *recData,unsigned char length) { printf("Data Receive: "); int i; for(i=0;i<length;i++) { printf("%02hhx ", recData[i]); } printf("\n"); isReponse = 1; } int main(int argc, char* argv[]) { hidApi_Init(datarec); isReponse = 1; while(1) { while(isReponse==0) usleep(500*1000); isReponse =0; hidApi_Write(bufferGoHome,0x13); usleep(500*1000); while(isReponse==0) usleep(500*1000); isReponse =0; hidApi_Write(bufferDown10,0x13); usleep(500*1000); while(isReponse==0) usleep(500*1000); isReponse =0; hidApi_Write(bufferDown50,0x13); while(isReponse==0) usleep(500*1000); isReponse =0; hidApi_Write(bufferDown10,0x13); usleep(500*1000); usleep(2*1000*1000); while(isReponse==0) usleep(500*1000); isReponse =0; hidApi_Write(bufferGoHome,0x13); usleep(2*1000*1000); } hidApi_Close(); return 0; }
ab49ed91cafd1978d5e4f45f93ea11084547bb01
[ "C" ]
3
C
beatfan/Linux_HID_Communication
06f844057b1401168dfc209db2cd89536e8118ff
c4b04ad121d472951bf339ddd4672c7c873a0710
refs/heads/master
<repo_name>YxrSadhu/TestApi<file_sep>/src/core/handleConfig.js const buildURL = require('./buildURL.js') const { isPlainObject } = require('../utils/utils.js') /** * 序列化一个符合 Fetch 的 url 、init 对象 * @param {String} url * @param {Object} config */ function handleConfig(url, config) { let { method = 'GET', headers, params, data } = config const correctUrl = params ? buildURL(url, params) : url data = data && isPlainObject(data) ? JSON.stringify(data) : data let init = Object.create(null) init.method = method init.headers = headers data && (init.body = data) return { correctUrl, init } } module.exports = handleConfig <file_sep>/brower/server.js /** * build a express server to proxy browser request */ const express = require('express') const bodyParser = require('body-parser') const fetch = require('node-fetch') const app = express() const router = express.Router() const CN = 'https://cn-apia.coolkit.cn', US = 'https://us-apia.coolkit.cc', AS = 'https://as-apia.coolkit.cc', EU = 'https://eu-apia.coolkit.cc'; router.post('/user/register', bodyParser.json(), (req, res) => { fetch(CN + '/v2/user/register', { method: req.method, headers: Object.assign({}, { 'Host': 'cn-apia.coolkit.cn' }, req.headers), body: JSON.stringify(req.body) }).then(response => response.json()) .then(data => {console.log(data); res.json(data) }) .catch(e => console.log('出错 -> ', e)) }) router.post('/user/login', bodyParser.json(), (req, res) => { fetch(CN + '/v2/user/login', { method: req.method, headers: Object.assign({}, { 'Host': 'cn-apia.coolkit.cn' }, req.headers), body: JSON.stringify(req.body) }).then(response => response.json()) .then(data => {console.log(data); res.json(data) }) .catch(e => console.log('出错 -> ', e)) }) router.post('/user/change-pwd', bodyParser.json(), (req, res) => { fetch(CN + '/v2/user/change-pwd', { method: req.method, headers: Object.assign({}, { 'Host': 'cn-apia.coolkit.cn' }, req.headers), body: JSON.stringify(req.body) }).then(response => response.json()) .then(data => {console.log(data); res.json(data) }) .catch(e => console.log('出错 -> ', e)) }) router.post('/user/close-account', bodyParser.json(), (req, res) => { fetch(CN + '/v2/user/close-account', { method: req.method, headers: Object.assign({}, { 'Host': 'cn-apia.coolkit.cn' }, req.headers), body: JSON.stringify(req.body) }).then(response => response.json()) .then(data => {console.log(data); res.json(data) }) .catch(e => console.log('出错 -> ', e)) }) router.post('/user/verification-code', bodyParser.json(), (req, res) => { fetch(CN + '/v2/user/verification-code', { method: req.method, headers: Object.assign({}, { 'Host': 'cn-apia.coolkit.cn' }, req.headers), body: JSON.stringify(req.body) }).then(response => response.json()) .then(data => {console.log(data); res.json(data) }) .catch(e => console.log('出错 -> ', e)) }) app.use('/v2', router) app.use(express.static('../dist')) const port = process.env.PORT || 9002 // 启用 node.js 没有传端口的话,默认就用 9002 这个端口 module.exports = app.listen(port, function (err) { // 启动服务监听端口 if (err) { console.log(err) return } console.log('Listening at http://localhost:' + port + '\n') })<file_sep>/test/beforeLogin.spec.js const chai = require('chai') const asyncObj = require('../src/asyncTest.js') const expect = chai.expect describe("酷宅登录前接口测试", function() { this.timeout(0) before(() => console.info("开始测试")) describe("用户类接口测试", () => { describe("测试账号登录", () => { const api = asyncObj.user.pwdLogin() it("成功响应", (done) => { api.then((res) => { expect(res.error).to.equal(0) done() }).catch(err => done(err)) }) it("接口应当返回一个 json 对象", (done) => { api.then(res => { expect(res).to.be.an("object") done() }).catch(err => done(err)) }) it("data 字段应当包含的 key", (done) => { api.then(res => { expect(res.data) .to.have.all.keys("user", "at", "rt", "region"); done(); }).catch(err => done(err)); }) it("user 字段应当包含的 key", (done) => { api.then(res => { expect(res.data.user) .to.contains.all.keys("apikey","accountLevel"); done(); }).catch(err => done(err)); }) }) /* 登录前的每个登录相关请求都会改变 at 等信息,故集体跑测试时任选其一登录 */ describe("测试账号注册", () => { const api = asyncObj.user.userRegister() it("成功响应", (done) => { api.then(res => { expect(res.error).to.equal(0) done() }).catch(err => done(err)) }) it("接口应当返回一个 json 对象", (done) => { api.then(res => { expect(res).to.be.an("object") done() }).catch(err => done(err)) }) it("data 字段应当包含的 key", (done) => { api.then(res => { expect(res.data) .to.have.all.keys("user", "at", "rt", "region"); done(); }).catch(err => done(err)); }) it("user 字段应当包含的 key", (done) => { api.then(res => { expect(res.data.user) .to.contains.all.keys("apikey","accountLevel"); done(); }).catch(err => done(err)); }) }) describe("测试验证码登录", () => { const api = asyncObj.user.verificationLogin() it("成功响应", (done) => { api.then(res => { expect(res.error).to.equal(0) done() }).catch(err => done(err)) }) it("接口应当返回一个 json 对象", (done) => { api.then(res => { expect(res).to.be.an("object") done() }).catch(err => done(err)) }) it("data 字段应当包含的 key", (done) => { api.then(res => { expect(res.data) .to.have.all.keys("user", "at", "rt", "region"); done(); }).catch(err => done(err)); }) it("user 字段应当包含的 key", (done) => { api.then(res => { expect(res.data.user) .to.contains.all.keys("apikey", "accountLevel"); done(); }).catch(err => done(err)); }) }) describe("测试发送验证码", () => { const api = asyncObj.user.sentVerification() it("成功响应", (done) => { api.then(res => { expect(res.error).to.equal(0) done() }).catch(err => done(err)) }) it("接口应当返回一个 json 对象", (done) => { api.then(res => { expect(res).to.be.an("object") done() }).catch(err => done(err)) }) it("data 字段无数据", (done) => { api.then(res => { expect(res.data).to.be.empty done() }).catch(err => done(err)) }) }) describe("测试重置密码", () => { const api = asyncObj.user.resetPwd() it("成功响应", (done) => { api.then(res => { expect(res.error).to.equal(0) done() }).catch(err => done(err)) }) it("接口应当返回一个 json 对象", (done) => { api.then(res => { expect(res).to.be.an("object") done() }).catch(err => done(err)) }) it("data 字段应当包含的 key", (done) => { api.then(res => { expect(res.data) .to.have.all.keys("user", "at", "rt", "region"); done(); }).catch(err => done(err)); }) it("user 字段应当包含的 key", (done) => { api.then(res => { expect(res.data.user) .to.contains.all.keys("apikey", "accountLevel"); done(); }).catch(err => done(err)); }) }) }) after(() => console.info('结束测试')) }) <file_sep>/src/asyncTest.js const dispatchRequest = require('./core/dispatchRequest.js') const { getSign, getEnv, getDigest } = require('./utils/utils.js') const { WS } = require('../WS') const fs = require('fs') const CN = 'https://cn-apia.coolkit.cn', US = 'https://us-apia.coolkit.cc', AS = 'https://as-apia.coolkit.cc', EU = 'https://eu-apia.coolkit.cc'; const ALLOT_SERVER_CN = 'https://cn-dispa.coolkit.cn/dispatch/app', ALLOT_SERVER_US = 'https://us-dispa.coolkit.cc/dispatch/app', ALLOT_SERVER_EU = 'https://eu-dispa.coolkit.cc/dispatch/app', ALLOT_SERVER_AS = 'https://as-dispa.coolkit.cc/dispatch/app'; const COMMON_HEADERS = { 'Content-Type' : 'application/json', 'Host': 'cn-apia.coolkit.cn' } /** * 工厂模式造 headers * @param {String} type * @param {Object} body * @param {Boolean} flag true -> 登录前, false -> 登录后 */ function headersFactory(type, body = '', flag = false) { return Object.assign( type === 'user' ? { 'X-CK-Appid': 'oc3tvAdJPmaVOKrLv0rjCC0dzub4bbnD' } : {}, flag ? { 'Authorization' : 'Sign ' + getSign(body) } : { 'Authorization' : 'Bearer ' + getEnv('at')}, COMMON_HEADERS ) } /* 接口函数定义 */ const asyncObj = { user: { userRegister() { const data = { countryCode: '+86', phoneNumber: '+8617720837235', verificationCode: '9820', password: '<PASSWORD>' // 密码 } const promise = dispatchRequest(CN + '/v2/user/register', { method: 'POST', headers: headersFactory('user', data, true), data }) /* get token */ return promise.then(res => { if (res.error === 0 && Object.keys(res.data).length > 0) { fs.writeFileSync('env.json', JSON.stringify({ at: res.data.at, rt: res.data.rt, user: res.data.user, region: res.data.region }, null, 2), (err) => { if (err) throw err console.log('最新 Token 已写入本地') }) } return res }) }, pwdLogin() { const data = { lang: 'cn', // email: '<EMAIL>', 不存在文档描述的优先检查,一起传就报 400 错,有冲突 countryCode: "+86", phoneNumber: '+8617720837235', password: '<PASSWORD>' } const promise = dispatchRequest(CN + '/v2/user/login', { method: 'POST', headers: headersFactory('user', data, true), data }) /* get token */ return promise.then(res => { if (res.error === 0 && Object.keys(res.data).length > 0) { fs.writeFileSync('env.json', JSON.stringify({ at: res.data.at, rt: res.data.rt, user: res.data.user, region: res.data.region }, null, 2), (err) => { if (err) throw err console.log('最新 Token 已写入本地') }) } return res }) }, verificationLogin() { const data = { lang: 'cn', // email: '' 国外不能验证码 countryCode: "+86", phoneNumber: '+8617720837235', verificationCode: '8385' } const promise = dispatchRequest(CN + '/v2/user/sms-login', { method: 'POST', headers: headersFactory('user', data, true), data }) /* get token */ return promise.then(res => { if (res.error === 0 && Object.keys(res.data).length > 0) { fs.writeFileSync('env.json', JSON.stringify({ at: res.data.at, rt: res.data.rt, user: res.data.user, region: res.data.region }, null, 2), (err) => { if (err) throw err console.log('最新 Token 已写入本地') }) } return res }) }, sentVerification() { /** * 请求限制: 1分钟内不能超过3次 1小时内不能超过20次 1天内不能超过100次 */ const data = { type: 1, // Number, 0 - 注册、1 - 重置、3 - 注销账号、4 - 验证码登录 phoneNumber: '+8617720837235' // 或邮箱 } return dispatchRequest(CN + '/v2/user/verification-code', { method: 'POST', headers: headersFactory('user', data, data.type === 3 ? false : true), data }) }, resetPwd() { const data = { phoneNumber: '+8617720837235', // 或 email verificationCode: '9977', password: '<PASSWORD>' } const promise = dispatchRequest(CN + '/v2/user/reset-pwd', { method: 'POST', headers: headersFactory('user', data, true), data }) /* get token */ return promise.then(res => { if (res.error === 0 && Object.keys(res.data).length > 0) { fs.writeFileSync('env.json', JSON.stringify({ at: res.data.at, rt: res.data.rt, user: res.data.user, region: res.data.region }, null, 2), (err) => { if (err) throw err console.log('最新 Token 已写入本地') }) } return res }) }, /* 以上是登录前,必须加签名; 以下是登录后,必须加 token */ changePwd() { const data = { oldPassword: '<PASSWORD>', newPassword: '<PASSWORD>' } return dispatchRequest(CN + '/v2/user/change-pwd', { method: 'POST', headers: headersFactory('user'), data }) }, getUserInfo() { // console.log('special: ', headersFactory('user')) return dispatchRequest(CN + '/v2/user/profile', { method: 'GET', headers: headersFactory('user') }) }, changeUserInfo() { const data = { /* 这三个参数都可不传,不传就是不更新 */ nickname: 'Sadhu', acceptEmailAd: false, accountConsult: true // 固定值为 true,不可填其它 } return dispatchRequest(CN + '/v2/user/profile', { method: 'POST', headers: headersFactory('user'), data }) }, /* 异步更新的 at,在 mocha 中可能还没设置好 at 就发其它请求了,mocha 中测试 describe 不按顺序 */ refreshToken() { console.log(getEnv('rt')) const data = { rt: getEnv('rt') } const promise = dispatchRequest(CN + '/v2/user/refresh', { method: 'POST', headers: headersFactory('user'), data }) return promise.then(res => { if (res.error === 0 && Object.keys(res.data).length > 0) { const env = JSON.parse(fs.readFileSync('env.json', 'utf-8')) env.at = res.data.at env.rt = res.data.rt fs.writeFileSync('env.json', JSON.stringify(env, null, 2), (err) => { if (err) throw err console.log('最新 Token 已写入本地') }) } return res }) }, signOut() { return dispatchRequest(CN + '/v2/user/logout', { method: 'DELETE', headers: headersFactory('user') }) }, destroyAccount() { const data = { verificationCode: '3899' } return dispatchRequest(CN + '/v2/user/close-account', { method: 'POST', headers: headersFactory('user'), data }) } }, homePage: { reqHome() { const data = { "lang": "cn", "clientInfo": { "os": "iOs" }, "getUser": {}, "getFamily": {}, "getThing": { "num": 10 }, "getScene": {}, "getMessage": {} } return dispatchRequest(CN + '/v2/homepage', { method: 'POST', headers: headersFactory('homePage'), data }) } }, device: { getThingsList() { /* Thing包括: 设备(自己的和别人分享的)、设备群组 */ const params = { lang: 'cn', // familyid: '' 不传则默认当前家庭 num: 0, // 获取数量,默认 30, 0 表示所有 // beginIndex: -9999999 从哪个序号开始获取列表数据,不填就默认这个 } return dispatchRequest(CN + '/v2/device/thing', { method: 'GET', headers: headersFactory('device'), params }) }, getChooseThing() { /* thingList items 数量必须大于 0, 小于等于 10 */ const data = { thingList: [{ itemType: 1, id: '1000d4f0f3' // itemType 为 1 时 -> deviceid,为 3 -> 群组 id }] } return dispatchRequest(CN + '/v2/device/thing', { method: 'POST', headers: headersFactory('device'), data }) }, getThingStatus() { // 设备的状态属性 const params = { type: 1, // 1 - 设备, 2 - 群组 id: '1000d4f0f3', params: 'sledOnline|switch' // 按这种格式,选择要获取哪些状态属性 } return dispatchRequest(CN + '/v2/device/thing/status', { method: 'GET', headers: headersFactory('device'), params }) }, changeThingStatus() { // 设备的状态属性 const data = { type: 1, // 1 - 设备, 2 - 群组 id: '1000d4f0f3', params: { // 更新设备时,会向设备下发控制指令,如果设备不在线或发送失败则返回错误,群组无视"不在线"或"发失败"情况 switch: 'on' } } return dispatchRequest(CN + '/v2/device/thing/status', { method: 'POST', headers: headersFactory('device'), data }) }, changeBatchThingStatus() { // 该接口会实际向设备下发控制指令,为不能走长连接更新状态的设备准备的 const data = { thingList: [ // 0 < length < 10 { type: 2, id: '5fc4b1845a5a2a0007ec8b12', params: { switch: 'on' } }, { type: 1, id: '1000d4f0f3', params: { startup: 'on' } } ], timeout: 0 // 等待设备响应的时间 默认为 0 } return dispatchRequest(CN + '/v2/device/thing/batch-status', { method: 'POST', headers: headersFactory('device'), data }) }, addWifiDev() { /* 取巧法1,单通道插座 */ const deviceid = '1000d4f0f3', devicekey = "76ef199a-1609-4fce-bdfb-fa7ca7650382", chipid = "00E0604B"; const data = { name: 'Sadhu 单通道', deviceid, digest: getDigest(deviceid, devicekey), chipid } return dispatchRequest(CN + '/v2/device/add', { method: 'POST', headers: headersFactory('device'), data }) }, addGsm() { // 扫码得到: 'api.coolkit.cc:8080/api/user/device/addGsm?id=625faaf9b71e044c745728c521907abf' const id = '625faaf9b71e044c745728c521907abf' const data = { id, name: 'sadhu gsm' } return dispatchRequest(CN + '/v2/device/add-gsm', { method: 'POST', headers: headersFactory('device'), data }) }, updateInfo() { const data = { deviceid: '1000d4f0f3', name: '单通道插座 update', // roomid: '' 房间id,只能更换到设备所在家庭下的房间,不能跨家庭更改 } return dispatchRequest(CN + '/v2/device/update-info', { method: 'POST', headers: headersFactory('device'), data }) }, deleteDevice() { const params = { deviceid: '10009c2bdd' } return dispatchRequest(CN + '/v2/device', { method: 'DELETE', headers: headersFactory('device'), params }) }, changeDeviceTags() { /* 用于自定义设备功能,如给设备新增一个功能,与服务端约定 'xx' == 'xx' 的 tags,客户端请求该接口把约定字段传过去,服务端就知道目的了 */ const data = { deviceid: '1000d4f0f3', type: 'replace', // 不填默认 replace,还可以 merge tags: { 'sadhuTag': 'on' } } return dispatchRequest(CN + '/v2/device/tags', { method: 'POST', headers: headersFactory('device'), data }) }, getGroupList() { const params = { lang: 'cn' // 默认 en } return dispatchRequest(CN + '/v2/device/group', { method: 'GET', headers: headersFactory('device'), params }) }, addGroup() { // 如果使用别人分享的设备作为主设备来新增群组,则当分享撤销时,该群组也会被一并删除 const data = { name: 'sadhu 群组2', mainDeviceId: '1000d4f0f3', // familyid: '', 群组所属的家庭id,如果为空,表示添加到当前家庭 // roomid: '' 群组所属的房间id,如果为空,表示添加到【未分配】下 // sort: 1 给新群组分配序号的方式 1=更小的序号 2=更大的序号 // deviceidList Array<String> 创建群组时加入到该群组的设备的id列表,不需要将主设备id传入,如果列表中的设备uiid与主设备的不一致,则不会将该设备添加到群组 } return dispatchRequest(CN + '/v2/device/group', { method: 'POST', headers: headersFactory('device'), data }) }, changeGroup() { // 只能修改群组名称 const data = { id: '5fc4b1845a5a2a0007ec8b12', name: '修改第一个群组', } return dispatchRequest(CN + '/v2/device/group', { method: 'PUT', headers: headersFactory('device'), data }) }, deleteGroup() { const params = { id: '5fc4b151d2a2ba0008aabc28', } return dispatchRequest(CN + '/v2/device/group', { method: 'DELETE', headers: headersFactory('device'), params }) }, changeGroupStatus() { // 只保存数据,不作联动设备状态修改处理 const data = { id: '5fc4b0e51dd83d00086499b4', params: { switch: "off" } } return dispatchRequest(CN + '/v2/device/group/status', { method: 'POST', headers: headersFactory('device'), data }) }, addDevInGroup() { // 设备 uuid 必须与主设备 uuid 相同 // 响应更新后的群组的设备列表: updatedThingList const data = { id: '5fc4b0e51dd83d00086499b4', deviceidList: ['1000d4f0f3'] // 设备id列表,数量最小1,最大30 } return dispatchRequest(CN + '/v2/device/group/add', { method: 'POST', headers: headersFactory('device'), data }) }, deleteDevInGroup() { // 响应更新后的群组的设备列表: updatedThingList const data = { id: '5fc4b0785a5a2a0007ec8b0f', deviceidList: ['1000d4f0f3'] // 设备id列表,数量最小1,最大30 } return dispatchRequest(CN + '/v2/device/group/delete', { method: 'POST', headers: headersFactory('device'), data }) }, updateGroupsDevices() { // 重新覆盖群组内的设备列表 // 响应更新后的群组的设备列表: updatedThingList const data = { id: '5fc45473c6ec8400080aa9f9', deviceidList: ['1000d4f0f3'] // 设备id列表,必须最少包含群组的主设备deviceid,否则报错 } return dispatchRequest(CN + '/v2/device/group/update', { method: 'POST', headers: headersFactory('device'), data }) }, shareDev() { const data = { deviceidList: ['1000d4f0f3'], user: { countryCode: "+86", phoneNumber: "+8618059556779" }, permit: 15, comment: 'from sadhu' } return dispatchRequest(CN + '/v2/device/share', { method: 'POST', headers: headersFactory('device'), data }) }, changePermit() { const data = { deviceid: '1000d4f0f3', apikey: '9765de04-598a-4ca8-a7aa-e26c73a5d5f6', permit: 1 } return dispatchRequest(CN + '/v2/device/share/permit', { method: 'POST', headers: headersFactory('device'), data }) }, cancelShare() { const params = { deviceid: '1000d4f0f3', apikey: '9765de04-598a-4ca8-a7aa-e26c73a5d5f6' } return dispatchRequest(CN + '/v2/device/share', { method: 'DELETE', headers: headersFactory('device'), params }) }, getDevHistory() { const params = { deviceid: '1000d4f0f3', // from 时间戳,精确到毫秒,表示从什么时间开始,获取更早之前的消息,不填则默认为当前时间 // num 最多拉取的消息数量,1<= num <= 30,不填则默认为30 } return dispatchRequest(CN + '/v2/device/history', { method: 'GET', headers: headersFactory('device'), params }) }, deleteDevHistory() { const params = { deviceid: '1000d4f0f3', } return dispatchRequest(CN + '/v2/device/history', { method: 'DELETE', headers: headersFactory('device'), params }) }, queryOTA() { /* OTA 只应用于固件升级吗。有些设备无升级信息 otaInfoList 是空数组 */ const data = { deviceInfoList: [{ deviceid: '1000d4f0f3', model: 'PSA-B01-GL', // 设备的模块型号 version: '8' // 当前设备的固件版本号 }], } return dispatchRequest(CN + '/v2/device/ota/query', { method: 'POST', headers: headersFactory('device'), data }) } }, family: { getFamily() { const params = { lang: 'cn' } return dispatchRequest(CN + '/v2/family', { method: 'GET', headers: headersFactory('family'), params }) }, addHouse() { const data = { name: 'new House', sort: 2, // 1 - 更小的序号, 2 - 更大 roomNameList: ['one', 'tow'] // 为空则没房间 } return dispatchRequest(CN + '/v2/family', { method: 'POST', headers: headersFactory('family'), data }) }, addRoom() { const data = { familyid: '5fc4b075132a4c00079435d5', name: 'new four', sort: 1, // 1 - 更小的序号, 2 - 更大 } return dispatchRequest(CN + '/v2/family/room', { method: 'POST', headers: headersFactory('family'), data }) }, changeHouse() { // 当前只支持修改家庭名称 const data = { id: '5fc4b075132a4c00079435d5', // 不填则为当前家庭 name: 'new name' } return dispatchRequest(CN + '/v2/family', { method: 'PUT', headers: headersFactory('family'), data }) }, changeRoom() { // 当前只支持修改房间名称 const data = { id: '5fc062d7a705f900084af948', // 不填则为当前房间 name: 'newName' } return dispatchRequest(CN + '/v2/family/room', { method: 'PUT', headers: headersFactory('family'), data }) }, sortRoom() { // 客户端必须将家庭下的所有房间上传,统一排序 const data = { familyid: '5fc062d7a705f900084af94a', // 不填则为当前家庭 idList: ['5fc062d7a705f900084af947', '5fc062d7a705f900084af948'] // item 顺序即是排列顺序 } return dispatchRequest(CN + '/v2/family/room/index', { method: 'POST', headers: headersFactory('family'), data }) }, deleteHouse() { const params = { id: '5fc4e378c59256000893a14a', // 待删除家庭 id deviceFamily: '5fc062d7a705f900084af94a', // 该家庭的设备要迁移的家庭 id switchFamily: '5fc062d7a705f900084af94a' // 删除家庭后要切换的 id } return dispatchRequest(CN + '/v2/family', { method: 'DELETE', headers: headersFactory('family'), params }) }, deleteRoom() { const params = { id: '<KEY>', // 待删除房间 id } return dispatchRequest(CN + '/v2/family/room', { method: 'DELETE', headers: headersFactory('family'), params }) }, sortThingInHouse() { // 客户端必须将家庭下的所有设备和群组上传,统一排序 const data = { familyid: '5fc062d7a705f900084af94a', // 待排序设备所在家庭 id thingList: [ // 服务端按照列表的顺序对相应位置的id作排序 { itemType: 1, id: '1000d4f0f3' }, { itemType: 3, id: '5fc4b1845a5a2a0007ec8b12' }, { itemType: 3, id: '5fc4b0e51dd83d00086499b4' }, { itemType: 3, id: '5fc4b0785a5a2a0007ec8b0f' }, { itemType: 3, id: '5fc45473c6ec8400080aa9f9' } ] } return dispatchRequest(CN + '/v2/family/thing/sort', { method: 'POST', headers: headersFactory('family'), data }) }, setThingInRoom() { /* 客户端将房间原有的thing列表和调整后的thing列表传入, 服务端据此计算出要从房间删除的thing,以及要添加到房间的thing。 客户端应保证oldThingList的正确性,如果有遗漏项,可能导致从房间删除失败; 如果其中一项不属于roomid所属的房间,服务端返回错误。 */ const data = { roomid: '5fc062d7a705f900084af947', oldThingList: [], newThingList: [ { itemType: 3, id: '5fc4b0785a5a2a0007ec8b0f' } ] } return dispatchRequest(CN + '/v2/family/room/thing', { method: 'POST', headers: headersFactory('family'), data }) }, switchHouse() { const data = { id: '5fc062d7a705f900084af94a' // 切换家庭的 id } return dispatchRequest(CN + '/v2/family/current', { method: 'POST', headers: headersFactory('family'), data }) } }, message: { /* 407 - reason: appid 是应用的标识,应用方给你的,登录的时候带上,登录后能请求到的资源对应该 appid 有权限操作的资源 */ getMessageList() { const params = { familyid: '5fc062d7a705f900084af94a', // 如果不填则为当前家庭 from: '1606323142000', // 时间戳,精确到毫秒,表示从什么时间开始,获取更早之前的消息,不填则默认为当前时间 num: 30 // 拉取数量,不填默认 30, 1 < num < 30 } return dispatchRequest(CN + '/v2/message/read', { method: 'GET', headers: headersFactory('message'), params }) } }, controlDevice: { allotService() { return dispatchRequest(ALLOT_SERVER_CN, { method: 'GET', headers: headersFactory('controlDevice'), credentials: 'include' }) } } } /* websocket 测试 */ const firstData = { "action":"userOnline", "version":8, "ts":parseInt(new Date().getTime()/1000).toString(), "at":getEnv('at'), "userAgent":"app", "apikey":getEnv('user').apikey, "appid":"McFJj4Noke1mGDZCR1QarGW7P9Ycp0Vr", "nonce":"2plz69ax", "sequence":new Date().getTime().toString() } function appWS(data) { console.log('服务端推送:', data) } const ws = new WS('wss://cn-pconnect2.coolkit.cc:8080/api/ws', appWS, 'appServer') // 握手 ws.connect(firstData) // 更新设备状态 setTimeout(() => { ws.sendHandle({ "action":"update", "deviceid":"1000d4f0f3", "apikey":"1c2e1b91-12ee-4f7e-8bfd-79db6bffe835", "userAgent":"app", "sequence": new Date().getTime().toString(), "ts":0, "params":{ "switch": "off" // 单通道设备 } }) }, 2000) // 查询设备状态 setTimeout(() => { ws.sendHandle({ "action":"query", "deviceid":"1000d4f0f3", "apikey":"1c2e1b91-12ee-4f7e-8bfd-79db6bffe835", "userAgent":"app", "sequence": new Date().getTime().toString(), "ts":0, "params": ['switch', 'fwVersion'] }) }, 4000) module.exports = asyncObj<file_sep>/WS.js const WebSocket = require('ws') class WS { /** * 初始化实例属性 * @param {String} url ws 的接口 * @param {Function} msgCb 服务端传数据的回调 * @param {String} name */ constructor(url, msgCb, name) { this.url = url this.msgCb = msgCb this.name = name this.ws = null // websocket 对象 this.status = null // 连接状态 this.interval = null // 间隔时间 } /** * 首次或重连时候建立 WebSocket 连接 * @param {params} data 可选 */ connect(data) { this.ws = new WebSocket(this.url) // 成功连接事件 this.ws.on('open', (e) => { this.status = 'open'; console.log(`${this.name}连接成功`, e) // 有要传的数据就发给后端 data && this.ws.send(JSON.stringify(data)) }) // 监听服务端返回信息 this.ws.on('message', (data) => { if (data !== 'pong') { data = JSON.parse(data) if (data.config && data.config.hb === 1) { this.interval = data.config.hbInterval * Math.random(0.8, 1) this.heartCheck() } this.msgCb(data) } }) // 手动关闭触发关闭事件 this.ws.on('close', (e) => { this.closeHandle(e) }) // 连接出错回调 this.ws.on('error', (e) => { this.closeHandle(e) }) } heartCheck() { this.pingInterval = setInterval(() => { if (this.ws.readyState === 1) { // ws 为连接状态 this.ws.send('ping'); // 客户端发送ping } }, this.interval) } /** * * @param {params} data 发送消息给服务器 */ sendHandle(data) { return this.ws.send(JSON.stringify(data)); } /** * 因为 WebSocket 并不稳定,规定只能手动关闭(调closeMyself方法),否则就重连 * @param {Event} e */ closeHandle(e = 'err') { // 清除定时器 if (this.pingInterval !== undefined) { clearInterval(this.pingInterval) } if (this.status !== 'close') { console.log(`${this.name}断开,重连 websocket `, e) this.connect(); // 重连 } else { console.log(`${this.name} websocket 手动关闭`) } } // 手动关闭 closeMyself() { console.log(`手动关闭${this.name}`) this.status = 'close'; return this.ws.close(); } } module.exports = { WS }<file_sep>/README.md ## Project Tree ```js . ├── README.md -- 项目说明 ├── WS.js -- WebSocket 类 ├── brower -- 浏览器端测试所用脚本 │ ├── run.js -- 跑 node.js 兼容 ES6 Module │ └── server.js -- express router proxy ├── docs -- 测试日志 ├── env.json -- 环境变量 ├── mocha.launcher.js -- 启动测试脚本 ├── package-lock.json ├── package.json ├── src │ ├── asyncTest.js -- 接口函数定义 & websocket 测试 │ ├── core -- 请求库核心 │ │ ├── buildURL.js -- 构建规范 url │ │ ├── dispatchRequest.js -- core request │ │ └── handleConfig.js -- 序列化 config │ └── utils │ └── utils.js -- 工具函数 ├── test -- 测试目录 │ ├── beforeLogin.spec.js -- 登录前测试用例 │ └── loggedIn.spec.js -- 登录后测试用例 └── webpack.config.js ``` ## 项目启动 可以在 node 端测,也可以在浏览器端测,自行选择。 ### node 端 有两种方法可以启动,无论哪种方法都先安装依赖 `npm install` 。 1. 运行启动测试脚本 -> `node mocha.launcher.js` > 注:这种方式要单独测试某个 `xxx.spec.js` 文件或有生成测试日志的需求,则自行到脚本中修改。 2. 利用 npm scripts - `npm run "test:before"` 测试登录前的测试用例 - `npm run "test:after"` 测试登录后的测试用例 - `npm run "test:doc1"` 生成登录前测试用例的测试日志 - `npm run "test:doc2"` 生成登录后测试用例的测试日志 > 注:若要修改,自行定义 package.json ### 浏览器端 1. `npm install` 安装依赖 2. webpack 打包项目 `npm run build`,打包后会出现个 dist 目录 3. `node ./brower/server.js` 命令行启动 server 代理 dist 目录下的静态资源即可利用 Chrome 开发者工具测试 > 注:打包前把 CommonJs 改为 ES6 Module ## 项目技术栈 - 请求:基于 Fetch 封装的请求库 - 测试框架:Mocha - 断言库:Chai - 打包:Webpack - 服务端:Node + Express ## 接口文档 https://coolkit-carl.gitee.io/apidocs/#/zh-cmn/%E6%8E%A5%E5%8F%A3%E4%B8%AD%E5%BF%83_v2 ## 测试日志 测试日志利用 Mocha 的生成文档 Feature -> `mocha ./test/*.js --reporter mochawesome --reporter-options reportDir=docs/` > 注:--reporter-options reportDir是生成的报告放在哪个文件夹 本项目的测试日志在 `./docs` 目录下,点击对应目录下的 html 文件即可查看。 ## 注意 本项目所有代码以及测试日志归作者本人以及所在公司深圳酷宅科技所有,未经许可,禁止私用。若想商用、建议、转载,请联系邮箱: `<EMAIL>`<file_sep>/src/core/buildURL.js const { isDate, isPlainObject } = require('../utils/utils.js') /** * @param {String} val */ function encode(val) { return encodeURIComponent(val) // 保留一些特殊字符 .replace(/%40/g, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ',') .replace(/%20/g, '+') .replace(/%5B/gi, '[') .replace(/%5D/gi, ']') } /** * 序列化参数后拼接符合规范的 URI * @param {String} url * @param {Object} params */ function buildURL(url, params) { let serializedParams = '' const parts = [] Object.keys(params).forEach((key) => { let val = params[key] if (val === null || typeof val === undefined) { return // just break this iterate } let tmp = [] // temporary array, for managing kinds of params with same way. if (Array.isArray(val)) { tmp = val key += '[]' } else { tmp = [val] } tmp.forEach((val) => { if (isDate(val)) { val = val.toISOString() // standard } else if (isPlainObject(val)) { val = JSON.stringify(val) } parts.push(`${encode(key)}=${encode(val)}`) }) }) serializedParams = parts.join('&') if (serializedParams) { const hashIdx = url.indexOf('#') // ignore hash if (hashIdx !== -1) { url = url.slice(0, hashIdx) } url += (url.indexOf('?') !== -1 ? '&' : '?') + serializedParams } return url } module.exports = buildURL
69780317fb85cd22531a024c03c05fd69008b41c
[ "JavaScript", "Markdown" ]
7
JavaScript
YxrSadhu/TestApi
4d468e48c3afe7c6ea64da667b34a77442b97da3
a02b38416260124495c9096737eaf6be1888bbe9
refs/heads/master
<file_sep><!DOCTYPE html> <html> <head> <title>introduccion</title> <meta charset="UTF-8"> <script src="http://maps.google.com/maps?file=api&v=2&key=COLOCAR_AQUI_NUESTRA_KEY" type="text/javascript"></script> <script type="text/javascript"> function iniciar() { var mapOptions = { center: new google.maps.LatLng(40.416728, -3.703801), zoom: 10, mapTypeId: google.maps.MapTypeId.HYBRID}; var map = new google.maps.Map(document.getElementById("map"),mapOptions);} </script> </head> <body> <?php echo $_GET["latitud"]?> <?php echo $_GET["longitud"]?> <div id="map" style="width:500px;height:250px;"></div> <script src="http://maps.google.com/maps/api/js?sensor=false&callback=iniciar"></script> </body> </html> <?php/*enlaces https://developers.google.com/maps/documentation/javascript/examples/event-simple?hl=es * http://www.rubenalcaraz.es/pinakes/informatica/introduccion-a-google-maps-apiv3-parte-5-multiples-marcadores-con-infowindow/#codesyntax_4 * http://w3.unpocodetodo.info/utiles/mapa-con-chincheta.php*/?> <file_sep><?php $insertar = 1; $id = $_GET["id"]; echo $id; ?> <!DOCTYPE html> <html> <head> <title>Añadir Estación</title> <meta charset="UTF-8"> </head> <body> <h1 align="center">Introduce los datos de una nueva Estación</h1><br><br><br><br><br> <form action="index.php" method="get"> <p align = "center">Nombre de usuario: <input size="15" name="nom_usu" value="nom_usu"><br><br><br> Correo: <input size="15" name="correo_n" value="correo_n"><br><br><br><br> Cooredenadas de la estación meteorologica: <br><br> Latitud: <input size="15" name="latutid_n" value="latutid_n"><br><br><br> Longitud: <input size="15" name="longitud_n" value="longitud_n"><br><br><br><br> Nota: Asegurese de tener los siguientes sensores: <br><br> <input type=checkbox value=si name=temperatura> Temperatura<br> <input type=checkbox value=si name=presion> Presión<br> <input type=checkbox value=si name=humedad> Humedad<br><br><br><br> <input size="0" value=<?php echo $insertar?> name="insertar"> <input size="0" value=<?php echo $id?> name="id"> <input size="0" value="0" name=d_h> <input type="submit" value="Enviar"></p> </form> </body> </html> <file_sep><?php require_once ('jpgraph/jpgraph.php'); require_once ('jpgraph/jpgraph_line.php'); include_once './clases.php'; include_once './conexion_consultas.php'; $k=0; for($i=0; $i<=count($registroH); $i++){ if ($registroH[$i]->idEstacion2 == $_GET["id2"]){ $temperatura_g[$k] = $registroH[$i]->temperatura; $humeda_g[$k] = $registroH[$i]->humedad; $presion_g[$k] = $registroH[$i]->presion; $k++; } } // Setup the graph $graph = new Graph(925,350); $graph->SetScale("textlin"); $theme_class=new UniversalTheme; $graph->SetTheme($theme_class); $graph->img->SetAntiAliasing(false); $graph->title->Set('Evolucion del clima por horas'); $graph->SetBox(false); $graph->img->SetAntiAliasing(); $graph->yaxis->HideZeroLabel(); $graph->yaxis->HideLine(false); $graph->yaxis->HideTicks(false,false); $graph->xgrid->Show(); $graph->xgrid->SetLineStyle("solid"); $graph->xaxis->SetTickLabels(array('00:00','01:00','02:00','03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00')); $graph->xgrid->SetColor('#E3E3E3'); // Create the first line $p1 = new LinePlot($temperatura_g); $graph->Add($p1); $p1->SetColor("#6495ED"); $p1->SetLegend('Temperatura'); // Create the second line $p2 = new LinePlot($humeda_g); $graph->Add($p2); $p2->SetColor("#B22222"); $p2->SetLegend('Humedad'); // Create the third line $p3 = new LinePlot($presion_g); $graph->Add($p3); $p3->SetColor("#FF1493"); $p3->SetLegend('Presion'); $graph->legend->SetFrameWeight(1); $graph->legend->SetPos(0.5,0.98,'center','bottom'); // Output line $graph->Stroke(); ?> <file_sep><?php include_once './clases.php'; include_once './conexion_consultas.php'; include './imagen.php'; ?> <!DOCTYPE html> <html> <head> <title>Principal</title> <meta charset="UTF-8"> </head> <body> <img src="<?= "/trabajo_final/imagenes/".$imagen.".jpg"?>" width=100% height="200"> <table height="70" width=100%> <tr> <?php if($inicio4 == 0){ ?> <form action="index.php?id=<?php echo $inicio3?>&d_h=1" method="post"> <td width=33.33% align="center"><input type="submit" value="Registro Diario"></td> <td width=33.33% align="center">Te muestra el regitro por horas</td> </form> <?php }else{ ?> <form action="index.php?id=<?php echo $inicio3?>&d_h=0" method="post"> <td width=33.33% align="center"><input type="submit" value="Registro Horario"></td> <td width=33.33% align="center">Te muestra el registro por dias</td> </form> <?php }; ?> <form action="anadir_estacion.php?id=<?php echo $inicio3?>" method="post"> <td width=33.33% align="center"><input type="submit" value="Nueva Estación"></td> </form> </tr> </table> <?php include './mapa1.js'; ?> <div id="map" style="width:100%;height:400px;"></div> <script src="http://maps.google.com/maps/api/js?sensor=false&callback=iniciar"></script> <?php if($inicio4 == 0){ ?> <table height="80" width=100%> <tr> <td width=33.33% align="center">Ultima temperatura: <?php echo $final_temperatura;?></td> <td width=33.33% align="center">Ultima Presion: <?php echo $final_presion;?></td> <td width=33.33% align="center">Ultima humedad: <?php echo $final_humedad;?></td> </tr> </table> <?php }else{ ?> <table height="80" width=100%> <tr> <td width=33.33% align="center">Temperatura media del dia anterior anterior: <?php echo $final_temperatura;?></td> <td width=33.33% align="center">Presion media del dia anterioranterior: <?php echo $final_presion;?></td> <td width=33.33% align="center">humedad media del dia anterior anterior: <?php echo $final_humedad;?></td> </tr> </table> <table height="80" width=100%> <tr> <td width=50% align="center">Temperatura maxima del dia anteriror: <?php echo $ultimo_maximo;?></td> <td width=50% align="center">Temperatura minima del dia anterior: <?php echo $ultimo_minimo;?></td> </tr> </table> <?php }?> <?php if($inicio4 == 0){ ?> <img src="grafico.php?id2=<?php echo $inicio3?>" alt="" border=100% align="center"> <?php }else{ ?> <img src="grafico_D.php?id2=<?php echo $inicio3?>" alt="" border=100% align="center"> <?php }?> </body> </html>
425be397c773c0df8c0a15b1ebed733dd18a9bf3
[ "PHP" ]
4
PHP
javier301/proyectoEstacion
76bec88c3f4d64dbefbf7ad3a49cb4473e89c13c
7f163275407fd3e1921649627cf6bdb70ee0c244
refs/heads/main
<repo_name>killas96/bitri_canonical<file_sep>/canonical.php <? $protocol = (CMain::IsHTTPS()) ? "https://" : "http://"; if (isset($_REQUEST['PAGEN_1']) || isset($_REQUEST['set_filter']) ) \Bitrix\Main\Page\Asset::getInstance()->addString('<link rel="canonical" href="' . $protocol . $_SERVER['HTTP_HOST'] . $APPLICATION->GetCurPage(false) . '" />');
2a4059681ef83cb81c93a3e68ba060e89b6d5e29
[ "PHP" ]
1
PHP
killas96/bitri_canonical
9ad808fa30aedbae5febb533551b2c94d0ed868c
e5ad8ae69c872858466f8d73baf6995cf06d8994
refs/heads/master
<file_sep>package com.example.demo; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; public interface PatientRepository extends MongoRepository<Patients, Integer>{ List<Patients> findAll() ; }
93d9deb5f3e18da377930344b5ce9032ec7dcc95
[ "Java" ]
1
Java
nesserine0/SpringBoot_Activity10
56919288b3a0008c8206d3d18cf4069c3da26b53
37f9c7b81d81a77f827990cac437c3c52f6f0613
refs/heads/master
<file_sep> import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import QRCode from 'qrcode.react'; import Connection from '../connection'; import { D_GRAY, DARK_SLATE, WHITE } from '../utils/Colors'; const Wrapper = styled.div` display: flex; justify-content: center; flex-direction: column; font-size: 2rem; margin-top: 5vh; @media only screen and (max-width: 600px) { width: 100%; } `; const OptionsWrapper = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; `; const Option = styled.div` display: flex; flex-direction: row; justify-content: center; align-content: center; align-items: center; width: 20rem; height: 10rem; margin: 1rem 0; user-select: none; color: ${(props) => props.color}; border: 2px solid ${(props) => props.color}; ${(props) => props.selected && ` background-color: ${props.color}; color: ${WHITE}; `} `; const Picking = ({ players, playerId }) => { const currentPlayer = players[playerId]; console.log(players) return ( <Wrapper> <br /> <OptionsWrapper> {['ROCK', 'PAPER', 'SCISSORS'].map(option => ( <Option color={currentPlayer.color} onClick={() => Connection.makeMove(option)} selected={currentPlayer.move == option} key={option} > {option} </Option> ))} </OptionsWrapper> </Wrapper> ); }; const mapStateToProps = (state) => ({ players: state.players, playerId: state.playerId, }); export default connect(mapStateToProps)(Picking); <file_sep>dnspython==1.16.0 eventlet==0.25.1 greenlet==0.4.15 monotonic==1.5 python-engineio==3.10.0 python-socketio==4.3.1 six==1.13.0 gunicorn==20.0.0<file_sep> import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import QRCode from 'qrcode.react'; import { D_GRAY, DARK_SLATE, WHITE } from '../utils/Colors'; const Wrapper = styled.div` display: flex; justify-content: center; flex-direction: column; font-size: 2rem; margin-top: 5vh; color: ${WHITE}; @media only screen and (max-width: 600px) { width: 100%; } `; const Row = styled.div` display: flex; flex-direction: row; justify-content: center; ${(props) => props.small && ` font-size: 1.5rem; `}} `; const QRWrapper = styled.div` align-self: center; background-color: ${WHITE}; border-radius: 0.25rem; padding: 0.7rem 0.7rem 0.3rem; margin: 1rem; `; const Landing = ({ status, gameId, playerId, players }) => { // You are not in the game // You are in the game, waiting for another const isInGame = !!players[playerId]; console.log(players) const prompt = isInGame ? 'Waiting for another player' : 'Game currently full'; return ( <Wrapper> <Row>Welcome</Row> <Row>Game:{gameId} | Player:{playerId}</Row> <Row>{prompt}</Row> </Wrapper> ); }; const mapStateToProps = (state) => ({ status: state.status, gameId: state.gameId, playerId: state.playerId, players: state.players, }); export default connect(mapStateToProps)(Landing); <file_sep> import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import QRCode from 'qrcode.react'; import { getStatus } from '../store/selectors'; import { D_GRAY, DARK_SLATE, WHITE } from '../utils/Colors'; const Wrapper = styled.div` display: flex; justify-content: center; flex-direction: column; font-size: 6rem; margin-top: 5vh; color: ${WHITE}; @media only screen and (max-width: 600px) { width: 100%; } `; const Row = styled.div` display: flex; flex-direction: row; justify-content: center; ${(props) => props.small && ` font-size: 4.5rem; `}} `; const QRWrapper = styled.div` align-self: center; background-color: ${WHITE}; border-radius: 0.25rem; padding: 1rem; margin: 20vh; `; console.log(process.env.REMOTE_HOST) const BASE_HOST = process.env.REMOTE_HOST || 'localhost' const BASE = `${BASE_HOST}:5001`; // const BASE = 'arkade.ngrok.io'; // const BASE = 'http://ixn-arkade.s3-website-us-east-1.amazonaws.com'; const Landing = ({ gameId, status }) => { const gameUrl = `${BASE}/?id=${gameId}` console.log(gameUrl) let prompt = 'Default prompt'; if (status === 'SLEEPING') prompt = '^ Scan to Start ^'; else if (status === 'JOINING') prompt = 'Waiting for one more...'; return ( <Wrapper> <Row>Rock,</Row> <Row>Paper,</Row> <Row>Scissors</Row> <QRWrapper> <a href={gameUrl}> <QRCode size={500} value={gameUrl} /> </a> </QRWrapper> <Row small>{prompt}</Row> </Wrapper> ); }; const mapStateToProps = (state) => ({ status: getStatus(state), gameId: state.gameId, }); export default connect(mapStateToProps)(Landing); <file_sep>import io from 'socket.io-client'; import * as Actions from './store/actions'; import { getStatus } from './store/selectors'; const API_BASE = 'localhost:3000'; // const API_BASE = 'http://api.arkade.ngrok.io'; // const API_BASE = '192.168.3.11'; class Connection { init(store) { this.store = store; this.io = io(API_BASE); this.io.on('connect', () => { const { gameId } = this.store.getState(); console.log(`Connected: Game ${gameId}`) this.io.emit('create_game', gameId); this.registerHandlers(); }); } registerHandlers() { this.io.on('new_player', (playerId) => { this.store.dispatch(Actions.addPlayer(playerId)); }); this.io.on('new_move', ({ player_id, move }) => { console.log(player_id) this.store.dispatch(Actions.setMove(player_id, move)); }); this.io.on('disconnect', (e) => { console.log(e) }); const unsubscribe = store.subscribe(() => { const state = store.getState(); const gameState = { status: getStatus(state), ...state, }; console.log(gameState) this.io.emit('update_state', state.gameId, gameState); }); } } export default new Connection();<file_sep>import { combineReducers } from 'redux'; import { connectRouter } from 'connected-react-router'; import * as Actions from './actions'; const url = new URL(location); const urlParameters = new URLSearchParams(url.search); const GAME_ID = urlParameters.get('id') || Math.round(Math.random()*10000); const gameId = () => GAME_ID; export const players = (state = {}, action) => { switch (action.type) { case Actions.ADD_PLAYER: { if (Object.keys(state).length < 2) { const color = Object.keys(state).length == 0 ? 'OrangeRed': 'DodgerBlue'; return { [action.playerId]: { id: action.playerId, color, move: null, winner: null, }, ...state, } } return state; } case Actions.SET_MOVE: { const player = state[action.playerId]; return { ...state, [action.playerId]: { ...player, move: action.move, }, }; } case Actions.RESET_MOVES: { return Object.entries(state).reduce((prev, [id, player]) => ({ ...prev, [id]: { ...player, move: null, } }), {}); } case Actions.SET_WINNER: { const player = state[action.playerId]; return { ...state, [action.playerId]: { ...player, winner: true, }, }; } default: return state; } }; export default (history) => combineReducers({ router: connectRouter(history), gameId, players, }); <file_sep> import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import QRCode from 'qrcode.react'; import * as Actions from '../store/actions'; import { D_GRAY, DARK_SLATE, WHITE } from '../utils/Colors'; const Wrapper = styled.div` display: flex; justify-content: center; flex-direction: column; font-size: 4rem; margin-top: 5vh; color: ${WHITE}; @media only screen and (max-width: 600px) { width: 100%; } `; const Row = styled.div` display: flex; flex-direction: row; justify-content: center; ${(props) => props.small && ` font-size: 1.5rem; `}} `; const SelectionWrapper = styled.div` display: flex; flex-direction: row; justify-content: center; width: 50%; height: 50%; padding: 20rem 0; background-color: ${(props) => props.color}; ${(props) => props.small && ` font-size: 1.5rem; `}} `; const PlayerSelection = ({ color, move }) => { return move ? ( <SelectionWrapper color={color}> READY </SelectionWrapper> ) : ( <SelectionWrapper> WAITING </SelectionWrapper> ); } const moveMap = { ROCK: 'SCISSORS', PAPER: 'ROCK', SCISSORS: 'PAPER', } const getWinningMove = ([moveA, moveB]) => { if (moveA === moveB) return null; if (moveMap[moveA] === moveB) return moveA; else return moveB; } const pickWinner = (players) => { const moves = Object.values(players).map(player => player.move); const winningMove = getWinningMove(moves) if (!winningMove) return null; const winningPlayer = Object.values(players).find(player => player.move === winningMove); return winningPlayer; } class Picking extends React.Component { constructor(props) { super(props); } componentDidUpdate(prevProps, prevState) { const { players, dispatch } = this.props; const numMoves = (play) => Object.values(play).filter(player => player.move).length; if (numMoves(prevProps.players) != numMoves(players)) { const [playerA, playerB] = Object.values(players); if (playerA.move && playerB.move) { // FOR SUSPENSE setTimeout(() => { const winner = pickWinner(players); if (winner === null) { iziToast.info({ title: 'TIE', titleSize: '2rem', position: 'center', timeout: 1000, }); setTimeout(() => dispatch(Actions.resetMoves()), 1000); } else { dispatch(Actions.setWinner(winner.id)); } }, 1500); } } } render() { const { dispatch, players } = this.props; const [playerA, playerB] = Object.values(players); return ( <Wrapper> <Row>CHOOSE WISELY</Row> <br /> <Row> <PlayerSelection color={playerA.color} move={playerA.move} /> <PlayerSelection color={playerB.color} move={playerB.move} /> </Row> </Wrapper> ); } } const mapStateToProps = (state) => ({ players: state.players, }); const mapDispatchToProps = (dispatch) => ({ dispatch, }); export default connect(mapStateToProps, mapDispatchToProps)(Picking); <file_sep>export const SET_STATUS = 'SET_STATUS'; export const SET_PLAYERS = 'SET_PLAYERS'; export const setStatus = (status) => ({ type: SET_STATUS, status }); export const setPlayers = (players) => ({ type: SET_PLAYERS, players }); <file_sep># base image FROM python:3 # set working directory WORKDIR /app # install and cache app dependencies COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app/ # start app CMD ["python", "/app/app.py"]<file_sep> import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import QRCode from 'qrcode.react'; import Connection from '../connection'; import { D_GRAY, DARK_SLATE, WHITE } from '../utils/Colors'; const Wrapper = styled.div` display: flex; justify-content: center; flex-direction: column; font-size: 2rem; margin-top: 20vh; text-align: center; color: ${(props) => props.color}; @media only screen and (max-width: 600px) { width: 100%; } `; const COOL_ADJECTIVES = ['AWESOME', 'GLORIOUS', 'ILLUSTRIOUS', 'MAGNIFICENT']; const COOL_NOUNS = ['CHAMPION', 'GENIUS', 'PSYCHIC', 'EXPERT']; const BAD_ADJECTIVES = ['UNLUCKY', 'UNFORTUNATE', 'POOR', 'SORRY']; const BAD_NOUNS = ['SOD', 'FOOL', 'AMATEUR', 'NOOB']; const getRandom = (items) => items[Math.floor(Math.random()*items.length)]; const Result = ({ players, playerId }) => { const player = players[playerId]; const isWinner = players[playerId].winner; const winningContent = `${getRandom(COOL_ADJECTIVES)} ${getRandom(COOL_NOUNS)}`; let losingContent = `${getRandom(BAD_ADJECTIVES)} ${getRandom(BAD_NOUNS)}`; if (Math.floor(Math.random()*10) < 3) { losingContent = 'THE WRONG SIDE OF A TERNARY OPEARATOR MY FRIEND'; } return ( <Wrapper color={player.color}> {isWinner ? 'WINNER!' : 'LOSER!'} <br /> <br /> {isWinner ? winningContent : losingContent} </Wrapper> ); }; const mapStateToProps = (state) => ({ players: state.players, playerId: state.playerId, }); export default connect(mapStateToProps)(Result); <file_sep> import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import QRCode from 'qrcode.react'; import * as Actions from '../store/actions'; import { D_GRAY, DARK_SLATE, WHITE } from '../utils/Colors'; const Wrapper = styled.div` display: flex; justify-content: center; flex-direction: column; font-size: 2rem; margin-top: 5vh; color: ${WHITE}; @media only screen and (max-width: 600px) { width: 100%; } `; const Row = styled.div` display: flex; flex-direction: row; justify-content: center; ${(props) => props.small && ` font-size: 1.5rem; `}} `; const WinnernWrapper = styled.div` display: flex; flex-direction: row; justify-content: center; width: 100%; padding: 20rem 0; background-color: ${(props) => props.color}; ${(props) => props.small && ` font-size: 1.5rem; `}} `; const Move = styled.span` color: ${(props) => props.color}; margin: 0 1rem; `; const Picking = ({ players }) => { const winner = Object.values(players).find(player => player.winner); const loser = Object.values(players).find(player => !player.winner); setTimeout(() => location.reload(), 5000) return ( <Wrapper> <Row> <Move color={winner.color}>{winner.move}</Move> beats <Move color={loser.color}>{loser.move}</Move> </Row> <br /> <Row> <WinnernWrapper color={winner.color}> Player {winner.id} wins! </WinnernWrapper> </Row> </Wrapper> ); }; const mapStateToProps = (state) => ({ players: state.players, }); const mapDispatchToProps = (dispatch) => ({ dispatch, }); export default connect(mapStateToProps, mapDispatchToProps)(Picking); <file_sep>import eventlet import socketio sio = socketio.Server(async_mode='eventlet', cors_allowed_origins='*') app = socketio.WSGIApp(sio) @sio.event def connect(sid, data): print('connect ', sid) @sio.event def create_game(sid, game_id): game_room = f'game-{game_id}' print('create_game', sid, game_room) sio.enter_room(sid, game_room) @sio.event def join_game(sid, game_id, player_id): game_room = f'game-{game_id}' print('join_game', sid, game_room, player_id) sio.enter_room(sid, game_room) sio.emit('new_player', player_id, room=game_room) @sio.event def update_state(sid, game_id, game_state): game_room = f'game-{game_id}' sio.emit('new_game_state', game_state, room=game_room, skip_sid=sid) @sio.event def new_move(sid, game_id, player_id, move): game_room = f'game-{game_id}' print('new move', game_room, player_id, move) data = { 'player_id': player_id, 'move': move } sio.emit('new_move', data, room=game_room, skip_sid=sid) @sio.event def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': eventlet.wsgi.server(eventlet.listen(('', 3000)), app, debug=True)<file_sep># arkade PoC Rock, Paper, Scissors game that allows phones to join and function as controllers (via websockets) ### [Demo](https://s3.amazonaws.com/www.jdhayford.io/videos/quick-demo.mp4) ![Pic](https://s3.amazonaws.com/www.jdhayford.io/images/arkade-shot.png) ## Components - master-client - remote-client - server ### master-client This client (React) is meant to serve as the "screen" for the game. Starts with prompt (QR code) for a user to scan to "join". ### remote-cient This client (React) that one arrives at upon "joining" the game, see above. This serves as the users remote control that they can use to make a selection. ### Server The websocket server responsible for syncronizing game state between the clients. ## Running Locally Everything is setup with docker so all you need to do is: ``` docker-compose up ``` After that you can pull up `localhost:5000` for the host screen. To add a player, you click the QR code (when configured and deployed this can just be scanned by your phone). <file_sep>export const getSession = (state) => state.session; export const getSessionStatus = (state) => state.sessionStatus; export const getStatus = (state) => { const { players } = state; if (Object.keys(players).length == 0) return 'SLEEPING' if (Object.keys(players).length < 2) return 'JOINING' const isWinner = Object.values(players).find(player => player.winner); const moves = Object.values(players).map(player => player.move).filter(move => !!move); if (isWinner) return 'SHOWING'; if (moves.length <= 2) return 'PICKING'; return 'DEFAULT'; }
7c25da37bad5a4589d5f89bf809a428d3b173669
[ "JavaScript", "Markdown", "Python", "Text", "Dockerfile" ]
14
JavaScript
jdhayford/arkade
3b01284a5a5dd922011a7aabec188c7fa316b35b
a90376a1465dfa866eed0b2442636c32e792323c
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameEngine : MonoBehaviour { public GameObject selectedZombie; public List<GameObject> zombies; public Vector3 selectedSize; public Vector3 defaultSize; private int selectedZombieposition = 0; public Text scoreText; public int score = 0; // Start is called before the first frame update void Start() { SelectZombie(selectedZombie); scoreText.text = "Score: " + score; } // Update is called once per frame void Update() { if(Input.GetKeyDown("left")) { deSelectZombie(zombies[selectedZombieposition]); if (selectedZombieposition == 0) { SelectZombie(zombies[3]); selectedZombieposition = 3; } else { SelectZombie(zombies[(selectedZombieposition - 1)%4]); selectedZombieposition = (selectedZombieposition - 1)%4; } selectedZombie = zombies[selectedZombieposition]; } if(Input.GetKeyDown("right")) { deSelectZombie(zombies[selectedZombieposition]); SelectZombie(zombies[(selectedZombieposition + 1)%4]); selectedZombieposition = (selectedZombieposition + 1)%4; selectedZombie = zombies[selectedZombieposition]; } if(Input.GetKeyDown("up")) { PushUp(); } } void SelectZombie(GameObject newZombie) => newZombie.transform.localScale = selectedSize; void deSelectZombie(GameObject newZombie) => newZombie.transform.localScale = defaultSize; void PushUp() { Rigidbody rb = selectedZombie.GetComponent<Rigidbody>(); rb.AddForce(0,0,2,ForceMode.Impulse); } public void AddPoint() { score += 1; scoreText.text = "Score: " + score; } } <file_sep># Learning-Game-Development This repository consists of all games build by me while learning game development.
3af75dbbd74e2e956f3f5efd20362a43bf566d4a
[ "Markdown", "C#" ]
2
C#
The-An0rack/Learning-Game-Development
97af4a924edb790b2501e4c43b242cebb5cc1c12
a9d807996ebfa9304e651f70cd7ea3549ec507ea
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Cryptography { class PlayFairEncryption { List<string> steps = new List<string>(); public List<string> getStep() { return steps; } public String PFEncryption(String keyword, String input) { string key = keyword.ToLower(); string matrix = null; string alphabets = "abcdefghiklmnopqrstuvwxyz"; string inputMsg = input.ToLower(); string output = ""; #region _ Regex rgx = new Regex("[^a-z-]"); #endregion key = rgx.Replace(key, ""); key = key.Replace('j', 'i'); for (int i = 0; i < key.Length; i++) { if ((matrix == null) || (!matrix.Contains(key[i]))) { steps.Add("Function is making matrix of keyword and inserting " + key[i] + " "+"in that matrix"); matrix += key[i]; } } steps.Add("Complete matrix is : " + matrix +" and removing repeating alphabet"); for (int i = 0; i < alphabets.Length; i++) { if (!matrix.Contains(alphabets[i])) { steps.Add("Complete Matrix with alphabets, here is " + alphabets[i].ToString()); matrix += alphabets[i]; } } inputMsg = rgx.Replace(inputMsg, ""); inputMsg = inputMsg.Replace('j', 'i'); steps.Add("Removing j from alphabets because the matrix is 5 * 5"); for (int i = 0; i < inputMsg.Length; i += 2) { if (((i + 1) < inputMsg.Length) && (inputMsg[i] == inputMsg[i + 1])) { inputMsg = inputMsg.Insert(i + 1, "x"); steps.Add("Function is replacing x on repeating alphabets"); } } if ((inputMsg.Length % 2) > 0) { steps.Add("Input message is odd number then add x = " + inputMsg + "x"); inputMsg += "x"; } int iTemp = 0; do { int iPosA = matrix.IndexOf(inputMsg[iTemp]); int iPosB = matrix.IndexOf(inputMsg[iTemp + 1]); int iRowA = iPosA / 5; int iColA = iPosA % 5; int iRowB = iPosB / 5; int iColB = iPosB % 5; if (iColA == iColB) { iPosA += 5; iPosB += 5; } else { if (iRowA == iRowB) { if (iColA == 4) { iPosA -= 4; } else { iPosA += 1; } if (iColB == 4) { iPosB -= 4; } else { iPosB += 1; } } else { if (iRowA < iRowB) { iPosA -= iColA - iColB; iPosB += iColA - iColB; } else { iPosA += iColB - iColA; iPosB -= iColB - iColA; } } } if (iPosA >= matrix.Length) { iPosA = 0 + (iPosA - matrix.Length); } if (iPosB >= matrix.Length) { iPosB = 0 + (iPosB - matrix.Length); } output += matrix[iPosA].ToString() + matrix[iPosB].ToString(); iTemp += 2; } while (iTemp < inputMsg.Length); steps.Add("Function is completed, encrypted message is " + output); return output; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Cryptography { public partial class Form3 : Form { public Form3() { InitializeComponent(); } PlayFairEncryption pfe = new PlayFairEncryption(); PlayFairDecryption pfd = new PlayFairDecryption(); public void print() { } private void button1_Click(object sender, EventArgs e) { String a = pfe.PFEncryption(textBox1.Text.ToLower(), richTextBox1.Text.ToLower()); listBox1.Items.Clear(); richTextBox2.Text = a; listBox1.Items.Clear(); List<string> steps = pfe.getStep(); for (int i = 0; i < steps.Count; i++) { listBox1.Items.Add(steps[i]); } } private void button2_Click(object sender, EventArgs e) { String a = pfd.PFDecryption(textBox1.Text.ToLower(), richTextBox1.Text.ToLower()); richTextBox2.Text = a; listBox1.Items.Clear(); List<string> steps = pfd.getStep(); for (int i = 0; i < steps.Count; i++) { listBox1.Items.Add(steps[i]); } } private void button3_Click(object sender, EventArgs e) { Application.Exit(); } private void button4_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); f1.Show(); this.Hide(); } private void button5_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); f3.Show(); this.Hide(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cryptography { class PlayFairDecryption { List<string> steps = new List<string>(); public List<string> getStep() { return steps; } public String PFDecryption(String keyword, String input) { string sKey = keyword.ToLower(); string sGrid = null; string sAlpha = "abcdefghiklmnopqrstuvwxyz"; string sInput = input.ToLower(); string sOutput = ""; sKey = sKey.Replace('j', 'i'); for (int i = 0; i < sKey.Length; i++) { if ((sGrid == null) || (!sGrid.Contains(sKey[i]))) { steps.Add("Keyword is : " + sKey[i] + " in that matrix"); sGrid += sKey[i]; } } steps.Add("complete matrix is : " + sGrid + " and removing repeating alphabet"); for (int i = 0; i < sAlpha.Length; i++) { if (!sGrid.Contains(sAlpha[i])) { steps.Add("Complete Matrix with alphabets, here is " + sAlpha[i].ToString()); sGrid += sAlpha[i]; } } int iTemp = 0; do { int iPosA = sGrid.IndexOf(sInput[iTemp]); int iPosB = sGrid.IndexOf(sInput[iTemp+1]); int iRowA = iPosA / 5; int iColA = iPosA % 5; int iRowB = iPosB / 5; int iColB = iPosB % 5; if (iColA == iColB) { iPosA -= 5; iPosB -= 5; } else { if (iRowA == iRowB) { if (iColA == 0) { iPosA += 4; } else { iPosA -= 1; } if (iColB == 0) { iPosB += 4; } else { iPosB -= 1; } } else { if (iRowA < iRowB) { iPosA -= iColA - iColB; iPosB += iColA - iColB; } else { iPosA += iColB - iColA; iPosB -= iColB - iColA; } } } if (iPosA > sGrid.Length) { iPosA = 0 + (iPosA - sGrid.Length); } if (iPosB > sGrid.Length) { iPosB = 0 + (iPosB - sGrid.Length); } if (iPosA < 0) { iPosA = sGrid.Length + iPosA; } if (iPosB < 0) { iPosB = sGrid.Length + iPosB; } sOutput += sGrid[iPosA].ToString() + sGrid[iPosB].ToString(); iTemp += 2; } while (iTemp < sInput.Length-1); steps.Add("Function is completed, decrypted message is " + sOutput); return sOutput; } } }
ddd2b9db9c6e31d30d20b90fa269ca97685633c4
[ "C#" ]
3
C#
alighaffari14/PlayFairCipherCsharp
8305ca5ea1d740602d8f60f986121d1537a5493c
d61f9b342fe7a9d72c2cfdf2b0ae48862b95a4c4
refs/heads/master
<repo_name>RiccardoCantoni/spaceInvadersAI<file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/FuzzyBehaviour.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FuzzyBehaviour { public bool spacebarOutput; public float movementOutput; protected Sensor sensor; protected GameObject displayObject; public virtual void updateOutputs (){ } public void init(Sensor s, GameObject display){ this.sensor = s; this.displayObject = display; } protected void setDisplayMessage(List<string> msg){ displayObject.GetComponent<Display> ().stringList = msg; } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/AttackLowest.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AttackLowest : FuzzyBehaviour { #region targetPosition FuzzyClass targetCloseRight = new FuzzyClass (0, 0.5f, 1, 3); FuzzyClass targetRight = new FuzzyClass (1, 3, 5, 7); FuzzyClass targetFarRight = new FuzzyClass (5, 7, 16, 17); FuzzyClass targetCloseLeft = new FuzzyClass (-3, -1, -0.5f, 0); FuzzyClass targetLeft = new FuzzyClass (-7, -5, -3, -1); FuzzyClass targetFarLeft = new FuzzyClass (-17, -16, -7, -5); #endregion #region shield CrispClass underShield = new CrispClass (-0.8f, 0.8f); #endregion #region alienSpeed FuzzyClass speedLowPositive = new FuzzyClass (0, 0.75f, 1.15f, 1.45f); FuzzyClass speedMediumPositive = new FuzzyClass (1.15f, 1.45f, 1.95f, 2.35f); FuzzyClass speedHighPositive = new FuzzyClass (1.95f, 2.35f, 2.75f, 3); FuzzyClass speedLowNegative = new FuzzyClass (-1.45f, -1.15f, -0.75f, 0); FuzzyClass speedMediumNegative = new FuzzyClass (-2.35f, -1.95f, -1.45f, 1.15f); FuzzyClass speedHighNegative = new FuzzyClass (-3, -2.75f, -2.35f, -1.95f); #endregion public override void updateOutputs(){ //variabile composta float targetPosition = sensor.lowestAlienDistance + sensor.lowestAlienLead; //fuzzyficazione float tgp, tgpp, tgppp, tgn, tgnn, tgnnn; tgp = targetCloseRight.calculateMembership (targetPosition); tgpp = targetRight.calculateMembership (targetPosition); tgppp = targetFarRight.calculateMembership (targetPosition); tgn = targetCloseLeft.calculateMembership (targetPosition); tgnn = targetLeft.calculateMembership (targetPosition); tgnnn = targetFarLeft.calculateMembership (targetPosition); float shield; shield = underShield.calculateMembership (sensor.shieldDistance); float sp, spp, sppp, sn, snn, snnn; sp = speedLowPositive.calculateMembership (sensor.alienVelocity); spp = speedMediumPositive.calculateMembership (sensor.alienVelocity); sppp = speedHighPositive.calculateMembership (sensor.alienVelocity); sn = speedLowNegative.calculateMembership (sensor.alienVelocity); snn = speedMediumNegative.calculateMembership (sensor.alienVelocity); snnn = speedHighNegative.calculateMembership (sensor.alienVelocity); //FAM float hardRight, right, hardLeft, left; float tgMovingRight, tgMovingLeft; float tgIsRight, tgIsLeft; // tgppp //OR // tgpp & (mvright | sn) //OR // shield & isright tgMovingRight = FuzzyLib.fuzzyOr(sp, spp, sppp); tgIsRight = FuzzyLib.fuzzyOr (tgp, tgpp, tgppp); hardRight = tgppp; hardRight = FuzzyLib.fuzzyOr(hardRight, FuzzyLib.fuzzyAnd(tgpp, FuzzyLib.fuzzyOr(tgMovingRight, sn))); hardRight = FuzzyLib.fuzzyOr(hardRight, FuzzyLib.fuzzyAnd (shield, tgIsRight)); // tgp //OR // (tgpp & (tgnn | tgnnn)) tgMovingLeft = FuzzyLib.fuzzyOr(tgnn, tgnnn); right = FuzzyLib.fuzzyOr (tgp, FuzzyLib.fuzzyAnd (tgpp, tgMovingLeft)); right = FuzzyLib.fuzzyAnd (right, FuzzyLib.fuzzyNot (shield)); // tgn //OR // (tgnn & (tgpp | tgppp)) tgMovingRight = FuzzyLib.fuzzyOr(tgpp, tgppp); left = FuzzyLib.fuzzyOr (tgn, FuzzyLib.fuzzyAnd (tgnn, tgMovingRight)); left = FuzzyLib.fuzzyAnd (left, FuzzyLib.fuzzyNot (shield)); // tgnnn //OR // (tgnn & (mvleft | sp) //OR // shield & isleft tgMovingLeft = FuzzyLib.fuzzyOr(sn, snn, snnn); tgIsLeft = FuzzyLib.fuzzyOr (tgn, tgnn, tgnnn); hardLeft = tgnnn; hardLeft = FuzzyLib.fuzzyOr(hardLeft, FuzzyLib.fuzzyAnd(tgnn, FuzzyLib.fuzzyOr(tgMovingLeft, sp))); hardLeft = FuzzyLib.fuzzyOr(hardLeft, FuzzyLib.fuzzyAnd(shield, tgIsLeft)); //defuzzyficazione movementOutput = (-0.8f)*hardLeft +(-0.4f)*left + 0.4f*right + 0.8f*hardRight ; if ((left + hardLeft + right + hardRight)>1) Debug.Log (left.ToString("F2") + hardLeft.ToString("F2") + right .ToString("F2")+ hardRight.ToString("F2")); spacebarOutput = FuzzyLib.toBool (FuzzyLib.fuzzyNot(shield)); //display List<string> message = new List<string>(); message.Add ("==ATK LOWEST=="); message.Add ("target distance:"); message.Add (tgnnn.ToString("F2") + "|" + tgnn.ToString ("F2") + "|" + tgn.ToString ("F2") + (" l")); message.Add (tgp.ToString("F2") + "|" + tgpp.ToString("F2") + "|" + tgppp.ToString("F2") + (" r")); message.Add ("target velocity:"); message.Add (snnn.ToString ("F2") + "|" + snn.ToString ("F2") + "|" + sn.ToString ("F2")+ (" l")); message.Add (sp.ToString ("F2") + "|" + spp.ToString ("F2") + "|" + sppp.ToString ("F2")+ (" r")); message.Add ("shield:"); message.Add (shield.ToString("F2")); message.Add ("movement:"); message.Add (hardLeft.ToString("F2") + "|" + left.ToString("F2") + "|" + right.ToString("F2") + "|" + hardRight.ToString("F2")); message.Add ("shooting"); message.Add (spacebarOutput.ToString()); setDisplayMessage (message); } } <file_sep>/Space Invaders/Assets/Scripts/aliens/MovementManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovementManager : MonoBehaviour { public float initialVerticalSpeed; public float finalVerticalSpeed; public float initialHorizontalSpeed; public float finalHorizontalSpeed; float horizontalSpeedIncrease; float verticalSpeedIncrease; public Vector2 alienVelocityVector; void Start(){ horizontalSpeedIncrease = (finalHorizontalSpeed - initialHorizontalSpeed) / 55f; verticalSpeedIncrease = (finalVerticalSpeed - initialVerticalSpeed) / 55f; } public void DownLeft(float timeDown){ StartCoroutine (DownLeftCoroutine (timeDown)); } public void DownRight(float timeDown){ StartCoroutine (DownRightCoroutine (timeDown)); } IEnumerator DownRightCoroutine(float timeDown){ alienVelocityVector = (Vector3.down * initialVerticalSpeed); yield return new WaitForSeconds (timeDown); alienVelocityVector = (Vector3.right * initialHorizontalSpeed); } IEnumerator DownLeftCoroutine(float timeDown){ alienVelocityVector = (Vector3.down * initialVerticalSpeed); yield return new WaitForSeconds (timeDown); alienVelocityVector = (Vector3.left * initialHorizontalSpeed); } public void initiate (Vector3 vector){ alienVelocityVector = (vector*initialHorizontalSpeed); } public void increaseGameSpeed(){ initialVerticalSpeed += verticalSpeedIncrease; initialHorizontalSpeed += horizontalSpeedIncrease; updateVelocityVector (); } private void updateVelocityVector(){ Vector3 dir = alienVelocityVector.normalized; if (dir.x == 0) { // up down alienVelocityVector = dir * initialVerticalSpeed; } else { //left right alienVelocityVector = dir * initialHorizontalSpeed; } } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/fuzzyLogic/CrispClass.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CrispClass{ float p1, p2; public CrispClass(float p1, float p2){ this.p1 = p1; this.p2 = p2; } public float calculateMembership(float inputValue){ if (inputValue <= p1) return 0; if (inputValue < p2) return 1; return 0; } } <file_sep>/Space Invaders/Assets/Scripts/player units/player controllers/playerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerController : MonoBehaviour { public float Velocity; public float timeBetweenShots; public GameObject bullet; public float bound; Vector3 initialPos; float nextShootingWindow; void Start(){ initialPos = transform.position; nextShootingWindow = Time.time; } void Update () { float input = Input.GetAxis ("Horizontal"); Vector3 newpos = transform.position + Vector3.right * input * Velocity * Time.deltaTime; if (newpos.x > initialPos.x - bound & newpos.x < initialPos.x + bound) { transform.position = newpos; } if (Input.GetKeyDown ("space")) { shoot (); } } void shoot() { if (Time.time > nextShootingWindow) { Instantiate (bullet, transform.position, transform.rotation); nextShootingWindow = Time.time + timeBetweenShots; } } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/AttackRedShip.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AttackRedShip : FuzzyBehaviour { #region targetPosition FuzzyClass targetCloseRight = new FuzzyClass (0, 0.5f, 1, 3); FuzzyClass targetRight = new FuzzyClass (1, 3, 5, 7); FuzzyClass targetFarRight = new FuzzyClass (5, 7, 16, 17); FuzzyClass targetCloseLeft = new FuzzyClass (-3, -1, -0.5f, 0); FuzzyClass targetLeft = new FuzzyClass (-7, -5, -3, -1); FuzzyClass targetFarLeft = new FuzzyClass (-17, -16, -7, -5); #endregion #region shield CrispClass underShield = new CrispClass (-0.8f, 0.8f); #endregion public override void updateOutputs(){ //variabile composta float targetPosition = sensor.redShipDistance + sensor.redShipLead; //fuzzyficazione float tgp, tgpp, tgppp, tgn, tgnn, tgnnn; tgp = targetCloseRight.calculateMembership (targetPosition); tgpp = targetRight.calculateMembership (targetPosition); tgppp = targetFarRight.calculateMembership (targetPosition); tgn = targetCloseLeft.calculateMembership (targetPosition); tgnn = targetLeft.calculateMembership (targetPosition); tgnnn = targetFarLeft.calculateMembership (targetPosition); float shield; shield = underShield.calculateMembership (sensor.shieldDistance); //FAM float hardLeft, left, right, hardRight; hardLeft = FuzzyLib.fuzzyOr (tgn, FuzzyLib.fuzzyOr (tgnn, tgnnn)); hardRight = FuzzyLib.fuzzyOr (tgp, FuzzyLib.fuzzyOr (tgpp, tgppp)); left = 0; right = 0; //defuzzyficazione movementOutput = -0.8f*hardLeft -0.4f*left + 0.4f*right + 0.8f*hardRight ; spacebarOutput = FuzzyLib.toBool (FuzzyLib.fuzzyNot(shield)); //display List<string> message = new List<string>(); message.Add ("==ATK RED SHIP=="); message.Add ("target distance:"); message.Add (tgnnn.ToString("F2") + "|" + tgnn.ToString ("F2") + "|" + tgn.ToString ("F2") + (" l")); message.Add (tgp.ToString("F2") + "|" + tgpp.ToString("F2") + "|" + tgppp.ToString("F2") + (" r")); message.Add ("shooting"); message.Add (spacebarOutput.ToString()); setDisplayMessage (message); } }<file_sep>/Space Invaders/Assets/Scripts/fuzzy/MainFuzzyController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainFuzzyController : MonoBehaviour { public float horizontalAxisInput; public bool spacebarInput; public int behaviourIndex; public GameObject behaviourDisplay, selectorDisplay; BehaviourSelector behaviourSelector = new BehaviourSelector (); FuzzyBehaviour avoidBehavior = new Avoid (); FuzzyBehaviour shelterBehavior = new Shelter (); FuzzyBehaviour atkRedShipBehaviour = new AttackRedShip (); FuzzyBehaviour atkClosestBehaviour = new AttackClosest (); FuzzyBehaviour atkLowestBehaviour = new AttackLowest (); FuzzyBehaviour currentBehaviour; GameObject marker; Sensor sensor; void Start(){ sensor = gameObject.GetComponent<Sensor>(); sensor.initSensor (); behaviourSelector.init (sensor, selectorDisplay); avoidBehavior.init (sensor, behaviourDisplay); shelterBehavior.init (sensor, behaviourDisplay); atkRedShipBehaviour.init (sensor, behaviourDisplay); atkClosestBehaviour.init (sensor, behaviourDisplay); atkLowestBehaviour.init (sensor, behaviourDisplay); } void Update(){ sensor.updateSensor (); behaviourSelector.selectBehaviour (); switch (behaviourSelector.behaviourIndex) { case 0: currentBehaviour = avoidBehavior; break; case 1: currentBehaviour = shelterBehavior; break; case 2: currentBehaviour = atkRedShipBehaviour; break; case 3: currentBehaviour = atkClosestBehaviour; break; case 4: currentBehaviour = atkLowestBehaviour; break; default: Debug.Log ("index error"); Time.timeScale = 0; break; } currentBehaviour.updateOutputs (); horizontalAxisInput = currentBehaviour.movementOutput; spacebarInput = currentBehaviour.spacebarOutput; if (Mathf.Abs (currentBehaviour.movementOutput) > 1) { Debug.Log ("input error, behaviour " + behaviourIndex); } } } <file_sep>/Space Invaders/Assets/Scripts/game mechanics/ExplosionManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExplosionManager : MonoBehaviour { public GameObject explosion; public void explode(){ Instantiate (explosion, transform.position, transform.rotation); } } <file_sep>/Space Invaders/Assets/menu/SelectorScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SelectorScript : MonoBehaviour { public GameObject selectorPrefab; public List<GameObject> buttons; public GameObject placeholder; GameObject selector; public void onHover(int parameter){ if (selector == null) { selector = Instantiate (selectorPrefab); selector.transform.parent = transform; } switch (parameter) { case 0: selector.transform.position = new Vector3 (placeholder.transform.position.x, buttons[0].transform.position.y, 100); break; case 1: selector.transform.position = new Vector3 (placeholder.transform.position.x, buttons[1].transform.position.y, 100); break; case 2: selector.transform.position = new Vector3 (placeholder.transform.position.x, buttons[2].transform.position.y, 100); break; default: break; } } } <file_sep>/Space Invaders/Assets/Scripts/player units/shields/ShieldStage.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShieldStage : MonoBehaviour { void OnCollisionEnter2D () { ShieldScript shield = transform.parent.gameObject.GetComponent<ShieldScript> (); shield.isHit (); } } <file_sep>/Space Invaders/Assets/Scripts/player units/player controllers/autoPlayerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class autoPlayerController: MonoBehaviour { public float Velocity; public float timeBetweenShots; public GameObject bullet; public float bound; public float input; float nextShootingWindow; MainFuzzyController MFC; void Start(){ nextShootingWindow = Time.time; MFC = gameObject.GetComponent<MainFuzzyController> (); } void Update () { input = MFC.horizontalAxisInput; Vector3 newpos = transform.position + Vector3.right * input * Velocity * Time.deltaTime; if (newpos.x > (-1f*bound) & newpos.x < bound) { transform.position = newpos; } if (MFC.spacebarInput) { shoot (); } } void shoot() { if (Time.time > nextShootingWindow) { Instantiate (bullet, transform.position, transform.rotation); nextShootingWindow = Time.time + timeBetweenShots; } } } <file_sep>/Space Invaders/Assets/Scripts/aliens/ShootingManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShootingManager : MonoBehaviour { public float FireDelay; List<GameObject> aliens=new List<GameObject>(); public void Initiate () { StartCoroutine (commandShoot()); } IEnumerator commandShoot(){ while (true) { yield return new WaitForSeconds (FireDelay); aliens.Clear (); foreach (Transform child in transform) { aliens.Add (child.gameObject); } if (aliens.Count>0){ int i = Random.Range (0, aliens.Count); alienController shooter = aliens [i].GetComponent<alienController> (); shooter.shoot (); } } } } <file_sep>/Space Invaders/Assets/Scripts/player units/shields/ShieldScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShieldScript : MonoBehaviour { public int hp; public GameObject st1; public GameObject st2; public GameObject st3; GameObject curStage; void Start () { hp = 3; curStage=Instantiate (st1, transform.position, transform.rotation); curStage.transform.parent = transform; } public void isHit(){ hp--; Destroy (curStage); switch (hp) { case 2: curStage = Instantiate (st2, transform.position + Vector3.down*0, transform.rotation); curStage.transform.parent = transform; break; case 1: curStage = Instantiate (st3, transform.position + Vector3.down*0, transform.rotation); curStage.transform.parent = transform; break; case 0: Destroy (gameObject); break; } } } <file_sep>/Space Invaders/Assets/Scripts/aliens/RedShipController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class RedShipController : MonoBehaviour { public float velocity; public Vector2 direction; Rigidbody2D rb; void Start(){ rb = gameObject.GetComponent<Rigidbody2D> (); } public void initiate(Vector3 dir){ direction = new Vector2 (dir.x, dir.y); } void Update () { rb.MovePosition (rb.position + direction * velocity * Time.deltaTime); } } <file_sep>/Space Invaders/Assets/Scripts/game mechanics/TimeToLive.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TimeToLive : MonoBehaviour { public float time; void Start(){ StartCoroutine (selfDestruct()); } IEnumerator selfDestruct(){ yield return new WaitForSeconds (time); Destroy (gameObject); } } <file_sep>/Space Invaders/Assets/menu/GameData.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public static class GameData{ public static bool gameWon; public static bool gameHuman; public static int gameScore; public static GameManager gameManager; public static bool hasData; public static float startTime; public static float gameDuration; } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/fuzzyLogic/FuzzyLib.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FuzzyLib{ public static float fuzzyAnd(float a, float b){ return Mathf.Min (a, b); } public static float fuzzyAnd (float a, float b, float c){ return fuzzyAnd (a, fuzzyAnd (b, c)); } public static float fuzzyOr(float a, float b){ return Mathf.Max (a, b); } public static float fuzzyOr(float a, float b, float c){ return fuzzyOr (a, fuzzyOr (b, c)); } public static float fuzzyNot(float a){ return 1f - a; } public static float fuzzyOrMultiple(List<float> list){ return Mathf.Max (list.ToArray ()); } public static bool toBool (float f){ if (f == 0) { return false; } return true; } } <file_sep>/Space Invaders/Assets/Scripts/aliens/gridManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class gridManager : MonoBehaviour { public GameObject alien; public Vector3 startPos; public float cellWidth; public float cellHeight; public float rightBound; public float leftBound; public float timeDown; int state = 0; //right int rows = 5; int columns = 11; MovementManager movementmanager; ShootingManager shootingmanager; void Start () { spawnGrid (); shootingmanager = gameObject.GetComponent<ShootingManager> (); shootingmanager.Initiate (); movementmanager = gameObject.GetComponent<MovementManager> (); movementmanager.initiate (Vector3.right); } public void spawnGrid(){ GameObject a; alienController script; Vector3 pos = startPos; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { a=Instantiate (alien, pos, transform.rotation); a.transform.parent = transform; script = a.GetComponent<alienController> (); script.gridpos = new Vector2 (c,r); pos += Vector3.right * cellWidth; } pos.x = startPos.x; pos += Vector3.down * cellHeight; } } void Update(){ foreach (Transform child in transform) { if (state==0 && child.transform.position.x>=rightBound){ state = 1; movementmanager.DownLeft (timeDown); } if (state==1 & child.transform.position.x<=leftBound){ state = 0; movementmanager.DownRight (timeDown); } } } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/fuzzyLogic/FuzzyClass.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FuzzyClass { float p1, p2, p3, p4; public FuzzyClass(float p1, float p2, float p3, float p4){ this.p1 = p1; this.p2 = p2; this.p3 = p3; this.p4 = p4; } public FuzzyClass(float p1, float p2, float p3){ this.p1 = p1; this.p2 = p2; this.p3 = p2; this.p4 = p3; } public float calculateMembership(float inputValue){ float ratio; if (inputValue <= p1 | inputValue >= p4) { return 0; } if (inputValue > p1 & inputValue < p2 ) { ratio = Mathf.Abs(inputValue - p1) / Mathf.Abs(p2 - p1); return (Mathf.Lerp(0,1,ratio)); } if (inputValue >= p2 & inputValue <= p3) { return 1; } if (inputValue > p3 & inputValue < p4) { ratio = Mathf.Abs(inputValue - p3) / Mathf.Abs(p4 - p3); return (Mathf.Lerp(1,0,ratio)); } return 0; } public static FuzzyClass mirrorPositive(FuzzyClass x){ return new FuzzyClass (x.p4 * (-1), x.p3 * (-1), x.p2 * (-1), x.p1 * (-1)); } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/MyUtils.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class MyUtils{ public static float closest(List<float> list, float playerPos){ float minDistance = Mathf.Abs (list [0] - playerPos); int closestIndex = 0; for (int i = 1; i < list.Count; i++) { float d = Mathf.Abs (list [i] - playerPos); if (d < minDistance) { minDistance = d; closestIndex = i; } } return list[closestIndex]; } public static float calculateLead(float tgSpeed, float tgHeight, float projectileSpeed){ float res = Mathf.Abs(tgSpeed * tgHeight / projectileSpeed); if (tgSpeed > 0) { return res; } else { return res *(-1); } } public static Vector3 gridToVector3(int x, int y, GameObject offsetMarker) { return new Vector3 (x * 1.36f + offsetMarker.transform.position.x - 7.8f, y * -1 + offsetMarker.transform.position.y + 4, -10); } public static int argmax(float[] values){ int minIndex = -1; float minValue = 0; for (int i = 0; i < values.Length; i++) { if (values [i] > minValue) { minIndex = i; } } return minIndex; } public static void appendToFile(string filename, string text){ System.IO.File.AppendAllText (filename, text+Environment.NewLine); } } <file_sep>/Space Invaders/Assets/Scripts/others/Display.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Display : MonoBehaviour { public string title; public List<string> stringList; Text text; void Start () { stringList = new List<string> (); text = gameObject.transform.GetChild (0).transform.GetChild (0).GetComponent<Text> (); } void Update () { string newText = title + "\n"; foreach (string s in stringList) { newText = newText + (s + "\n"); } text.text = newText; } } <file_sep>/Space Invaders/Assets/Scripts/others/markerMover.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class markerMover : MonoBehaviour { MovementManager mvm; Rigidbody2D rb ; void Start(){ mvm = GameObject.Find ("alienManager").GetComponent<MovementManager> (); rb = gameObject.GetComponent<Rigidbody2D> (); } void Update () { rb.MovePosition (rb.position + mvm.alienVelocityVector*Time.deltaTime); } } <file_sep>/Space Invaders/Assets/menu/ButtonScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtonScript : MonoBehaviour { GameManager gm; public void buttonClicked(int parameter){ gm = GameObject.Find ("GameMaster").GetComponent<GameManager> (); switch (parameter) { case 0: Application.Quit (); break; case 1: gm.startGameHuman (); break; case 2: gm.startGameAuto (); break; default: MyUtils.appendToFile ("log.txt", "====="); Application.Quit (); break; } } } <file_sep>/Space Invaders/Assets/Scripts/others/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public bool logging; int alienCount; void Awake(){ GameData.gameManager = this; if (GameObject.FindObjectsOfType (GetType ()).Length>1) { Destroy (gameObject); } } public void startGameAuto () { Cursor.visible = false; alienCount = 55; GameData.gameHuman = false; SceneManager.LoadScene ("auto"); GameData.startTime = Time.time; } public void startGameHuman () { Cursor.visible = false; alienCount = 55; GameData.gameHuman = true; SceneManager.LoadScene ("human"); GameData.startTime = Time.time; } public void endGame (bool won, bool human, int finalScore){ GameData.gameDuration = Time.time - GameData.startTime; GameData.gameWon = won; GameData.gameHuman = human; GameData.gameScore = finalScore; GameData.hasData = true; if (logging) logLastGame ("log.txt"); Cursor.visible = true; SceneManager.LoadScene ("menu"); } public void alienDead(){ alienCount--; if (alienCount == 0) { Score score = GameObject.Find ("score").GetComponent<Score>(); endGame (true, GameData.gameHuman, score.totalScore); } } public void playerDead() { Score score = GameObject.Find ("score").GetComponent<Score>(); endGame (false, GameData.gameHuman, score.totalScore); } private void logLastGame(string filename){ MyUtils.appendToFile(filename, "-----"); MyUtils.appendToFile(filename, "won: " + GameData.gameWon.ToString ()); MyUtils.appendToFile(filename, "human: " + GameData.gameHuman.ToString ()); MyUtils.appendToFile(filename, "score: " + GameData.gameScore.ToString ()); MyUtils.appendToFile(filename, "duration: " + GameData.gameDuration.ToString ("F2")); } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/Shelter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shelter : FuzzyBehaviour { FuzzyClass shieldFarLeft = new FuzzyClass (-16f, -15f, -2f, -1.5f); FuzzyClass shieldLeft = new FuzzyClass (-2.5f, -2f, -0.2f, 0.1f); FuzzyClass shieldRight = new FuzzyClass (-0.1f, 0.2f, 2f, 2.5f); FuzzyClass shieldFarRight = new FuzzyClass (1.5f, 2f, 15f, 16f); float sfl, sl, sr, sfr; float hardLeft, left, right, hardRight; public override void updateOutputs(){ //fuzzyficazione sfl = shieldFarLeft.calculateMembership(sensor.shieldDistance); sl = shieldLeft.calculateMembership (sensor.shieldDistance); sr = shieldRight.calculateMembership (sensor.shieldDistance); sfr = shieldFarRight.calculateMembership (sensor.shieldDistance); //FAM hardLeft = FuzzyLib.fuzzyOr (sl,sfl); left = 0; right = 0; hardRight = FuzzyLib.fuzzyOr (sr,sfr); //defuzzyficazione spacebarOutput = false; movementOutput = hardLeft * (-0.8f) + left * (-0.4f) + right * (0.4f) + hardRight * (0.8f); //display List<string> message = new List<string>(); message.Add ("==SHELTER=="); message.Add ("shield distance:"); message.Add (sfl.ToString("F2") + "|" + sl.ToString ("F2") + "|" + sr.ToString ("F2") + "|" + sfr.ToString ("F2") ); message.Add ("movement:"); message.Add (hardLeft.ToString("F2") + "|" + left.ToString("F2") + "|" + right.ToString("F2") + "|" + hardRight.ToString("F2")); message.Add ("shooting"); message.Add (spacebarOutput.ToString()); setDisplayMessage (message); } } <file_sep>/Space Invaders/Assets/Scripts/game mechanics/ConstantMover.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConstantMover : MonoBehaviour { public float velocity; Rigidbody2D rb; void Start(){ rb = gameObject.GetComponent<Rigidbody2D> (); } void Update () { rb.MovePosition (rb.position + Vector2.up * velocity * Time.deltaTime); } } <file_sep>/Space Invaders/Assets/menu/PauseScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PauseScript : MonoBehaviour { bool paused; GameObject menu; void Start(){ menu = gameObject.transform.GetChild (0).gameObject; } void Update () { if (Input.GetKeyDown ("escape")) { if (SceneManager.GetActiveScene ().buildIndex > 0) { if (paused) { unpause (1); } else { pause (1); } } } } public void pause(int trash){ Cursor.visible = true; Time.timeScale = 0; paused = true; menu.SetActive (true); } public void unpause(int trash){ Cursor.visible = false; menu.SetActive (false); paused = false; Time.timeScale = 1; } public void backToMenu(int trash){ unpause (0); GameData.gameManager.endGame (false, GameData.gameHuman, GameObject.Find ("score").GetComponent<Score> ().totalScore); } } <file_sep>/Space Invaders/Assets/menu/LastGameText.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LastGameText : MonoBehaviour { Text text; string firstLine = "last game results: \n"; string playerType, gameResult, score, time; void Start(){ if (GameData.hasData) { text = gameObject.GetComponent<Text> (); playerType = GameData.gameHuman ? "human" : "auto"; gameResult = GameData.gameWon ? "victory" : "defeat"; score = GameData.gameScore.ToString (); time = GameData.gameDuration.ToString ("F2"); text.text = firstLine + "player: " + playerType + "\n" + "result: " + gameResult + "\n" + "score: " + score + "\n" + "game duration: " + time; } } } <file_sep>/Space Invaders/Assets/Scripts/aliens/RedShipSpawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class RedShipSpawner : MonoBehaviour { public float spawnTimer; private float timerOffset; public GameObject redShip; GameObject newShip; Sensor sensor; void Start () { StartCoroutine (spawnCoroutine ()); if (!GameData.gameHuman) { sensor = GameObject.Find ("autoPlayer").GetComponent<Sensor> (); } } IEnumerator spawnCoroutine(){ while (true) { timerOffset = Random.value * 3f; yield return new WaitForSeconds (spawnTimer + timerOffset); spawnRandomised (); } } void spawnRandomised(){ int x = Random.Range(0,2); if (x == 0) { newShip = Instantiate (redShip, transform.position + new Vector3 (-8.3f, 0, 0), transform.rotation); RedShipController rsc = newShip.GetComponent<RedShipController> (); rsc.initiate (Vector3.right); } else { newShip = Instantiate (redShip, transform.position + new Vector3 (8.3f, 0, 0), transform.rotation); RedShipController rsc = newShip.GetComponent<RedShipController> (); rsc.initiate (Vector3.left); } if (!GameData.gameHuman) { sensor.setRedShip (newShip); } } } <file_sep>/Space Invaders/Assets/tester.cs using System.Collections; using System.Collections.Generic; using System; using UnityEngine; public class tester : MonoBehaviour { // Use this for initialization void Start () { string str = "test test line1"+Environment.NewLine; string str2 = "test line2"; MyUtils.appendToFile ("output.txt", str); MyUtils.appendToFile ("output.txt", str2); print ("done"); } } <file_sep>/Space Invaders/Assets/AutoRestarter.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AutoRestarter : MonoBehaviour { void Start () { StartCoroutine (restartCoroutine (1)); } IEnumerator restartCoroutine(float time){ yield return new WaitForSeconds (time); GameObject.Find ("MainMenu").GetComponent<ButtonScript> ().buttonClicked (2); } } <file_sep>/Space Invaders/Assets/Scripts/game mechanics/Score.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Score : MonoBehaviour { public int alienScore; public int redShipScore; public int totalScore; Text scoreText; GameManager gm; void Start () { totalScore = 0; scoreText = GameObject.Find ("ScoreText").GetComponent<Text>(); gm = GameObject.Find ("GameMaster").GetComponent<GameManager> (); } public void updateScore(GameObject obj){ if (obj.tag == "Alien") { totalScore += alienScore; gm.alienDead (); } else { totalScore += redShipScore; } scoreText.text = "SCORE: " + totalScore; } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/BehaviourSelector.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BehaviourSelector : FuzzyBehaviour { int avoid = 0; int shelter = 1; int atkRedship = 2; int atkClosest = 3; int atkLowest = 4; public int behaviourIndex; float[] behaviours = new float[5]; #region danger FuzzyClass dangerLow = new FuzzyClass(-0.1f, 0, 0.2f, 0.5f); FuzzyClass dangerMedium = new FuzzyClass (0.2f, 0.5f, 0.8f); FuzzyClass dangerHigh = new FuzzyClass (0.5f, 0.8f, 5, 10); #endregion #region shield FuzzyClass shieldClose = new FuzzyClass (-1, 0, 0.9f, 1.35f); FuzzyClass shieldFar = new FuzzyClass (0.9f, 1.35f, 100, 101); #endregion #region redship CrispClass redShipPresent = new CrispClass (0.75f, 1.25f); FuzzyClass screenWeak = new FuzzyClass (-1, 0, 4, 9); FuzzyClass screenMedium = new FuzzyClass (4, 9, 16, 21); FuzzyClass screenStrong = new FuzzyClass (16, 21, 35, 36); #endregion #region grid FuzzyClass distributionHorizontal = new FuzzyClass(0,1,1.4f,1.8f); FuzzyClass distributionUndefined = new FuzzyClass(1.4f, 1.8f, 2.3f, 2.7f); FuzzyClass distributionVertical = new FuzzyClass(2.3f, 2.7f, 10f, 11f); FuzzyClass lowestAlienLow = new FuzzyClass(-1, 0, 2.5f, 4.5f); FuzzyClass lowestAlienHigh = new FuzzyClass(2.5f, 4.5f, 10, 11); #endregion public override void updateOutputs(){ Debug.Log ("ERROR: updateOutputs called on selector"); } public void selectBehaviour(){ //fuzzyficazione float dngl, dngm, dngh; dngl = dangerLow.calculateMembership (sensor.danger); dngm = dangerMedium.calculateMembership (sensor.danger); dngh = dangerHigh.calculateMembership (sensor.danger); float shc, shf; shc = shieldClose.calculateMembership (Mathf.Abs(sensor.shieldDistance)); shf = shieldFar.calculateMembership (Mathf.Abs(sensor.shieldDistance)); float rs; rs = redShipPresent.calculateMembership (sensor.redShipPresent); float sw, sm, ss; sw = screenWeak.calculateMembership (sensor.redShipScreen); sm = screenMedium.calculateMembership (sensor.redShipScreen); ss = screenStrong.calculateMembership (sensor.redShipScreen); float dh, du, dv; dh = distributionHorizontal.calculateMembership (sensor.alienDistributionIndex); du = distributionUndefined.calculateMembership (sensor.alienDistributionIndex); dv = distributionVertical.calculateMembership (sensor.alienDistributionIndex); float lwh, lwl; lwh = lowestAlienHigh.calculateMembership (sensor.lowestAlienHeight); lwl = lowestAlienLow.calculateMembership (sensor.lowestAlienHeight); //FAM float defend = FuzzyLib.fuzzyOr (dngm, dngh); float attack = dngl; //avoid = defend & !shc behaviours[avoid] = FuzzyLib.fuzzyAnd(defend, shf); //shelter = defend & shc behaviours [shelter] = FuzzyLib.fuzzyAnd (defend, shc); //atkred = attack & pres & (sw | dv | (sm & du & lwh)) behaviours[atkRedship] = FuzzyLib.fuzzyAnd( attack, rs, FuzzyLib.fuzzyOr(sw, dv, FuzzyLib.fuzzyAnd(sm, du, lwh))); //atkClosest = attack & lwh & (dh | (!rs & (du | dv))) behaviours[atkClosest] = FuzzyLib.fuzzyAnd( attack, lwh, FuzzyLib.fuzzyOr( dh, FuzzyLib.fuzzyAnd( FuzzyLib.fuzzyNot(rs), FuzzyLib.fuzzyOr(du, dv)))); //atkLowest = attack & lwl behaviours[atkLowest] = FuzzyLib.fuzzyAnd(attack, lwl); //defuzzyficazione behaviourIndex = MyUtils.argmax (behaviours); //display List<string> message = new List<string>(); message.Add ("==SELECTOR=="); message.Add ("danger level:"); message.Add (dngl.ToString("F2") + "|" + dngm.ToString ("F2") + "|" + dngh.ToString ("F2")); message.Add ("shield:"); message.Add (shc.ToString("F2") + "|" + shf.ToString ("F2")); message.Add ("red ship present:"); message.Add (rs.ToString("F2")); if (sensor.redShipPresent > 0) { message.Add ("red ship screen:"); message.Add (sw.ToString ("F2") + "|" + sm.ToString ("F2") + "|" + ss.ToString ("F2")); } message.Add ("alien distribution:"); message.Add (dh.ToString("F2") + "|" + du.ToString ("F2") + "|" + dv.ToString ("F2")); message.Add ("lowest alien height:"); message.Add (lwh.ToString("F2") + "|" + lwl.ToString ("F2")); message.Add ("behavior index:"); message.Add (behaviourIndex.ToString()); setDisplayMessage (message); } } <file_sep>/Space Invaders/Assets/Scripts/aliens/alienController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class alienController : MonoBehaviour { public GameObject bomb; public Vector2 gridpos; MovementManager mvm; Rigidbody2D rb ; GameObject bombHolder; void Start(){ mvm = transform.root.GetComponent<MovementManager> (); rb = gameObject.GetComponent<Rigidbody2D> (); } void Update () { rb.MovePosition (rb.position + mvm.alienVelocityVector*Time.deltaTime); } public void shoot(){ Instantiate (bomb, transform.position+(Vector3.back), transform.rotation); } } <file_sep>/Space Invaders/Assets/Scripts/game mechanics/CollisionManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollisionManager : MonoBehaviour { Sensor sensor; GameManager gm; void Start(){ gm = GameData.gameManager; } void OnCollisionEnter2D (Collision2D col){ if (gameObject.tag == "Alien") { Score score = GameObject.Find ("score").GetComponent<Score> (); score.updateScore (gameObject); MovementManager mm = GameObject.Find ("alienManager").GetComponent<MovementManager> (); mm.increaseGameSpeed (); if (!GameData.gameHuman) { Sensor s = GameObject.Find ("autoPlayer").GetComponent<Sensor> (); s.removeFromGrid (gameObject.GetComponent<alienController> ().gridpos); } ExplosionManager e = gameObject.GetComponent<ExplosionManager> (); e.explode(); } if (gameObject.tag == "RedShip") { Score score = GameObject.Find ("score").GetComponent<Score> (); score.updateScore (gameObject); if (!GameData.gameHuman) { if (sensor == null) { sensor = GameObject.Find ("autoPlayer").GetComponent<Sensor> (); } sensor.setRedShip (null); } } if (gameObject.tag == "FinishLine" && col.gameObject.tag == "Alien") { gm.startGameAuto (); } if (gameObject.tag == "Player") { gm.playerDead (); } if (gameObject.tag != "FinishLine") { Destroy (gameObject); } } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/sensors/Sensor.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sensor : MonoBehaviour { public float bombFunction; public float boundDistance; public float shieldDistance; public float alienVelocity; public float lowestAlienDistance; public float lowestAlienLead; public float lowestAlienHeight; public float closestAlienDistance; public float closestAlienHeight; public float closestAlienLead; public float redShipPresent; public float redShipDistance; public float redShipLead; public float redShipScreen; public float danger; public float alienDistributionIndex; private List <GameObject> bombList= new List<GameObject>(); private int alienNumber = 55; GameObject offsetMarker; MovementManager movementManager; GameObject currentRedShip; GameObject debug; public void initSensor(){ offsetMarker = GameObject.Find("offsetMarker"); debug = GameObject.CreatePrimitive (PrimitiveType.Sphere); movementManager = GameObject.Find ("alienManager").GetComponent<MovementManager> (); } public void updateSensor(){ updateBombFunction (transform.position, 6); updateBoundDistance (); updateShieldDistance (); updateAlienVelocity (); updateLowestAlienData (); updateLowestAlienLead (); updateClosestAlienData (); updateClosestAlienLead (); updateRedShipPresent (); if (currentRedShip != null) { updateRedShipDistance (); updateRedShipLead (); updateRedShipScreen (); } updateDanger (4,10); updateAlienDistributionIndex (); } #region bombs private void updateBombFunction(Vector3 playerPos, float maxDistance){ List<Vector3> nearbyBombs = new List<Vector3> (); Vector3 nearest = new Vector3(100,100,100); float nearestDistance = 100; float currentDistance = 100; updateBombList (); foreach (GameObject b in bombList){ currentDistance = Vector3.Distance (playerPos, b.transform.position); if (currentDistance <= maxDistance) { if (currentDistance < nearestDistance) { nearest = b.transform.position; nearestDistance = currentDistance; } nearbyBombs.Add (b.transform.position); } } float res = nearest.x; nearbyBombs.Remove (nearest); bombFunction = res-playerPos.x; } private void updateBombList(){ bombList.Clear (); bombList.AddRange(GameObject.FindGameObjectsWithTag ("AlienBullet")); } #endregion #region bounds private void updateBoundDistance (){ if (transform.position.x <= 0) { boundDistance = (-8.7f) - transform.position.x; } else { boundDistance = 8.7f - transform.position.x; } } #endregion #region shields private void updateShieldDistance(){ shieldDistance = calculateShieldDistance(); } private float calculateShieldDistance(){ GameObject[] shields = GameObject.FindGameObjectsWithTag ("Shield"); float closestDistance = 100; float shieldDistance = 100; foreach (GameObject s in shields) { float currentDistance = Mathf.Abs (s.transform.position.x - transform.position.x); if (currentDistance < closestDistance) { closestDistance = currentDistance; shieldDistance = s.transform.position.x - transform.position.x; } } return shieldDistance; } #endregion #region grid bool[,] alienGrid = new bool[11,5]; //F -> alive , T-> dead public void removeFromGrid (Vector2 pos){ alienGrid [(int)pos.x,(int)pos.y] = true; alienNumber--; } private bool isAlive(int x, int y){ if (alienGrid [x, y]==false) return true; return false; } private int getNumberOfRows(){ bool foundHighest = false; int highest = 0; int lowest = 4; for (int r = 0; r < 5; r++) { if (!foundHighest) { if (isAliveRow (r)) { //highest highest = r; foundHighest = true; } } else { if (!isAliveRow (r)) { //lowest+1 lowest = r-1; break; } } } return lowest - highest + 1; } private bool isAliveRow(int rowDown){ for (int i = 0; i < 11; i++) { if (isAlive (i, rowDown)) { return true; } } return false; } #endregion #region lowest void updateLowestAlienData(){ List<float> lowestLevel = new List<float> (); lowestLevel.Clear (); int lowestY = 4; for (int y = 4; y >= 0; y--) { for (int x = 0; x < 11; x++) { if (isAlive (x, y)) { lowestLevel.Add (MyUtils.gridToVector3(x, y, offsetMarker).x); } } if (lowestLevel.Count > 0) { lowestY = y; break; } } if (lowestLevel.Count > 0) { //game ends lowestAlienDistance = MyUtils.closest (lowestLevel, transform.position.x) - transform.position.x; lowestAlienHeight = MyUtils.gridToVector3 (0, lowestY, offsetMarker).y + 5.3f; } } void updateLowestAlienLead(){ lowestAlienLead = MyUtils.calculateLead (alienVelocity, lowestAlienHeight, 10f); } #endregion #region closest void updateClosestAlienData(){ Vector3 closest = Vector3.zero; float minDistance = 100; for (int y = 0 ; y < 5; y++) { for (int x = 0; x < 11; x++) { if (isAlive (x, y)) { Vector3 curPos = MyUtils.gridToVector3 (x, y, offsetMarker); float curDistance = Vector3.Distance (transform.position, curPos); if (curDistance < minDistance) { closest = curPos; minDistance = curDistance; } } } } closestAlienDistance = closest.x - transform.position.x; closestAlienHeight = closest.y - transform.position.y; } void updateClosestAlienLead(){ closestAlienLead = MyUtils.calculateLead (alienVelocity, closestAlienHeight, 10f); } #endregion #region alienVelocity void updateAlienVelocity(){ alienVelocity = movementManager.alienVelocityVector.x; } #endregion #region redship public void setRedShip(GameObject rs){ currentRedShip = rs; } void updateRedShipDistance(){ redShipDistance = currentRedShip.transform.position.x - transform.position.x; } void updateRedShipLead(){ float absoluteLead = MyUtils.calculateLead (currentRedShip.GetComponent<RedShipController> ().velocity, 10.37f, 10); if (currentRedShip.GetComponent<RedShipController> ().direction.x > 0) { redShipLead = absoluteLead; } else { redShipLead = (-1)*absoluteLead; } } void updateRedShipScreen(){ float lead = Mathf.Abs (redShipLead); Vector3 boxCenter = new Vector3 (currentRedShip.transform.position.x + redShipLead, 0, -10); redShipScreen = Physics2D.OverlapBoxAll (boxCenter, new Vector2 (lead, 8), 0, 1<<8).Length; //Debug.DrawLine (boxCenter + new Vector3 (-lead/2f, 4, 0), boxCenter + new Vector3 (lead/2f, -4, 0)); //Debug.Log (redShipScreen); //Debug.DrawLine (boxCenter + new Vector3 (boxWidth/2f, boxHeight/2f, 0), boxCenter + new Vector3 (-boxWidth/2f, -boxHeight/2f, 0)); } void updateRedShipPresent(){ if (currentRedShip != null) { redShipPresent = 1; } else { redShipPresent = -1; } } #endregion #region danger void updateDanger(float boxWidth, float boxHeight){ Vector3 boxCenter = transform.position+Vector3.up*(boxHeight/2f - 0.5f); Collider2D[] bombColliders = Physics2D.OverlapBoxAll (boxCenter, new Vector2 (boxWidth, boxHeight+1), 0, 1 << 10); float res = 0; foreach (Collider2D col in bombColliders) { res += 1 / Vector3.Distance (col.transform.position, transform.position); } danger = res; } #endregion #region distribution void updateAlienDistributionIndex(){ float rows = getNumberOfRows (); float res = (rows*11f / (float)alienNumber); if (res > 10) { alienDistributionIndex = 10; } else { alienDistributionIndex = res; } } #endregion } <file_sep>/Space Invaders/Assets/Scripts/game mechanics/onDestroy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class onDestroy : MonoBehaviour { void OnDestroy(){ Score score = GameObject.Find ("score").GetComponent<Score> (); score.updateScore (gameObject); } } <file_sep>/Space Invaders/Assets/Scripts/fuzzy/behaviours/Avoid.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Avoid : FuzzyBehaviour{ static float maxDistance = 6; #region bombs FuzzyClass bombsFarLeft = new FuzzyClass ( (-1) * maxDistance - 1, (-1) * maxDistance, maxDistance / -2f - 0.5f, maxDistance / -2f + 0.5f); FuzzyClass bombsLeft = new FuzzyClass ( maxDistance / -2f - 0.5f, maxDistance / -2f + 0.5f, -0.1f, 0.5f); FuzzyClass bombsRight = new FuzzyClass ( 0, 0.1f, maxDistance / 2f - 0.5f, maxDistance / 2f + 0.5f); FuzzyClass bombsFarRight = new FuzzyClass ( maxDistance / 2f - 0.5f, maxDistance / 2f + 0.5f, maxDistance, maxDistance + 1); #endregion #region bounds float bfl, bl, br, bfr; FuzzyClass boundCloseLeft = new FuzzyClass ( -3, -0.5f, -0.1f, 0); FuzzyClass boundCloseRight = new FuzzyClass ( 0, 0.1f, 0.5f, 3); float bdl, bdr; #endregion float hardLeft, left, right, hardRight; public override void updateOutputs(){ //fuzzyficazione bfl = bombsFarLeft.calculateMembership (sensor.bombFunction); bl = bombsLeft.calculateMembership (sensor.bombFunction); br = bombsRight.calculateMembership (sensor.bombFunction); bfr = bombsFarRight.calculateMembership (sensor.bombFunction); bdl = boundCloseLeft.calculateMembership (sensor.boundDistance); bdr = boundCloseRight.calculateMembership (sensor.boundDistance); //FAM hardLeft = FuzzyLib.fuzzyOr(br, bdr); left = bfr; right = bfl; hardRight = FuzzyLib.fuzzyOr(bl, bdl); //defuzzyficazione movementOutput = hardLeft * (-0.8f) + left * (-0.4f) + right * (0.4f) + hardRight * (0.8f); //display List<string> message = new List<string>(); message.Add ("==AVOID=="); message.Add ("bombs distance:"); message.Add (bfl.ToString("F2") + "|" + bl.ToString("F2") + "|" + br.ToString("F2") + "|" + bfr.ToString("F2")); message.Add ("bound distance:"); message.Add (bdl.ToString ("F2") + "|" + bdr.ToString ("F2")); message.Add ("movement:"); message.Add (hardLeft.ToString("F2") + "|" + left.ToString("F2") + "|" + right.ToString("F2") + "|" + hardRight.ToString("F2")); message.Add ("shooting"); message.Add ("false"); setDisplayMessage (message); } }
42a61539ae9f35193fbed0799b5210d44b7f85f0
[ "C#" ]
38
C#
RiccardoCantoni/spaceInvadersAI
258a53d3ec479241631d3e19758715d69ec1b65c
22dd717549998b8c14a25392239310468e6fc2ec
refs/heads/master
<file_sep>package main import ( //"fmt" //"time" "net/http" //."github.com/vycb/gorazortpl/tpl/bench" "github.com/vycb/gorazortpl/tpl/helper" ."github.com/vycb/gorazortpl/tpl" ) func main() { http.HandleFunc("/", root) http.ListenAndServe(":8080", nil) //fmt.Println(Home(2, &helper.User{"UserName", "User@email", "User Intro"})) //fmt.Println(Bench(&Page{"UserName", []string{"User Intro","red","black"}, time.Now().Year()})) } func root(w http.ResponseWriter, r *http.Request) { w.Write([]byte(Home(2, &helper.User{"UserName", "User@email", "User Intro"}))) //fmt.Println(Bench(&Page{"UserName", []string{"User Intro","red","black"}, time.Now().Year()})) //page := &Page{ // Title: "Bob", // FavoriteColors: []string{"blue", "green", "mauve"}, // Year: time.Now().Year(), //} } <file_sep>package tpl import ( "bytes" "github.com/sipin/gorazor/gorazor" . "github.com/vycb/gorazortpl/tpl/bench" "strings" ) func Bench(p *Page) string { var _buffer bytes.Buffer _buffer.WriteString(gorazor.HTMLEscape(Header(p))) _buffer.WriteString("\n<h1>Hello ") _buffer.WriteString(gorazor.HTMLEscape(strings.TrimSpace(p.Title))) _buffer.WriteString(" !</h1>\n\n<p>Here's a list of your favorite colors:</p>\n<ul>\n\t") for _, colorName := range p.FavoriteColors { _buffer.WriteString("<li>") _buffer.WriteString(gorazor.HTMLEscape(colorName)) _buffer.WriteString("</li>") } _buffer.WriteString("\n</ul>") _buffer.WriteString(gorazor.HTMLEscape(Footer(p))) return _buffer.String() } <file_sep>package bench import ( "bytes" "github.com/sipin/gorazor/gorazor" ) func Footer(p *Page) string { var _buffer bytes.Buffer _buffer.WriteString("\n\n<div>") _buffer.WriteString(gorazor.HTMLEscape(p.Year)) _buffer.WriteString(" Year</div>\n</body>\n</html>") return _buffer.String() } <file_sep>package bench type Page struct { Title string FavoriteColors []string Year int }<file_sep>package helper type User struct { Name string Email string Intro string }<file_sep>package bench import ( "bytes" "github.com/sipin/gorazor/gorazor" ) func Header(p *Page) string { var _buffer bytes.Buffer _buffer.WriteString("\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"UTF-8\">\n\t<title>") _buffer.WriteString(gorazor.HTMLEscape(p.Title)) _buffer.WriteString("</title>\n</head>\n<body>") return _buffer.String() } <file_sep>package main import ( "fmt" "testing" "time" ."github.com/vycb/gorazortpl/tpl/bench" ."github.com/vycb/gorazortpl/tpl" ) func BenchmarkMain(*testing.B) { // Parallel benchmark for text/template.Template.Execute on a single object. testing.Benchmark(func(b *testing.B) { page := &Page{ Title: "Bob", FavoriteColors: []string{"blue", "green", "mauve"}, Year: time.Now().Year(), } // RunParallel will create GOMAXPROCS goroutines // and distribute work among them. b.RunParallel(func(pb *testing.PB) { // Each goroutine has its own bytes.Buffer. for pb.Next() { // The loop body is executed b.N times total across all goroutines. fmt.Println(Bench(page)) } }) }) }
9faf5808dfb4f48d5a2eec8e1e0093e8608c2634
[ "Go" ]
7
Go
vycb/gorazortpl
7c7e0a3dd1f18d61f6afb1fd3181349f282600ff
7f1e2ec1981a3d4b6a1326a85b1b48e75f33ff22
refs/heads/master
<file_sep>import sqlite3 import datetime def create_table(): sqliteConnection = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_create_table_query = '''CREATE TABLE transaction_details ( bookid text, author TEXT NOT NULL, searchdate timestamp);''' cursor = sqliteConnection.cursor() cursor.execute(sqlite_create_table_query) def search_book_name(): sqliteConnection = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) name=input("Enter book name ") cursor=sqliteConnection.execute("select bookid,bookname,author_name from book_details where bookname=?",(name,)) data=cursor.fetchall() if len(data)==0: print('No Record found') else: print('Book Id \t Book Name \t\t Author Name ') for row in data: author_id=row[2] book_id=row[0] print(row[0],"\t\t",row[1],"\t\t",row[2]) sqlite_insert_with_param = """INSERT INTO 'transaction_details' ('bookid','author','searchdate') VALUES (?, ?, ?);""" cursor1 = sqliteConnection.cursor() data_tuple = (book_id,author_id,datetime.datetime.now().date()) cursor1.execute(sqlite_insert_with_param, data_tuple) sqliteConnection.commit() def search_book_by_ids(): sqliteConnection = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) book_id=input("Enter book id (enter upper case ") cursor=sqliteConnection.execute("select bookid,bookname,author_name from book_details where bookid=?",(book_id,)) data=cursor.fetchall() if len(data)==0: print('No Record found') else: print('Book Id \t Book Name \t\t Author Name ') for row in data: print(row[0],"\t\t",row[1],"\t\t",row[2]) for row in data: author_id=row[2] book_id=row[0] print(row[0],"\t\t",row[1],"\t\t",row[2]) sqlite_insert_with_param = """INSERT INTO 'transaction_details' ('bookid','author','searchdate') VALUES (?, ?, ?);""" cursor1 = sqliteConnection.cursor() data_tuple = (book_id,author_id,datetime.datetime.now().date()) cursor1.execute(sqlite_insert_with_param, data_tuple) sqliteConnection.commit() def no_of_books(): conn = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) cursor=conn.execute("select count(bookid) from transaction_details where searchdate=?",(datetime.datetime.now().date(),)) data=cursor.fetchall() print("Total number of books searched today ") for p in data: print(p[0]) def max_author_search(): author=[] conn = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) cursor=conn.execute("select author,count(author) as a from transaction_details where searchdate=? group by author order by a desc ",(datetime.datetime.now().date(),)) data=cursor.fetchall() print("Maximum author searched today ") for p in data: author.append(p[0]) print(p[0]) def max_book_search(): author=[] conn = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) cursor=conn.execute("select bookid,count(bookid) as a from transaction_details where searchdate=? group by author order by a desc ",(datetime.datetime.now().date(),)) data=cursor.fetchall() print("Maximum book searched today ") for p in data: author.append(p[0]) print(p[0]) def number_of_visitor(): author=[] conn = sqlite3.connect('book.db',detect_types=sqlite3.PARSE_DECLTYPES |sqlite3.PARSE_COLNAMES,timeout=1) cursor=conn.execute("select count(searchdate) as a from transaction_details where searchdate=? group by author order by a desc ",(datetime.datetime.now().date(),)) data=cursor.fetchall() print("No of visitors today ") for p in data: author.append(p[0]) print(p[0]) #create_table() while True: print("1. Search Book by id ") print("2. Search Book by Name ") print("3. Number of books searched in a day ") print("4. Most searched book ") print("5. Most searched author ") print("6. Number of visitor in a day ") print("7. Exit ") option=int(input("Enter your option ")) if option==1: search_book_by_ids() elif option==2: search_book_name() elif option==3: no_of_books() elif option==4: max_book_search() elif option==5: max_author_search() elif option==6: number_of_visitor() elif option==7: break else: print("Invalid option selected ")
7b595a74595ac772de795a7eb605e3a7fc7865f3
[ "Python" ]
1
Python
SimranjitSinghMonga/digital_library
82c8233c95db4d294a0e6ce21181c73ec64191b9
bda54c424b936f9c6c78d25ae818928870fd6b0a
refs/heads/master
<repo_name>andrebeu/SEMCSW<file_sep>/cpu_arr_jobsub.cmd #!/usr/bin/env bash #SBATCH -t 2:59:00 # runs for 48 hours (max) #SBATCH -N 1 # node count #SBATCH -c 1 # number of cores #SBATCH --mem 4000 #SBATCH -o ./slurms/output.%j.%a.out # module load pyger/0.9 conda init bash conda activate sem # nosplit=${1} # condition=${2} # learn_rate=${3} # alfa=${4} # lmda=${5} slurm_arr_idx=${SLURM_ARRAY_TASK_ID} param_str=`python get_param_jobsub.py ${slurm_arr_idx}` echo ${param_str} # submit job srun python PY-gs-acc.py "${param_str}" sacct --format="CPUTime,MaxRSS" <file_sep>/PY-sem_seed_exp.py # import sys # import os # import pandas as pd # import numpy as np # import torch as tr # from CSWSEM import * # # sweep params # learn_rate = float(sys.argv[]) # alfa = float(sys.argv[]) # lmda = float(sys.argv[]) # stsize = 25 # ## gridsearch tag # gs_name = 'gs2' # ## looping # seedL = np.arange(51) # condL = ['blocked','interleaved'] # dfL = [] # populate from each condition # for nosplit,condition,seed in itertools.product([0,1],condL,seedL): # np.random.seed(seed) # tr.manual_seed(seed) # ## model tag # model_tag = 'nosplit_%i__cond_%s__learnrate_%.3f__alfa_%f__lmbda_%f__seed_%i'%( # int(nosplit),condition,learn_rate,alfa,lmda,seed) # print('\n\n**',model_tag,'**\n\n') # # params # exp_kwargs={ # 'condition':condition, # 'n_train':160, # 'n_test':40 # } # sem_kwargs={ # 'nosplit':nosplit, # 'stsize':stsize, # 'lmda':lmda, # 'alfa':alfa, # 'learn_rate':learn_rate, # 'seed':seed, # } # # setup # task = CSWTask() # sem = SEM(**sem_kwargs) # # run # exp,curr = task.generate_experiment(**exp_kwargs) # sem_data = sem.forward_exp(exp) # # record curriculum (not ideal, recording with every obs) # sem.data.record_exp('curriculum',curr) # # save # save_fpath = 'gsdata/%s/%s'%(gs_name,model_tag) # sem_data_df = pd.DataFrame(sem_data) # sem_data_df.to_csv(save_fpath) # just in case # dfL.append(sem_data_df) # ## save again: prefer this # full_tag = 'learnrate_%.3f__alfa_%f__lmbda_%f'%(learn_rate,alfa,lmda) # save_fpath = 'gsdata/%s/%s'%(gs_name,full_tag) # pd.concat(dfL).to_csv(save_fpath) <file_sep>/README.md # liketest (03/26/21) - how to change interleaved without affecting blocked? - look into likelihood computation - setup 40 trials of interleaved vs single (blocked) - note RNN size: realized that even when RNN size was set to 1, performance on blocked would not exhibit CI, suggesting learning happening in projection layers. to fix this, inputs are projected down to size 3. - refactor argument passing to RNN - made batch_sim and BIexp wrapper funs - gridsearch over pdim and stsize: - small B>I results when pdim=4,stsize=5 - todo: - refactor likelihood - check effect of: - remove input layer - rnn vs gru vs lstm - update prior count by 1 vs 5 - - result: good BIseparation on early trials when embed_size == stsize = 10 or 15 (lr=0.05) # gs2 notes - change to gridsearch procedure - single job contains multiple seeds - parameter passing controlled `get_param_jobsub.py` - caution: this gridsearch procedure repeats LSTM sims for all SEM sims # procedural notes - NB-run_sem.pynb used for debugging and testing before launching gridsearch - code in here should be kept in a state that is amenable to gridsearching # Model of Curriculum Effect on Schema Learning ## Results - blocked > interleaved - early > middle/late ## Modeling procedure - Fit SEM on blocked/interleaved - Evaluate on early/middle/late ** MOVING TO DIFFERENT FOLDER: when switching between AB and NF repos, github sometimes bugs out with finder: new files wont load. <file_sep>/code/utils_analysis.py import os import numpy as np import torch as tr from glob import glob as glob import pandas as pd from matplotlib import pyplot as plt from CSWSEM import * def make_gsdf_absem(gsname,save=False): gs_dir = "gsdata/%s/"%gsname fpathL = glob(gs_dir+'*') seed_df_L = [] for fpath in fpathL: condition = fpath.split('/')[-1].split('__')[1].split('_')[1] seed_df = pd.read_csv(fpath) seed_df.loc[:,'model'] = ['LSTM','SEM'][sum(seed_df.loc[:,'nosplit']==1)>0] seed_df.loc[:,'condition'] = condition seed_df_L.append(seed_df) gsdf = pd.concat(seed_df_L) gsdf.index = np.arange(len(gsdf)) gsdf.drop(columns=['Unnamed: 0','like','prior']) if save: gsdf.to_csv('gsdata/%s.csv'%gsname) print('saved %s.csv'%gsname) return gsdf <file_sep>/cpu_jobsub.cmd #!/usr/bin/env bash #SBATCH -t 4:00:00 # runs for 48 hours (max) #SBATCH -N 1 # node count #SBATCH -c 1 # number of cores #SBATCH --mem 3000 #SBATCH -o ./slurms/output.%j.%a.out #SBATCH -e ./slurms/err.%j.%a # module load pyger/0.9 conda init bash conda activate sem model=${1} cond=${2} lr=${3} epoch=${4} alfa=${5} lmbda=${6} seed=${7} srun python PY-batch_exp.py "${model}" "${cond}" "${lr}" "${epoch}" "${alfa}" "${lmbda}" "${seed}" sacct --format="CPUTime,MaxRSS" <file_sep>/code/test_sem_impl.py from CSWSEM import * seed = 0 np.random.seed(10) task = CSWTask() exp_kwargs={ 'condition':'single', 'n_train':100, 'n_test':10 } exp = task.generate_experiment(**exp_kwargs) learn_rate = 0.01 sch_kwargs={ 'stsize':10, 'seed':seed, "learn_rate":learn_rate } sch = CSWSchema(**sch_kwargs) event = exp[0] event_hat = sch.forward(event) sem_kwargs={ 'lmda':1, 'alfa':10, 'nosplit':True } sem = SEM(**sem_kwargs) # sem.forward_trial(event) sem.forward_exp(exp) <file_sep>/code/PY-LSTMbatchexp.py #!/usr/bin/env python # coding: utf-8 # This script runs one param_set. Outputs results{}.csv and trialxtrial{}.csv # In[1]: import sys import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import seaborn as sns from tqdm import tqdm from sklearn import metrics import pandas as pd from sklearn.metrics import adjusted_rand_score from sklearn.preprocessing import normalize from sklearn.linear_model import LogisticRegression from scipy.special import logsumexp from scipy.stats import norm from glob import glob # In[2]: from CSWSEM import generate_exp, seed_exp from vanilla_lstm import VanillaLSTM from sem.event_models import NonLinearEvent # ### gridsearch params # In[3]: # parameter search over lr, n_epochs, alpha, lambda model_type = str('LSTM') seed = int(sys.argv[1]) lr = float(sys.argv[2]) n_epochs = int(sys.argv[3]) # In[4]: log_alpha = float(0.0) # sCRP alpha is set in log scale log_lambda = float(0.0) # sCRP lambda is set in log scale # In[5]: condition = 'blocked' n_train = 160 n_test = 40 # In[6]: save_dir = 'gsdata/lstm2_aw0/' model_tag = "%s_cond_%s_lr_%.3f_nepchs_%i_alpha_%.3f-lambda_%.3f_seed_%i"%( model_type,condition,lr,n_epochs,log_alpha,log_lambda,seed ) print(model_tag) # ### SEM configuration # In[7]: optimizer_kwargs = dict( lr=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-5, amsgrad=False ) f_opts=dict( batch_size=25, batch_update=False, dropout=0.0, l2_regularization=0.0, n_epochs=n_epochs, optimizer_kwargs=optimizer_kwargs ) # final param dict sem_kwargs = dict( lmda=np.exp(log_lambda), alfa=np.exp(log_alpha), f_opts=f_opts, f_class=VanillaLSTM ) # # Run model # # main fun call # In[ ]: """ main fun call """ stories_kwargs = {'actor_weight':0.0} results, trialXtrial, _ = seed_exp( sem_kwargs, stories_kwargs=stories_kwargs, model_type=model_type, n_train=n_train, n_test=n_test, condition=condition,seed=seed, ) # In[ ]: # convert from JSON file format (dict) to pandas df results = pd.DataFrame(results) trialXtrial = pd.DataFrame(trialXtrial) # # save # # In[ ]: results_fpath = save_dir + "results_" + model_tag + '.csv' trial_fpath = save_dir + "trial_X_trial_" + model_tag + '.csv' # In[ ]: results.to_csv(results_fpath) trialXtrial.to_csv(trial_fpath) <file_sep>/get_param_jobsub.py import sys import itertools """ controls the gridsearch parameter space given an index, return parameter string """ param_set_idx = int(sys.argv[1]) lr = [0.01, 0.05] alfa =[0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000, 100000] lmbda =[0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000, 100000] itrprod = itertools.product(lr,alfa,lmbda) for idx,paramL in enumerate(itrprod): if idx == param_set_idx: print(" ".join([str(i) for i in paramL])) break <file_sep>/loop_jobsub.cmd #!/usr/bin/env bash # parameter search over learn_rate, n_epochs, alpha, lambda # declare -a learn_rate_arr=(0.001 0.005 0.01 0.05) # declare -a epoch_arr=(1 2 4 8 16 32 64) declare -a learn_rate_arr=(0.01 0.05 0.1) declare -a condition_arr=("blocked" "interleaved") declare -a alfa_arr=(0.01 0.1 1 10 100 1000 10000 100000) declare -a lmda_arr=(0.01 0.1 1 10 100 1000 10000 100000) ## slurm array idx passed to py script: # builds product of params # takes idx as input # returns str param set for learn_rate in "${learn_rate_arr[@]}"; do for condition in "${condition_arr[@]}"; do # LSTM sbatch --array=0-50 cpu_arr_jobsub.cmd "1" "${condition}" "${learn_rate}" "99" "99" for alfa in "${alfa_arr[@]}"; do for lmda in "${lmda_arr[@]}"; do # SEM sbatch --array=0-50 cpu_arr_jobsub.cmd "0" "${condition}" "${learn_rate}" "${alfa}" "${lmda}" done done done done <file_sep>/runtest.py import time import os import numpy as np import torch as tr from scipy.stats import norm from CSWSEM import * sem_kwargs={ 'nosplit':0, 'alfa':10000000, 'lmda':0.1, 'seed':np.random.randint(99), 'stsize':15, 'learn_rate':0.05 } exp_kwargs = { 'condition':'single', 'n_train':10,'n_test':2 } sem = SEM(**sem_kwargs) task = CSWTask() exp,curr = task.generate_experiment(**exp_kwargs) sem_data = sem.forward_exp(exp,curr) print('** DONE')<file_sep>/PY-sem_batch_exp.py import sys import os import itertools import pandas as pd import numpy as np import torch as tr from CSWSEM import * ## input params param_str = str(sys.argv[1]) learn_rate,alfa,lmda = param_str.split() learn_rate = float(learn_rate) alfa = float(alfa) lmda = float(lmda) stsize = 25 ## gridsearch tag gs_name = 'gs2' ## looping seedL = np.arange(51) condL = ['blocked','interleaved'] dfL = [] # populate from each condition for nosplit,condition,seed in itertools.product([0,1],condL,seedL): np.random.seed(seed) tr.manual_seed(seed) ## model tag model_tag = 'nosplit_%i__cond_%s__learnrate_%.3f__alfa_%f__lmbda_%f__seed_%i'%( int(nosplit),condition,learn_rate,alfa,lmda,seed) print('\n\n**',model_tag,'**\n\n') # params exp_kwargs={ 'condition':condition, 'n_train':160, 'n_test':40 } sem_kwargs={ 'nosplit':nosplit, 'stsize':stsize, 'lmda':lmda, 'alfa':alfa, 'learn_rate':learn_rate, 'seed':seed, } # setup exp_start_time = time.time() task = CSWTask() sem = SEM(**sem_kwargs) # run exp,curr = task.generate_experiment(**exp_kwargs) sem_data = sem.forward_exp(exp,curr) # record curriculum (not ideal, recording with every obs) sem.data.record_exp('condition',condition) exp_end_time = time.time() sem.data.record_exp('delta_time',exp_end_time-exp_start_time) # save sem_data_df = pd.DataFrame(sem_data) dfL.append(sem_data_df) # save_fpath = 'gsdata/%s/%s'%(gs_name,model_tag) # sem_data_df.to_csv(save_fpath) # just in case ## save again: prefer this batch_tag = 'batch-learnrate_%.3f__alfa_%f__lmbda_%f'%(learn_rate,alfa,lmda) save_fpath = 'gsdata/%s/%s'%(gs_name,batch_tag) pd.concat(dfL).to_csv(save_fpath) <file_sep>/code/PY-run_simulations.py #!/usr/bin/env python # coding: utf-8 # This script runs one param_set. Outputs results{}.csv and trialxtrial{}.csv import sys import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import seaborn as sns from tqdm import tqdm from sklearn import metrics import pandas as pd from sklearn.metrics import adjusted_rand_score from sklearn.preprocessing import normalize from sklearn.linear_model import LogisticRegression from scipy.special import logsumexp from scipy.stats import norm from glob import glob from schema_prediction_task_9_8_20 import generate_exp, batch_exp from vanilla_lstm import VanillaLSTM from sem.event_models import NonLinearEvent ### simulation information save_dir = 'data/gridsearch_full1/' # parameter search over lr, n_epochs, alpha, lambda model_type = str(sys.argv[1]) lr = float(sys.argv[2]) n_epochs = int(sys.argv[3]) # what does this control? log_alpha = float(sys.argv[4]) # sCRP alpha is set in log scale log_lambda = float(sys.argv[5]) # sCRP lambda is set in log scale model_tag = "%s-lr-%.3f-nepchs-%i-alpha-%.3f-lambda-%.3f"%( model_type,lr,n_epochs,log_alpha,log_lambda ) print(model_tag) # In[4]: conditions = ['interleaved','blocked','early','middle','late'] n_batch = 50 # ### SEM configuration # number of trials n_train = 160 n_test = 40 story_kwargs = dict(seed=None, err=0.2, actor_weight=1.0, instructions_weight=0.0) optimizer_kwargs = dict( lr=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-5, amsgrad=False ) f_opts=dict( batch_size=25, batch_update=False, dropout=0.0, l2_regularization=0.0, n_epochs=n_epochs, optimizer_kwargs=optimizer_kwargs ) f_class = VanillaLSTM # event model class # final param dict sem_kwargs = dict( lmda=np.exp(log_lambda), alfa=np.exp(log_alpha), f_opts=f_opts, f_class=f_class ) # toggle between SEM (False) and LSTM (True) if model_type == 'SEM': no_split=False elif model_type == 'LSTM': no_split=True """ batch_exp main fun call """ results, trialXtrial, _ = batch_exp( sem_kwargs, story_kwargs, no_split=no_split, sem_progress_bar=False, progress_bar=False, n_train=n_train, n_test=n_test, n_batch=n_batch, conditions=conditions ) # convert from JSON file format (dict) to pandas df results = pd.DataFrame(results) trialXtrial = pd.DataFrame(trialXtrial) ## save results_fpath = save_dir + "results_" + model_tag + '.csv' trial_fpath = save_dir + "trial_X_trial_" + model_tag + '.csv' results.to_csv(results_fpath) trialXtrial.to_csv(trial_fpath) <file_sep>/CSWSEM.py import time import os import numpy as np import torch as tr from scipy.stats import norm """ event (len6): B,L,2,3,4,E event_hat (len5): Lh,2h,3h,4h,Eh event_target (len5): Lt,...,Et """ ## common across all objects OBSDIM = 10 class SEM(object): def __init__(self, nosplit, lmda, alfa, stsize, learn_rate, seed): """ """ self.seed = seed tr.manual_seed(seed) np.random.seed(seed) # SEMBase.__init__() self.nosplit = nosplit # params self.lmda = lmda self.alfa = alfa self.obsdim = OBSDIM self.rnn_kwargs = { 'stsize':stsize, 'learn_rate':learn_rate, } # collect sem data; locals() returns kwargs dict sem_kwargs = locals() sem_params = {**sem_kwargs} self.data = SEMData(sem_params) """ schlib always has one "inactive" schema similarly, dimensions of prior,likelihood,posterior will be len(schlib) == 1+num_active_schemas """ self.active_schema_idx = 0 self.prev_schema_idx = None self._init_schlib() self.in_layer = tr.nn.Linear(self.obsdim,self.obsdim) return None def _init_schlib(self): self.prior = np.array([self.alfa,self.alfa]) self.schlib = [ CSWSchema(**self.rnn_kwargs), CSWSchema(**self.rnn_kwargs) ] self.schema_count = np.array([1,0]) self.active_schema = self.schlib[0] return None def get_logpriors(self): """ 3 cases: 1) new/inactive schema: prior = alfa 2) old schema, active on previous trial: prior = count + lamda 3) old schema, not active on previous trial: prior = count - CRP calculation relies on `schema_count` which is an array that counts number of times (#obs) each schema was used - len(prior) == len(schlib) """ ## init prior prior = self.schema_count.copy().astype(float) ## active schemas if type(self.prev_schema_idx)==int: prior[self.prev_schema_idx] += self.lmda elif self.prev_schema_idx==None: # tstep0 prior[0] = self.alfa ## new/inactive schema prior[-1] = self.alfa assert len(prior) == len(self.schlib) return np.log(prior) def get_loglikes(self,event): """ wrapper around schema.calc_like - active schemas + one inactive schema """ loglikes = -99*np.ones(len(self.schlib)) for sch_idx,schema in enumerate(self.schlib): loglikes[sch_idx] = schema.calc_event_loglike(event) return loglikes def get_active_schema_idx(self,log_prior,log_like): """ splitting SEM uses argmax of posterior log probability nonsplitting SEM takes single event """ if self.nosplit: return 0 # edge case first trial if self.prev_schema_idx==None: return 0 log_post = log_prior + log_like # print(log_prior,log_like,log_post) return np.argmax(log_post) def select_schema(self,log_prior,log_like): """ returns index of active schema updates previous_schema_index if new schema, append to library """ # select model active_schema_idx = self.get_active_schema_idx(log_prior,log_like) # update previous schema index self.prev_schema_idx = active_schema_idx # if new active_schema, update schlib (need to wrap this) if active_schema_idx == len(self.schema_count)-1: self.schema_count = np.concatenate([self.schema_count,[0]]) self.schlib.append(CSWSchema(**self.rnn_kwargs)) self.data.record_trial('active_schema',active_schema_idx) # todo: move count update into select_schema self.schema_count[active_schema_idx] += 5 active_schema = self.schlib[active_schema_idx] return active_schema # run functions def forward_trial(self, event): """ wrapper for within trial calculations select schema using argmax(posterior) forward and back prop on active schema records trial data """ # embed event = tr.Tensor(event).unsqueeze(1) # include batch dim assert event.shape == (6,1,10) # gradient step loss = self.active_schema.backprop(event) self.data.record_trial('loss',loss) # prior & likelihood of each schema log_priors = self.get_logpriors() log_likes = self.get_loglikes(event) assert len(log_priors) == len(log_likes) == len(self.schlib) # update active schema and update count self.active_schema = self.select_schema(log_priors,log_likes) return None def forward_exp(self,exp,curr): """ wrapper for run_trial """ # loop over events print('active schema of trial t happens at t-1') lossL = [] for trial_num,event in enumerate(exp): # print('\n\nTRIAL',trial_num,'nsc',len(self.schlib)) self.data.new_trial(trial_num) self.data.record_trial('curriculum',curr[trial_num]) self.forward_trial(event) # close data exp_data = self.data.finalize() return exp_data class CSWSchema(tr.nn.Module): def __init__(self,stsize,learn_rate): super().__init__() ## network parameters self.obsdim = OBSDIM self.stsize = stsize self.learn_rate = learn_rate # setup self._build() # backprop self.lossop = tr.nn.MSELoss() self.optiop = tr.optim.Adam( self.parameters(), lr=self.learn_rate) # init settings self.is_active = False # loglike params (from NF) # NB a function of obs dimension self.variance_prior_mode = 1/self.obsdim self.var_df0 = 1 self.var_scale0 = 0.3 self.sigma = np.ones(self.obsdim)/self.obsdim return None def _build(self): ## architecture setup # embedding handled within self.elayer = tr.nn.Linear(self.obsdim,self.stsize) # self.lstm = tr.nn.LSTM(self.embsize,self.stsize) self.gru = tr.nn.GRU(self.stsize,self.stsize) self.init_lstm = tr.nn.Parameter(tr.rand(2,1,1,self.stsize),requires_grad=True) self.out_layer = tr.nn.Linear(self.stsize,self.obsdim) return None # supervised def forward(self,event): ''' receives full event, returns ehat len(event)-1 main wrapper event is Tensor [tsteps,1,scene_dim] returns event_hat ''' eventx = event[:-1] # prop ehat = eventx h_lstm,c_lstm = self.init_lstm ehat = self.elayer(ehat) # ehat,(h_lstm,c_lstm) = self.lstm(ehat,(h_lstm,c_lstm)) ehat,hn = self.gru(ehat,h_lstm) ehat = self.out_layer(ehat) # numpy mode for like assert len(ehat) == len(event)-1 return ehat def backprop(self,event): """ update weights """ ehat = self.forward(event) etarget = event[1:] assert ehat.shape == etarget.shape == (5,1,10) ## self.update_variance(ehat,etarget) ## back prop loss = 0 self.optiop.zero_grad() for tstep in range(len(ehat)): loss += self.lossop(ehat[tstep],etarget[tstep]) loss.backward(retain_graph=1) self.optiop.step() self.is_active = True # update variance return loss.detach().numpy() # like funs def calc_event_loglike_inactive(self,event): """ - evaluate likelihood of each scene under normal_pdf summing over components (obsdim) - NB currently evaluating Begin,...,4 i.e. leaveing out end returns int, loglike of entire event """ eventx = event[:-1] assert self.is_active == False loglike_event = 0 for scene in eventx: normal_pdf = norm(0, self.variance_prior_mode ** 0.5) scene_loglike = normal_pdf.logpdf(scene).sum() loglike_event += scene_loglike return loglike_event def calc_event_loglike(self,event): """ NB self.sigma is a function of prediction error and thus changes over time - not fully confident with handling of inactive schema returns int, loglike of entire event """ ## inactive schema: # if not self.is_active: # return self.calc_event_loglike_inactive(event) # like of schema is function of eventPE ehat = self.forward(event).detach().numpy() etarget = event[1:].detach().numpy() # rm BEGIN assert ehat.shape == etarget.shape == (5,1,10) # t,batch,obs event_pes = np.sum([etarget,-ehat],0).squeeze() # t,obs # loop over scenes of event loglike_event = 0 for scene_pe in event_pes: loglike_event += self.fast_mvnorm_diagonal_logprob(scene_pe, self.sigma) return loglike_event # NF misc def fast_mvnorm_diagonal_logprob(self, x, variances): """ Assumes a zero-mean mulitivariate normal with a diagonal covariance function Parameters: x: array, shape (D,) observations variances: array, shape (D,) Diagonal values of the covariance function output ------ log-probability: float """ log_2pi = np.log(2.0 * np.pi) return -0.5 * (log_2pi * np.shape(x)[0] + np.sum(np.log(variances) + (x**2) / variances )) def map_variance(self, samples, nu0, var0): """ This estimator assumes an scaled inverse-chi squared prior over the variance and a Gaussian likelihood. The parameters d and scale of the internal function parameterize the posterior of the variance. Taken from Bayesian Data Analysis, ch2 (Gelman) samples: N length array or NxD array, where N is the number of samples and D is the dimensions nu0: prior degrees of freedom var0: prior scale parameter returns: float or D-length array, mode of the posterior ## Calculation ## the posterior of the variance is thus (Gelman, 2nd edition, page 50): p(var | y) ~ Inv-X^2(nu0 + n, (nu0 * var0 + n * v) / (nu0 + n) ) where n is the sample size and v is the empirical variance. The mode of this posterior simplifies to: mode(var|y) = (nu0 * var0 + n * v) / (v0 + n + 2) which is just a weighted average of the two modes """ # get n and v from the data n = np.shape(samples)[0] v = np.var(samples, axis=0) mode = (nu0 * var0 + n * v) / (nu0 + n + 2) return mode def update_variance(self,ehat,etarget): ehat = ehat.detach().numpy().squeeze() etarget = etarget.detach().numpy().squeeze() PE = ehat - etarget ## self.sigma = self.map_variance(PE, self.var_df0, self.var_scale0) return None class CSWTask(): """ """ def __init__(self ): A1,A2,B1,B2 = self._init_paths() self.paths = [[A1,A2],[B1,B2]] # keep obs dim fixed: NF plate's formula # calculations assumes 10 self.obsdim = OBSDIM self.tsteps = len(self.paths[0][0]) self.exp_int = None return None # helper init def _init_paths(self): """ begin -> locA -> node11, node 21, node 31, end begin -> locA -> node12, node 22, node 32, end begin -> locB -> node11, node 22, node 31, end begin -> locB -> node12, node 21, node 32, end """ begin,locA,locB = 0,1,2 node11,node12 = 3,4 node21,node22 = 5,6 node31,node32 = 7,8 end = 9 A1 = np.array([begin,locA, node11,node21,node31,end ]) A2 = np.array([begin,locA, node12,node22,node32,end ]) B1 = np.array([begin,locB, node11,node22,node31,end ]) B2 = np.array([begin,locB, node12,node21,node32,end ]) return A1,A2,B1,B2 def _init_emat(self): self.n_obs = 11 self.embed_mat = np.random.normal( loc=0., scale=1./np.sqrt(self.obsdim), size=(self.n_obs, self.obsdim) ) return None # used to generate exp def get_curriculum(self,condition,n_train,n_test): """ order of events NB blocked: ntrain needs to be divisible by 4 """ curriculum = [] if condition == 'blocked': assert n_train%4==0 curriculum = \ [0] * (n_train // 4) + \ [1] * (n_train // 4) + \ [0] * (n_train // 4) + \ [1] * (n_train // 4 ) elif condition == 'early': curriculum = \ [0] * (n_train // 4) + \ [1] * (n_train // 4) + \ [0, 1] * (n_train // 4) elif condition == 'middle': curriculum = \ [0, 1] * (n_train // 8) + \ [0] * (n_train // 4) + \ [1] * (n_train // 4) + \ [0, 1] * (n_train // 8) elif condition == 'late': curriculum = \ [0, 1] * (n_train // 4) + \ [0] * (n_train // 4) + \ [1] * (n_train // 4) elif condition == 'interleaved': curriculum = [0, 1] * (n_train // 2) elif condition == 'single': ## DEBUG curriculum = \ [0] * (n_train) else: print('condition not properly specified') assert False # curriculum += [int(np.random.rand() < 0.5) for _ in range(n_test)] return np.array(curriculum) def embed_path(self,path_int): """ given exp_int (tsteps) returns exp (ntrials,tsteps,obsdim) """ return self.embed_mat[path_int] # main wrapper def generate_experiment(self,condition,n_train,n_test): """ exp arr of events (vec) returns [n_train+n_test,tsteps,obsdim] """ self._init_emat() # get curriculum n_trials = n_train+n_test curr = self.get_curriculum(condition,n_train,n_test) # generate trials exp = -np.ones([n_trials,self.tsteps,self.obsdim]) self.exp_int = -np.ones([n_trials,self.tsteps],dtype=int) for trial_idx in range(n_train+n_test): # select A1,A2,B1,B2 event_type = curr[trial_idx] path_type = np.random.randint(2) path_int = self.paths[event_type][path_type] # embed self.exp_int[trial_idx] = path_int exp[trial_idx] = self.embed_path(path_int) return exp,curr class SEMData(object): def __init__(self, semparams): self.semparams = semparams self.sem_data = [] return None def new_trial(self,trial_num): """ init dict containing trial data NB** trial_data is first appended to sem_data and is then modified at runtime. """ self.trial_data = {'trial':trial_num} self.sem_data.append(self.trial_data) def record_trial(self,key,value): """ populate trial dict NB** trial_data is a dict that has already been appended to sem_data. this method modifies self.trial_data """ self.trial_data[key] = value def record_exp(self,key,value): """ record experiment wide keyvalue in sem_data """ for trial_dict in self.sem_data: trial_dict.update({key:value}) return None def record_semparams(self): """ update each dict in sem_data to include sem semparams """ semparams = {k:v for k,v in self.semparams.items() if k!='self'} for trial_dict in self.sem_data: trial_dict.update(semparams) return None def finalize(self): self.record_semparams() return self.sem_data <file_sep>/code/PY-gs-acc.py #!/usr/bin/env python # coding: utf-8 import sys import itertools import os import numpy as np import torch as tr import pandas as pd from CSWSEM import * ## input params gs_name = 'gs-acc' ## input params param_str = str(sys.argv[1]) learn_rate,alfa,lmda = param_str.split() learn_rate = float(learn_rate) alfa = float(alfa) lmda = float(lmda) stsize = 25 num_seeds = 50 condL = ['blocked','interleaved'] exp_kwargs={ 'n_train':160, 'n_test':40 } # NB only SEM - no LSTM sem_kwargs={ 'nosplit':False, 'stsize':stsize, 'lmda':lmda, 'alfa':alfa, 'learn_rate':learn_rate, } dataL = [] exphat = -np.ones([num_seeds,len(condL),200,5,10]) # (trials,tsteps,obsdim) ## loop over seeds and conditions (Blocked/interleaved) for seed in np.arange(num_seeds): for cidx,cond in enumerate(condL): print(seed,cond) np.random.seed(seed) tr.manual_seed(seed) # setup sem_kwargs['seed'] = seed exp_kwargs['condition'] = cond task = CSWTask(seed) sem = SEM(**sem_kwargs) # run exp,curr = task.generate_experiment(**exp_kwargs) sem_data = sem.forward_exp(exp,curr) ### eval exphat[seed,cidx] = np.array([tdata['event_hat'] for tdata in sem_data]) # record data sem.data.record_exp('condition',exp_kwargs['condition']) dataL.append(pd.DataFrame(sem_data)) ## save save_fpath = 'gsdata/%s/'%(gs_name) batch_tag = 'learnrate_%.3f__alfa_%f__lmbda_%f'%(learn_rate,alfa,lmda) np.save(save_fpath+'exphat__'+batch_tag,exphat) pd.concat(dataL).to_csv(save_fpath+'semdata__'+batch_tag+'.csv')
5fbb3ccab1c0e0bdfb2a8ded531390697d927614
[ "Markdown", "Python", "Shell" ]
14
Shell
andrebeu/SEMCSW
0b3a7ce285ca923d54b47cdb65488b92b5c1014c
919a482492607d63863ee86c049dddb7941d8e27
refs/heads/master
<repo_name>MrPanBeixing/DEMO-Praise<file_sep>/app/src/main/java/com/ai/code/customview/view/IndicatorView.java package com.ai.code.customview.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.ai.code.customview.R; /** * 指示器 * Created by AICode-Pan on 20/05/10. */ public class IndicatorView extends View { private Paint mCirclePaint; private int mCount = 3; // indicator 的数量 private int mRadius = 10;//半径 private int mSelectWidth = 0; private int mSelectColor = Color.RED; private int mDotNormalColor = Color.WHITE;// 小圆点默认颜色 private int mSpace = 20;// 圆点之间的间距 private int mSelectPosition = 0; // 选中的位置 public IndicatorView(Context context) { super(context); init(); } public IndicatorView(Context context, AttributeSet attrs) { super(context, attrs); init(); getAttr(context, attrs); } public IndicatorView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); getAttr(context, attrs); } /** * 获取自定义属性 * * @param context * @param attrs */ private void getAttr(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.IndicatorView); mRadius = typedArray.getDimensionPixelSize(R.styleable.IndicatorView_indicatorRadius, 10); mSpace = typedArray.getDimensionPixelSize(R.styleable.IndicatorView_indicatorSpace, 20); // color mSelectColor = typedArray.getColor(R.styleable.IndicatorView_indicatorSelectColor, Color.WHITE); mDotNormalColor = typedArray.getColor(R.styleable.IndicatorView_indicatorColor, Color.GRAY); mSelectWidth = typedArray.getDimensionPixelSize(R.styleable.IndicatorView_indicatorSelectWidth, 0); typedArray.recycle(); } private void init() { mCirclePaint = new Paint(); mCirclePaint.setDither(true); mCirclePaint.setAntiAlias(true); mCirclePaint.setStyle(Paint.Style.FILL); mCirclePaint.setStrokeCap(Paint.Cap.ROUND); mCirclePaint.setColor(mDotNormalColor); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = mRadius * 2 * mCount + mSpace * (mCount - 1) + mSelectWidth; int height = mRadius * 2 + mSpace * 2; Log.d("IndicatorView", "onMeasure width=" + width + " ,height=" + height); setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { int cx = 0; int cy = getMeasuredHeight() / 2; for (int i = 0; i < mCount; i++) { if (i == 0) { cx = mRadius; } else { cx += mRadius * 2 + mSpace; } float x = cx; float y = cy; Log.d("IndicatorView", "onDraw isSelected=" + (mSelectPosition == i) + " view.x=" + x + " ,view.y=" + y); if (mSelectPosition == i) { mCirclePaint.setColor(mSelectColor); if (mSelectWidth == 0) { canvas.drawCircle(x, y, mRadius, mCirclePaint); } else { mCirclePaint.setStrokeWidth(mRadius * 2); canvas.drawLine(x, y, x + mSelectWidth, y, mCirclePaint); cx += mSelectWidth; } } else { mCirclePaint.setColor(mDotNormalColor); canvas.drawCircle(x, y, mRadius, mCirclePaint); } } } public void setCount(int count) { this.mCount = count; invalidate(); } /** * 设置选中的item * @param position */ public void setSelectPosition(int position) { if (mCount > 0 && mSelectPosition < mCount) { this.mSelectPosition = position; invalidate(); } } /** * 设置半径 * @param radius */ public void setRadius(int radius) { this.mRadius = radius; } /** * 设置选中的颜色 * @param color */ public void setSelectColor(int color) { this.mSelectColor = color; } /** * 设置间距 * @param space */ public void setSpace(int space) { this.mSpace = space; } public void setDotNormalColor(int color) { this.mDotNormalColor = color; } } <file_sep>/README.md ## 简介 通过Canvas或者继承View,写的一些常用的控件,记录一下。有需要的朋友可以自取。 ### PersicopeLayout [效果](https://aicode-pan.oss-cn-beijing.aliyuncs.com/video/1592570155492374.mp4) 点赞动画,通过贝塞尔曲线绘制悬浮路径,图片复用。 <br/> ### BlurView [效果](https://aicode-pan.oss-cn-beijing.aliyuncs.com/video/20200620110203.MP4) 仿IOS Blur控件。因为Android手机计算能力问题,Android没有类似控件。其实实现原理很简单,先裁剪View获取相应位 置Bitmap,再对Bitmap进行压缩处理和模糊处理,最后绘制出来就好了。为了使效果更像IOS的,我加了一个透明白色蒙板。 <br/> ### IndicatorView [效果](https://aicode-pan.oss-cn-beijing.aliyuncs.com/video/1592570074332320.mp4) 指示器,用于画廊,导览,开屏广告,viewpager <br/> ### SlideSelectView [效果](https://aicode-pan.oss-cn-beijing.aliyuncs.com/video/1592570074324749.mp4) 滑动选择器 <br/><file_sep>/app/src/main/java/com/ai/code/customview/view/SlideSelectView.java package com.ai.code.customview.view; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.text.TextPaint; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.animation.AccelerateInterpolator; import com.ai.code.customview.R; /** * Created by AICode-Pan on 20/05/10. */ public class SlideSelectView extends View { //线距离两头的边距 private static float MARGEN_LINE = 60; //小圆半径 private int smallCircleRadius; //大圆半径 private float bigCircleRadius; //大圆圆心半径 private float bigCircleCenterRadius; //小圆的数量 private int countOfSmallCircle; //小圆的横坐标 private float circlesX[]; private Context mContext; //线的画笔 private Paint mLinePaint; //小圆画笔 private Paint mSmallCirclePaint; //大圆画笔 private Paint mBigCirclePaint; //圆心画笔 private Paint mBigCircleCenterPaint; //文字画笔 private TextPaint mTextPaint; //控件高度 private float mHeight; //控件宽度 private float mWidth; //大圆的横坐标 private float bigCircleX; //是否是手指跟随模式 private boolean isFollowMode; //手指按下的x坐标 private float startX; //线的颜色 private int lineColor; //线的宽度 private int lineStrokeWidth; //小圆颜色 private int smallCircleColor; //大圆颜色 private int bigCircleColor; //圆心颜色 private int bigCircleCenterColor; //文字大小 private float textSize; //文字颜色 private int textColor; //文字选中颜色 private int textSelectColor; //文字宽度 private float textWidth; //当前大球距离最近的位置 private int currentPosition; //小圆之间的间距 private float distanceX; //文字顶部间距 private int textTopMargin; //利率文字 private String[] text4Rates = {}; //依附效果实现 private ValueAnimator valueAnimator; //用于纪录松手后的x坐标 private float currentPositionX; private onSelectListener selectListener; public SlideSelectView(Context context) { this(context, null); } public SlideSelectView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlideSelectView); lineColor = a.getColor(R.styleable.SlideSelectView_lineColor, 0xff717171); lineStrokeWidth = a.getDimensionPixelSize(R.styleable.SlideSelectView_lineStrokeWidth, 10); smallCircleColor = a.getColor(R.styleable.SlideSelectView_smallCircleColor, 0xff717171); smallCircleRadius = a.getDimensionPixelSize(R.styleable.SlideSelectView_smallCircleRadius, 0); bigCircleColor = a.getColor(R.styleable.SlideSelectView_bigCircleColor, 0xffEB535E); bigCircleRadius = a.getDimensionPixelSize(R.styleable.SlideSelectView_bigCircleRadius, 30); bigCircleCenterColor = a.getColor(R.styleable.SlideSelectView_bigCenterColor, 0xffffffff); bigCircleCenterRadius = a.getDimensionPixelSize(R.styleable.SlideSelectView_bigCenterRadius, 0); countOfSmallCircle = a.getInt(R.styleable.SlideSelectView_circleCount, 5); textSize = a.getDimensionPixelSize(R.styleable.SlideSelectView_textSize, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics())); textTopMargin = a.getDimensionPixelSize(R.styleable.SlideSelectView_textTopMargin, 4); textColor = a.getColor(R.styleable.SlideSelectView_textColor, 0xff717171); textSelectColor = a.getColor(R.styleable.SlideSelectView_textSelectColor, 0xffEB535E); a.recycle(); MARGEN_LINE = bigCircleRadius + 20; mLinePaint = new Paint(); mLinePaint.setStyle(Paint.Style.STROKE); mLinePaint.setColor(lineColor); mLinePaint.setStrokeWidth(lineStrokeWidth); mLinePaint.setAntiAlias(true); if (smallCircleRadius != 0) { mSmallCirclePaint = new Paint(); mSmallCirclePaint.setStyle(Paint.Style.FILL); mSmallCirclePaint.setColor(smallCircleColor); mSmallCirclePaint.setAntiAlias(true); } mBigCirclePaint = new Paint(); mBigCirclePaint.setStyle(Paint.Style.FILL); mBigCirclePaint.setColor(bigCircleColor); mBigCirclePaint.setAntiAlias(true); if (bigCircleCenterRadius != 0) { mBigCircleCenterPaint = new Paint(); mBigCircleCenterPaint.setStyle(Paint.Style.FILL); mBigCircleCenterPaint.setColor(bigCircleCenterColor); mBigCircleCenterPaint.setAntiAlias(true); } mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mTextPaint.setColor(textColor); mTextPaint.setTextSize(textSize); currentPosition = countOfSmallCircle / 2; } /** * 设置显示文本 * * @param strings */ public void setString(String[] strings) { text4Rates = strings; textWidth = mTextPaint.measureText(text4Rates[0]); if (countOfSmallCircle != text4Rates.length) { throw new IllegalArgumentException("the count of small circle must be equal to the " + "text array length !"); } } /** * 设置监听器 * * @param listener */ public void setOnSelectListener(onSelectListener listener) { selectListener = listener; } @Override protected void onDraw(Canvas canvas) { //画中间的线 drawLine(canvas); //画小圆 if (smallCircleRadius != 0) { for (int i = 0; i < countOfSmallCircle; i++) { canvas.drawCircle(circlesX[i], mHeight / 2, smallCircleRadius, mSmallCirclePaint); } } //画大圆的默认位置 canvas.drawCircle(bigCircleX, mHeight / 2, bigCircleRadius, mBigCirclePaint); //如果圆心半径不为0,绘制圆心 if (bigCircleCenterRadius != 0) { canvas.drawCircle(bigCircleX, mHeight / 2, bigCircleCenterRadius, mBigCircleCenterPaint); } //画文字 for (int i = 0, size = text4Rates.length; i < size; i++) { textWidth = mTextPaint.measureText(text4Rates[i]); if (i == currentPosition) { mTextPaint.setColor(textSelectColor); } else { mTextPaint.setColor(textColor); } canvas.drawText(text4Rates[i], circlesX[i] - textWidth / 2, (mHeight / 2) + bigCircleRadius * 2 + textTopMargin, mTextPaint); } } //修改线的类型,如果为true,线一直未一种颜色,如果为false,头到大圆的位置为大圆的颜色,大圆到尾,是线原本的颜色。 private boolean lineMode = false; private void drawLine(Canvas canvas) { if (lineMode) { canvas.drawLine(MARGEN_LINE, mHeight / 2, mWidth - MARGEN_LINE, mHeight / 2, mLinePaint); } else { mLinePaint.setColor(bigCircleColor); canvas.drawLine(MARGEN_LINE, mHeight / 2, bigCircleX, mHeight / 2, mLinePaint); mLinePaint.setColor(lineColor); canvas.drawLine(bigCircleX, mHeight / 2, mWidth - MARGEN_LINE, mHeight / 2, mLinePaint); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: startX = event.getX(); //如果手指按下的x坐标与大圆的x坐标的距离小于半径,则是follow模式 if (Math.abs(startX - bigCircleX) <= bigCircleRadius) { isFollowMode = true; } else { isFollowMode = false; } break; case MotionEvent.ACTION_MOVE: //如果是follow模式,则大圆跟随手指移动 if (isFollowMode) { //防止滑出边界 if (event.getX() >= MARGEN_LINE && event.getX() <= (mWidth - MARGEN_LINE)) { //LogHelper.d("TAG", "event.getX()=" + event.getX() + "__mWidth=" + mWidth); bigCircleX = event.getX(); int position = (int) ((event.getX() - MARGEN_LINE) / (distanceX / 2)); //更新当前位置 currentPosition = (position + 1) / 2; invalidate(); } } break; case MotionEvent.ACTION_UP: if (isFollowMode) { float endX = event.getX(); //当前位置距离最近的小白点的距离 float currentDistance = endX - MARGEN_LINE - currentPosition * distanceX; //拉到最后或者最头 if ((currentPosition == 0 && currentDistance < 0) || (currentPosition == (text4Rates.length - 1) && currentDistance > 0)) { bigCircleX = currentPosition * distanceX + MARGEN_LINE; invalidate(); if (null != selectListener) { selectListener.onSelect(currentPosition); } return true; } currentPositionX = bigCircleX; valueAnimator = ValueAnimator.ofFloat(currentDistance); valueAnimator.setInterpolator(new AccelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float slideDistance = (float) animation.getAnimatedValue(); bigCircleX = currentPositionX - slideDistance; invalidate(); } }); valueAnimator.setDuration(100); valueAnimator.start(); if (null != selectListener) { selectListener.onSelect(currentPosition); } } else { float endX = event.getX(); //当前位置距离最近的小白点的距离 float currentDistance = endX - MARGEN_LINE - currentPosition * distanceX; // 是否点击到小圆,点击误差小于allowDistanErr float distanceErr = currentDistance % distanceX; int allowDistanErr = 20; // 允许出错范围 boolean isClickCircle = Math.abs(distanceErr) < allowDistanErr || distanceX - Math.abs(distanceErr) < allowDistanErr; if (isClickCircle) { // 计算当前点击的pos位置 int currentDistancePositon = (int) (currentDistance / distanceX); if (distanceErr > 0 && distanceErr > allowDistanErr) { currentDistancePositon++; } else if (distanceErr < 0 && Math.abs(distanceErr) > allowDistanErr) { currentDistancePositon--; } currentDistance = currentDistancePositon * distanceX; currentPosition = currentPosition + currentDistancePositon; currentPositionX = bigCircleX; bigCircleX = currentPositionX + currentDistance; invalidate(); if (null != selectListener) { selectListener.onSelect(currentPosition); } } } break; } return true; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mHeight = h; mWidth = w; //计算每个小圆点的x坐标 circlesX = new float[countOfSmallCircle]; distanceX = (mWidth - MARGEN_LINE * 2) / (countOfSmallCircle - 1); for (int i = 0; i < countOfSmallCircle; i++) { circlesX[i] = i * distanceX + MARGEN_LINE; } bigCircleX = circlesX[currentPosition]; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int screenSize[] = getScreenSize(); int resultWidth; int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode == MeasureSpec.EXACTLY) { resultWidth = widthSize; } else { resultWidth = screenSize[0]; if (widthMode == MeasureSpec.AT_MOST) { resultWidth = Math.min(widthSize, screenSize[0]); } } int resultHeight; int heightSize = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.EXACTLY) { resultHeight = heightSize; } else { resultHeight = (int) (bigCircleRadius * 6); if (heightMode == MeasureSpec.AT_MOST) { resultHeight = Math.min(heightSize, resultHeight); } } setMeasuredDimension(resultWidth, resultHeight); } private int[] getScreenSize() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); DisplayMetrics displayMetrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(displayMetrics); return new int[]{displayMetrics.widthPixels, displayMetrics.heightPixels}; } public interface onSelectListener { public void onSelect(int index); } /** * 上一个 */ public void pre() { if (currentPosition > 0) { currentPosition--; bigCircleX = currentPositionX = bigCircleX - distanceX; invalidate(); if (null != selectListener) { selectListener.onSelect(currentPosition); } } } /** * 下一个 */ public void next() { if (currentPosition < (text4Rates.length - 1)) { currentPosition++; bigCircleX = currentPositionX = bigCircleX + distanceX; invalidate(); if (null != selectListener) { selectListener.onSelect(currentPosition); } } } //设置当前颜色 public void setCurrentPosition(int currentPosition) { this.currentPosition = currentPosition; bigCircleX = currentPositionX = currentPosition * distanceX; invalidate(); } }
9b01b8c37dca3fbe8d30c8e7c0f0cfb8336b5d9a
[ "Markdown", "Java" ]
3
Java
MrPanBeixing/DEMO-Praise
df9fedf9dbafdbbf75bb63dd699a57384ac39f27
8d1509a563a4fb0d4b279898e7f264316150993b
refs/heads/master
<file_sep>// variables for potential letters and the words that may be selected to guess var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; var words = ["tipsy", "bashed", "befuddled", "buzzed", "crocked", "crocked", "flushed", "flying", "glazed", "inebriated", "laced", "lit", "muddled", "plastered", "potted", "sloshed", "stewed", "tanked", "totaled", "wasted", "juiced"]; // Creates a function to randomize an array function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }; // Randomizes the words to guess shuffle(words); // Creating a variable to hold the number of wins. Starts at 0. var wins = 0; // Per game variables of guesses remaining and letters already guessed var guesses = 12; var lettersGuessed = []; // Creates a counter variable to progress through the words and creates a varaiable to hold the current word. var counter = 0 var currentWord = words[counter]; // Creates an array from the word to be guessed and sets it as a variable var currentWordArray = Array.from(currentWord); // Creates an array of blanks the length of the word to be guessed var blanks = new Array(currentWordArray.length).fill("_"); // Creates a function to count the occurances of an input in an array function getOccurrence(array, value) { var count = 0; array.forEach((v) => (v === value && count++)); return count; } // Creates a function to return the positions of an element in array function count(array,element){ var counts = []; for (i = 0; i < array.length; i++){ if (array[i] === element) { counts.push(i); } } return counts; } // Variables that hold references to the places in the HTML where we want to display things. var directionsText = document.getElementById("directions-text"); var winsText = document.getElementById("wins-text"); var currentWordText = document.getElementById("current-word-text"); var guessesRemainingText = document.getElementById("guesses-remaining-text"); var lettersGuessedText = document.getElementById("letters-guessed-text"); var youWonText = document.getElementById("you-won-text"); // This function is run whenever the user presses a key. document.onkeyup = function(event) { console.log("Current Word Array: " + currentWordArray); // Determines which key was pressed. var userGuess = event.key; // Only run the following code block if the user presses a key in the letters array. if (letters.includes(userGuess)){ // console.log("Counter: " + counter); // console.log("Shuffled Words Array: " + words); // Check that the word has not been guessed before proceeding. if(getOccurrence(blanks, "_") == 1 && currentWordArray.indexOf(userGuess) == blanks.indexOf("_")) { if(counter < words.length - 1){ // Incriment wins and resets the game if the word has been guessed wins++; counter++; guesses = 12; lettersGuessed = []; currentWord = words[counter]; currentWordArray = Array.from(currentWord); blanks = new Array(currentWordArray.length).fill("_"); // If there are no more words, places the users guess into the blanks array and triggers a message }else{ i = currentWordArray.indexOf(userGuess); blanks[i] = userGuess.toUpperCase(); youWonText.textContent = "You Won! That's pretty much amazing. I'm all out of words. THERES NO MORE WORDS! OH THE HUMANITY!"; } }else{ // console.log("Letters Guessed userGuess index: " + lettersGuessed.indexOf(userGuess.toUpperCase())); // console.log("blanks userGuess index: " + blanks.indexOf(userGuess)); // console.log(count(currentWordArray, userGuess)) // // console.log(currentWordArray); // // console.log(words.indexOf(currentWord)); // Places the users guess into the blanks array if it is correct and has not been guessed if(currentWordArray.includes(userGuess) && blanks.indexOf(userGuess) < 0) { i = count(currentWordArray, userGuess); blanks[i[0]] = userGuess.toUpperCase(); blanks[i[1]] = userGuess.toUpperCase(); blanks[i[2]] = userGuess.toUpperCase(); blanks[i[3]] = userGuess.toUpperCase(); } // Take away a guess if the letter is not in the currentWordArray and add the letter to letters guessed if(lettersGuessed.indexOf(userGuess.toUpperCase()) < 0 && (blanks.indexOf(userGuess.toUpperCase()) < 0)){ guesses--; lettersGuessed.push(userGuess.toUpperCase()); // Resets the game if the guess count reaches zero if(guesses <= 0){ counter++; guesses = 12; lettersGuessed = []; currentWord = words[counter]; currentWordArray = Array.from(currentWord); blanks = new Array(currentWordArray.length).fill("_"); } } } // Hide the directions directionsText.textContent = ""; // Display the text associated with each element in the game winsText.textContent = "Wins: " + wins; currentWordText.textContent = "Current Word: " + blanks.join(" "); guessesRemainingText.textContent = "Guesses Remaining: " + guesses; lettersGuessedText.textContent = "Letters Guessed: " + lettersGuessed.join(", "); }; };
0f603ba47ca5c6a530af1686191c568456a1fc70
[ "JavaScript" ]
1
JavaScript
actualizeit/Word-Guess-Game
c5e094ef5caf4fe98131b8c2c623473212de55af
123e57023235b0b846dfbb947b207553ce24746e
refs/heads/master
<repo_name>PankajMehar/extend-the-face-detection-example-to-face-and-eye-detection<file_sep>/build.py import cv2 import matplotlib.pyplot as plt import numpy as np from copy import deepcopy def plotBGR2RGB(img): img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img_rgb) plt.show() return(1) # change face_detector to faceeye_detector def face_plot(imgpath): image_p = cv2.imread(imgpath) image_f = deepcopy(image_p) image_f = faceeye_detector(image_f) res = np.hstack((image_p, image_f)) plt.figure(figsize=(20, 10)) plotBGR2RGB(res) return (image_f)
5cf83b0ad5a22e79f2f6a37b3023c462205e7951
[ "Python" ]
1
Python
PankajMehar/extend-the-face-detection-example-to-face-and-eye-detection
ce3b18050a3dd5510fb043d9c1e9e8e60e6a644b
28a83596eae0c1be9881448378bbb203be6bed9f
refs/heads/master
<file_sep>class Poem < ApplicationRecord validates :balada, presence: true, uniqueness: true end <file_sep>Rails.application.routes.draw do root 'contest#index' post '/quiz', to: 'contest#quiz' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep>class AddWordsToPoemLines < ActiveRecord::Migration[5.0] def change add_column :poem_lines, :first_word, :string add_column :poem_lines, :last_word, :string add_index :poem_lines, :first_word add_index :poem_lines, :last_word end end <file_sep>class PoemLine < ApplicationRecord validates :sort_letters, presence: true, uniqueness: true end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'mechanize' require 'colorize' URL = "http://ilibrary.ru/text/" mechanize = Mechanize.new { |agent| agent.user_agent_alias = 'Linux Firefox' } page = mechanize.get("http://ilibrary.ru/author/pushkin/l.all/index.html") links = page.parser.css('.list a') id_poems = links.map { |l| l.attributes['href'].value } .select { |l| l =~ %r{/text/\d+/index\.html} } .map { |l| l.scan(/\d+/)[0] }.uniq num = 0 size = id_poems.size puts "About to write #{size} poems..." Poem.delete_all # begin work with another model PoemLine.delete_all id_poems.each do |id| link = URL + id + "/p.1/index.html" page = mechanize.get(link) title = page.parser.css('.title h1').text text_arr = [] page.parser.css('.vl').each do |line| text_arr << line.text.lstrip # begin work with another model # poem_line = PoemLine.new # poem_line.title = title # poem_line.line = line.text.lstrip # # second space has 160 asci value # letters_sorted_in_line = line.text.delete('.,!?:;()—«»').delete(' ').delete(" ").chars.sort.join('') # poem_line.sort_letters = letters_sorted_in_line # poem_line.length = letters_sorted_in_line.length # poem_line.save temp_line = line.text.gsub(/\u0097/, "\u2014") poem_line = PoemLine.new poem_line.title = title poem_line.line = temp_line.lstrip # second space has 160 asci value letters_sorted_in_line = temp_line.delete('.,!?:;()—«»').delete(' ').delete(" ").chars.sort.join('') poem_line.sort_letters = letters_sorted_in_line poem_line.length = letters_sorted_in_line.length # add first and last word in line line_on_words = temp_line.delete('.,!?:;()—«»').delete(" ").split(' ') poem_line.first_word = line_on_words.first poem_line.last_word = line_on_words.last poem_line.save end text = text_arr.join("\n") text.gsub!(/\u0097/, "\u2014") # replacement of unprintable symbol text.gsub!(/^\n/, "") # remove first \n puts "=".cyan*30 puts title.green puts "#{num} of #{size}".cyan num += 1 next if text.blank? poem = Poem.new poem.title = title poem.balada = text poem.save end <file_sep>class ContestController < ApplicationController skip_before_filter :verify_authenticity_token def index @temps = Temp.all.reverse end def quiz answer_params = referral_params_answer level = answer_params[:level] question = answer_params[:question] id = answer_params[:id] case level.to_s when '1' answer = first_level(question) when '2' answer = second_level(question) when '3' answer = second_level(question) when '4' answer = second_level(question) when '5' answer = fiveth_level(question) when '6' answer = sixth_level(question) when '7' answer = sixth_level(question) when '8' answer = eight_level(question) else answer = "No answer" end @@token ||= Token.last.value send_answer(answer, id, @@token) temp = Temp.new temp.answer = answer temp.question = question temp.id_poem = id temp.level = level temp.save render json: "ok" end def referral_params_answer json_params = ActionController::Parameters.new( JSON.parse(request.body.read) ) return json_params.permit(:level, :question, :id) end URI = URI("http://pushkin.rubyroidlabs.com/quiz") def send_answer(answer, id, token) parameters = { answer: answer, token: token, task_id: id } Net::HTTP.post_form(URI, parameters) end # ------------------------------------------------------------------------- # def first_level(question) # Poem.find_by("balada ~* ?", question).try(:title) # end # def first_level(question) # sorted_question = question.delete('.,!?:;()—«»').delete(' ').delete(" ").chars.sort # sorted_question_line = sorted_question.join # question_letters_count = sorted_question.size # PoemLine.find_by(length: question_letters_count, sort_letters: sorted_question_line).try(:title) # # PoemLine.find_by(line: question).try(:title) # end def first_level(question) sorted_question = question.delete('.,!?:;()—«»').delete(' ').delete(" ").chars.sort sorted_question_line = sorted_question.join PoemLine.find_by(sort_letters: sorted_question_line).try(:title) end # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # def second_level(questions) # question = questions.split("\n").first # question_parts = question.split('%WORD%').sort_by(&:length).reverse # poem = Poem.find_by("balada ~* ?", question_parts[0]).balada # return find_searched_words(poem, questions) # end # def find_searched_words(poem, questions) # searched_words = [] # poem_on_line = poem.split("\n") # questions.split("\n").each do |question| # question_parts = question.split('%WORD%') # poem_on_line.each do |line| # if is_your_str?(question_parts, line) # searched_word = line # question_parts.each do |part| # searched_word.sub!(part, "") # end # searched_words << searched_word.delete('.,!?:;()—') # break # end # end # end # return searched_words.join(',') # end # def is_your_str?(question_parts, line) # question_parts.each do |part| # return false unless line.include? part # end # return true # end # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def second_level(questions) indexes = [] searched_words = [] questions.split("\n").each_with_index do |question, num_question| question_parts = question.split('%WORD%') question_on_words = question.delete('.,!?:;()—«»').delete(" ").split(' ') if indexes.size > 0 searched_words << return_searched_word(question_parts, PoemLine.find(indexes.first + num_question).line) else if question_on_words.last == '%WORD%' PoemLine.where(first_word: question_on_words.first).each do |line| if is_your_str?(question_parts, line.line) indexes << line.id searched_words << return_searched_word(question_parts, line.line) end end else PoemLine.where(last_word: question_on_words.last).each do |line| if is_your_str?(question_parts, line.line) indexes << line.id searched_words << return_searched_word(question_parts, line.line) end end end end end return searched_words.join(',') end def return_searched_word(question_parts,line) searched_word = line question_parts.each do |part| searched_word.sub!(part, "") end searched_word.delete('.,!?:;()—') end def is_your_str?(question_parts, line) question_parts.each do |part| return false unless line.include? part end return true end # ---------------------------------------------------------------------- # def fiveth_level(question) # possible_sentence = create_all_possible_variation question # regexp = possible_sentence.join('|') # my_line = Poem.find_by("balada ~ ?", regexp).try(:balada).match(regexp).to_s # return find_different_words(question, my_line) # end # def create_all_possible_variation(question) # possible_sentence = [] # question_on_words = question.split(" ") # question_on_words.count.times do # possible_sentence << question.split(" ") # end # possible_sentence.each_with_index do |arr, i| # arr[i].sub!(/^[А-Яа-яA-Za-z\-«»]+/, "\\S+") # end # possible_sentence.map! { |a| a.join(" ") } # return possible_sentence # end # def find_different_words(question, line) # line_on_words = line.delete('.,!?:;()—').split(" ") # question_on_words = question.delete('.,!?:;()—').split(" ") # return ((line_on_words - question_on_words) | (question_on_words - line_on_words)).join(',') # end # ---------------------------------------------------------------------- # -------------------------------------------------------------------- def fiveth_level(question) possible_sentence = create_all_possible_variation question regexp = possible_sentence.join('|') question_on_words = question.delete('.,!?:;()—«»').delete(" ").split(' ') PoemLine.where(last_word: question_on_words.last). or(PoemLine.where(first_word: question_on_words.first)).each do |line| if Regexp.new(regexp) =~ line.line return find_different_words(question, line.line) end end return ' ' end def create_all_possible_variation(question) possible_sentence = [] question_on_words = question.split(" ") question_on_words.count.times do |i| possible_sentence << question.split(" ") possible_sentence[i][i].sub!(/^[А-Яа-яA-Za-z\-«»]+/, "\\S+") possible_sentence[i] = possible_sentence[i].join(" ") end return possible_sentence end def find_different_words(question, line) line_on_words = line.delete('.,!?:;()—').split(" ") question_on_words = question.delete('.,!?:;()—').split(" ") return ((line_on_words - question_on_words) | (question_on_words - line_on_words)).join(',') end # -------------------------------------------------------------------- def sixth_level(question) sorted_question = question.delete(' ').delete(" ").chars.sort sorted_question_line = sorted_question.join PoemLine.find_by(sort_letters: sorted_question_line).try(:line) # question_letters_count = sorted_question.size # PoemLine.find_by(length: question_letters_count, sort_letters: sorted_question_line).line end # ---------------------------------------------------------------------- def eight_level(question) question_on_letters = question.delete(' ').chars letters_question_count = question_on_letters.length PoemLine.where(length: letters_question_count).each do |line| if has_unsuitable_element?(line.sort_letters, question.delete(' ')) return line.line end end return nil end def has_unsuitable_element?(arr1, arr2) arr1 = arr1.chars arr2 = arr2.chars unsuitable_array = [] arr1.length.times do shift_element = arr2.shift if arr1.include? shift_element arr1.delete_at( arr1.index shift_element) else unsuitable_array << shift_element return false if unsuitable_array.size > 1 end end true end # ---------------------------------------------------------------------- end
de733e7c695d8dbf2cc1c87051605254ee07a88e
[ "Ruby" ]
6
Ruby
juggleross/pushkin-contest-bot
7c0064cc402f0bfc967b164229cc24c2478538e6
ed72f18387bdaeed065a001d42a829b06d601e32
refs/heads/main
<file_sep>import React from 'react' import './Header.css' function Header() { return ( <div className='header'> <div className="head_logo"> <img src="https://mir-s3-cdn-cf.behance.net/project_modules/fs/0a46b329632909.55fc107b86e40.png" alt="" /> </div> <div className="head_right"> <a href="#">My Account</a> <a href="#">Courses[+]</a> <a href="#">Membership</a> <a href="#">Sign Out</a> </div> </div> ) } export default Header<file_sep> import './App.css'; import Bar from './Bar'; import Bar2 from './Bar2' import Header from './Header' import Reminder from './Reminder'; import Tutorials from './Tutorials'; import Whatever from './Whatever' function App() { return ( <div className="App"> <Header/> <Bar/> <Reminder/> </div> ); } export default App;
11a380643d82cdc194ed192810136660f04da3bb
[ "JavaScript" ]
2
JavaScript
agneus/a_courses
0066d02d3526a4df2253d310f051c6f908d97054
7c09ce46c30fc289c06690a0770c62b977023c51
refs/heads/master
<repo_name>siemantic/StratisBitcoinFullNode<file_sep>/src/Stratis.Bitcoin.Features.Consensus.Tests/PeerBanningTest.cs using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Moq; using NBitcoin; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.P2P.Peer; using Xunit; namespace Stratis.Bitcoin.Features.Consensus.Tests { public class PeerBanningTest { public PeerBanningTest() { Block.BlockSignature = false; Transaction.TimeStamp = false; } [Fact] public async Task NodeIsSynced_PeerSendsABadBlockAndPeerDiconnected_ThePeerGetsBanned_Async() { string dataDir = Path.Combine("TestData", nameof(PeerBanningTest), nameof(this.NodeIsSynced_PeerSendsABadBlockAndPeerDiconnected_ThePeerGetsBanned_Async)); Directory.CreateDirectory(dataDir); TestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, dataDir); var peer = new IPEndPoint(IPAddress.Parse("172.16.31.10"), context.Network.DefaultPort); context.MockReadOnlyNodesCollection.Setup(s => s.FindByEndpoint(It.IsAny<IPEndPoint>())).Returns((NetworkPeer)null); var blocks = await TestChainFactory.MineBlocksAsync(context, 2, new Key().ScriptPubKey); var block = blocks.First(); block.Header.HashPrevBlock = context.Chain.Tip.HashBlock; await context.Consensus.AcceptBlockAsync(new BlockValidationContext { Block = block, Peer = peer }); Assert.True(context.PeerBanning.IsBanned(peer)); } [Fact] public async Task NodeIsSynced_PeerSendsABadBlockAndPeerIsConnected_ThePeerGetsBanned_Async() { string dataDir = Path.Combine("TestData", nameof(PeerBanningTest), nameof(this.NodeIsSynced_PeerSendsABadBlockAndPeerIsConnected_ThePeerGetsBanned_Async)); Directory.CreateDirectory(dataDir); TestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, dataDir); var peer = new IPEndPoint(IPAddress.Parse("1.2.3.4"), context.Network.DefaultPort); var connectionManagerBehavior = new ConnectionManagerBehavior(false, context.ConnectionManager, context.LoggerFactory); using (var node = new NetworkPeer(context.DateTimeProvider, context.LoggerFactory)) { node.Behaviors.Add(connectionManagerBehavior); context.MockReadOnlyNodesCollection.Setup(s => s.FindByEndpoint(It.IsAny<IPEndPoint>())).Returns(node); var blocks = await TestChainFactory.MineBlocksAsync(context, 2, new Key().ScriptPubKey); // create a new block that breaks consensus. var block = blocks.First(); block.Header.HashPrevBlock = context.Chain.Tip.HashBlock; await context.Consensus.AcceptBlockAsync(new BlockValidationContext { Block = block, Peer = peer }); Assert.True(context.PeerBanning.IsBanned(peer)); } } [Fact] public async Task NodeIsSynced_PeerSendsABadBlockAndPeerIsWhitelisted_ThePeerIsNotBanned_Async() { string dataDir = Path.Combine("TestData", nameof(PeerBanningTest), nameof(this.NodeIsSynced_PeerSendsABadBlockAndPeerIsWhitelisted_ThePeerIsNotBanned_Async)); Directory.CreateDirectory(dataDir); TestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, dataDir); var peer = new IPEndPoint(IPAddress.Parse("1.2.3.4"), context.Network.DefaultPort); var connectionManagerBehavior = new ConnectionManagerBehavior(false, context.ConnectionManager, context.LoggerFactory) { Whitelisted = true }; using (var node = new NetworkPeer(context.DateTimeProvider, context.LoggerFactory)) { node.Behaviors.Add(connectionManagerBehavior); context.MockReadOnlyNodesCollection.Setup(s => s.FindByEndpoint(It.IsAny<IPEndPoint>())).Returns(node); var blocks = await TestChainFactory.MineBlocksAsync(context, 2, new Key().ScriptPubKey); // create a new block that breaks consensus. var block = blocks.First(); block.Header.HashPrevBlock = context.Chain.Tip.HashBlock; await context.Consensus.AcceptBlockAsync(new BlockValidationContext { Block = block, Peer = peer }); Assert.False(context.PeerBanning.IsBanned(peer)); } } [Fact] public async Task NodeIsSynced_PeerSendsABadBlockAndErrorIsNotBanError_ThePeerIsNotBanned_Async() { string dataDir = Path.Combine("TestData", nameof(PeerBanningTest), nameof(this.NodeIsSynced_PeerSendsABadBlockAndErrorIsNotBanError_ThePeerIsNotBanned_Async)); Directory.CreateDirectory(dataDir); TestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, dataDir); var peer = new IPEndPoint(IPAddress.Parse("1.2.3.4"), context.Network.DefaultPort); var connectionManagerBehavior = new ConnectionManagerBehavior(false, context.ConnectionManager, context.LoggerFactory) { Whitelisted = true }; using (var node = new NetworkPeer(context.DateTimeProvider, context.LoggerFactory)) { node.Behaviors.Add(connectionManagerBehavior); context.MockReadOnlyNodesCollection.Setup(s => s.FindByEndpoint(It.IsAny<IPEndPoint>())).Returns(node); var blocks = await TestChainFactory.MineBlocksAsync(context, 2, new Key().ScriptPubKey); // create a new block that breaks consensus. var block = blocks.First(); block.Header.HashPrevBlock = context.Chain.Tip.HashBlock; await context.Consensus.AcceptBlockAsync(new BlockValidationContext { Block = block, Peer = peer, BanDurationSeconds = BlockValidationContext.BanDurationNoBan }); Assert.False(context.PeerBanning.IsBanned(peer)); } } [Fact] public async Task NodeIsSynced_PeerSendsABadBlockAndPeerIsBandAndBanIsExpired_ThePeerIsNotBanned_Async() { string dataDir = Path.Combine("TestData", nameof(PeerBanningTest), nameof(this.NodeIsSynced_PeerSendsABadBlockAndPeerIsBandAndBanIsExpired_ThePeerIsNotBanned_Async)); Directory.CreateDirectory(dataDir); TestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, dataDir); var peer = new IPEndPoint(IPAddress.Parse("1.2.3.4"), context.Network.DefaultPort); var connectionManagerBehavior = new ConnectionManagerBehavior(false, context.ConnectionManager, context.LoggerFactory) { Whitelisted = true }; using (var node = new NetworkPeer(context.DateTimeProvider, context.LoggerFactory)) { node.Behaviors.Add(connectionManagerBehavior); context.MockReadOnlyNodesCollection.Setup(s => s.FindByEndpoint(It.IsAny<IPEndPoint>())).Returns(node); var blocks = await TestChainFactory.MineBlocksAsync(context, 2, new Key().ScriptPubKey); // create a new block that breaks consensus. var block = blocks.First(); block.Header.HashPrevBlock = context.Chain.Tip.HashBlock; await context.Consensus.AcceptBlockAsync(new BlockValidationContext { Block = block, Peer = peer, BanDurationSeconds = 1 }); // ban for 1 second // wait 1 sec for ban to expire. Thread.Sleep(1000); Assert.False(context.PeerBanning.IsBanned(peer)); } } } } <file_sep>/src/Stratis.Bitcoin.Tests/P2P/PeerConnectorTests.cs using System; using System.IO; using System.Net; using NBitcoin; using NBitcoin.Protocol; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Configuration.Logging; using Stratis.Bitcoin.Configuration.Settings; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.P2P; using Stratis.Bitcoin.P2P.Peer; using Stratis.Bitcoin.Utilities; using Xunit; namespace Stratis.Bitcoin.Tests.P2P { public sealed class PeerConnectorTests : TestBase { private readonly IAsyncLoopFactory asyncLoopFactory; private readonly ExtendedLoggerFactory extendedLoggerFactory; private readonly INetworkPeerFactory networkPeerFactory; private readonly NetworkPeerConnectionParameters networkPeerParameters; private readonly NodeLifetime nodeLifetime; private readonly Network network; public PeerConnectorTests() { this.extendedLoggerFactory = new ExtendedLoggerFactory(); this.extendedLoggerFactory.AddConsoleWithFilters(); this.asyncLoopFactory = new AsyncLoopFactory(this.extendedLoggerFactory); this.network = Network.Main; this.networkPeerParameters = new NetworkPeerConnectionParameters(); this.networkPeerFactory = new NetworkPeerFactory(this.network, DateTimeProvider.Default, this.extendedLoggerFactory); this.nodeLifetime = new NodeLifetime(); } [Fact] public void PeerConnectorAddNode_FindPeerToConnectTo_Returns_AddNodePeers() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var ipAddressOne = IPAddress.Parse("::ffff:192.168.0.1"); var endpointAddNode = new IPEndPoint(ipAddressOne, 80); var ipAddressTwo = IPAddress.Parse("::ffff:192.168.0.2"); var endpointDiscoveredNode = new IPEndPoint(ipAddressTwo, 80); peerAddressManager.AddPeer(endpointAddNode, IPAddress.Loopback); peerAddressManager.AddPeer(endpointDiscoveredNode, IPAddress.Loopback); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); connectionSettings.AddNode.Add(endpointAddNode); // TODO: Once we have an interface on NetworkPeer we can test this properly. //var connector = this.CreatePeerConnecterAddNode(nodeSettings, peerAddressManager); //connector.OnConnectAsync().GetAwaiter().GetResult(); //Assert.Contains(networkAddressAddNode, connector.ConnectedPeers.Select(p => p.PeerAddress)); } [Fact] public void PeerConnectorAddNode_CanAlwaysStart() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); var connector = this.CreatePeerConnecterAddNode(nodeSettings, connectionSettings, peerAddressManager); Assert.True(connector.CanStartConnect); } [Fact] public void PeerConnectorConnect_FindPeerToConnectTo_Returns_ConnectNodePeers() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var ipAddressOne = IPAddress.Parse("::ffff:192.168.0.1"); var endpointAddNode = new IPEndPoint(ipAddressOne, 80); var ipAddressTwo = IPAddress.Parse("::ffff:192.168.0.2"); var endpointDiscoveredNode = new IPEndPoint(ipAddressTwo, 80); var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var endpointConnectNode = new IPEndPoint(ipAddressThree, 80); peerAddressManager.AddPeer(endpointAddNode, IPAddress.Loopback); peerAddressManager.AddPeer(endpointConnectNode, IPAddress.Loopback); peerAddressManager.AddPeer(endpointDiscoveredNode, IPAddress.Loopback); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); connectionSettings.Connect.Add(endpointConnectNode); var connector = this.CreatePeerConnectorConnectNode(nodeSettings, connectionSettings, peerAddressManager); // TODO: Once we have an interface on NetworkPeer we can test this properly. //var connector = this.CreatePeerConnecterAddNode(nodeSettings, peerAddressManager); //connector.OnConnectAsync().GetAwaiter().GetResult(); //Assert.Contains(networkAddressConnectNode, connector.ConnectedPeers.Select(p => p.PeerAddress)); } [Fact] public void PeerConnectorConnect_WithConnectPeersSpecified_CanStart() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var endpointConnectNode = new NetworkAddress(ipAddressThree, 80); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); connectionSettings.Connect.Add(endpointConnectNode.Endpoint); var connector = this.CreatePeerConnectorConnectNode(nodeSettings, connectionSettings, peerAddressManager); Assert.True(connector.CanStartConnect); } [Fact] public void PeerConnectorConnect_WithNoConnectPeersSpecified_CanNotStart() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); var connector = this.CreatePeerConnectorConnectNode(nodeSettings, connectionSettings, peerAddressManager); Assert.False(connector.CanStartConnect); } [Fact] public void PeerConnectorDiscovery_FindPeerToConnectTo_Returns_DiscoveredPeers() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var ipAddressOne = IPAddress.Parse("::ffff:192.168.0.1"); var endpointAddNode = new IPEndPoint(ipAddressOne, 80); var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var endPointConnectNode = new IPEndPoint(ipAddressThree, 80); var ipAddressTwo = IPAddress.Parse("::ffff:192.168.0.2"); var endpointDiscoveredNode = new IPEndPoint(ipAddressTwo, 80); peerAddressManager.AddPeer(endpointAddNode, IPAddress.Loopback); peerAddressManager.AddPeer(endPointConnectNode, IPAddress.Loopback); peerAddressManager.AddPeer(endpointDiscoveredNode, IPAddress.Loopback); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); connectionSettings.AddNode.Add(endpointAddNode); connectionSettings.Connect.Add(endPointConnectNode); var connector = this.CreatePeerConnectorDiscovery(nodeSettings, connectionSettings, peerAddressManager); // TODO: Once we have an interface on NetworkPeer we can test this properly. //var connector = this.CreatePeerConnecterAddNode(nodeSettings, peerAddressManager); //connector.OnConnectAsync().GetAwaiter().GetResult(); //Assert.Contains(networkAddressDiscoverNode, connector.ConnectedPeers.Select(p => p.PeerAddress)); } [Fact] public void PeerConnectorDiscover_WithNoConnectPeersSpecified_CanStart() { var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); var connector = this.CreatePeerConnectorDiscovery(nodeSettings, connectionSettings, peerAddressManager); Assert.True(connector.CanStartConnect); } [Fact] public void PeerConnectorDiscover_WithConnectPeersSpecified_CanNotStart() { var nodeSettings = new NodeSettings(); nodeSettings.LoadArguments(new string[] { }); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(nodeSettings); var ipAddressThree = IPAddress.Parse("::ffff:192.168.0.3"); var networkAddressConnectNode = new NetworkAddress(ipAddressThree, 80); connectionSettings.Connect.Add(networkAddressConnectNode.Endpoint); var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerConnectorTests")); var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory); var connector = this.CreatePeerConnectorDiscovery(nodeSettings, connectionSettings, peerAddressManager); Assert.False(connector.CanStartConnect); } private PeerConnectorAddNode CreatePeerConnecterAddNode(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager) { var peerConnector = new PeerConnectorAddNode(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, nodeSettings, connectionSettings, peerAddressManager); var connectionManager = CreateConnectionManager(nodeSettings, connectionSettings, peerAddressManager, peerConnector); peerConnector.Initialize(connectionManager); return peerConnector; } private PeerConnectorConnectNode CreatePeerConnectorConnectNode(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager) { var peerConnector = new PeerConnectorConnectNode(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, nodeSettings, connectionSettings, peerAddressManager); var connectionManager = CreateConnectionManager(nodeSettings, connectionSettings, peerAddressManager, peerConnector); peerConnector.Initialize(connectionManager); return peerConnector; } private PeerConnectorDiscovery CreatePeerConnectorDiscovery(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager) { var peerConnector = new PeerConnectorDiscovery(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, nodeSettings, connectionSettings, peerAddressManager); var connectionManager = CreateConnectionManager(nodeSettings, connectionSettings, peerAddressManager, peerConnector); peerConnector.Initialize(connectionManager); return peerConnector; } private IConnectionManager CreateConnectionManager(NodeSettings nodeSettings, ConnectionManagerSettings connectionSettings, IPeerAddressManager peerAddressManager, IPeerConnector peerConnector) { var connectionManager = new ConnectionManager( DateTimeProvider.Default, this.loggerFactory, this.network, this.networkPeerFactory, nodeSettings, this.nodeLifetime, this.networkPeerParameters, peerAddressManager, new IPeerConnector[] { peerConnector }, null, connectionSettings); return connectionManager; } } }<file_sep>/src/Stratis.Bitcoin.IntegrationTests/P2P/PeerConnectionTests.cs using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Configuration.Logging; using Stratis.Bitcoin.Configuration.Settings; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.IntegrationTests.EnvironmentMockUpHelpers; using Stratis.Bitcoin.P2P; using Stratis.Bitcoin.P2P.Peer; using Stratis.Bitcoin.Utilities; using Xunit; namespace Stratis.Bitcoin.IntegrationTests.P2P { public sealed class PeerConnectionTests { private ILoggerFactory loggerFactory; private NetworkPeerConnectionParameters parameters; private NetworkPeerFactory networkPeerFactory; private INodeLifetime nodeLifetime; private NodeSettings nodeSettings; private ConnectionManagerSettings connectionSetting; private IPeerAddressManager peerAddressManager; private readonly Network network; public PeerConnectionTests() { this.network = Network.Main; } /// <summary> /// This tests the fact that we can't find and connect to a /// peer that is already connected. /// </summary> [Fact] public void PeerConnectorAddNode_PeerAlreadyConnected_Scenario1() { this.CreateTestContext("PeerConnectorAddNode_PeerAlreadyConnected_Scenario1"); var peerConnectorAddNode = new PeerConnectorAddNode(new AsyncLoopFactory(this.loggerFactory), DateTimeProvider.Default, this.loggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, this.nodeSettings, this.connectionSetting, this.peerAddressManager); var peerDiscovery = new PeerDiscovery(new AsyncLoopFactory(this.loggerFactory), this.loggerFactory, this.network, this.networkPeerFactory, this.nodeLifetime, this.nodeSettings, this.peerAddressManager); var connectionSettings = new ConnectionManagerSettings(); connectionSettings.Load(this.nodeSettings); IConnectionManager connectionManager = new ConnectionManager( DateTimeProvider.Default, this.loggerFactory, this.network, this.networkPeerFactory, this.nodeSettings, this.nodeLifetime, this.parameters, this.peerAddressManager, new IPeerConnector[] { peerConnectorAddNode }, peerDiscovery, connectionSettings); // Create a peer to add to the already connected peers collection. using (NodeBuilder builder = NodeBuilder.Create()) { CoreNode coreNode = builder.CreateStratisPowNode(); builder.StartAll(); using (NetworkPeer networkPeer = coreNode.CreateNetworkPeerClient()) { // Add the network peers to the connection manager's // add node collection. connectionManager.AddNodeAddress(networkPeer.PeerEndPoint); // Add the peer to the already connected // peer collection of connection manager. // // This is to simulate that a peer has successfully connected // and that the add node connector's Find method then won't // return the added node. connectionManager.AddConnectedPeer(networkPeer); // Re-initialize the add node peer connector so that it // adds the successful address to the address manager. peerConnectorAddNode.Initialize(connectionManager); // TODO: Once we have an interface on NetworkPeer we can test this properly. // The already connected peer should not be returned. //var peer = peerConnectorAddNode.FindPeerToConnectTo(); //Assert.Null(peer); } } } private void CreateTestContext(string folder) { this.loggerFactory = new ExtendedLoggerFactory(); this.loggerFactory.AddConsoleWithFilters(); this.parameters = new NetworkPeerConnectionParameters(); var testFolder = TestDirectory.Create(folder); this.nodeSettings = new NodeSettings(); this.nodeSettings.LoadArguments(new string[] { }); this.nodeSettings.DataFolder = new DataFolder(this.nodeSettings.DataDir); this.connectionSetting = new ConnectionManagerSettings(); this.connectionSetting.Load(this.nodeSettings); this.peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, this.nodeSettings.DataFolder, this.loggerFactory); var peerAddressManagerBehaviour = new PeerAddressManagerBehaviour(DateTimeProvider.Default, this.peerAddressManager) { PeersToDiscover = 10 }; this.parameters.TemplateBehaviors.Add(peerAddressManagerBehaviour); this.networkPeerFactory = new NetworkPeerFactory(this.network, DateTimeProvider.Default, this.loggerFactory); this.nodeLifetime = new NodeLifetime(); } } }<file_sep>/src/Stratis.Bitcoin/P2P/Peer/NetworkPeerCollection.cs using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using NBitcoin; using Stratis.Bitcoin.P2P.Protocol; using Stratis.Bitcoin.Utilities; namespace Stratis.Bitcoin.P2P.Peer { public class NetworkPeerEventArgs : EventArgs { public bool Added { get; private set; } public NetworkPeer peer { get; private set; } public NetworkPeerEventArgs(NetworkPeer peer, bool added) { this.Added = added; this.peer = peer; } } public interface IReadOnlyNetworkPeerCollection : IEnumerable<NetworkPeer> { event EventHandler<NetworkPeerEventArgs> Added; event EventHandler<NetworkPeerEventArgs> Removed; NetworkPeer FindByEndpoint(IPEndPoint endpoint); NetworkPeer FindByIp(IPAddress ip); NetworkPeer FindLocal(); } public class NetworkPeerCollection : IEnumerable<NetworkPeer>, IReadOnlyNetworkPeerCollection { private ConcurrentDictionary<NetworkPeer, NetworkPeer> networkPeers; public int Count { get { return this.networkPeers.Count; } } public event EventHandler<NetworkPeerEventArgs> Added; public event EventHandler<NetworkPeerEventArgs> Removed; /// <summary> /// Provides a comparer to specify how peers are compared for equality. /// </summary> public class NetworkPeerComparer : IEqualityComparer<NetworkPeer> { public bool Equals(NetworkPeer peerA, NetworkPeer peerB) { if ((peerA == null) || (peerB == null)) return (peerA == null) && (peerB == null); return (peerA.RemoteSocketAddress.MapToIPv6().ToString() == peerB.RemoteSocketAddress.MapToIPv6().ToString()) && (peerA.RemoteSocketPort == peerB.RemoteSocketPort); } public int GetHashCode(NetworkPeer peer) { if (peer == null) return 0; return peer.RemoteSocketPort.GetHashCode() ^ peer.RemoteSocketAddress.MapToIPv6().ToString().GetHashCode(); } } public NetworkPeerCollection() { this.networkPeers = new ConcurrentDictionary<NetworkPeer, NetworkPeer>(new NetworkPeerComparer()); } public bool Add(NetworkPeer peer) { Guard.NotNull(peer, nameof(peer)); if (this.networkPeers.TryAdd(peer, peer)) { this.OnPeerAdded(peer); return true; } return false; } public bool Remove(NetworkPeer peer, string reason) { NetworkPeer old; if (this.networkPeers.TryRemove(peer, out old)) { this.OnPeerRemoved(old); peer.Dispose(reason); return true; } return false; } private void OnPeerAdded(NetworkPeer peer) { this.Added?.Invoke(this, new NetworkPeerEventArgs(peer, true)); } public void OnPeerRemoved(NetworkPeer peer) { this.Removed?.Invoke(this, new NetworkPeerEventArgs(peer, false)); } public NetworkPeer FindLocal() { return this.FindByIp(IPAddress.Loopback); } public NetworkPeer FindByIp(IPAddress ip) { ip = ip.EnsureIPv6(); return this.networkPeers.Where(n => Match(ip, null, n.Key)).Select(s => s.Key).FirstOrDefault(); } public NetworkPeer FindByEndpoint(IPEndPoint endpoint) { IPAddress ip = endpoint.Address.EnsureIPv6(); int port = endpoint.Port; return this.networkPeers.Select(n => n.Key).FirstOrDefault(n => Match(ip, port, n)); } private static bool Match(IPAddress ip, int? port, NetworkPeer peer) { if (port.HasValue) { return ((peer.State > NetworkPeerState.Disconnecting) && peer.RemoteSocketAddress.Equals(ip) && (peer.RemoteSocketPort == port.Value)) || (peer.PeerVersion.AddressFrom.Address.Equals(ip) && (peer.PeerVersion.AddressFrom.Port == port.Value)); } else { return ((peer.State > NetworkPeerState.Disconnecting) && peer.RemoteSocketAddress.Equals(ip)) || peer.PeerVersion.AddressFrom.Address.Equals(ip); } } public IEnumerator<NetworkPeer> GetEnumerator() { return this.networkPeers.Select(n => n.Key).AsEnumerable().GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public void DisconnectAll(string reason, CancellationToken cancellation = default(CancellationToken)) { foreach (KeyValuePair<NetworkPeer, NetworkPeer> peer in this.networkPeers) peer.Key.Dispose(reason); } public void Clear() { this.networkPeers.Clear(); } } }
b3d24beb42463cc83a3f7297ccb7ed5601593769
[ "C#" ]
4
C#
siemantic/StratisBitcoinFullNode
b016ac9af47f00a1f5d3fa7acd6aaabe07788ddc
47a23a676ffc5f663ad1d7c79bfee5c7d6ce414c
refs/heads/master
<repo_name>apryab/GeekBrains-HW-7<file_sep>/Task 2.py from abc import ABC, abstractmethod def my_decorator(func): def wrapper(self): if hasattr(self, 'size'): print('Количество ткани для пальто -', end=' ') if hasattr(self, 'height'): print('Количество ткани для костюма -', end=' ') answer = func(self) print(answer) return wrapper class Clothes(ABC): @abstractmethod def __init__(self): pass @abstractmethod def fabric_count(self): pass class Coat(Clothes): def __init__(self, size): super().__init__() try: self.size = int(size) except(TypeError, ValueError): print('Неправильный формат роста. Будет присвоено значение -1') self.size = -1 @my_decorator def fabric_count(self): if self.size <= 0: raise ValueError else: return self.size / 6.5 + 0.5 class Costume(Clothes): def __init__(self, height): super().__init__() try: self.height = float(height) except(TypeError, ValueError): print('Неправильный формат роста, надо ввести число.') self.height = -1 @my_decorator def fabric_count(self): if self.height <= 0: raise ValueError else: return 2 * self.height + 0.3 my_coat_1 = Coat(5) my_costume = Costume(4) my_coat_2 = Coat('r') try: my_coat_1.fabric_count() my_costume.fabric_count() my_coat_2.fabric_count() except(TypeError, ValueError): print('\n') print('Неправильный формат данных у объекта') <file_sep>/Task 1.py import copy class Matrix: def __init__(self, my_list): mistake = 0 try: len(my_list) except TypeError: print('Матрица должна быть списком списков') mistake = 1 if mistake != 1: if len(my_list) > 0: try: n = len(my_list[0]) except TypeError: print('Матрица должна быть списком списков') n = -1 mistake = 1 try: if mistake != 1: for elem in my_list: if len(elem) != n: mistake = 1 break for item in elem: float(item) except(ValueError, TypeError): print('Неправильный формат данных в матрице') mistake = 1 if mistake == 0: self.height = len(my_list) self.width = len(my_list[0]) self.list = my_list else: mistake = 1 if mistake == 1: self.height = 0 self.width = 0 self.list = [] print('Будет создана матрица нулевого размера') def __str__(self): big_str = '[' for elem in self.list: big_str += '[' for item in elem: big_str += str(item) big_str += ', ' if self.width > 0: big_str = big_str[:-2] big_str += ']' big_str += ', ' if self.height > 0: big_str = big_str[:-2] big_str += ']' return big_str def __add__(self, other): if type(other) == Matrix: if(self.width == other.width) and (self.height == other.height): answer_list = [] for i in range(len(self.list)): temp_list = [] for j in range(len(self.list[i])): temp_list.append(self.list[i][j] + other.list[i][j]) answer_list.append(copy.deepcopy(temp_list)) temp_list.clear() return Matrix(answer_list) else: print('Размеры матриц не равны') return ValueError else: print('Неправильные типы данных операндов') return TypeError my_matrix_1 = Matrix([[1, 100, 6], [2, 5, 1], [5, 8, 1]]) my_matrix_2 = Matrix([[2, 5, 8], [1, 4, 2], [2, 7, 3]]) answer_matrix = my_matrix_1 + my_matrix_2 print(answer_matrix) <file_sep>/Task 3.py class Cell: def __init__(self, numb_of_cells): try: self.numb_of_cells = float(numb_of_cells) if self.numb_of_cells % 1 == 0: self.numb_of_cells = int(self.numb_of_cells) if self.numb_of_cells == 0: print('В ячейке не может быть 0 клеток. Будет создана единичная клетка') self.numb_of_cells = 1 else: print('Неправильный формат данных. Будет создана единичная клетка') self.numb_of_cells = 1 except(ValueError, TypeError): print('Ошибка в формате данных. Будет создана единичная клетка') self.numb_of_cells = 1 def __add__(self, other): if type(other) == Cell: sum_of_two = self.numb_of_cells + other.numb_of_cells return Cell(sum_of_two) else: print('Неправильный тип операндов. Будет создана единичная клетка') return Cell(1) def __mul__(self, other): if type(other) == Cell: multi_of_two = self.numb_of_cells * other.numb_of_cells return Cell(multi_of_two) else: print('Неправильный тип операндов. Будет создана единичная клетка') return Cell(1) def __sub__(self, other): if type(other) == Cell: sub_of_two = self.numb_of_cells - other.numb_of_cells if sub_of_two <= 0: print('Клеток в ячейке не может быть меньше нуля. Будет создана единичная клетка') return Cell(1) else: return Cell(sub_of_two) else: print('Неправильный тип операндов. Будет создана единичная клетка') return Cell(1) def __truediv__(self, other): if type(other) == Cell: div_of_two = self.numb_of_cells // other.numb_of_cells if div_of_two != 0: return Cell(div_of_two) else: print('Количество ячеек в первой клетке должно быть больше чем во второй.', end=' ') print('Будет создана единичная клетка') return Cell(1) else: return Cell(1) def make_order(self, numb_in_row): try: row_numb = float(numb_in_row) answer_str = '' if row_numb != 0: if row_numb % 1 == 0: row_numb = int(row_numb) for i in range(1, self.numb_of_cells + 1): answer_str += '*' if i % row_numb == 0: if i != self.numb_of_cells: answer_str += '\n' return answer_str else: print('Неправильный формат данных. Будет создана пустая строка') return '' else: print('Ячеек в ряду не может быть ноль. Будет создана пустая строка') return '' except(TypeError, ValueError): print('Введите целое число в качестве длины строки. Будет создана пустая строка') return '' my_cell_1 = Cell(8) my_cell_2 = Cell(5) my_cell_3 = Cell(5.3) print((my_cell_1 + my_cell_2).numb_of_cells) print((my_cell_1 - my_cell_2).numb_of_cells) print((my_cell_1 * my_cell_2).numb_of_cells) print((my_cell_1 / my_cell_2).numb_of_cells) print(my_cell_1.make_order(0)) <file_sep>/README.md # GeekBrains-HW-7 Домашние задания для изучения Python
f5a46e564db4b937989b7c82fee92b0b5bb2525d
[ "Markdown", "Python" ]
4
Python
apryab/GeekBrains-HW-7
a5a81bab03337d73e8aa9a01004a9688901b4939
6813daddf83c632db159d9a8c951000bea9b70e6
refs/heads/master
<file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/expenses.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); const Sale = require('../../models/v2/sales.model'); const Purchase = require('../../models/v2/purchases.model').Model; module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const docs = await Model.paginate( { title: { $regex: `${search}`, $options: 'i' } }, { projection: { __v: 0 }, populate: { path: 'type', select: '-__v' }, lean: true, page, limit, sort } ); res.status(200).json( _.pick(docs, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.addOne = catchAsync(async function (req, res, next) { const doc = _.pick(req.body, ['title', 'amount']); await Model.create(doc); res.status(200).json(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); module.exports.getKhaata = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const salesPromise = Sale.find( { $and: [{ isRemaining: true }, { $and: [{ customer: { $ne: null } }, { customer: { $ne: undefined } }] }] }, { __v: 0, isRemaining: 0 } ) .populate({ path: 'customer', select: '_id name' }) .lean(); const inventoriesPromise = Purchase.find({ isRemaining: true }, { __v: 0, isRemaining: 0 }) .populate({ path: 'supplier', select: '_id name' }) .lean(); const [sales, inventories] = await Promise.all([salesPromise, inventoriesPromise]); const data = [ ...sales.map((s) => ({ ...s, type: 'sale' })), ...inventories.map((i) => ({ ...i, type: 'inventory' })), ]; const totalDocs = data.length; const offset = page * limit; const docs = data.slice(0, limit); const totalPages = Math.ceil(totalDocs / limit); const hasPrevPage = page > 1; const hasNextPage = totalDocs > offset; const pagingCounter = (page - 1) * offset + 1; res.status(200).json({ docs, totalDocs, totalPages, hasPrevPage, hasNextPage, pagingCounter }); }); <file_sep>const router = require('express').Router(); const autoParams = require('../../utils/autoParams'); const { getAll, addOne, remove, edit } = require('../../controllers/v2/inventories.controller'); router.get('/', autoParams, getAll); router.route('/').post(addOne); router.patch('/', edit); router.route('/id/:id').delete(remove); module.exports = router; <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const dayjs = require('dayjs'); const Model = require('../../models/v2/inventories.model'); const Product = require('../../models/v2/products.model'); const Unit = require('../../models/v2/units.model'); const { convertUnitsOfInventory, convertUnits } = require('../../models/v2/purchases.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); const { readQuantityFromString } = require('../../utils/readUnit'); const Logger = require('../../utils/logger'); const stringify = require('../../utils/stringify'); const logger = Logger('inventories'); async function createInventories(inventories, next) { const body = inventories.map((b) => _.pick(b, ['product', 'quantity', 'variants'])); logger.debug(`createInventories() body ${stringify(body)}`); const productIds = [...new Set(body.map((b) => b.product))].map((e) => mongoose.Types.ObjectId(e)); logger.debug(`createInventories() productIds ${stringify(productIds)}`); const productsInDB = await Product.find({ _id: { $in: productIds } }, { __v: 0 }).lean(); logger.debug(`createInventories() productsInDB ${stringify(productsInDB)}`); if (productsInDB.length < productIds.length) return next(new AppError('Product(s) does not exist', 404)); const inventoriesInDB = await Model.find({ 'product._id': { $in: productIds } }).lean(); logger.debug(`createInventories() inventoriesInDB ${stringify(inventoriesInDB)}`); const promises = []; body.forEach((b, index) => { logger.debug(`createInventories() b${index} ${stringify(b)}`); b.product = productsInDB.find((e) => e._id.toString() === b.product.toString()); logger.debug(`createInventories() b.product ${stringify(b.product)}`); const inventoryInDB = inventoriesInDB.find((e) => e.product._id.toString() === b.product._id.toString()); logger.debug(`createInventories() inventoryInDB ${stringify(inventoryInDB)}`); if (inventoryInDB) { if (b.quantity) { inventoryInDB.quantity += typeof b.quantity === 'number' ? b.quantity : readQuantityFromString(b.quantity, b.product.unit.value); logger.debug(`createInventories() inventoryInDB.quantity ${stringify(inventoryInDB.quantity)}`); } else if (b.variants) { Object.entries(b.variants).forEach(([key, value], i) => { let q = inventoryInDB.variants[key] ?? 0; logger.debug(`createInventories() key-value-q-${i} ${stringify({ key, value, q })}`); q += typeof value === 'number' ? value : readQuantityFromString(value, b.product.unit.value); inventoryInDB.variants[key] = q; }); } else return next(new AppError('Something went wrong', 400)); promises.push(Model.findByIdAndUpdate(inventoryInDB._id, inventoryInDB)); } else if (!inventoryInDB) { const newInventory = { product: b.product }; if (b.quantity) { newInventory.quantity = typeof b.quantity === 'number' ? b.quantity : readQuantityFromString(b.quantity, b.product.unit.value); } else if (b.variants) { const variants = {}; Object.entries(b.variants).forEach(([key, value]) => { variants[key] = typeof value === 'number' ? value : readQuantityFromString(value, b.product.unit.value); }); newInventory.variants = variants; } else return next(new AppError('Something went wrong', 400)); promises.push(Model.create(newInventory)); } }); await Promise.all(promises); } async function consumeInventories(inventories, next) { const body = inventories.map((b) => _.pick(b, ['product', 'quantity', 'variants'])); logger.debug(`consumeInventories() body ${stringify(body)}`); const productIds = [...new Set(body.map((b) => b.product))].map((e) => mongoose.Types.ObjectId(e)); logger.debug(`consumeInventories() productIds ${stringify(productIds)}`); const productsInDB = await Product.find({ _id: { $in: productIds } }, { __v: 0 }).lean(); logger.debug(`consumeInventories() productsInDB ${stringify(productsInDB)}`); if (productsInDB.length < productIds.length) return next(new AppError('Product(s) does not exist', 404)); const inventoriesInDB = await Model.find({ 'product._id': { $in: productIds } }).lean(); logger.debug(`consumeInventories() inventoriesInDB ${stringify(inventoriesInDB)}`); const promises = []; body.forEach((b, index) => { logger.debug(`consumeInventories() b${index} ${stringify(b)}`); b.product = productsInDB.find((e) => e._id.toString() === b.product.toString()); logger.debug(`consumeInventories() b.product ${stringify(b.product)}`); const inventory = inventoriesInDB.find((e) => e.product._id.toString() === b.product._id.toString()); logger.debug(`consumeInventories() inventory ${stringify(inventory)}`); if (!inventory) return next(new AppError('Product not in stock', 404)); const { type, unit } = inventory.product; if (type.title.toLowerCase() === 'tile') { const inventoryVariants = { ...inventory.variants }; Object.entries(b.variants).forEach(([key, value]) => { const quantity = typeof value === 'number' ? value : readQuantityFromString(value, unit.value); logger.debug(`consumeInventories() key-value-quantity ${stringify({ key, value, quantity })}`); const inventoryQuantity = inventory.variants[key] - quantity; logger.debug( `consumeInventories() key-value-inventoryQuantity ${stringify({ key, value, inventoryQuantity })}` ); if (inventoryQuantity < 0) return next(new AppError('Insufficient inventory', 404)); inventoryVariants[key] = inventoryQuantity; }); Object.entries(inventoryVariants).forEach(([key, value]) => { if (value === 0) delete inventoryVariants[key]; }); promises.push(Model.findByIdAndUpdate(inventory._id, { variants: inventoryVariants })); } else { const quantity = typeof b.value === 'number' ? b.value : readQuantityFromString(b.quantity, unit.value); inventory.quantity -= quantity; if (inventory.quantity === 0) promises.push(Model.findByIdAndDelete(inventory._id)); else if (inventory.quantity < 0) return next(new AppError('Insufficient inventory', 404)); else promises.push(Model.findByIdAndUpdate(inventory._id, { quantity: inventory.quantity })); } }); await Promise.all(promises); } module.exports.createInventories = createInventories; module.exports.consumeInventories = consumeInventories; module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const results = await Model.paginate( { 'product.modelNumber': { $regex: `${search}`, $options: 'i' }, }, { projection: { __v: 0 }, lean: true, page, limit, sort } ); // eslint-disable-next-line no-param-reassign results.docs.forEach((d) => { const unit = d.product.unit.value; if (d.quantity !== undefined && d.quantity !== null) d.quantity = convertUnits(d.quantity, unit); else if (d.variants) { Object.entries(d.variants).forEach(([key, value]) => { d.variants[key] = convertUnits(value, unit); }); } }); res.status(200).json( _.pick(results, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.addOne = catchAsync(async function (req, res, next) { const inventories = req.body; await createInventories(inventories, next); res.status(200).json(); }); module.exports.edit = catchAsync(async function (req, res, next) { const inventories = req.body; logger.debug(`edit() inventories ${stringify(inventories)}`); const deleted = await Model.findOneAndDelete({ 'product._id': mongoose.Types.ObjectId(inventories[0].product) }); logger.debug(`edit() deleted ${stringify(deleted)}`); await createInventories(inventories, next); res.status(200).json(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const mongoose = require('mongoose'); const mongoosePagiante = require('mongoose-paginate-v2'); const schema = new mongoose.Schema({ name: { type: String, required: [true, 'Please enter a name'], }, phone: String, // createdBy: { type: mongoose.ObjectId, ref: 'User', select: false }, createdAt: { type: Date, required: true, default: Date.now() }, }); schema.plugin(mongoosePagiante); const Model = mongoose.model('Customer', schema); module.exports = Model; <file_sep>const { promisify } = require('util'); const _ = require('lodash'); const mongoose = require('mongoose'); const jwt = require('jsonwebtoken'); const { signToken } = require('../utils/jwt'); const User = require('../models/users.model'); const { catchAsync } = require('./errors.controller'); const AppError = require('../utils/AppError'); module.exports.getUsers = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const results = await User.paginate( { name: { $regex: `${search}`, $options: 'i' } }, { projection: { __v: 0, password: 0 }, lean: true, page, limit, sort: { isConfirmed: 1 } } ); res.status(200).json( _.pick(results, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.registerUser = catchAsync(async function (req, res, next) { const newUser = _.pick(req.body, ['name', 'password', '<PASSWORD>']); if (!Object.keys(newUser).length) return next(new AppError('Please enter a valid user', 400)); const createdUser = await User.create(newUser); const token = signToken(createdUser._id); const filteredUser = _.pick(createdUser, ['_id', 'name', 'role']); res.status(200).json({ ...filteredUser, token }); }); module.exports.loginUser = catchAsync(async function (req, res, next) { const body = _.pick(req.body, ['name', 'password']); if (Object.keys(body).length < 2) return next(new AppError('Please enter email and password', 400)); const user = await User.findOne({ name: body.name }); if (!user) return next(new AppError('Invalid username or password', 401)); const isValidPassword = await user.isValidPassword(body.password, user.password); if (!isValidPassword) return next(new AppError('Invalid username or password', 401)); if (!user.isConfirmed) return next(new AppError('Your access is pending', 403)); const token = signToken(user._id); res.status(200).json(token); }); module.exports.protect = catchAsync(async function (req, res, next) { let token; if (req.headers.authorization) { if (req.headers.authorization === 'dev') return next(); if (req.headers.authorization.startsWith('Bearer ')) // eslint-disable-next-line prefer-destructuring token = req.headers.authorization.split(' ')[1]; } if (!token) return next(new AppError('Please login to get access', 401)); const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); const freshUser = await User.findById(decoded.id); if (!freshUser) return next(new AppError('Please login again', 401)); const hasChangedPassword = freshUser.changedPasswordAfter(decoded.iat); if (hasChangedPassword) return next(new AppError('Please login again', 401)); const { isConfirmed } = freshUser; if (!isConfirmed) return next(new AppError('Your access is pending', 403)); res.locals.user = freshUser; next(); }); module.exports.allowAccess = (...roles) => async function (req, res, next) { if (!roles.includes(req.user.role)) return next(new AppError('Unauthorized access to this route', 403)); next(); }; module.exports.confirmUser = catchAsync(async function (req, res, next) { const { id: userId, role } = req.params; if (!mongoose.isValidObjectId(userId)) return next(new AppError('Please enter a valid id', 400)); const user = await User.findById(userId); if (!user) return next(new AppError('User does not exist', 404)); await user.updateOne({ isConfirmed: true, role: role.toUpperCase() }); res.status(200).json(_.pick(user, ['_id', 'name', 'role', 'createdAt'])); }); module.exports.editUser = catchAsync(async function (req, res, next) { const { id: userId } = req.params; if (res.locals.user._id.toString() !== userId) return next(new AppError('You are not authorized to edit user', 403)); const newUser = _.pick(req.body, ['name', 'password', 'passwordConfirm']); if (!Object.keys(newUser).length) return next(new AppError('Please enter a valid user', 400)); if (!mongoose.isValidObjectId(userId)) return next(new AppError('Please enter a valid id', 400)); const user = await User.findById(userId); if (!user) return next(new AppError('User does not exist', 404)); if (newUser.password) user.password = <PASSWORD>; if (newUser.name) user.name = newUser.name; if (newUser.passwordConfirm) user.passwordConfirm = <PASSWORD>; await user.save(); res.status(200).json(); }); module.exports.authorizeUser = catchAsync(async function (req, res, next) { const { id: userId, role } = req.params; if (!mongoose.isValidObjectId(userId)) return next(new AppError('Please enter a valid id', 400)); const user = await User.findById(userId); if (!user) return next(new AppError('User does not exist', 404)); await user.update({ role: role.toUpperCase() }, { runValidators: true }); res.status(200).json(); }); module.exports.decodeToken = catchAsync(async function (req, res, next) { const { token } = req.params; const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); const user = await User.findById(decoded.id, { __v: 0, password: 0 }).lean(); res.status(200).json(user); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await User.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../models/employees.model'); const { catchAsync } = require('./errors.controller'); const AppError = require('../utils/AppError'); const { getSalaries } = require('./v2/expenses.controller'); module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const results = await Model.paginate( { $or: [{ name: { $regex: `${search}`, $options: 'i' } }], }, { projection: { __v: 0 }, populate: 'employee', lean: true, page, limit, sort } ); res.status(200).json( _.pick(results, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.getOne = catchAsync(async function (req, res, next) { const { id } = req.params; const { page, limit, sort } = req.query; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const employee = await Model.findById(id, { __v: 0 }).lean(); if (!employee) return next(new AppError('Employee does not exist', 404)); const salaries = await getSalaries({ query: { 'employee._id': id }, page, limit, sort, next }); res.status(200).json({ employee, salaries: _.omit(salaries, ['page', 'prevPage', 'nextPage', 'limit']), }); }); module.exports.addMany = catchAsync(async function (req, res, next) { const docs = req.body; if (!docs || !docs.length) return next(new AppError('Please enter valid employees', 400)); await Model.insertMany(docs); res.status(200).json(); }); module.exports.addOne = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['name', 'phone', 'cnic', 'address', 'salary']); await Model.create(newDoc); res.status(200).send(); }); module.exports.edit = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['name', 'phone', 'cnic', 'address', 'salary']); const employeeId = req.params.id; if (!mongoose.isValidObjectId(employeeId)) return next(new AppError('Invalid employee id', 400)); const employee = await Model.findById(employeeId); if (!employee) return next(new AppError('Employee does not exist')); employee.name = newDoc.name; employee.phone = newDoc.phone; employee.cnic = newDoc.cnic; employee.address = newDoc.address; employee.salary = newDoc.salary; await employee.save(); res.status(200).send(); }); module.exports.edit = catchAsync(async function (req, res, next) { const { id } = req.params; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const newDoc = _.pick(req.body, ['name', 'phone', 'cnic', 'address', 'salary']); if (!Object.keys(newDoc).length) return next(new AppError('Please enter a valid employee', 400)); await Model.updateOne({ _id: id }, newDoc, { runValidators: true }); res.status(200).json(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/salaries.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); const Employee = require('../../models/employees.model'); module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit } = req.query; const docs = await Model.paginate( {}, { projection: { __v: 0 }, page, limit, } ); res.status(200).json(_.omit(docs, ['nextPage', 'prevPage', 'page', 'limit', 'offset'])); }); module.exports.addOne = catchAsync(async function (req, res, next) { const body = _.pick(req.body, ['employee', 'amount']); if (!mongoose.isValidObjectId(body.employee)) return next(new AppError('Invalid employee id', 400)); const employee = await Employee.findById(body.employee); if (!employee) return next(new AppError('Employee does not exist', 404)); body.employee = employee; await Model.create(body); res.status(200).send(); }); module.exports.edit = catchAsync(async function (req, res, next) { const body = _.pick(req.body, ['employee', 'amount']); const salaryId = req.params.id; if (!mongoose.isValidObjectId(salaryId)) return next(new AppError('Invalid salary id', 400)); const salary = Model.findById(salaryId); if (!salary) return next(new AppError('Salary does not exist', 404)); if (!mongoose.isValidObjectId(body.employee)) return next(new AppError('Invalid employee id', 400)); const employee = await Employee.findById(body.employee); if (!employee) return next(new AppError('Employee does not exist', 404)); body.employee = employee; salary.employee = body.employee; salary.amount = body.amount; await salary.save(); res.status(200).send(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const router = require('express').Router(); const { getAll, addOne, remove, getCount, refund, pay, getOne, edit, } = require('../../controllers/v2/sales.controller'); const autoParams = require('../../utils/autoParams'); router.get('/count', getCount); router.get('/id/:id', getOne); router.get('/', autoParams, getAll); router.route('/').post(addOne); router.patch('/id/:id', edit); router.route('/pay/id/:id/amount/:amount').post(pay); router.route('/id/:id').delete(remove); module.exports = router; <file_sep>const mongoose = require('mongoose'); const mongoosePagiante = require('mongoose-paginate-v2'); const schema = new mongoose.Schema({ modelNumber: { type: String, required: [true, 'Please enter a model number'], }, type: { type: mongoose.SchemaTypes.Mixed, required: [true, 'Type is required'], }, unit: { type: mongoose.SchemaTypes.Mixed, required: [true, 'Unit is required'] }, variants: {}, // createdBy: { type: mongoose.ObjectId, ref: 'User', select: false }, createdAt: { type: Date, required: true, default: Date.now() }, }); schema.plugin(mongoosePagiante); const Model = mongoose.model('Product', schema); module.exports = Model; <file_sep>## Diamond Tiles POS Backend ###### Developed and Maintained by [<NAME>](http://github.com/muneeebnaveeed) Backend application for serving data from MongoDB database to React frontend (built in NodeJS) #### Initializing - Install project dependencies. To install the project dependencies: `$ npm install` - Add two environment files named `.development.env` and `.production.env` and add the following block of code to run the project as intended: ```ruby DB_CONNECTION_STRING=mongodb://127.0.0.1:27017 PORT=5100 JWT_SECRET=secret JWT_EXPIRES_IN=30d ``` - Run the application in development mode using: `$ npm run dev` - Run the application using: `$ npm start` <file_sep>const express = require('express'); const path = require('path'); const dotenv = require('dotenv'); const cors = require('cors'); const chalk = require('chalk'); const Database = require('./utils/db'); const AppError = require('./utils/AppError'); const tilesRoute = require('./routes/v2/products.route'); const customersRoute = require('./routes/v2/customers.route'); const employeesRoute = require('./routes/employees.route'); const suppliersRoute = require('./routes/v2/suppliers.route'); const typesRoute = require('./routes/v2/types.route'); const unitsRoute = require('./routes/v2/units.route'); const inventoriesRoute = require('./routes/v2/inventories.route'); const purchasesRoute = require('./routes/v2/purchases.route'); const salesRoute = require('./routes/v2/sales.route'); const expensesRoute = require('./routes/v2/expenses.route'); const salariesRoute = require('./routes/v2/salaries.route'); const dashboardRoute = require('./routes/dashboard.route'); const authRoute = require('./routes/auth.route'); const { errorController } = require('./controllers/errors.controller'); const { protect } = require('./controllers/auth.controller'); const Logger = require('./utils/logger'); const app = express(); dotenv.config({ path: path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`) }); const port = process.env.PORT || 5500; const logger = Logger('app'); app.listen(port, () => { logger.info(`Server running on PORT ${chalk.green(port)}`); new Database() .connect() .then(() => logger.info('Connected to DB')) .catch((err) => logger.error('Unable to connect to DB', err)); app.use(express.json()); app.use(cors()); app.get('/', (req, res) => { res.status(200).send(`Server running at PORT ${port}`); }); app.use('/products', protect, tilesRoute); app.use('/customers', protect, customersRoute); app.use('/employees', protect, employeesRoute); app.use('/salaries', protect, salariesRoute); app.use('/suppliers', protect, suppliersRoute); app.use('/types', protect, typesRoute); app.use('/units', protect, unitsRoute); app.use('/inventories', protect, inventoriesRoute); app.use('/purchases', protect, purchasesRoute); app.use('/sales', protect, salesRoute); app.use('/expenses', protect, expensesRoute); app.use('/dashboard', protect, dashboardRoute); app.use('/auth', authRoute); app.use('*', (req, res, next) => next(new AppError(`Cannot find ${req.originalUrl} on the server!`, 404))); app.use(errorController); }); <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/units.model'); const Type = require('../../models/v2/types.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); module.exports.getAll = catchAsync(async function (req, res, next) { const { type } = req.query; let query = {}; if (type) { if (!mongoose.isValidObjectId(type)) return next(new AppError('Invalid Type ID', 400)); query = { 'type._id': type }; } const docs = await Model.find(query, { __v: 0 }).lean(); res.status(200).json(docs); }); module.exports.addOne = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['title', 'value', 'type']); if (Object.keys(newDoc).length !== 3) return next(new AppError('Please enter a valid unit', 400)); const type = await Type.findById(newDoc.type, { __v: 0 }).lean(); if (!type) return next(new AppError('Type does not exist', 404)); newDoc.type = type; await Model.create(newDoc); res.status(200).send(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const stringify = (json) => JSON.stringify(json, null, 2); module.exports = stringify; <file_sep>const mongoose = require('mongoose'); const mongoosePagiante = require('mongoose-paginate-v2'); const schema = new mongoose.Schema({ name: { type: String, required: [true, 'Please enter a name'], }, phone: String, cnic: String, address: String, salary: { type: String, required: [true, 'Please enter salary'], }, // createdBy: { type: mongoose.ObjectId, ref: 'User', select: false }, createdAt: { type: Date, required: true, default: Date.now() }, }); schema.index({ name: 'text', phone: 'text' }); schema.plugin(mongoosePagiante); const Model = mongoose.model('Employee', schema); module.exports = Model; <file_sep>const router = require('express').Router(); const autoParams = require('../../utils/autoParams'); const { getAll, addOne, remove, getCount, getOne, edit } = require('../../controllers/v2/purchases.controller'); router.get('/count', getCount); router.get('/', autoParams, getAll); router.get('/id/:id', getOne); router.patch('/id/:id', edit); router.route('/').post(addOne); router.route('/id/:id').delete(remove); module.exports = router; <file_sep>const router = require('express').Router(); const autoParams = require('../utils/autoParams'); const { getAll, addOne, edit, remove, getOne } = require('../controllers/employees.controller'); router.get('/', autoParams, getAll); router.get('/id/:id', autoParams, getOne); router.route('/').post(addOne); router.get('/id/:id', edit); router.route('/id/:id').patch(edit); router.route('/id/:id').delete(remove); module.exports = router; <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/suppliers.model'); const Purchase = require('../../models/v2/purchases.model').Model; const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); const { convertUnitsOfInventory } = require('../../models/v2/purchases.model'); module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const results = await Model.paginate( { $or: [ { name: { $regex: `${search}`, $options: 'i' } }, { phone: { $regex: `${search}`, $options: 'i' } }, { company: { $regex: `${search}`, $options: 'i' } }, ], }, { projection: { __v: 0 }, lean: true, page, limit, sort } ); res.status(200).json( _.pick(results, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.getOne = catchAsync(async function (req, res, next) { const { id } = req.params; const { page, limit, sort } = req.query; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const supplier = await Model.findById(id, { __v: 0 }).lean(); if (!supplier) return next(new AppError('Supplier does not exist', 404)); // const product = await Product.findById(inventory.product._id, { __v: 0, inventory: 0 }).lean(); const inventories = await Purchase.paginate( { supplier: id }, { projection: { __v: 0, inventory: 0 }, populate: { path: 'supplier', select: { __v: 0 } }, lean: true, page: page, limit: limit, sort: sort, } ); // eslint-disable-next-line no-param-reassign inventories.docs.forEach((d) => (d = convertUnitsOfInventory(d))); res.status(200).json({ supplier, inventories: _.omit(inventories, ['page', 'prevPage', 'nextPage', 'limit']), }); }); module.exports.addOne = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['name', 'phone', 'company']); await Model.create(newDoc); res.status(200).send(); }); module.exports.edit = catchAsync(async function (req, res, next) { const { id } = req.params; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const newDoc = _.pick(req.body, ['name', 'phone', 'company']); if (!Object.keys(newDoc).length) return next(new AppError('Please enter a valid supplier', 400)); await Model.findByIdAndUpdate(id, newDoc, { runValidators: true }); res.status(200).json(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/customers.model'); const Sale = require('../../models/v2/sales.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const results = await Model.paginate( { $or: [{ name: { $regex: `${search}`, $options: 'i' } }, { phone: { $regex: `${search}`, $options: 'i' } }], }, { projection: { __v: 0 }, lean: true, page, limit, sort } ); res.status(200).json( _.pick(results, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.getOne = catchAsync(async function (req, res, next) { const { id } = req.params; const { page, limit, sort } = req.query; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const customer = await Model.findById(id, { __v: 0 }).lean(); if (!customer) return next(new AppError('Customer does not exist', 404)); const sales = await Sale.paginate( { customer: mongoose.Types.ObjectId(id) }, { populate: { path: 'customer', select: '-__v' }, projection: { __v: 0 }, lean: true, page, limit, sort, } ); res.status(200).json({ customer, sales: _.omit(sales, ['page', 'prevPage', 'nextPage', 'limit']), }); }); module.exports.addOne = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['name', 'phone']); await Model.create(newDoc); res.status(200).send(); }); module.exports.edit = catchAsync(async function (req, res, next) { const { id } = req.params; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const newDoc = _.pick(req.body, ['name', 'phone']); if (!Object.keys(newDoc).length) return next(new AppError('Please enter a valid customer', 400)); await Model.updateOne({ _id: id }, newDoc, { runValidators: true }); res.status(200).json(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const router = require('express').Router(); const { getAll, addOne, remove } = require('../../controllers/v2/units.controller'); router.route('/').get(getAll); router.route('/').post(addOne); router.route('/id/:id').delete(remove); module.exports = router; <file_sep>const router = require('express').Router(); const { getUsers, loginUser, registerUser, confirmUser, editUser, protect, decodeToken, remove, } = require('../controllers/auth.controller'); router.route('/').get(getUsers); router.get('/decode/:token', decodeToken); router.route('/confirm/:id/:role').put(confirmUser); // router.put('/:id', protect, editUser); router.route('/register').post(registerUser); router.route('/login').post(loginUser); router.route('/id/:id').delete(remove); module.exports = router; <file_sep>const mongoose = require('mongoose'); const Logger = require('./logger'); const logger = Logger('app'); module.exports = class Database { constructor() { logger.debug('Created instance of DB'); this.connectionString = process.env.DB_CONNECTION_STRING; // this.authString = this.getAuthString(process.env.DB_PASSWORD); this.authString = process.env.DB_CONNECTION_STRING; } getAuthString(password) { return this.connectionString.replace('<password>', password); } connect() { logger.debug('Connecting to DB...'); return mongoose.connect(this.authString, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true, }); } }; <file_sep>const mongoose = require('mongoose'); const mongoosePagiante = require('mongoose-paginate-v2'); const schema = new mongoose.Schema({ customer: { type: mongoose.Types.ObjectId, ref: 'Customer' }, products: { type: mongoose.SchemaTypes.Mixed, required: [true, 'Please enter products'] }, paid: { type: Number, required: [true, 'Please enter paid price'], }, isRemaining: Boolean, totalRetailPrice: Number, // createdBy: { type: mongoose.ObjectId, ref: 'User', select: false }, createdAt: { type: Date, required: true, default: Date.now() }, }); schema.plugin(mongoosePagiante); const Model = mongoose.model('Sale', schema); module.exports = Model; <file_sep>const mongoose = require('mongoose'); const mongoosePagiante = require('mongoose-paginate-v2'); const schema = new mongoose.Schema({ title: { type: String, required: [true, 'Please enter a name'], }, value: { type: Number, required: [true, 'Please enter a value'], min: [1, 'Please enter a valid value'], }, type: { type: mongoose.model('Type').schema, required: [true, 'Type is required'], }, // createdBy: { type: mongoose.ObjectId, ref: 'User', select: false }, createdAt: { type: Date, required: true, default: Date.now() }, }); schema.plugin(mongoosePagiante); const Model = mongoose.model('Unit', schema); module.exports = Model; <file_sep>const router = require('express').Router(); const autoParams = require('../utils/autoParams'); const { getPurchases, getSales, getRevenue, getProfit, getExpenses } = require('../controllers/dashboard.controller'); router.get('/purchases', autoParams, getPurchases); router.get('/sales', autoParams, getSales); router.get('/revenue', autoParams, getRevenue); router.get('/expenses', autoParams, getExpenses); router.get('/profit', autoParams, getProfit); module.exports = router; <file_sep>const _ = require('lodash'); const Purchase = require('../models/v2/purchases.model').Model; const Sale = require('../models/v2/sales.model'); const Expense = require('../models/v2/expenses.model'); const Salary = require('../models/v2/salaries.model'); const { catchAsync } = require('./errors.controller'); module.exports.getPurchases = catchAsync(async function (req, res, next) { const { startDate, endDate } = req.query; console.log(await Purchase.find(), startDate, endDate); const results = await Purchase.find({ createdAt: { $gte: startDate, $lte: endDate } }).lean(); const prices = results.map((item) => item.totalSourcePrice); let sum = 0; if (prices.length > 1) sum = prices.reduce((prev, curr) => prev + curr, 0); else if (prices.length === 1) sum = prices[0]; res.status(200).send({ sum, count: results.length, }); }); module.exports.getSales = catchAsync(async function (req, res, next) { const { startDate, endDate } = req.query; const results = await Sale.find({ createdAt: { $gte: startDate, $lte: endDate } }).lean(); const prices = results.map((item) => item.totalRetailPrice); let sum = 0; if (prices.length > 1) sum = prices.reduce((prev, curr) => prev + curr, 0); else if (prices.length === 1) sum = prices[0]; res.status(200).send({ sum, count: results.length, }); }); async function getRevenue(startDate, endDate) { const sales = await Sale.find({ createdAt: { $gte: startDate, $lte: endDate } }).lean(); const retailPrices = sales.map((item) => item.totalRetailPrice); const sourcePrices = []; sales.forEach((sale) => sale.products.forEach((product) => sourcePrices.push(product.sourcePrice))); let retailPrice = 0; if (retailPrices.length) { retailPrice = retailPrices.length > 1 ? retailPrices.reduce((prev, curr) => prev + curr, 0) : retailPrices[0]; } let sourcePrice = 0; if (sourcePrices.length) { sourcePrice = sourcePrices.length > 1 ? sourcePrices.reduce((prev, curr) => prev + curr, 0) : sourcePrices[0]; } return retailPrice - sourcePrice; } module.exports.getRevenue = catchAsync(async function (req, res, next) { const { startDate, endDate } = req.query; const revenue = await getRevenue(startDate, endDate); res.status(200).json(revenue); }); async function getExpenses(startDate, endDate) { const [expenses, salaries] = await Promise.all([ Expense.find({ createdAt: { $gte: startDate, $lte: endDate } }).lean(), Salary.find({ createdAt: { $gte: startDate, $lte: endDate } }).lean(), ]); const totalExpenses = expenses.map((item) => item.amount).reduce((prev, curr) => prev + curr, 0); const totalSalaries = salaries.map((item) => item.amount).reduce((prev, curr) => prev + curr, 0); return totalExpenses + totalSalaries; } module.exports.getProfit = catchAsync(async function (req, res, next) { // Revenue - Expenses const { startDate, endDate } = req.query; const revenue = await getRevenue(startDate, endDate); const expenses = await getExpenses(startDate, endDate); res.status(200).json({ profit: revenue - expenses }); }); module.exports.getExpenses = catchAsync(async function (req, res, next) { const { startDate, endDate } = req.query; const amount = await getExpenses(startDate, endDate); res.status(200).json(amount); }); <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/types.model'); const Product = require('../../models/v2/products.model'); const Unit = require('../../models/v2/units.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); module.exports.getAll = catchAsync(async function (req, res, next) { const docs = await Model.find({}, { __v: 0 }); res.status(200).json(docs); }); module.exports.addOne = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['title']); await Model.create(newDoc); res.status(200).send(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); }); <file_sep>const mongoose = require('mongoose'); const _ = require('lodash'); const Model = require('../../models/v2/products.model'); const Purchase = require('../../models/v2/purchases.model').Model; const Sale = require('../../models/v2/sales.model'); const Type = require('../../models/v2/types.model'); const { catchAsync } = require('../errors.controller'); const AppError = require('../../utils/AppError'); const Unit = require('../../models/v2/units.model'); module.exports.getAll = catchAsync(async function (req, res, next) { const { page, limit, sort, search } = req.query; const results = await Model.paginate( { $or: [{ modelNumber: { $regex: `${search}`, $options: 'i' } }], }, { projection: { __v: 0 }, lean: true, page, limit, sort, } ); res.status(200).json( _.pick(results, ['docs', 'totalDocs', 'hasPrevPage', 'hasNextPage', 'totalPages', 'pagingCounter']) ); }); module.exports.getOne = catchAsync(async function (req, res, next) { const { id } = req.params; const { inventoriesPage, inventoriesLimit, inventoriesSort, salesPage, salesLimit, salesSort } = req.query; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const product = await Model.findById(id, { __v: 0 }).lean(); if (!product) return next(new AppError('Product does not exist', 404)); const inventories = await Purchase.paginate( { 'product._id': mongoose.Types.ObjectId(id) }, { populate: { path: 'supplier', select: '-__v' }, projection: { __v: 0 }, lean: true, page: inventoriesPage, limit: inventoriesLimit, sort: inventoriesSort, } ); let relevantInventoryIds = []; inventories.docs.forEach((i) => { if (i.product && i.product._id) relevantInventoryIds.push(i.product._id.toString()); }); relevantInventoryIds = [...new Set(relevantInventoryIds)].map((inventoryId) => mongoose.Types.ObjectId(inventoryId) ); const sales = Sale.paginate( { 'inventory._id': { $in: relevantInventoryIds } }, { populate: { path: 'customer', select: '-__v' }, projection: { __v: 0 }, lean: true, page: salesPage, limit: salesLimit, sort: salesSort, } ); res.status(200).json({ product, inventories: _.omit(inventories, ['page', 'prevPage', 'nextPage', 'limit']), sales: _.omit(sales, ['page', 'prevPage', 'nextPage', 'limit']), }); }); module.exports.addOne = catchAsync(async function (req, res, next) { const newDoc = _.pick(req.body, ['modelNumber', 'type', 'unit']); if (Object.keys(newDoc).length < 3) return next(new AppError('Please enter a valid product', 400)); const [type, unit] = await Promise.all([ Type.findById(newDoc.type, { __v: 0 }).lean(), Unit.findById(newDoc.unit, { __v: 0 }).lean(), ]); if (!type) return next(new AppError('Type does not exist', 404)); if (!unit) return next(new AppError('Unit does not exist', 404)); if (unit.type.title !== type.title) return next(new AppError('Unit not compatible', 400)); newDoc.type = type; newDoc.unit = _.omit(unit, ['type']); await Model.create(newDoc); res.status(200).send(); }); module.exports.edit = catchAsync(async function (req, res, next) { const { id } = req.params; if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter a valid id', 400)); const newDoc = _.pick(req.body, ['modelNumber', 'type', 'retailPrice']); if (!Object.keys(newDoc).length) return next(new AppError('Please enter a valid product', 400)); const [type, unit] = await Promise.all([Type.findById(newDoc.type).lean(), Unit.findById(newDoc.unit)].lean()); if (!type) return next('Type or unit does not exist', 404); if (!unit) return next('Unit or unit does not exist', 404); newDoc.type = type; newDoc.unit = unit; await Model.findByIdAndUpdate(id, newDoc, { runValidators: true }); res.status(200).json(); }); module.exports.remove = catchAsync(async function (req, res, next) { let ids = req.params.id.split(','); for (const id of ids) { if (!mongoose.isValidObjectId(id)) return next(new AppError('Please enter valid id(s)', 400)); } ids = ids.map((id) => mongoose.Types.ObjectId(id)); await Model.deleteMany({ _id: { $in: ids } }); res.status(200).json(); });
5ab011bb06ec8c61dd8a26f3fb4b9ff514449acf
[ "JavaScript", "Markdown" ]
27
JavaScript
muneeebnaveeed/diamond-tiles-backend-v2
ca9a1fc46844dad77dba626111c97132195c8ba9
55645d10c9750784da12a8946add34771d106eea
refs/heads/master
<file_sep>#Count NUMBER OF SUBSET WITH GIVEN DIFFERENCE arr=[3, 1, 4, 1, 5] d=2 s= (d+sum(arr))//2 n=len(arr) k=[[0 for i in range (s+1)] for j in range(n+1)] for i in range(n+1): k[i][0]=1 for i in range(1,s+1): k[0][i]=0 for i in range(1,n+1): for j in range(1,s+1): if arr[i-1]> j: k[i][j]= k[i-1][j] else: k[i][j]= k[i-1][j-arr[i-1]] + k[i-1][j] print("Given Array {}\nNumber of Subset with given difference {} is {}".format(arr,d,k[n][s])) '''Here we have to find S2-S1 equal to given difference So eq [1]-> s2-s1= difference eq [2]-> s2+s1 = Total SUM =>eq[1] + eq[2] 2s2= difference + Total SUM s2 = (difference + Total SUM)/ 2 Hence s2 can be found i.e the required SUM'''<file_sep># -*- coding: utf-8 -*- """ Created on Fri Jun 12 21:04:30 2020 @author: MrMaak """ #12321 to check for palindrome to number #best way is to convert it to string and then check it by #reversing. def palin(num): snum=str(num) rnum=snum[::-1] return rnum==snum # if conversion to string is not allowed then: # using while loop [O[n]] def palindrome(num): n=num rev=0 while num>0: d = num % 10 rev = rev * 10 + d num = num // 10 return rev==n # using Recursion def recursion(num, rev=0): if num==0: return rev return recursion(num//10, rev*10+num%10 ) n=121 print("True" if recursion(n)==n else "False") <file_sep>s="hello sam i am your senior" cs=[i for i in s.split() if i[0]=='s'] print(cs) <file_sep># -*- coding: utf-8 -*- """ Created on Tue Jun 16 16:23:48 2020 @author: MrMaak """ # STRING COMPRESSION # Given an array of characters, compress it in-place. # The length after compression must always be smaller than or equal to the original array. # Every element of the array should be a character (not int) of length 1. # After you are done modifying the input array in-place, return the new length of the array. # Follow up: # Could you solve it using only O(1) extra space? # Example 1: # Input: # ["a","a","b","b","c","c","c"] # Output: # Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] # Explanation: # "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". # Example 2: # Input: # ["a"] # Output: # Return 1, and the first 1 characters of the input array should be: ["a"] # Explanation: # Nothing is replaced. # Example 3: # Input: # ["a","b","b","b","b","b","b","b","b","b","b","b","b"] # Output: # Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. # Explanation: # Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". # Notice each digit has it's own entry in the array. def compression(arr): if arr == None or len(arr) < 1: return 0; start, end, index = 0,0,0 while start < len(arr): end=start while end < len(arr) and arr[start]==arr[end]: end+=1 arr[index]=arr[start] index+=1 if end-start>1: for s in str(end-start): arr[index]=s index+=1 start=end return index arr=["a","a","b","b","c","c","c","c","c","c","c","c","c","c","c","c"] print(compression(arr)) <file_sep>/*Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better understanding, please follow the numbers of the next array consecutively: array = [[1,2,3], [8,9,4], [7,6,5]] snail(array) #=> [1,2,3,4,5,6,7,8,9] This image will illustrate things more clearly: NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern. NOTE 2: The 0x0 (empty matrix) is represented as [[]] ------------------------------------ CODE#*/ import java.util.Arrays; public class Snail { public static int[] snail(int[][] array) { if(array[0].length <= 0) return new int[0]; if(array[0].length == 1) { int[] j=new int[1]; j[0]=array[0][0];return j;} else{ int m=array[0].length,k=0,l=0,n=array[1].length,j=0; String s=""; while(k<m&&l<n) { for(int i=k;i<m;i++) s=s+" "+array[k][i]; k++; for(int i=k;i<n;i++) s=s+" "+(array[i][n-1]); n--; if(k<m) { for(int i=n-1;i>=l;--i) s=s+" "+(array[m-1][i]); m--; } if(l<n) { for(int i=m-1;i>=k;--i) s=s+" "+(array[i][l]); l++; } } s=s.trim(); String[] stra=s.split(" "); int[] arra = Arrays.asList(stra).stream().mapToInt(Integer::parseInt).toArray(); return arra; } } } <file_sep>''' DYNAMIC PROGRAMMING --[COIN CHANGE]-min number of coin required to give the change amount''' def coinchange(coins,amount): coins.sort() dp=[amount+1]*(amount+1) dp[0]=0 for i in range(0,amount+1): for j in coins: if j<=i: dp[i]=min(dp[i],1+dp[i-j]) return dp[amount] if dp[amount]<amount else -1 print(coinchange([1,2,5],46))<file_sep>def isPowerOfFour(n: int) -> bool: if n==1: return True if n>0 and n%4==0: n//=4 return isPowerOfFour(n) print(isPowerOfFour(36)==True)<file_sep>''' TARGET SUM --> https://leetcode.com/problems/target-sum/ You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3.''' nums=[1,0] S=1 def kaa(nums, S): c=0 for i in nums: if i==0: c+=1 if S > sum(nums): return 0; if (S+sum(nums))%2!=0 : return 0; s= (S+sum(nums))//2 n=len(nums) k=[[0 for i in range (s+1)] for j in range(n+1)] for i in range(n+1): k[i][0]=1 for i in range(1,s+1): k[0][i]=0 for i in range(1,n+1): for j in range(1,s+1): if nums[i-1]==0: k[i][j] = k[i-1][j]; elif nums[i-1]> j: k[i][j]= k[i-1][j] else: k[i][j]= k[i-1][j-nums[i-1]] + k[i-1][j] return 2**c * k[n][s]; print("Given Array {}\nNumber of Subset with -/+ given TOTAL SUM {} is {}".format(nums, S, kaa(nums, S))) '''Basically we have to find 2 subset one for + and another for negative so it is a Count number of subset with given difference problem. Let us assume S as d and +ve_subset as s2 and -ve_subset as s1 Here we have to find S2-S1 equal to given difference i.e d So eq [1]-> s2+(-s1)== s2-s1= d eq [2]-> s2-(-s1)== s2+s1 = Total SUM =>eq[1] + eq[2] 2s2= difference + Total SUM s2 = (difference + Total SUM)/ 2 Hence s2 can be found i.e the required SUM'''<file_sep># -*- coding: utf-8 -*- """ Created on Mon Jun 15 00:50:28 2020 @author: MrMaak """ # Remove Duplicates from Sorted Array II # Medium # Given a sorted array nums, remove the duplicates in-place such that # duplicates appeared at most twice and return the new length. # Do not allocate extra space for another array, # you must do this by modifying the input array in-place with O(1) extra memory. # Example 1: # Given nums = [1,1,1,2,2,3], # Your function should return length = 5, # with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. # It doesn't matter what you leave beyond the returned length. # Example 2: # Given nums = [0,0,1,1,1,1,2,3,3], # Your function should return length = 7, # with the first seven elements of nums being modified # to 0, 0, 1, 1, 2, 3 and 3 respectively. # It doesn't matter what values are set beyond the returned length. def removedup2(nums): if len(nums)==0: return False i=0 for j in nums: if nums[i]==j: i+=1 nums[] nums=[1,1,1,2,2,3] print(removedup2(nums)) <file_sep># -*- coding: utf-8 -*- """ Created on Sun Jun 14 23:17:39 2020 @author: MrMaak """ # WORD SEARCH # Given a 2D board and a word, find if the word exists in the grid. # The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. # Example: # board = # [ # ['A','B','C','E'], # ['S','F','C','S'], # ['A','D','E','E'] # ] # Given word = "ABCCED", return true. # Given word = "SEE", return true. # Given word = "ABCB", return false. # Constraints: # board and word consists only of lowercase and uppercase English letters. # 1 <= board.length <= 200 # 1 <= board[i].length <= 200 # 1 <= word.length <= 10^3 # Accepted def searchword(board, word, i): for i in range (0, len(board)): for j in range( 0, len(board[i])): if board[i][j]== word[0] and dfs(board, word, i, j, 0): return True return False def dfs(board, word, i, j, count): if count==len(word): return True if i<0 or i>=len(board) or j<0 or j>= len(board[i]) or board[i][j]!= word[count]: return False temp= board[i][j] board[i][j]="" found= dfs(board, word, i-1, j, count+1) or dfs(board, word, i+1, j, count+1)or dfs(board, word, i, j-1, count+1) or dfs(board, word, i, j+1, count+1) board[i][j]=temp return found board =[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E']] word="SEE" print(searchword(board, word, 0))<file_sep>def myPow(x: float, n: int) -> float: if n==0 : return 1 else : if n>0 : return power(x,n) else : return 1/power(x,-n) def power(x,n) : if n==0 : return 1 temp=power(x,n//2) ans=temp*temp if n%2==0 : return ans else : return x*ans print(myPow(2.1,3))<file_sep>def top(x,y,m,n): k=[[0 for j in range(n+1)] for i in range(m+1)] maximum=0 for i in range(1,m+1): for j in range(1,n+1): if x[i-1]==y[j-1]: k[i][j]= 1+ k[i-1][j-1] maximum=max(k[i][j], maximum) else: k[i][j]=0 return maximum x="abcdefz" y="abcfghijxyz" print(top(x,y,len(x), len(y)))<file_sep>class Node: # Constructor to create a new node def __init__(self, val): self.val = val self.left = None self.right = None def maxPathSum(root) -> int: res=[-9999] def solve(root, res): if root is None: return 0 l= solve(root.left, res) r=solve(root.right, res) temp=max(l,r)+root.val if root.left is None and root.right is None: temp=max(temp, root.val) ans=max(temp, root.val+l+r) res[0] =max(res[0], ans) return temp solve(root, res) return res[0] # Driver program to test above function root = Node(-15) root.left = Node(5) root.right = Node(6) root.left.left = Node(-8) root.left.right = Node(1) root.left.left.left = Node(2) root.left.left.right = Node(6) root.right.left = Node(3) root.right.right = Node(9) root.right.right.right= Node(0) root.right.right.right.left = Node(4) root.right.right.right.right = Node(-1) root.right.right.right.right.left = Node(10) print ("Max pathSum of the given binary tree is{}".format( maxPathSum( root))) ''' Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. The maximum sum path may or may not go through root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity is O(n). '''<file_sep>import heapq points=[[3,3],[5,-1],[-2,4]] K=2 heap = [] heapq.heapify(heap) for i in range(len(points)): x = points[i][0] y = points[i][1] d = (x*x + y*y) heapq.heappush(heap,[d, [x, y]]) res = [] print(heap) res.append([y for x, y in heapq.nsmallest(K, heap)]) out=[] out=res.pop() print(out) #maxheap<file_sep>/*Perimeter of squares in a rectangle The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It's easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80 Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing: #Hint: See Fibonacci sequence #Ref: http://oeis.org/A000045 The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares. perimeter(5) should return 80 perimeter(7) should return 216 CODE#*/ import java.math.BigInteger; public class SumFct { public static BigInteger perimeter(BigInteger n) { BigInteger a,temp,out,sum,i; a=BigInteger.valueOf(1);temp=BigInteger.valueOf(0);out=BigInteger.valueOf(0); sum = BigInteger.valueOf(0);i = BigInteger.valueOf(0); while(i.compareTo(n)<0){ out=a.add(temp); temp=a; a=out; sum=sum.add(out); i=i.add(BigInteger.valueOf(1));} return (sum.add(BigInteger.valueOf(1))).multiply(BigInteger.valueOf(4)); }} <file_sep># -*- coding: utf-8 -*- """ Created on Sat Jun 13 00:23:51 2020 @author: MrMaak """ '''Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]''' rst=[] def possible(curr,start): if len(curr)==k: rst.append(curr) return for i in range(start,n+1): possible(curr+[i],i+1) n,k=4,2 possible([],1) print(rst) <file_sep># -*- coding: utf-8 -*- """ Created on Sat Jun 20 00:32:47 2020 @author: MrMaak """ # Given two integers dividend and divisor, #divide two integers without using #multiplication, division and mod operator. # Return the quotient after dividing dividend by divisor. # The integer division should truncate toward zero, # which means losing its fractional part. #For example, truncate(8.345) = 8 and truncate(-2.7335) = -2. # Example 1: # Input: dividend = 10, divisor = 3 # Output: 3 # Explanation: 10/3 = truncate(3.33333..) = 3. # Example 2: # Input: dividend = 7, divisor = -3 # Output: -2 # Explanation: 7/-3 = truncate(-2.33333..) = -2. # Note: # Both dividend and divisor will be 32-bit signed integers. # The divisor will never be 0. # Assume we are dealing with an environment which could only #store integers within the 32-bit signed integer range:[−231,231 − 1]. # For the purpose of this problem, assume that your function #returns 231 − 1 when the division result overflows. def divison(dividend, divisor): neg = (dividend< 0) != (divisor<0) dividend= abs(dividend) divisor = div = abs(divisor) ans, count = 0, 1 while dividend >= divisor : dividend-= div div+= div ans+= count count+= count if dividend < div: div=divisor count=1 if neg: return max(-ans, -2147483648) else: return min(ans, 2147483648) print(divison(10, 3)) <file_sep>/*Kata Task A bird flying high above a mountain range is able to estimate the height of the highest peak. Can you? Example The birds-eye view ^^^^^^ ^^^^^^^^ ^^^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^^ ^^^^ The bird-brain calculations 111111 1^^^^111 1^^^^11 1^^^1 1^^^^111111 1^^^11 1111 ---------------------------- 111111 12222111 12^^211 12^21 12^^2111111 122211 1111 ------------------------------ 111111 12222111 1233211 12321 12332111111 122211 1111 Height = 3*/ public class birdmountain { public static void main(String[] args) { char[][] mountains={ "^^^^^^ ".toCharArray(), " ^^^^^^^^ ".toCharArray(), " ^^^^^^^ ".toCharArray(), " ^^^^^ ".toCharArray(), " ^^^^^^^^^^^ ".toCharArray(), " ^^^^^^ ".toCharArray(), " ^^^^ ".toCharArray() }; int my=mountains.length; int mx=mountains[0].length; char[][] arr=mountains.clone(); int height=0; boolean f; do { f=false; char[][] next=new char[my][mx]; for (int y = 0; y < my; y++) { for (int x = 0; x < mx; x++) { next[y][x] = arr[y][x]; if (arr[y][x] == '^' && (y == 0 || x == 0 || y == my-1 || x == mx-1 || arr[y-1][x] == ' ' || arr[y+1][x] == ' ' || arr[y][x-1] == ' ' || arr[y][x+1] == ' ')) { f = true; next[y][x] = ' '; } } } if(f) { height++; arr=next;} }while (f); System.out.println(height); } } <file_sep>def sorting(arr,n): #BASE CASE if n==1: return #INDUCTION sorting(arr,n-1) #HYPOTHETICAL last=arr[n-1] j=n-2 while j>=0 and arr[j]>last : arr[j+1]=arr[j] j-=1 arr[j+1]=last arr=[5,1,7,3,5,-1] print("orignal array-->{}".format(arr)) sorting(arr,len(arr)) print("sorted array-->{}".format(arr))<file_sep># -*- coding: utf-8 -*- """ Created on Wed Jun 24 00:50:42 2020 @author: MrMaak """ ''' Input: Given an array A of -positive -sorted -no duplicate -integer A positive integer k Output: Count of all such subsets of A, Such that for any such subset S, Min(S) + Max(S) = k subset should contain atleast two elements 1. Backtracking approach to get subsets 2. Get min and max of subset 3. Add min and max and put them in Hashmap (or update the count) 4. repeat this process for all subsets 5. search for k in hashmap and return count of k input: {1,2,3,4,5} subsets: 1, 2, 3, 4, 5, {1,2},{1,3} k = 5 count = 5 {1, 4},{2,3} {1,2,4}, {1,2,3,4} {1,3,4}''' def countSubsets(nums,k): nums.sort() count = 0 for i in range(len(nums)): for j in range(i,len(nums)): if nums[i]+nums[j]>k: break if nums[i]+nums[j]==k: count += 2**((j-i-1) if j-i>1 else 0) print(count) return count countSubsets([1,2,3,4,5], 5) <file_sep> def stair(n): if n<=1: return n ways= stair(n-1) + stair(n-2) return ways n=4 print(stair(n+1))<file_sep>def sub(x,y,m,n): #BASE CONDITION if m==0 or n==0: return 0 #memorization if t[m][n]!=-1: return t[m][n] #CHOICE DIAGRAM if x[m-1]==y[n-1]: t[m][n]= 1+ sub(x,y,m-1,n-1) return t[m][n] else: t[m][n]=max(sub(x,y,m-1,n), sub(x,y,m,n-1)) return t[m][n] def top(x,y,m,n): k=[[0 for j in range(n+1)] for i in range(m+1)] for i in range(1,m+1): for j in range(1,n+1): if x[i-1]==y[j-1]: k[i][j]= 1+ k[i-1][j-1] else: k[i][j]=max(k[i-1][j], k[i][j-1]) return k[m][n] x="abcdefz" y="abcfghijxyz" t=[[-1 for j in range(len(y)+1)] for i in range(len(x)+1)] print(sub(x,y,len(x), len(y))) print(top(x,y,len(x), len(y)))<file_sep>def reverse(arr): if len(arr)==1: return l=arr.pop(len(arr)-1) reverse(arr) insert(arr,l) def insert(arr, element): if len(arr)==0: arr.append(element) return p=arr.pop(len(arr)-1) insert(arr,element) arr.append(p) arr=[1,2,3,4,5] print("orignal array-->{}".format(arr)) reverse(arr) print("reversed array-->{}".format(arr))<file_sep>def mah(arr): stack=[] left=[] for i in range(len(arr)): if len(stack)==0: left.append(-1) elif len(stack)>0 and stack[-1][0]<arr[i]: left.append(stack[-1][1]) elif len(stack)>0 and stack[-1][0]>=arr[i]: while len(stack)>0 and stack[-1][0]>=arr[i]: stack.pop() if len(stack)==0: left.append(-1) else: left.append(stack[-1][1]) stack.append([arr[i],i]) stack=[] right=[] #NEXT SMALLER TO RIGHT for i in range(len(arr)-1,-1,-1): if len(stack)==0: right.append(len(arr)) elif len(stack)>0 and stack[-1][0]<arr[i]: right.append(stack[-1][1]) elif len(stack)>0 and stack[-1][0]>=arr[i]: while len(stack)>0 and stack[-1][0]>=arr[i]: stack.pop() if len(stack)==0: right.append(len(arr)) else: right.append(stack[-1][1]) stack.append([arr[i],i]) right=right[::-1] out=[0] *len(arr) for i in range(len(arr)): out[i]=(right[i]-left[i]-1)*arr[i] return max(out) def MaxAreaRectangleinbinarymatrix(matrix): maz=[] for u in matrix[0]: maz.append(u) maxi=mah(maz) for i in range(1,len(matrix)): for j in range(len(matrix[i])): if matrix[i][j]==0: maz[j]=0 else: maz[j]=maz[j]+matrix[i][j] maxi=max(maxi, mah(maz)) return maxi matrix=[[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]] print(MaxAreaRectangleinbinarymatrix(matrix))<file_sep>/*Count the number of Duplicates Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. Example "abcde" -> 0 # no characters repeats more than once "aabbcde" -> 2 # 'a' and 'b' "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`) "indivisibility" -> 1 # 'i' occurs six times "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice "aA11" -> 2 # 'a' and '1' "ABBA" -> 2 # 'A' and 'B' each occur twice CODE#*/ public class CountingDuplicates { public static int duplicateCount(String text) { int i=0,j=0,c=0,a=0; text=text.toLowerCase(); for(i=0;i<text.length();i++) {for(j=0;j<text.length();j++) { if(text.charAt(i)==text.charAt(j)) {c++;} } if(c>1){a++;} String d= String.valueOf(text.charAt(i)).trim(); text=text.replaceAll(d,""); c=0; i=0; j=0; } return a; } } <file_sep># -*- coding: utf-8 -*- """ Created on Sat Jun 13 01:19:29 2020 @author: MrMaak """ #RECURSIVE IMPLEMENTATION OF #CONVERTING A STRING TO AN INTEGER def convert(s,num): if len(s)==1: return int(s)+ num*10 num = int(s[0]) + num*10 return convert(s[1:],num) s="123" convert(s,0)<file_sep>arr=[3,4,0,0] stack=[] left=[] #NEXT SMALLER TO LEFT for i in range(len(arr)): if len(stack)==0: left.append(-1) elif len(stack)>0 and stack[-1][0]<arr[i]: left.append(stack[-1][1]) elif len(stack)>0 and stack[-1][0]>=arr[i]: while len(stack)>0 and stack[-1][0]>=arr[i]: stack.pop() if len(stack)==0: left.append(-1) else: left.append(stack[-1][1]) stack.append([arr[i],i]) stack=[] right=[] #NEXT SMALLER TO RIGHT for i in range(len(arr)-1,-1,-1): if len(stack)==0: right.append(len(arr)) elif len(stack)>0 and stack[-1][0]<arr[i]: right.append(stack[-1][1]) elif len(stack)>0 and stack[-1][0]>=arr[i]: while len(stack)>0 and stack[-1][0]>=arr[i]: stack.pop() if len(stack)==0: right.append(len(arr)) else: right.append(stack[-1][1]) stack.append([arr[i],i]) right=right[::-1] out=[0] *len(arr) for i in range(len(arr)): out[i]=(right[i]-left[i]-1)*arr[i] print("The maximum area possible in given gistogram is {}".format(max(out))) maz=[] matrix=[[1,2],[3,4]] for u in matrix[0]: maz.append(u) maz[0]=12 print(maz) print(matrix)<file_sep>'''find all the prime number till N''' import math n=30 arr=[1]*(n+1) i=2 while i*i<=n: if arr[i]==1: for j in range((i*i),n+1,i): arr[j]=0 i+=1 count=0 for i in arr: if i==1: count+=1 print(arr) print("Numbers of prime number in range",n,"is",count)<file_sep>from functools import lru_cache @lru_cache(100) def grammar(n,k): if n==1 or k==1: return 0 mid=(2**(n-1))//2 if k<=mid: return int(grammar(n-1,k)) else: return int(not(grammar(n-1,k-mid))) print(grammar(3,3)) #0 #01 #0110 #01101001<file_sep>arr=[1,2,4,8,9,12,16] n=len(arr) c=4 low, high, best =arr[0], arr[n-1], 0 while (low<=high): mid=(low+high+1)/2 left, cnt= 0, 1 for (i,c) in zip(range(1,n), range(1,c)): if (arr[i]-arr[left])>=mid: left=i cnt+=1 if cnt>= c: low=mid+1 best=mid else: high=mid-1 print(int(best))<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import sys class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: if root is None: return 0 res=[-99999] def solve(root, res): if root is None: return 0 l = solve(root.left, res) r = solve(root.right, res) temp= 1+ max(l,r) #PASS ABOVE ans = max(temp, 1+l+r) #INCLUDE IN ANS res[0] = max(res[0], ans) return temp solve(root,res) return res[0] -1 ##LEETCODE<file_sep>#6--5--4--15 for i in range(10): n=int(input("Enter a number")) if n%9!=0: x=n%9 else: x=9 print(x)<file_sep>def per(i,o): if len(i)==1: print(o+i[0]) return o1=o o2=o o1=o1+i[0] o2=o2+i[0]+"_" i=i[1:] per(i,o1) per(i,o2) per("abc","") '''OUTPUT:- abc ab_c a_bc a_b_c '''<file_sep># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: res=[-9999] def solve(root, res): if root is None: return 0 l= solve(root.left, res) r=solve(root.right, res) temp=max(max(l,r)+root.val , root.val) ans=max(temp, root.val+l+r) res[0] =max(res[0], ans) return temp solve(root, res) return res[0] #LEETCODE ''' For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Input: [1,2,3] 1 / \ 2 3 Output: 6 '''<file_sep>import heapq arr=[1,1,1,2,2,3] k=2 freq={} for i in arr: if i in freq: freq[i]+=1 else: freq[i]=1 arr=[] for x,y in freq.items(): arr.append([y,x]) heap = [] heapq.heapify(heap) for i in range(len(arr)): heapq.heappush(heap,arr[i]) res = [] res.append([y for x, y in heapq.nlargest(k, heap)]) out=[] out=res.pop() print(out) print("dhd;")<file_sep>def binarysearch(arr,low,high,x): if high<low: return -1 mid=low+(high-low)//2 if x==arr[mid]: return mid elif x<arr[mid]: return binarysearch(arr,low,mid-1,x) elif x>arr[mid]: return binarysearch(arr,mid+1,high,x) arr=[1,5,8,12,13] print(6," is at index ",binarysearch(arr,0,len(arr)-1,6))<file_sep>def isPrime(i): count=1 for j in range(1,i//2+1): if i%j==0: count+=1 if count==2: return 1 return 0 def factor(num,arr): for i in range(1,num//2+1): if num%i==0 and isPrime(i): arr.append(i) num=int(input("Enter a number...\n")) arr=[] factor(num, arr) print(arr)<file_sep># -*- coding: utf-8 -*- """ Created on Tue Jun 23 13:47:45 2020 @author: MrMaak """ #SUBSET SUM PROBLEM #RECURSIVE APPROACH def subrec(arr, s, n): #BASE CASE if s==0: return True if n==0 and s !=0: return False #CHOICE DIAGRAM if arr[n-1] > s: return subrec(arr, s, n-1) else: return ((subrec(arr, s-arr[n-1], n-1)) or (subrec(arr, s, n-1))) #DP --> MEMORIZATION def submem(arr, s, n): #BASE CASE if s==0: return True if n==0 and s !=0: return False if t[n][s] != -1: return t[n][s] #CHOICE DIAGRAM if arr[n-1] > s: t[n][s]= submem(arr, s, n-1) return t[n][s] else: t[n][s]= ((submem(arr, s-arr[n-1], n-1)) or (submem(arr, s, n-1))) return t[n][s] #DP --> TOP-DOWN def topdown(arr, s, n): for i in range(1,(s+1)): k[0][i]=False for i in range(n+1): k[i][0]=True for i in range(n+1): for j in range(s+1): if arr[i-1]> j: k[i][j]=k[i-1][j] else: k[i][j]= k[i-1][j-arr[i-1]] or k[i-1][j] return k[n][s] arr=[1,2,3,5,14] s=6 n=len(arr) t=[[-1 for i in range(s+1)] for j in range(n+1)] k=[[False for i in range(s+1)] for j in range(n+1)] print("FOUND THE SUM RECURSIVE= {}? --> {}".format(s,subrec(arr,s, n))) print("FOUND THE SUM MEMORIZATION= {}? --> {}".format(s,submem(arr,s, n))) print("FOUND THE SUM TOPDOWN = {}? --> {}".format(s,topdown(arr,s,n)))<file_sep>def fib_fast(n): if n <= 1: return n a = [0, 1] while True: a.append((a[-1]+a[-2]) % 10) if a[-1] == 1 and a[-2] == 0: a.pop() a.pop() break return a[n % len(a)] n=7 print((fib_fast(n+1))*(fib_fast(n) % 10))<file_sep>def per(i,o,s): if i=="": s.add(o) return o1=o o2=o o1=o1+i[0].lower() o2=o2+i[0].upper() i=i[1:] per(i,o1,s) per(i,o2,s) s=set() per("a1B2","",s) print(s) ''' OUTPUT:- A1b2 a1B2 A1B2 a1b2 '''<file_sep># -*- coding: utf-8 -*- """ Created on Fri Jun 12 23:15:49 2020 @author: MrMaak """ ''' Given a set of characters and a positive integer k, possibleint all possible strings of length k that can be formed from the given set. Input: set[] = {'a', 'b'}, k = 3 Output: aaa aab aba abb baa bab bba bbb Input: set[] = {'a', 'b', 'c', 'd'}, k = 1 Output: a b c d ''' rst=[] def possible(curr): if len(curr)==k: rst.append(curr) return for i in aset: possible(curr+i) aset={'1','2'} k=4 possible("") print(rst)<file_sep>'''from CountNUMBEROFSUBSETWITHGIVENDIFFERENCE import * print("\n\n") from TARGET_SUM import *''' print("\n\n") from combinationoflengthR import *<file_sep>def areConsecutive(m, n): if ( n < 1 ): return False Min = min(m) Max = max(m) if (Max - Min + 1 == n): visited = [False for i in range(n)] for i in range(n): if (visited[m[i] - Min] != False): return False visited[m[i] - Min] = True return True return False def check(): arr=[5,4,3,2,1] maxi=-999 for i in range(len(arr)): curr=arr[i] res=0 l=[] for j in range(len(arr)): temp=arr[j] if curr<= temp: res+=curr l.append(j) c=res if areConsecutive(l, len(l)): maxi=max(maxi, c) return maxi print(check())<file_sep>def activate(arr): n=len(arr) i=0 while(i<=n-1): try: if arr[i]==0: i+=1 if arr[i]==1: arr[i-2]=1 arr[i-1]=1 arr[i+1]=1 arr[i+2]=1 i+=3 except IndexError: pass if sum(arr)==n-1: ''' Problem Description There is a corridor in a Jail which is N units long. Given an array A of size N. The ith index of this array is 0 if the light at ith position is faulty otherwise it is 1. All the lights are of specific power B which if is placed at position X, it can light the corridor from [ X-B+1, X+B-1]. Initially all lights are off. Return the minimum number of lights to be turned ON to light the whole corridor or -1 if the whole corridor cannot be lighted. ''' <file_sep>def mySqrt(x: int) -> int: l=0 r=x while l+1<r: mid= l+(r-l)//2 sq=mid * mid if sq==x: return mid elif sq>x: r=mid else: l=mid if l*l ==x: return l elif r*r==x: return r else: return l print(mySqrt(8))<file_sep>#TYPE OF UNBOUNDED KNAPSACK. n=10 k=[[0 for i in range(n+1)] for j in range(n+1)] for i in range(1,n+1): k[0][i]=0 for i in range(n+1): k[i][0]=1 for i in range(1,n+1): for j in range(1,n+1): if i > j: k[i][j]=k[i-1][j] else: k[i][j]= max(i * k[i][j-i] , k[i-1][j]) print(k) print(k[n-1][n]) <file_sep> n, k = [int(c) for c in input().split()] l=[int(c) for c in input().split()] p=[0]* n print(l) queries=[] for _ in range(k): t = [int(c) for c in input().split()] queries.append(t) def update(arr): p=[0]*len(arr) p[0]=arr[0] for i in range(1,len(arr)): p[i]=arr[i]+ p[i-1] for i in queries: if i[0]==1: for j in range(i[1]-1, i[2]): if l[j]==0: l[j]=1 else: l[j]==0 update(l) else: summ=0 for j in range(i[1]-1, i[2]): summ+=l[j] print(summ%(10^9 + 7)) '''Sample Input: 9 6 1 0 0 1 1 0 0 0 1 1 2 6 1 4 8 2 1 9 2 3 5 1 2 7 2 5 8 Sample Output: 41 12 8 Explanation: Array P initially: [1, 1, 1, 2, 3, 3, 3, 3, 4] After 1st query: A: [1, 1, 1, 0, 0, 1, 0, 0, 1] P: [1, 2, 3, 3, 3, 4, 4, 4, 5] After 2nd query: A: [1, 1, 1, 1, 1, 0, 1, 1, 1] P: [1, 2, 3, 4, 5, 5, 6, 7, 8] '''<file_sep>list=[] s=20 arr=[3,2,2,3,4,6] for k in range(1,5): for i in arr: list.append(i/k) total=sum(list) list=[] if total<s: break print(k) <file_sep>def leader(arr): out=[] n=len(arr) curr=arr[n-1] out.append(curr) for i in range(n-2, -1, -1): if arr[i]> curr: out.append(arr[i]) curr=arr[i] return out arr=[16, 17, 4, 3, 5, 2] print(leader(arr))<file_sep>arr=[1,20,6,4,5] def merge_sort(arr,n): temp=[0]*n return mergesort(arr,temp,0,len(arr)-1) def mergesort(arr,temp,left,right): # MERGE SORT BASICS STEPS count=0 if left<right: mid=(left+right)//2 count+=mergesort(arr,temp,0,mid) # LEFT SIDE ARRAY count+=mergesort(arr,temp,mid+1,right) # RIGHT SIDE ARRAY count+=merge(arr,temp,left,mid,right) # MERGING BOTH LEFT AND RIGHT ARRAY return count def merge(arr,temp,l,mid,r): i=l # i for left array j=mid+1 # j for right array k=l # k for temp array count=0 while i<=mid and j<=r: # Conditions are checked to make sure that i and j don't exceed their subarray limits. if arr[i]<=arr[j]: # NO INVERSION temp[k]=arr[i] # just copying elements to temp i+=1 k+=1 else: # INVERSION temp[k]=arr[j] count+=mid-i+1 # In merge process, let i is used for indexing left sub-array and j for right sub-array. # At any step in merge(), if a[i] is greater than a[j], then there are (mid – i) inversions. # because left and right subarrays are sorted, so all the remaining elements in left-subarray # (a[i+1], a[i+2] … a[mid]) will be greater than a[j] j+=1 k+=1 while i<=mid: # Copy the remaining elements of LEFT subarray into temporary array. temp[k]=arr[i] i+=1 k+=1 while j<=r: # Copy the remaining elements of RIGHT subarray into temporary array. temp[k]=arr[j] j+=1 k+=1 for x in range(l, r + 1): # Copy the elements of temp into arr. arr[x] = temp[x] return count print(merge_sort(arr,len(arr)))<file_sep>/*BAGELS Here's a seemingly simple challenge. We're giving you a class called bagel, exactly as it appears below. All it really does is return an int, specifically 3. sealed class Bagel { public int Value { get; private set; } = 3; } The catch? For the solution, we're testing that the result is equal to 4. But as a little hint, the solution to this Kata is (almost) exactly the same as the example test cases. ------------------------------- CODE#*/ import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class BagelSolver { public static Bagel getBagel() { try { Field f = Boolean.class.getField("TRUE"); Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); modifiers.setInt(f, f.getModifiers() & ~Modifier.FINAL); f.set(null, false); } catch (Exception e){} return new Bagel(); } } <file_sep># -*- coding: utf-8 -*- """ Created on Tue Jun 16 02:01:02 2020 @author: MrMaak """ #Longest Common Prefix # Write a function to find the longest common prefix string # amongst an array of strings. # If there is no common prefix, return an empty string "". # Example 1: # Input: ["flower","flow","flight"] # Output: "fl" # Example 2: # Input: ["dog","racecar","car"] # Output: "" # Explanation: There is no common prefix among the input strings. # Note: # All given inputs are in lowercase letters a-z. def longestCommonPrefix(strs): prefix = strs[0] if strs else '' while True: if all(s.startswith(prefix) for s in strs): return prefix prefix = prefix[:-1] print(longestCommonPrefix(["flower","flow","flight"])) <file_sep>package javas; /*Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square! Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number. The result will be an array of arrays or of tuples (in C an array of Pair) or a string, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors. #Examples: list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]] list_squared(42, 250) --> [[42, 2500], [246, 84100]]*/ import java.util.ArrayList; public class recreationinteger { public static void main(String[] args) { ArrayList<Long> divisors = new ArrayList<Long>(); ArrayList<ArrayList<Long>> res = new ArrayList<ArrayList<Long>>(); long m=1,n=42; for (long c = m; c <= n; c++) { divisors.clear(); for (long i = 1; i <= c / 2; i++) { if (c % i == 0) divisors.add(i); } divisors.add(c); long sum = new Long(0); for (int i = 0; i < divisors.size(); i++) { sum += (long) Math.pow(divisors.get(i).longValue(), 2); } Double d = new Double(Math.sqrt(sum)); if (d.toString().substring(d.toString().indexOf('.')).equals(".0")) { ArrayList<Long> r = new ArrayList<Long>(); r.add(c); r.add(sum); res.add(r); } } System.out.println(res); } } <file_sep>def compute_min_refills(distance, tank, stops): fuel=tank count=0 stops += [distance, distance] for i in range(len(stops)-1): if fuel<stops[i]: return -1 if fuel<stops[i+1]: fuel=stops[i]+tank count+=1 return count print(compute_min_refills(200,250,[100,150])) <file_sep>print("Hello <NAME>") <file_sep>/*Nice Array A Nice array is defined to be an array where for every value n in the array, there is also an element n-1 or n+1 in the array. example: [2,10,9,3] is Nice array because 2=3-1 10=9+1 3=2+1 9=10-1 Write a function named isNice/IsNice that returns true if its array argument is a Nice array, else false. You should also return false if input array has no elements. */ import java.util.ArrayList; public class nicearray { public static void main(String[] args) { Integer[] arr= {2,10,9,3}; System.out.println(st(arr)); } private static boolean st(Integer[] arr) { ArrayList<Integer> ar=new ArrayList<Integer>(); ArrayList<Integer> ar2=new ArrayList<Integer>(); for(int i=0;i<arr.length;i++) ar.add(arr[i]); for(int k=0;k<arr.length;k++) if(ar.contains(arr[k]+1)||ar.contains(arr[k]-1)) ar2.add(arr[k]) ; if(!(ar2.size()==arr.length)||arr.length==0) return false; else return true; } } <file_sep>def lcsp(m,n): for i in range(1,m+1): for j in range(1,n+1): if x[i-1]==y[j-1]: t[i][j] =1+t[i-1][j-1] else: t[i][j]=max(t[i-1][j], t[i][j-1]) x="abcdef" y="acehgfhgk" t=[[0 for j in range(len(y)+1)] for i in range(len(x)+1)] lcsp(len(x),len(y)) #PRINT i, j=len(x),len(y) s="" while i>0 and j>0: if x[i-1]==y[j-1]: s+=x[i-1] i-=1 j-=1 else: if t[i][j-1]> t[i-1][j]: j-=1 else: i-=1 s=s[-1::-1] print(s)<file_sep>class Node(): def __init__(self, data, left=None, right= None): self.left= left self.right=right self.data=data def ctree(preorder, dict,start, end, pindex ): root= Node(preorder[pindex]) pindex= pindex+1 if pindex==len(preorder): return root, pindex index= dict.get(preorder[pindex]) if start<= index and index + 1<= end - 1: root.left, pindex= ctree(preorder, dict, start, index, pindex) root.right, pindex= ctree(preorder, dict, index+1, end-1, pindex) return root, pindex # Driver Code preorder = [1, 2, 4, 5, 3, 6, 8, 9, 7] postorder = [4, 5, 2, 8, 9, 6, 7, 3, 1] dict={} for i, e in enumerate(postorder): dict[e]=i start=0 end=len(postorder)-1 pindex=0 root=ctree(preorder, dict,start, end, pindex )[0] def inorder(root): if root: inorder(root.left) print(root.data) inorder(root.right) inorder(root)<file_sep>def rev(word): c=0 for i in range(2,word): b=True; for j in range(2,i): if i%j==0: b=False break if b: c+=1 return c print(rev(12))<file_sep># floor(log4(num))=ceil(log4(num) import math def isPowerOfFour(n: int) -> bool: if n==0: return False return math.floor(math.log(n,4))==math.ceil(math.log(n,4)) print(isPowerOfFour(-2147483648))<file_sep># Uses python3 import sys def get_fibonacci_last_digit_naive(n): f=[0,1] for i in range(2,n+1): f.append((f[i-1]+f[i-2])%10) return (f[n]) if __name__ == '__main__': input = sys.stdin.read() n = int(input) print(get_fibonacci_last_digit_naive(n)) <file_sep>def floor(arr, target): res=-1 low,high=0,len(arr)-1 while low<=high: mid=low+(high-low)//2 if arr[mid]>target: high=mid-1 elif arr[mid]<target: low=mid+1 res=arr[mid] else: return arr[mid] return res def ceil(arr,target): res=-1 low,high=0,len(arr)-1 while low<=high: mid=low+(high-low)//2 if arr[mid]>target: high=mid-1 res=arr[mid] elif arr[mid]<target: low=mid+1 else: return arr[mid] return res arr=[10,20,30,40] target=25 f=floor(arr,target) c=ceil(arr,target) if target-f < c-target: print(f) else: print(c)<file_sep>import sys from collections import namedtuple Item = namedtuple("Item", "value weight") def get_optimal_value(capacity, weights, values): value=0 weight_value_pairs = sorted([Item(v, w) for v, w in zip(values, weights)],key=lambda i: i.value / i.weight,reverse=True) current_weight=0 final_value=0.0 for i in weight_value_pairs: if current_weight+i.weight<=capacity: current_weight+=i.weight final_value+=i.value else: remain=capacity-current_weight final_value+=i.value*(remain/i.weight) break return final_value capacity=50 values=[60,100,120] weights=[20,50,30] print(get_optimal_value(capacity,weights,values))<file_sep>def majority(arr,low,size): m={} for i in range(size): if arr[i] in m: m[arr[i]]+=1 else: m[arr[i]]=1 count=0 for key in m: if m[key]>size//2: count=1 break print(m) if count==1: return 1 else: return 0 arr=[1,2,3,1] size=len(arr) print(majority(arr,0,size))<file_sep>''' Add 2 numbers represented as string / Sum of two large numbers Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these two numbers. Examples: Input : str1 = "3333311111111111", str2 = "44422222221111" Output : 3377733333332222 Input : str1 = "7777555511111111", str2 = "3332222221111" Output : 7780887733332222''' def addstring(num1,num2): # n2 must be greater than n1 if len(num1)>len(num2): temp=num1 num1=num2 num2=temp diff=len(num2)-len(num1) carry=0 out="" #for sum for i in range(len(num1)-1,-1,-1): sum=((ord(num1[i])-ord('0'))+int((ord(num2[i+diff])-ord('0'))) + carry) out=out+str(sum%10) carry=sum//10 # Add remaining digits of str2[] for i in range(diff-1,-1,-1): sum=ord(num2[i])-ord('0')+carry out=out+str(sum%10) carry=sum//10 if carry: out=out+str(carry) return out[::-1] print (addstring("9","9")) <file_sep>import sys def coinmin(arr,s): n=len(arr) k=[[0 for i in range(s+1)] for j in range(n+1)] for i in range(s+1): k[0][i]=sys.maxsize-1 for i in range(1,n+1): k[i][0]=0 for i in range(1,n+1): for j in range(1,s+1): if arr[i-1]> j: k[i][j]=k[i-1][j] else: k[i][j]= min(k[i][j-arr[i-1]], k[i-1][j]) return k[n][s] arr=[1,2,3] s=5 if s<0: print("NOT POSSIBLE") else: print("{} min coin is required to get sum= {} from coins={}".format(coinmin(arr,s),s,arr)) <file_sep>class Solution: def search(self, arr: List[int], target: int) -> int: if len(arr)==0 or arr==None: return -1 left=0 right=len(arr)-1 minindex=0 def minimum_element_index(left, right, arr): if len(arr)==0: return -1 if len(arr)==1: return 0 while left<= right: mid=left+(right-left)//2 if mid> 0 and arr[mid]< arr[mid-1]: return mid elif arr[mid]>= arr[left] and arr[mid]> arr[right]: left=mid+1 else: right=mid-1 return left minindex=minimum_element_index(left, right, arr)#RETURN MINIMUM ELEMENT's INDEX left=0 right=len(arr)-1 if target>= arr[minindex] and target<= arr[right]: left=minindex else: right=minindex while left<= right: #NORMAL BINARY SEARCH mid=left+(right-left)//2 if target == arr[mid]: return mid elif arr[mid]> target: right=mid-1 else: left=mid+1 return -1 #LEETCODE--> ''' https://leetcode.com/problems/search-in-rotated-sorted-array/ Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 '''<file_sep>class Solution: def findMin(self, arr: List[int]) -> int: if len(arr)==0: return -1 if len(arr)==1: return arr[0] left=0 right=len(arr)-1 while(left<= right): mid= left+(right-left)//2 if mid>0 and arr[mid]<arr[mid-1]: return arr[mid] elif arr[mid]>= arr[left] and arr[mid]> arr[right]: left= mid+1 else: right=mid-1 return arr[left] <file_sep># -*- coding: utf-8 -*- """ Created on Tue Jun 16 15:17:26 2020 @author: MrMaak """ # The count-and-say sequence is the sequence of integers with the first five terms as following: # 1. 1 # 2. 11 # 3. 21 # 4. 1211 # 5. 111221 # 1 is read off as "one 1" or 11. # 11 is read off as "two 1s" or 21. # 21 is read off as "one 2, then one 1" or 1211. # Given an integer n where 1 ≤ n ≤ 30, # generate the nth term of the count-and-say sequence. # You can do so recursively, in other words from the previous member # read off the digits, counting the number of digits in groups of # the same digit. # Note: Each term of the sequence of integers will be represented as a # string. # Example 1: # Input: 1 # Output: "1" # Explanation: This is the base case. # Example 2: # Input: 4 # Output: "1211" # Explanation: For n = 3 the term was "21" in which # we have two groups "2" and "1", "2" can be read as "12" which means # frequency = 1 and value = 2, the same way "1" is read as "11" # , so the answer is the concatenation of "12" and "11" which is "1211". def counter(n): if n==1: return "1" prev=counter(n-1) res, count, curr = "", 1, prev[0] for i in range(1, len(prev)): if curr== prev[i]: count+=1 else: res+=str(count)+str(curr) count, curr =1, prev[i] res+=str(count)+ str(curr) return res print(counter(6)) <file_sep>def triplet(arr,n): ans=0 for i in range(1, n-1): maxl=0 maxr=0 for j in range(0, i): if arr[i] > arr[j]: maxl=max(maxl, arr[j]) for j in range(i+1, n): if arr[i] < arr[j]: maxr=max(maxr, arr[j]) if maxl and maxr: ans= max(ans, maxl+arr[i]+maxr) return ans arr=[2,5,3,1,4,9] print(triplet(arr, len(arr))) ''' Instead of traversing through every triplets with three nested loops, we can traverse through two nested loops. While traversing through each number(assume as middle element(aj)), find maximum number(ai) smaller than aj preceding it and maximum number(ak) greater than aj beyond it. Now after that, update the maximum answer with calculated sum of ai + aj + ak '''<file_sep>/*LARGE FACTORIALS In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120 Your mission is simple: write a function that takes an integer n and returns the value of n!. You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string "" in C and C++). For non-negative numbers a full length number is expected for example, return 25! = "15511210043330985984000000" as a string. For more on factorials, see http://en.wikipedia.org/wiki/Factorial NOTES: The use of BigInteger or BigNumber functions has been disabled, this requires a complex solution I have removed the use of require in the javascript language. ------------------------- CODE#*/ import java.math.BigInteger; public class Kata { public static String Factorial(int n) { BigInteger fact = new BigInteger("1"); for (int i = 2; i <= n; i++) fact = fact.multiply(new BigInteger(i + "")); return fact.toString(); }} <file_sep>def check(summ): for i in prime: if i==summ: return 1 return 0 def g(stri, pos, summ, tight): if pos==len(stri): if check(summ) : return 1 else: return 0 elif dp[pos][summ][tight]!=-1: return dp[pos][summ][tight] elif tight==1: res=0 for i in range(0,int(stri[pos])): if i==int(stri[pos]): res+=g(stri,pos+1,summ+i,1) else: res+=g(stri,pos+1,summ+i,0) dp[pos][summ][tight]=res return res else: res=0 for i in range(0,9): res+=g(stri,pos+1,summ+i,0) dp[pos][summ][tight]=res return res prime=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109] l=10 r =19 l=l-1 a=str(l) b=str(r) dp=[[[-1 for k in range(2)] for j in range(80)]for i in range(10)] ans1=g(b,0,0,1) dp=[[[-1 for k in range(2)] for j in range(80)]for i in range(10)] ans2=g(a,0,0,1) print(ans1-ans2)<file_sep>def pig(word): f=word[0] if 'dog'=='adog eiou': return word+'ay' else: return word[1:]+'ay'+f print(pig("hello"))<file_sep>def max_dot_product(a, b): res = 0 while a: j=max(a) k=max(b) res+=j*k a.remove(j) b.remove(k) return res print(max_dot_product([23],[39]))<file_sep>def coin(arr,s): n=len(arr) k=[[0 for i in range(s+1)] for j in range(n+1)] for i in range(1,s+1): k[0][i]=0 for i in range(n+1): k[i][0]=1 for i in range(1,n+1): for j in range(1,s+1): if arr[i-1]> j: k[i][j]=k[i-1][j] else: k[i][j]= k[i][j-arr[i-1]] + k[i-1][j] return k[n][s] arr=[1,2,3] s=5 if s<0: print("NOT POSSIBLE") else: print("There are {} max ways to get sum= {} from coins={}".format(coin(arr,s),s,arr))<file_sep>def delete(k): if k==0: s.pop() return temp=s.pop() delete(k-1) s.append(temp) s = [1,2,3,4,5] s1=s.copy() k= len(s)//2-1 if len(s)%2==0 else len(s)//2 delete(k) print("The resultant stack after removing middle element from {} is {}".format(s1,s))<file_sep># -*- coding: utf-8 -*- """ Created on Tue Jun 23 15:47:00 2020 @author: MrMaak """ # EQUAL SUBSET PARTION PROBLEM #Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. # Note: # Each of the array element will not exceed 100. # The array size will not exceed 200. # Example 1: # Input: [1, 5, 11, 5] # Output: true # Explanation: The array can be partitioned as [1, 5, 5] and [11]. # Example 2: # Input: [1, 2, 3, 5] # Output: false # Explanation: The array cannot be partitioned into equal sum subsets. def recc(nums, s, n): if s==0: return True if n==0 and sum!=0: return False if t[n][s]!=- 1: return t[n][s] if nums[n-1]>s: t[n][s]= recc(nums, s, n-1) return t[n][s] else: t[n][s]= (recc(nums, s-nums[n-1], n-1) or recc(nums, s, n-1)) return t[n][s] def canPartition(nums) -> bool: s=sum(nums) if s%2!=0: return False else: s//=2 n=len(nums) k=[[False for i in range(s+1)] for j in range(n+1)] for i in range(n+1): k[i][0]=True for i in range(1,s+1): k[0][i]= False for i in range(n+1): for j in range(s+1): if nums[i-1]> j: k[i][j] = k[i-1][j] else: k[i][j]= k[i-1][j-nums[i-1]] or k[i-1][j] return k[n][s] nums=[1,5,11,5] s=sum(nums) n=len(nums) t=[[-1 for i in range(s+1)] for j in range(n+1)] a1=recc(nums, s//2, n) a=canPartition( nums) print(a1) <file_sep>def printpreorder(inorder, postorder, n): if postorder[-1] in inorder: root = inorder.index(postorder[-1]) stack.append(postorder[-1]) if root != 0: # left subtree exists printpreorder(inorder[:root], postorder[:root], len(inorder[:root])) if root != n - 1: # right subtree exists printpreorder(inorder[root + 1:], postorder[root: -1], len(inorder[root + 1:])) # Driver Code postorder = [4, 12, 10, 18, 24, 22, 15, 31,44, 35, 66, 90, 70, 50, 25] inorder = [4, 10, 12, 15, 18, 22, 24, 25,31, 35, 44, 50, 66, 70, 90] n = len(inorder) stack=[] printpreorder(inorder, postorder, n) print ("Preorder traversal: {}".format(stack)) #25 15 10 4 12 22 18 24 50 35 31 44 70 66 90<file_sep># python3 def max_pairwise_product(numbers): n = len(numbers) maxxx=max(numbers[0],numbers[1]) maxx=min(numbers[0],numbers[1]) for i in range(2,n): if numbers[i]>=maxxx: maxx=maxxx maxxx=numbers[i] else : if numbers[i]>=maxx: maxx=numbers[i] else: pass max_product=maxx*maxxx return max_product if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_product(input_numbers)) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Jun 15 23:08:12 2020 @author: MrMaak """ # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #REMOVING DUPLICATE 1: def removedup1(): arr=[1,1,2] i=0 for j in range(1, len(arr)): if arr[i]!= arr[j]: i+=1 arr[i]=arr[j] print(i+1) #REMOVING DUPLICATE 2: # Given a sorted array nums, #remove the duplicates in-place such that duplicates #appeared at most twice and return the new length. # Do not allocate extra space for another array, #you must do this by modifying the input array in-place # with O(1) extra memory. # Example 1: # Given nums = [1,1,1,2,2,3], # Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. # It doesn't matter what you leave beyond the returned length. # Example 2: # Given nums = [0,0,1,1,1,1,2,3,3], # Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. #It doesn't matter what values are set beyond the returned length. def removedup2(): arr=[1,1,1,2,2,3] i=1 for j in range(2, len(arr)): if arr[i-1]!=arr[j]: i+=1 arr[i]=arr[j] print(i+1) #CALLING FUNCTION print(removedup1()) print(removedup2()) <file_sep>stack=[]# storing index value nums=[1,3,0,0,1,2,4] stack.append(0) out=[0 for i in range(len(nums))] for i in range(len(nums)): if len(stack)==0: stack.append(i) continue while len(stack)!=0 and nums[stack[-1]]< nums[i]: out[stack[-1]]=nums[i] stack.pop() stack.append(i) for s in stack: out[s]=-1 print(out)<file_sep>def subset(i,o): if i=="": print(o) return o1=o o2=o o2=o2+i[0] i=i[1:] subset(i,o1) subset(i,o2) i="abc" o="" subset(i,o) ''' def subset(i,oi): if len(i)==0: print(oi) return o1=oi.copy() o2=oi.copy() o2.append(i[0]) i=i[1:] subset(i,o1) subset(i,o2) i=[1, 4, 9] oi=[] out=[] subset(i,oi) '''<file_sep>def subArraySum(arr, sumi,n ): for i in range(n): curr_sum = arr[i] j = i + 1 while j <= n: if curr_sum == sumi: print ("Sum found between") print("indexes % d and % d"%( i, j-1)) return 1 if curr_sum > sumi or j == n: break curr_sum = curr_sum + arr[j] j += 1 print ("No subarray found") return 0 arr=[1,2,3,7,5] subArraySum(arr, 12, len(arr))<file_sep>def tower(n, s, d ,h): if n==1: print("Move disk 1 from {} to {}".format(s,d)) return tower(n-1, s, h, d) print("Move disk {} from {} to {}".format(n,s,d)) tower(n-1, h, d, s) n=3 tower(n,'s','d','h')<file_sep># -*- coding: utf-8 -*- """ Created on Wed Jun 24 00:20:10 2020 @author: MrMaak """ s=5 arr=[1,2,3,5,10] n=len(arr) t=[[0 for j in range(s+1)] for i in range(n+1)] for i in range(1, s+1): t[0][i]= 0 for i in range(n+1): t[i][0]= 1 for i in range(n+1): for j in range(s+1): if arr[i-1]> j: t[i][j]= t[i-1][j] else: t[i][j]= t[i-1][j-arr[i-1]] + t[i-1][j] print(t[n][s])<file_sep>def rod(wt, n): for i in range(n+1): for j in range(wt+1): if w[i-1]>j: t[i][j]=t[i-1][j] else: t[i][j]=max((value[i-1]+t[i][j-w[i-1]]), (t[i-1][j])) return t[n][wt] def submem(n,wt): #BASE CASE if n==0 or wt==0: return 0 if k[n][wt] != -1: return k[n][wt] #CHOICE DIAGRAM if w[n-1] > wt: k[n][wt]= submem(n-1,wt) return k[n][wt] else: k[n][wt]= max((value[n-1]+submem( n, wt-w[n-1])) ,(submem(n-1,wt))) return k[n][wt] value=[2,5,7,8] w=[1,2,3,4] wt=5 n=len(value) k=[[-1 for j in range(wt+1)] for i in range(n+1)] t=[[0 for j in range(wt+1)] for i in range(n+1)] print(rod(wt,n)) print(submem(n,wt)) ''' |-------->length | | | ^' [size of array or the elements present in array] FILLED WITH 0 '''<file_sep>startindex, bufferindex= 0, 0 arr=[1,2,3,4,5] r=2 out=[0]*r def combination(startindex, arr, bufferindex, out): #BaseCase if bufferindex==r: print(out) return for i in range(startindex, len(arr)): #BACKTRACKING out[bufferindex]=arr[i] combination(i+1, arr, bufferindex+1, out) combination(startindex, arr, bufferindex,out) ''' from itertools import combinations lst = [1,2,3,4,5] lengthOfStrings = 3 for i in combinations(lst, lengthOfStrings): print(i) '''<file_sep>def per(i,o): if i=="": print(o) return o1=o o2=o o1=o1+i[0].lower() o2=o2+i[0].upper() i=i[1:] per(i,o1) per(i,o2) per("ab","") ''' OUTPUT: ab aB Ab AB '''<file_sep>def subset(i,oi): if len(i)==0: if len(oi)==3: out.append(oi) return o1=oi.copy() o2=oi.copy() o2.append(i[0]) i=i[1:] subset(i,o1) subset(i,o2) i=[1, 4, 45, 6, 10, 8] oi=[] out=[] subset(i,oi) sumi=22 outi=[] for k in out: if sum(k)==sumi: outi.append(k) print(outi)<file_sep>stack=[] k=4 out=[] arr=[10, 9, 8, 7, 4, 70, 60, 50] for i in arr: if len(stack)==0: stack.append(i) print(stack) continue elif len(stack)>0 and stack[-1]>i: stack.append(i) print(stack) elif len(stack)>0 and stack[-1]<i: stack=[i]+stack print(stack) if len(stack)>k: temp=min(stack) stack.remove(temp) out.append(temp) #kth largest and min heap print(stack) print(out)<file_sep>def desired(arr,c): sumi=sum(arr) c=0 while sumi!=0: if alleven(arr): c+=divide(arr) else: c+=substract(arr) sumi=sum(arr) return c def alleven(arr): all=False for i in range(0,len(arr)): if arr[i]%2==0: all=True else: all=False break return all def divide(arr): for i in range(0, len(arr)): arr[i]//=2 return 1 def substract(arr): t=0 for i in range(0,len(arr)): if arr[i]%2==0: pass else: arr[i]-=1 t+=1 return t c=0 arr=[2,1] print(desired(arr,c))<file_sep>def areBookingsPossible(arrival, departure, n, k): ans = [] # Create a common vector both arrivals # and departures. for i in range(0, n): ans.append((arrival[i], 1)) ans.append((departure[i], 0)) # Sort the vector ans.sort() #[(1, 1), (2, 0), (3, 1), (5, 1), (6, 0), (8, 0)] curr_active, max_active = 0, 0 for i in range(0, len(ans)): # If new arrival, increment current # guests count and update max active # guests so far if ans[i][1] == 1: curr_active += 1 max_active = max(max_active, curr_active) # if a guest departs, decrement # current guests count. else: curr_active -= 1 # If max active guests at any instant # were more than the available rooms, # return false. Else return true. return k >= max_active arrival = [1, 3, 5] departure = [2, 6, 8] n = len(arrival) k=3 if areBookingsPossible(arrival, departure, n, k): print("Yes") else: print("No") <file_sep>import random arr=[5,7,85,4,6,1,2,9,3,4] def quicksort(arr,l,r): if l >= r: return k = random.randint(l, r) arr[l], arr[k] = arr[k], arr[l] j, m = partition(arr, l, r) quicksort(arr,l,j-m) quicksort(arr,j+1,r) def partition(arr,l,r): pivot = arr[l] j,k,m=l,1,0 for i in range(l + 1, r + 1): if arr[i] < pivot: j += 1 arr[i], arr[j] = arr[j], arr[i] elif arr[i] == pivot: j += 1 arr[i], arr[j] = arr[j], arr[i] arr[j], arr[l + k] = arr[l + k], arr[j] k += 1 while m < k: arr[l + m], arr[j - m] = arr[j - m], arr[l + m] m += 1 return j, m quicksort(arr,0,len(arr)-1) print(arr)<file_sep>arr=[1,2,0,0,1,2,2] pivot=1 low=0 high=len(arr)-1 i=0 while i<=high: if arr[i]<pivot: arr[i],arr[low]=arr[low],arr[i] low+=1 i+=1 elif arr[i]>pivot: arr[i],arr[high]=arr[high],arr[i] high-=1 else: i+=1 print(arr)<file_sep>def wave(arr): arr.sort() for i in range(0,len(arr)-2,2): arr[i], arr[i+1]= arr[i+1], arr[i] return arr arr=[3, 6, 5, 10, 7, 20] print(wave(arr)) ''' Sort an array in wave form Given an unsorted array of integers, sort the array into a wave like array. An array ‘arr[0..n-1]’ is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ….. Input: arr[] = {3, 6, 5, 10, 7, 20} Output: arr[] = {6, 3, 10, 5, 20, 7} OR any other array that is in wave form '''<file_sep>def sumpossible(b,n, num): t=[[False for i in range(num+1)] for j in range((n+1))] for i in range (n+1): t[i][0]=True for i in range(1, num+1): t[0][i]=False for i in range(1,n+1): for j in range(1, num+1): if j< t[i-1]: t[i][j]=t[i-1][j] if j>=t[i-1]: t[i][j]=(t[i-1][j] or t[i-1][j-t[i-1]]) return t[n][num] #nu=int(input()) #arr=list(map(int, input().split())) #a=list(map(int,input().split())) #n2=int(input()) nu=2 arr=[3,2] n2=4 z=[3,8,11,13] print(n2) #z=list(map(int,input().split())) b=[] for i in range(nu): sumi=0 for j in range(i+1): sumi=sumi+(arr[j]* 2**j) b.append(sumi) print(b) out=[] ''' for i in z: if sumpossible(b,len(b),i): out.append("YES") else: out.append("NO") st=" ".join(out) print("{}".format(st)) '''<file_sep>def first(arr, target): res=-1 low,high=0,len(arr)-1 while low<=high: mid=low+(high-low)//2 if arr[mid]>target: high=mid-1 elif arr[mid]<target: low=mid+1 else: res=mid high=mid-1 return res def last(arr,target): res=-1 low,high=0,len(arr)-1 while low<=high: mid=low+(high-low)//2 if arr[mid]>target: high=mid-1 elif arr[mid]<target: low=mid+1 else: res=mid low=mid+1 return res arr=[1,2,2,2,3,4] res=-1 target=2 print(first(arr,target)) print(last(arr,target))<file_sep>from sys import maxsize def lcsum(arr): maxsumsofar= -maxsize-1 maxendinghere=0 for i in range(len(arr)): maxendinghere+=arr[i] if maxendinghere > maxsumsofar: maxsumsofar=maxendinghere if maxendinghere < 0: maxendinghere=0 return maxsumsofar def printlcsum(arr): maxsumsofar= -maxsize-1 maxendinghere=0 start,end=0,0 s=0 for i in range(len(arr)): maxendinghere+=arr[i] if maxendinghere > maxsumsofar: maxsumsofar=maxendinghere start=s end=i if maxendinghere < 0: maxendinghere=0 s=i+1 return maxsumsofar, start, end arr= [-2, -3, 4, -1, -2, 1, 5, -3] #[-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] print(lcsum(arr)) print(printlcsum(arr)) '''Largest Sum Contiguous Subarray Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum. '''<file_sep># Python program to print postorder # traversal from preorder and # inorder traversals def printpostorder(inorder, preorder, n): if preorder[0] in inorder: root = inorder.index(preorder[0]) if root != 0: # left subtree exists printpostorder(inorder[:root], preorder[1:root + 1], len(inorder[:root])) if root != n - 1: # right subtree exists printpostorder(inorder[root + 1:], preorder[root + 1:], len(inorder[root + 1:])) print(preorder[0]) # Driver Code inorder = [4, 2, 5, 1, 3, 6]; preorder = [1, 2, 4, 5, 3, 6]; n = len(inorder) print ("Postorder traversal ") printpostorder(inorder, preorder, n) <file_sep>import heapq def findsthLargest(nums, k): heap = [] heapq.heapify(heap) for i in range(len(nums)): heapq.heappush(heap,nums[i]) res=[] res.append([y for y in heapq.nsmallest(k, heap)]) print(res) return res[-1][-1] print(findsthLargest([5,2,3,1,9],4))<file_sep>def triplet(arr,n): total=0 for i in range(1, n-1): lc=0 rc=0 for j in range(0,i): if arr[i]> arr[j]: lc+=1 for j in range(i+1,n): if arr[i]< arr[j]: rc+=1 total+=lc*rc return total arr=[1,3,2] print(triplet(arr, len(arr)))<file_sep>def change(m): deno=[1,5,10] ans=[] i=len(deno)-1 while(i >= 0): while(m>=deno[i]): m-=deno[i] ans.append(deno[i]) i-=1 print(ans) return len(ans) print(change(23)) <file_sep>import heapq def findKthLargest(nums, k): heap = [] heapq.heapify(heap) for i in range(len(nums)): heapq.heappush(heap,nums[i]) res=[] res.append([y for y in heapq.nlargest(k, heap)]) print(res) return res[-1][-1] print(findKthLargest([3,1,2,4],2)) #minheap
62fdc2bce431ab1f26732c45a9c5c04ecfaf217b
[ "Java", "Python" ]
103
Python
MayankShekhar-MrMaaK/CODING-PRACTICE
ffd071019d80ed14518be88fb2386b0a85b0b3a7
796c8eec2ce298aba35f46790d92e3fa4afdd0ff
refs/heads/master
<file_sep><?php class RainhawkTest extends UnitTest { public $class = "Rainhawk"; public function __before() { rainhawk::select_database("tests"); return $this; } public function testSelectCollection() { $this->assert(rainhawk::select_collection("datasets")); } } ?><file_sep><?php require_once "includes/core.php"; require_once "includes/check_login.php"; $dataset = isset($_GET['dataset']) ? htmlspecialchars($_GET['dataset']) : null; $datasetInfo = $rainhawk->fetchDataset($dataset); $fields = $datasetInfo['fields']; $constraints = $datasetInfo['constraints']; $readList = $datasetInfo['read_access']; $writeList = $datasetInfo['write_access']; $accessList = array_unique(array_merge($readList, $writeList)); ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Properties</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> <script> rainhawk.apiKey = "<?php echo $mashape_key; ?>"; var dataset = "<?php echo $dataset; ?>"; var newUserCount = 0; $(function() { $(".confirm").confirm({ text: "Are you sure you wish to revoke this user's permission?", title: "Really revoke?", confirmButton: "Revoke", confirm: function(btn) { var username = $(btn).data("user"); rainhawk.access.remove(dataset, username, null, function(data) { $("[data-row-user='" + username + "']").remove(); }, function(message) { $("#accessBody").prepend("<div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button><strong>Error revoking.</strong> " + message + "</div>"); }); } }); $(document).on("change", ".writecheck", function(e) { var $write = $(this); var $read = $write.parents("tr").find(".readcheck"); if($write.is(":checked")) { $read.prop("checked", true); } }); }); function addUser() { window.newUserCount++; $("#tblPermissions").append( "<tr data-row-user-num=" + window.newUserCount + ">" + "<td><input type='text' name='newUser[" + window.newUserCount + "][user]' class='form-control'></td>" + "<td class='text-center'><input type='checkbox' class='readcheck' name='newUser[" + window.newUserCount + "][read]' value='read' checked></td>" + "<td class='text-center'><input type='checkbox' class='writecheck' name='newUser[" + window.newUserCount + "][write]' value='write'></td>" + "<td><button type='button' data-user-num=" + window.newUserCount + " onclick='cancelNewUser(this);' class='btn btn-warning btn-sm'>Cancel</button></td>" + "</tr>" ); } function cancelNewUser(btn) { $("[data-row-user-num='" + $(btn).data("user-num") + "']").remove(); } </script> </head> <body> <?php require_once "includes/nav.php"; ?> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <h1><?php echo $dataset; ?></h1> <p>Update the structure of your dataset...</p> </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h4>Fields</h4> </div> <div class="panel-body"> <form id="fieldForm" action="/proxy/dataset_constraints.php?dataset=<?php echo $dataset; ?>" method="post"> <table class='table'> <thead> <tr> <th class="col-md-7">Name</th> <th class="col-md-5">Constraint</th> </tr> </thead> <tbody> <?php foreach($fields as $field) { ?> <?php if($field == "_id") continue; ?> <?php $type = count($constraints) > 0 && in_array($field, array_keys($constraints)) ? $constraints[$field]['type'] : "none"; ?> <?php if(in_array($user, $writeList)) { ?> <tr> <td><?php echo $field; ?></td> <td> <select id="<?php echo $field; ?>" name="constraint[<?php echo $field; ?>]" class="form-control"> <?php foreach(array("none", "integer", "string", "latitude", "longitude", "float", "timestamp") as $possible) { ?> <option value="<?php echo $possible; ?>" <?php echo $type == $possible ? "selected" : null; ?>><?php echo ucwords($possible); ?></option> <?php } ?> </select> </td> </tr> <?php } else { ?> <tr> <td><?php echo $field; ?></td> <td><?php echo $type; ?></td> </tr> <?php } ?> <?php } ?> </tbody> </table> </form> </div> <?php if(in_array($user, $writeList)) { ?> <div class="panel-footer text-right"> <button type="submit" form="fieldForm" class="btn btn-success" formaction="/proxy/dataset_constraints.php?dataset=<?php echo $dataset; ?>&autoapply" formnovalidate>Auto-Detect</button> <button type="submit" form="fieldForm" class="btn btn-default">Apply Changes</button> </div> <?php } ?> </div> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h4>Permissions</h4> </div> <div id="accessBody" class="panel-body"> <form id="accessForm" action="/proxy/dataset_permissions.php?dataset=<?php echo $dataset; ?>" method="post"> <table class="table"> <thead> <tr> <th class="col-md-9">User</th> <th class="col-md-1 text-center">Read</th> <th class="col-md-1 text-center">Write</th> <th class="col-md-1 text-center"></th> </tr> </thead> <tbody id="tblPermissions"> <?php foreach($accessList as $key => $username) { ?> <?php $isWrite = in_array($username, $writeList); ?> <?php $isRead = in_array($username, $readList); ?> <?php if(in_array($user, $writeList)) { ?> <tr data-row-user="<?php echo $username; ?>"> <td><?php echo $username; ?></td> <td class="text-center"> <input type="checkbox" class="readcheck" name="currentUser[<?php echo $username; ?>][read]" value="read" <?php echo $isRead ? "checked" : null; ?>> </td> <td class="text-center"> <input type="checkbox" class="writecheck" name="currentUser[<?php echo $username; ?>][write]" value="write" <?php echo $isWrite ? "checked" : null; ?>> </td> <td> <button type="button" data-user="<?php echo $username; ?>" class="btn btn-sm btn-danger confirm">Revoke</a> </td> </tr> <?php } else { ?> <tr data-row-user="<?php echo $username; ?>"> <td><?php echo $username; ?></td> <td class="text-center"> <input type="checkbox" value="read" disabled <?php echo $isRead ? "checked" : null; ?>> </td> <td class="text-center"> <input type="checkbox" value="write" disabled <?php echo $isWrite ? "checked" : null; ?>> </td> <td></td> </tr> <?php } ?> <?php } ?> </tbody> <tfoot> <tr> <td class="text-center" colspan="100%"> <?php if(in_array($user, $writeList)) { ?> <button type="button" class="btn btn-sm btn-success" onclick="addUser()">Add User</a> <?php } ?> </td> </tr> </tfoot> </table> </form> </div> <?php if(in_array($user, $writeList)) { ?> <div class="panel-footer text-right"> <button type="submit" form="accessForm" class="btn btn-default">Apply</button> </div> <?php } ?> </div> </div> </div> </div> </body> </html><file_sep>eco.charts.glscatter = function() { return { title: '3D Scatter Graph', options : { width : 1024, height : 768, margin : { top: 30, right: 30, bottom: 30, left: 30 } }, render: function( data, xValue, yValue, zValue, target ) { var options = this.options, width = options.width, height = options.height; var margin = { top: options.margin.top, right: options.margin.right, bottom: options.margin.bottom, left: options.margin.left }; var state = { rotate: false, drag: false }; var canvas = document.createElement("canvas"); canvas.id = 'webglcanvas'; canvas.height = height; canvas.width = width; canvas.addEventListener( 'mousedown', onMouseDown ); canvas.addEventListener( 'mousewheel', onMouseWheel ); canvas.addEventListener( 'DOMMouseScroll', onMouseWheel ); target.appendChild( canvas ); var centre = new THREE.Vector3( 0, 0, 0 ); var size = 150; var camDist = 350, minCamDist = 300, maxCamDist = 400; var hAngle = Math.PI/2, vAngle = Math.PI/4; var hRotateSpeed = 1, vRotateSpeed = 0.5; var mouseStart = new THREE.Vector2(), mouseEnd = new THREE.Vector2(), mouseDelta = new THREE.Vector2(); var overlay = document.createElement("div"); overlay.id = 'webgloverlay'; var dimensions = []; var dCount = 0; if( xValue != "" ) { dCount++; dimensions.push( xValue ); } if( yValue != "" ) { dCount++; dimensions.push( yValue ); } if( zValue != "" ) { dCount++; dimensions.push( zValue ); } if( dCount == 0 ) alert( "Warning: no dimensions enabled!" ); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 45, width/height, 1, 4000 ); camera.position.z = 150; var renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true, alpha: true } ); renderer.setClearColor( 0x444444, 1 ); renderer.setSize( width, height ); var graph = createScatterGraph( data, dimensions, dCount ); updateCamera(); scene.add( graph ); animate(); //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// function createScatterGraph( data, dimensions, dCount ) { var graph = new THREE.Object3D(); var geometry = new THREE.Geometry(); var scale = []; for( var i = 0; i < dCount; i++ ) { scale.push( getScale( data, dimensions[i] ) ); } var axis = []; for( var i = 0; i < dCount; i++ ) { var lineGeo = new THREE.Geometry(); var origin = new THREE.Vector3(); var end = new THREE.Vector3(); var colour; if( i == 0 ) { colour = 0xff0000; end.x = size; } else if( i == 1 ) { colour = 0x0000ff; end.y = size; } else if( i == 2 ) { colour = 0x00ff00; end.z = size; } lineGeo.vertices.push( origin ); lineGeo.vertices.push( end ); var lineMat = new THREE.LineBasicMaterial( { color: colour } ); var line = new THREE.Line( lineGeo, lineMat ); axis.push( line ); } var rescale = []; for( var i = 0; i < dCount; i++ ) { var range = scale[i].high; rescale.push( size / range ); } for( var k in data ) { var vertex = new THREE.Vector3(); for( var i = 0; i < dCount; i++ ) { if( data[k].hasOwnProperty( dimensions[i] ) ) { if( i == 0 ) vertex.x = data[k][dimensions[i]] * rescale[i]; else if( i == 1 ) vertex.y = data[k][dimensions[i]] * rescale[i]; else if( i == 2 ) vertex.z = data[k][dimensions[i]] * rescale[i]; } } geometry.vertices.push( vertex ); } var material = new THREE.ParticleSystemMaterial( { size : 1 } ); var points = new THREE.ParticleSystem( geometry, material ); graph.add( points ); for( var i = 0; i < dCount; i++ ) graph.add( axis[i] ); return graph; } function getScale( data, dimension ) { var size = data.length; var scale; if( size > 0 ) { if( data[0].hasOwnProperty( dimension ) ) { scale = { low: data[0][dimension], high: data[0][dimension] }; for( var i = 1; i < size; i++ ) { if( data[i].hasOwnProperty( dimension ) ) { if( scale.low > data[i][dimension] ) scale.low = data[i][dimension]; else if( scale.high < data[i][dimension] ) scale.high = data[i][dimension]; } } return scale; } else { alert( "Invalid data." ); return { low: 0, high: 0 }; } } else { alert( "Could not generate scale: No data" ); return { low: 0, high: 0 }; } } function animate() { requestAnimationFrame( animate ); render(); } function render() { renderer.render( scene, camera ); } function updateCamera() { var newCam = new THREE.Vector3(); newCam.copy( centre ); newCam.x += camDist * Math.cos( vAngle ) * Math.sin( hAngle ); newCam.y += camDist * Math.sin( vAngle ); newCam.z += camDist * Math.cos( vAngle ) * Math.cos( hAngle ); camera.position.copy( newCam ); camera.lookAt( centre ); } function rotateHoriz( angle ) { hAngle -= hRotateSpeed * angle; if( hAngle > 2*Math.PI ) hAngle -= Math.PI*2; if( hAngle < 0 ) hAngle += Math.PI*2; updateCamera(); } function rotateVert( angle ) { vAngle = Math.max( -Math.PI/2, Math.min( Math.PI/2, vAngle + vRotateSpeed * angle )); updateCamera(); } function onMouseDown( event ) { if( event.button == 0 ) { state.rotate = true; if( !(state.drag) ) { mouseStart.set( event.clientX, event.clientY ); document.addEventListener( 'mousemove', onMouseMove ); document.addEventListener( 'mouseup', onMouseUp ); } } } function onMouseWheel( event ) { var delta = 0; if( event.wheelDelta !== undefined ) { delta = event.wheelDelta; } else if( event.detail !== undefined ) { delta = -event.detail; } if( delta > 0 ) { camDist = Math.max( minCamDist, camDist-10 ); } else { camDist = Math.min( maxCamDist, camDist+10 ); } updateCamera(); } function onMouseMove( event ) { if( state.rotate ) { mouseEnd.set( event.clientX, event.clientY ); mouseDelta.subVectors( mouseEnd, mouseStart ); var width = canvas.width; var height = canvas.height; rotateHoriz( 2 * Math.PI * mouseDelta.x / canvas.width ); rotateVert( 2 * Math.PI * mouseDelta.y / canvas.height ); mouseStart.copy( mouseEnd ); } } function onMouseUp( event ) { if( event.button == 0 ) { document.removeEventListener( 'mousemove', onMouseMove ); document.removeEventListener( 'mouseup', onMouseUp ); } } } } }; <file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; ?> <!DOCTYPE html> <html lang="en-GB" ng-app="eco"> <head> <title>Project Rainhawk - Visualise</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "../includes/meta.php"; ?> <link rel="stylesheet" href="style/charts.css"> <link rel="stylesheet" href="style/style.css"> <base href="/visualise/"> </head> <!-- Remove ng-controller here as it is injected in js/app.js and shouldn't be injected twice--> <body> <?php ob_start(); require_once "../includes/nav.php"; $nav = ob_get_clean(); ob_end_flush(); // We have to set the links to target the root page instead of Angular. echo str_replace('href=', 'target="_self" href=', $nav); ?> <div id="main"> <div ng-view></div> </div> <script> var apiKey = "<?php echo $mashape_key; ?>"; </script> <script src="vendor/jquery/dist/jquery.min.js"></script> <script src="vendor/angular/angular.min.js"></script> <script src="vendor/angular-bootstrap/ui-bootstrap.js"></script> <script src="vendor/angular-route/angular-route.min.js"></script> <script src="vendor/d3/d3.min.js"></script> <script src="vendor/vega/vega.min.js"></script> <script src="vendor/three.js/src/three.min.js"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> <script src="js/app.js"></script> <!-- ECO --> <script src="js/eco.charts.js"></script> <script src="js/controllers.js"></script> <script src="charts/d3barchart.js"></script> <script src="charts/d3piechart.js"></script> <script src="charts/d3map.js"></script> <script src="charts/d3bubblechart.js"></script> <script src="charts/d3treemap.js"></script> <script src="charts/d3linegraph.js"></script> <script src="charts/glscatter.js"></script> <script src="js/directives.js"></script> <script src="js/services.js"></script> </body> </html> <file_sep><?php /*! * Define different generic error messages, pre-json_encoded * for ease of use. */ define("JSON_ERROR_MAINTENANCE", json_encode(array( "meta" => array( "code" => 503, "version" => app::$version, "runtime" => app::runtime() ), "data" => array( "message" => "Maintenance is currently being performed." ) ))); define("JSON_ERROR_NOMETHOD", json_encode(array( "meta" => array( "code" => 402, "version" => app::$version, "runtime" => app::runtime() ), "data" => array( "message" => "No method was specified." ) ))); /*! * Define a function to handle displaying responses in a * simple to use way, with error messages and normal responses. */ function json_render($code = 200, $data = array()) { return json_encode(array( "meta" => array( "code" => $code, "version" => app::$version, "runtime" => app::runtime() ), "data" => $data )); } function json_render_error($code = 300, $message) { return json_render($code, array( "message" => $message )); } /*! * Define a function that takes JSON input and formats it nicely * into good looking JSON that's humanly readable. */ function json_beautify($json) { $result = ""; $pos = 0; $length = strlen($json); $indent = " "; $newline = "\n"; $previous_character = ""; $out_of_quotes = true; for($i = 0; $i <= $length; $i++) { $char = substr($json, $i, 1); if($char == '"' && $previous_character != '\\') { $out_of_quotes = !$out_of_quotes; } else if(($char == "}" || $char == "]") && $out_of_quotes) { if(substr(trim($result), -1) == "[") { $result = trim($result); $pos--; } else { $result .= $newline; $pos--; for($j = 0; $j < $pos; $j++) { $result .= $indent; } } } if($char == ":" && $previous_character == '"') $char .= " "; $result .= $char; if(($char == "," || $char == "{" || $char == "[") && $out_of_quotes) { $result .= $newline; if($char == "{" || $char == "[") $pos++; for($j = 0; $j < $pos; $j++) { $result .= $indent; } } $previous_character = $char; } return $result; } /*! * If our App is currently in maintenance mode, we instantly * kill all current operations, and output the maintenance * page. This page does not contain any includes so we can be * sure that it will not cause strain or perform any queries * on the server. */ if(app::$maintenance) { echo json_beautify(JSON_ERROR_MAINTENANCE); exit; } ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array(); /*! * Try and add the access to the dataset as the user has specified, * which will always work even if the access already exists. */ // Check if the username is set. if(empty($data->username)) { echo json_beautify(json_render_error(404, "You didn't specify the user to remove access from.")); exit; } // Check if the user is trying to revoke the owner's permissions. if($data->username == $dataset->prefix) { echo json_beautify(json_render_error(405, "You can't revoke the owner's access to the dataset.")); exit; } // Check if the type is set. if(empty($data->type)) { // Remove all access. foreach(array("read", "write") as $type) { if(in_array($data->username, $dataset->{$type . "_access"})) { $dataset->{$type . "_access"} = array_diff($dataset->{$type . "_access"}, array($data->username)); } } } else { // Check if the user has that access or not. if(!in_array($data->username, $dataset->{$data->type . "_access"})) { echo json_beautify(json_render_error(406, "The user you specified does not have " . $data->type . " access to this dataset.")); exit; } // Remove the user's access. $dataset->{$data->type . "_access"} = array_diff($dataset->{$data->type . "_access"}, array($data->username)); } // Store the dataset information in the index table. \rainhawk\sets::update($dataset); // Return the removed attribute to the JSON. $json['removed'] = true; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php namespace Rainhawk; /** * Rainhawk\Sets * * Dataset class to be used in the Rainhawk framework. This * class provides an interface for feeding data into and out * from a collection in MongoDB. * * @package Rainhawk\Sets */ class Sets { /** * Holds a reference to our "system.datasets" collection which * has information about each dataset. * * @var MongoCollection */ private static $datasets; /** * Create a new dataset in the system.datasets index, with the * relevant data so that we can start using other operations on * it. * * @param Dataset $dataset The dataset object to base the record on. * @return bool Whether the dataset was created or not. */ public static function create($dataset) { $datasets = self::get_system_datasets(); try { $datasets->insert(array( "prefix" => $dataset->prefix, "name" => $dataset->name, "description" => $dataset->description, "rows" => $dataset->rows, "fields" => $dataset->fields, "constraints" => $dataset->constraints, "read_access" => $dataset->read_access, "write_access" => $dataset->write_access )); return true; } catch(Exception $e) {} return false; } /** * Takes an input dataset and update the record in the system * dataset table. * * @param Dataset $dataset The dataset object to store. * @return bool Whether the dataset saved or not. */ public static function update($dataset) { $datasets = self::get_system_datasets(); try { $datasets->update(array( "prefix" => $dataset->prefix, "name" => $dataset->name ), array( '$set' => array( "name" => $dataset->name, "description" => $dataset->description, "rows" => $dataset->rows, "fields" => $dataset->fields, "constraints" => $dataset->constraints, "read_access" => $dataset->read_access, "write_access" => $dataset->write_access ) )); return true; } catch(Exception $e) {} return false; } /** * Remove the specified dataset from the system.datasets * table. * * @param Dataset $dataset The dataset object to remove. * @return bool Whether the dataset was removed or not. */ public static function remove($dataset) { $datasets = self::get_system_datasets(); try { $datasets->remove(array( "prefix" => $dataset->prefix, "name" => $dataset->name )); return true; } catch(Exception $e) {} return false; } /** * Takes an input dataset ID and returns whether or not that * dataset was found in the reference table or not. * * @param string $prefix The prefix for the user. * @param string $name The name of the dataset. * @return bool Whether the dataset was found or not. */ public static function exists($prefix, $name) { $datasets = self::get_system_datasets(); try { $results = $datasets->find(array("prefix" => $prefix, "name" => $name)); return ($results->count() > 0); } catch(Exception $e) {} return false; } /** * Fetch the metadata about a dataset from the "system.datasets" * collection, which stores everything about each set in the database. * * @param string $prefix The prefix for the user. * @param string $name The name of the dataset. * @return array An array of information about the set. */ public static function fetch_metadata($prefix, $name) { $datasets = self::get_system_datasets(); try { $results = $datasets->find(array("prefix" => $prefix, "name" => $name)); $data = $results->getNext(); unset($data['_id']); return $data; } catch(Exception $e) {} return false; } /** * Fetch a list of all of the datasets that the specified user * has read or write access to. * * @param string $username The username to search for. * @return MongoCursor A cursor to the list of datasets. */ public static function sets_for_user($username) { $datasets = self::get_system_datasets(); try { $results = $datasets->find(array( '$or' => array( array("read_access" => array('$in' => array($username, "global")) ), array("write_access" => array('$in' => array($username, "global")) ) ) )); return $results; } catch(Exception $e) {} return false; } /** * Check if the $datasets variable has been set, and if not * then set it. * * @return MongoCollection The collection containing the information. */ private static function get_system_datasets() { if(self::$datasets) { return self::$datasets; } self::$datasets = \rainhawk::select_collection("datasets"); return self::$datasets; } } ?><file_sep><?php require_once "includes/core.php"; ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Elgar's Coding Orchestra</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> <link rel="stylesheet" href="/css/style.css" type="text/css"> <script> $(function() { var $graph = $(".header .graph"); var width = $graph.width(); var height = $graph.height(); var data = [0, 0, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 3, 6, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 2, 7, 4, 0]; var x = d3.scale.linear().domain([0, data.length]).range([0, width]); var y = d3.scale.linear().domain([0, 18]).range([height, 0]); var line = d3.svg.line() .interpolate("basis") .x(function(d, i) { return x(i); }).y(function(d) { return y(d); }); var graph = d3.select(".graph").append("svg:svg") .attr("width", width) .attr("height", height) .append("svg:g"); var path = graph.append("svg:path") .attr("d", line(data)); var pathLength = path.node().getTotalLength(); path.attr("stroke-dashoffset", pathLength) .attr("stroke-dasharray", pathLength + " " + pathLength) .transition() .duration(2000) .ease("linear") .attr("stroke-dashoffset", 0); }); </script> </head> <body> <?php require_once "includes/nav.php"; ?> <div id="top" class="header"> <div class="vertical"> <h1>Project<strong>Rainhawk</strong></h1> <h3>An elegant <em>Visualisation Framework</em> with <em>Cloud Collaboration</em>.</h3> </div> <div class="graph"></div> </div> <div id="about" class="intro"> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 text-center"> <h2>Big data is all around us.</h2> <p class="lead">Unfortunately, meaning and correlations can be lost when data is stored in different formats in different places.</p> </div> </div> </div> </div> <div id="services" class="services"> <div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h2>What's the solution?</h2> </div> </div> <div class="row"> <div class="col-md-2 col-md-offset-2 text-center"> <div class="service-item"> <i class="service-icon fa fa-cloud"></i> <h4>1. Retrieve</h4> <p>You provide any number of files containing raw data to be uploaded.</p> </div> </div> <div class="col-md-2 text-center"> <div class="service-item"> <i class="service-icon fa fa-code"></i> <h4>2. Parse</h4> <p>We parse the data using our custom parser and store it in the cloud.</p> </div> </div> <div class="col-md-2 text-center"> <div class="service-item"> <i class="service-icon fa fa-hdd-o"></i> <h4>3. Manage</h4> <p>You use our management interface (or directly use the API) to manipulate your data.</p> </div> </div> <div class="col-md-2 text-center"> <div class="service-item"> <i class="service-icon fa fa-tasks"></i> <h4>4. Visualize</h4> <p>Correlations from your data can be graphically understood through our interactive visualizations.</p> </div> </div> </div> </div> </div> <div id="get-started" class="get-started"> <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1 text-center"> <h2>What are you waiting for? Let's get started.</h2> <p class="lead">You have two options to get started &mdash; you can either use our web-based data management interface to upload data and create visualizations instantly or, if you're a developer, read our API documentation so that you can build awesome applications using our highly scalable cloud-based API.</p> <p class="buttons"> <a href="/login.php?dest=/create.php" class="btn btn-lg btn-primary" role="button">Upload &amp; Visualize Online</a> <em>or</em> <a href="https://www.mashape.com/sneeza/project-rainhawk" class="btn btn-lg btn-primary btn-outline" role="button">API Documentation</a> </p> <p class="dev-note"> Note: If you're a developer then you may find <a href="https://github.com/zacoppotamus/ElgarsCodingOrchestra" target="_blank">the source code</a> for the entire project useful &mdash; we've created some wrapper libraries to make communicating with the API as simple as possible to get you started. </p> </div> </div> </div> </div> <hr> <div id="team" class="team"> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4 text-center"> <h2>Meet the dream team!</h2> </div> </div> <div class="row"> <div class="col-md-4 text-center"> <div class="team-item fade"> <a href="http://izac.us/"><img class="img-responsive" src="img/team-zac.jpg"></a> <h4><NAME></h4> </div> </div> <div class="col-md-4 text-center"> <div class="team-item fade"> <a href="http://benelgar.com/"><img class="img-responsive" src="img/team-ben.jpg"></a> <h4><NAME></h4> </div> </div> <div class="col-md-4 text-center"> <div class="team-item fade"> <a><img class="img-responsive" src="img/team-oscar.jpg"></a> <h4><NAME></h4> </div> </div> </div> <div class="row"> <div class="col-md-4 text-center"> <div class="team-item fade"> <a><img class="img-responsive" src="img/team-sam.jpg"></a> <h4><NAME></h4> </div> </div> <div class="col-md-4 text-center"> <div class="team-item fade"> <a href="http://sneeza.me/"><img class="img-responsive" src="img/team-luke.jpeg"></a> <h4><NAME></h4> </div> </div> <div class="col-md-4 text-center"> <div class="team-item fade"> <a><img class="img-responsive" src="img/team-steve.jpg"></a> <h4><NAME>-Tozer</h4> </div> </div> </div> </div> </div> <hr> <footer> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 text-center"> <p>Made in <strong>Bristol</strong> with ♥ <em>&mdash;</em> <strong>Elgar's Coding Orchestra</strong> <em>&mdash;</em> <?php echo date("Y"); ?></p> </div> </div> </div> </footer> <script src="/js/jquery-1.10.2.js"></script> <script src="/js/bootstrap.js"></script> <script src="/visualise/vendor/d3/d3.min.js"></script> </body> </html> <file_sep><?php /*! * This class takes an input nice looking URI, strips it down * and tries to match it with the rules that it's been given. The * advantage of doing this is that we can specify nice looking URIs * in PHP while bypassing Apache or Nginx's rewrite limitations. */ class Route { const GET = "GET"; const POST = "POST"; const PUT = "PUT"; const DELETE = "DELETE"; // Store an array of our defined routes. private static $routes = array(); /*! * Add a new route to the defined routes array, provided both * a request method and the regex for the path. */ public static function get($path, $callback) { $pattern = "/^" . str_replace("/", "\/", $path) . "$/"; self::$routes[self::GET][$pattern] = $callback; } /*! * Add a new route to the defined routes array, provided both * a request method and the regex for the path. */ public static function post($path, $callback) { $pattern = "/^" . str_replace("/", "\/", $path) . "$/"; self::$routes[self::POST][$pattern] = $callback; } /*! * Add a new route to the defined routes array, provided both * a request method and the regex for the path. */ public static function put($path, $callback) { $pattern = "/^" . str_replace("/", "\/", $path) . "$/"; self::$routes[self::PUT][$pattern] = $callback; } /*! * Add a new route to the defined routes array, provided both * a request method and the regex for the path. */ public static function delete($path, $callback) { $pattern = "/^" . str_replace("/", "\/", $path) . "$/"; self::$routes[self::DELETE][$pattern] = $callback; } /*! * Parse a request URI to see if we have any matches, and then * execute the related callback function with the provided params. */ public static function parse() { $url = isset($_GET['uri']) ? trim($_GET['uri']) : null; $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper(trim($_SERVER['REQUEST_METHOD'])) : "GET"; if(isset(self::$routes[$method])) { foreach(self::$routes[$method] as $pattern => $callback) { if(preg_match($pattern, $url, $params)) { array_shift($params); return call_user_func_array($callback, array_values($params)); } } } return false; } } ?><file_sep><?php /*! * This class is a global singleton which is used in every script, * providing global variables and dependency injection for lots of * helper classes. */ class App { // Some global toggles used when the server is under load. public static $development = false; public static $maintenance = false; public static $debug = false; // App specific variables. public static $version = null; public static $domain = null; public static $username = null; // Server configuration variables. public static $stack = array(); public static $root_path = null; public static $init_time = null; /*! * Given an array of field names, return which ones we think should * be indexed and which are non-essential. */ public static function find_index_names($fields) { $keywords = array("id", "name", "key"); $names = array(); foreach($fields as $field_name) { $matched = false; foreach($keywords as $keyword) { if(stripos($field_name, $keyword) !== false) { $matched = true; break; } } if($matched) { $names[] = $field_name; } } return $names; } /*! * Generate the humanly readable runtime, in seconds. */ public static function runtime() { return round(microtime(true) - self::$init_time, 3); } /*! * Log something, somewhere. */ public static function log($section, $message) { return error_log("[$section] $message\n", 0); } } ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "datasets" => array() ); // Perform a query to find the datasets. $datasets = rainhawk\sets::sets_for_user(app::$username); // Check if that query worked. if(!$datasets) { echo json_beautify(json_render_error(401, "There was a problem while trying to find your datasets.")); exit; } // Iterate through the results, if any. foreach($datasets as $dataset) { $json['datasets'][] = array( "name" => $dataset['prefix'] . "." . $dataset['name'], "description" => $dataset['description'], "rows" => $dataset['rows'], "fields" => array_keys($dataset['fields']), "read_access" => $dataset['read_access'], "write_access" => $dataset['write_access'] ); } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php namespace Rainhawk; /** * Rainhawk\Data * * Data class to be used in the Rainhawk framework. This class provides * a way to check a data type and enforce rules. * * @package Rainhawk\Data */ class Data { /** * The different supported data types. */ const STRING = "string"; const INTEGER = "integer"; const FLOAT = "float"; const TIMESTAMP = "timestamp"; const LATITUDE = "latitude"; const LONGITUDE = "longitude"; const ARR = "array"; /** * Create a new dataset in the system.datasets index, with the * relevant data so that we can start using other operations on * it. * * @param string $type The data type to enforce. * @param string $value The value to check. * @return mixed The result if success, null if false. */ public static function check($type, $value) { switch($type) { case self::STRING: return $value; break; case self::INTEGER: if(is_numeric($value) && is_int($value + 0)) { return $value + 0; } break; case self::FLOAT: if(is_numeric($value)) { return $value + 0; } break; case self::TIMESTAMP: if(strtotime($value) !== false) { return strtotime($value); } break; case self::LATITUDE: if(preg_match("/^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}$/", $value)) { return (float)$value; } break; case self::LONGITUDE: if(preg_match("/^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}$/", $value)) { return (float)$value; } break; case self::ARR: if(is_array($value) || is_object($value)) { return (array)$value; } } return null; } /** * Detect the data type given a simple string which can be used to * automatically work out what constraints to apply to a field or not. * * @param string $value * @return string */ public static function detect($value) { if(is_array($value) || is_object($value)) { return self::ARR; } $value = trim($value); if(is_numeric($value)) { if(is_int($value + 0)) { return self::INTEGER; } return self::FLOAT; } if(strtotime($value) !== false) { return self::TIMESTAMP; } return self::STRING; } } ?><file_sep><?php namespace Rainhawk; /** * Rainhawk\Dataset * * Dataset class to be used in the Rainhawk framework. This * class provides an interface for feeding data into and out * from a collection in MongoDB. * * @package Rainhawk\Dataset */ class Dataset { private $collection; public $prefix; public $name; public $description; public $rows = 0; public $fields = array(); public $constraints = array(); public $read_access = array(); public $write_access = array(); public $exists = false; /** * Create a new instance of Dataset, which initiates itself * using the provided ID and fetches relevant information from * MongoDB and our internal dataset structure. * * @param string $prefix The prefix for the user. * @param string $name The name of the dataset. * @return Dataset Our new Dataset instance. */ public function __construct($prefix, $name) { $this->prefix = $prefix; $this->name = $name; if(\rainhawk\sets::exists($prefix, $name)) { $set_data = \rainhawk\sets::fetch_metadata($prefix, $name); $this->collection = \rainhawk::select_collection($prefix . "." . $name); $this->name = $set_data['name']; $this->description = $set_data['description']; $this->rows = (int)$set_data['rows']; $this->fields = $set_data['fields']; $this->constraints = $set_data['constraints']; $this->read_access = $set_data['read_access']; $this->write_access = $set_data['write_access']; $this->exists = true; } } /** * Check if the supplied username has read access to the dataset * which will always return true if the user created it. * * @param string $username The username to check. * @return bool Whether or not the user can access it. */ public function have_read_access($username) { return $this->exists && (in_array($username, $this->read_access) || in_array($username, $this->write_access) || in_array("global", $this->read_access)); } /** * Check if the supplied username has write access to the dataset * which will always return true if the user created it. * * @param string $username The username to check. * @return bool Whether or not the user can access it. */ public function have_write_access($username) { return $this->exists && in_array($username, $this->write_access); } /** * Perform a find query on the dataset, which returns a Mongo * cursor to the results. We can then use this to iterate through * the results. * * @param array $query The query to run. * @param array $fields The fields to return. * @return MongoCursor The Mongo cursor. */ public function find($query, $fields = array()) { if(!$this->exists) { return false; } try { return $this->collection->find($query, $fields); } catch(Exception $e) {} return false; } /** * Perform an insertion of a single row of data into the dataset, * which just passes the rows to the batch insertion method. * * @param array $row The row of data to insert. * @return array The row of data that was inserted with _ids. */ public function insert($row) { $rows = $this-insert_multi(array($row)); if(!$rows) { return false; } return $rows; } /** * Perform an insertion of multiple rows of data into the dataset * in batch, to make API calls easier. * * @param array $rows The rows of data to insert. * @return array The rows that were inserted with _ids. */ public function insert_multi($rows) { if(!$this->exists) { return false; } try { $result = $this->collection->batchInsert($rows); if($result['ok'] == 1) { $this->rows += count($rows); foreach($rows as $row) { $fields = array_keys($row); foreach($fields as $field) { $this->fields[$field] = isset($this->fields[$field]) ? $this->fields[$field] + 1 : 1; } } \rainhawk\sets::update($this); return $rows; } } catch(Exception $e) {} return false; } /** * Perform an update query on the dataset, taking both the query * of things to match and the changes to make to those rows. * * @param array $query The rows to match. * @param array $changes The changes to make. * @return int The number of rows that were changed. */ public function update($query, $changes) { if(!$this->exists) { return false; } try { $result = $this->collection->find($query); if($result) { $ids = array(); $fields = array(); foreach($result as $row) { $id = $row['_id']; $ids[] = $id; $fields[(string)$id] = array_keys($row); } $result = $this->collection->update($query, $changes, array("multiple" => true)); if($result['ok'] == 1) { $updated = (int)$result['n']; $result = $this->collection->find(array("_id" => array('$in' => $ids))); if($result) { foreach($result as $row) { $new_fields = array_keys($row); foreach($fields as $field) { $field = (string)$field; if(!in_array($field, $new_fields)) { $this->fields[$field]--; if($this->fields[$field] <= 0) { unset($this->fields[$field]); } } } foreach($new_fields as $field) { $field = (string)$field; if(!in_array($field, $fields)) { $this->fields[$field] = isset($this->fields[$field]) ? $this->fields[$field] + 1 : 1; } } } \rainhawk\sets::update($this); return $updated; } } } } catch(Exception $e) {} return false; } /** * Perform a delete query on the dataset, using a MongoDB query * to select the rows that we need to delete. * * @param array $query The rows to match. * @return int The number of rows that have been removed. */ public function delete($query) { if(!$this->exists) { return false; } try { $result = $this->collection->find($query); if($result) { $this->rows -= $result->count(); foreach($result as $row) { $fields = array_keys($row); foreach($fields as $field) { $this->fields[$field]--; if($this->fields[$field] <= 0) { unset($this->fields[$field]); } } } $result = $this->collection->remove($query, array("justOne" => false)); if($result['ok'] == 1) { \rainhawk\sets::update($this); return (int)$result['n']; } } } catch(Exception $e) {} return false; } /** * List the indexes on this collection, returning them in array * format. * * @return array The indexes in an array. */ public function fetch_indexes() { if(!$this->exists) { return false; } try { return $this->collection->getIndexInfo(); } catch(Exception $e) {} return false; } /** * Create an index on a specified field, in a specified * direction. If it already exists then nothing will happen. * * @param string $field The field to add an index to. * @return bool Whether or not the indexes were created. */ public function add_index($field) { if(!$this->exists) { return false; } try { $result = $this->collection->ensureIndex(array($field => 1), array("background" => true)); if($result['ok'] == 1) { return true; } } catch(Exception $e) {} return false; } /** * Remove an index on the specified field. * * @param string $field The field to remove the index on. * @return bool Whether or not the indexes were removed. */ public function remove_index($field) { if(!$this->exists) { return false; } try { return $this->collection->deleteIndex($field); } catch(Exception $e) {} return false; } /** * Run an aggregation query on the dataset, which is used to * calculate the max/min of the set. * * @param array $query The query to run. * @return array The results of the calculations. */ public function aggregate($query) { if(!$this->exists) { return false; } try { $result = $this->collection->aggregate($query); if($result['ok'] == 1) { return $result['result']; } } catch(Exception $e) {} return false; } /** * Remove this dataset entirely, destroying the data and * removing the indexes from the index table. * * @return bool Whether or not the operation succeeded. */ public function remove() { if(!$this->exists) { return false; } try { $result = $this->collection->drop(); if($result['ok'] == 1) { \rainhawk\sets::remove($this); return true; } } catch(Exception $e) {} return false; } } ?> <file_sep>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <cstring> #include "readFile.h" #include "unzip.h" #define MAX_STRING_SIZE 256 const char* SHARED_STRINGS_PATH = "xl/sharedStrings.xml"; typedef struct { unsigned x; unsigned y; } coord; ///////////////////////////////////////////////////////////////// ///////// sheetNode Class implementation sheetNode::sheetNode() { jType = NULLVALUE; } sheetNode::sheetNode( string newString ) { jType = STRING; strval = newString; } sheetNode::sheetNode( long double newNumber ) { jType = NUMBER; numval = newNumber; } sheetNode::sheetNode( bool newBool ) { jType = BOOL; boolval = newBool; } string sheetNode::getString() { if( jType != STRING ) return ""; else return strval; } long double sheetNode::getNumber() { if( jType != NUMBER ) return 0; else return numval; } bool sheetNode::getBool() { if( jType != BOOL ) return false; else return boolval; } JType sheetNode::getType() { return jType; } ///////// End of implementation ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ///////// Utility functions string simpleToUpper( string input ) { unsigned length = input.length(); string upper = input; for( unsigned count = 0; count<length; count++ ) if( upper[count] > 96 && upper[count] < 123 ) upper[count] -= 32; return upper; } FileType getType( string fileName ) { unsigned marker = fileName.find_last_of('.'); string fileStr = fileName.substr(marker+1); fileStr = simpleToUpper( fileStr ); if( fileStr.compare( "CSV" ) == 0 ) return CSV; else if( fileStr.compare( "XLSX" ) == 0 ) return XLSX; else if( fileStr.compare( "ODS" ) == 0 ) return ODS; else return UNDEF; } string pageString( page spreadsheet ) { string output = ""; output += spreadsheet.name + '\n'; for( vector< vector<sheetNode> >::iterator outIt = spreadsheet.contents.begin(); outIt != spreadsheet.contents.end(); outIt++ ) { for( vector<sheetNode>::iterator inIt = outIt->begin(); inIt != outIt->end(); inIt++ ) { JType type = inIt->getType(); switch( type ){ case STRING: output += 'S'; break; case NUMBER: output += 'N'; break; case BOOL: output += 'B'; break; default: output += '_'; break; } output = output + '\t'; } output = output + '\n'; } return output; } ///////// End of utility functions ///////////////////////////////////////////////////////////////// // Section ends with cc = " and ifs.peek() != " regardless of the // length/meaning of the quote. void skipQuotes( long unsigned &pos, ifstream &ifs, unsigned &error ) { char cc; cc = ifs.get(); pos++; if( cc != '\"' ) { while( ifs.good() && cc != '\"' ) { cc = ifs.get(); pos++; if( cc == '\"' && ifs.peek() == '\"' ) { ifs.get(); pos++; cc = ifs.get(); pos++; } } if( ifs.eof() ) { error = 2; return; } if( ifs.fail() ) { error = 1; return; } } } void writeCell( sheet &target, size_t row, size_t col, string record ) { if( record == "" ) return; long double number; if( convertData( record, number ) ) { target[row][col].setValue( number ); return; } bool boolean; if( convertBool( record, boolean ) ) { target[row][col].setValue( boolean ); return; } target[row][col].setValue( record ); } void csvMarkers( vector<long unsigned> &commas, vector<long unsigned> &newls, ifstream &ifs, unsigned &error ) { long unsigned pos = 0; char cc = ifs.get(); while( ifs.good() ) { if( cc == '\"' ) skipQuotes( pos, ifs, error ); if( error != 0 ) return; if( cc == ',' ) commas.push_back( pos ); if( cc == '\n' ) newls.push_back( pos ); cc = ifs.get(); pos++; } if( ifs.bad() ) error = 1; } void csvDimensions( size_t &rows, size_t &cols, const vector<long unsigned> &commas, const vector<long unsigned> &newls ) { size_t max = newls.size(); size_t commaPos = 0; size_t newlPos = 0; long unsigned nextComma = ( commas.size() > 0 ) ? commas[0] : -1; long unsigned nextNewl = ( newls.size() > 0 ) ? newls[0] : -1; size_t dimensionPos = 0; vector<size_t> dimensions(1,1); while( newlPos < max ) { nextNewl = ( newls.size() > newlPos ) ? newls[newlPos] : -1; while( nextComma < nextNewl ) { dimensions[dimensionPos]++; commaPos++; nextComma = ( commas.size() > commaPos ) ? commas[commaPos] : -1; } dimensions.push_back(1); dimensionPos++; newlPos++; } rows = dimensions.size(); cols = 0; for( vector<size_t>::iterator it = dimensions.begin(); it != dimensions.end(); it++ ) { if( *it > cols ) cols = *it; } } void csvData( vector<long unsigned> &commas, vector<long unsigned> &newls, sheet &result, size_t rows, size_t cols, ifstream &ifs, unsigned &error ) { long unsigned pos = 0; size_t commaPos = 0; size_t newlPos = 0; long unsigned nextComma = ( commas.size() > 0 ) ? commas[0] : -1; long unsigned nextNewl = ( newls.size() > 0 ) ? newls[0] : -1; size_t row = 0; size_t col = 0; while( ifs.good() ) { col = 0; while( nextComma < nextNewl ) { string record; while( pos < nextComma ) { char cc = ifs.get(); pos++; if( cc == '\"' ) { cc = ifs.get(); pos++; } record += cc; } writeCell( result, row, col, record ); ifs.get(); pos++; col++; commaPos++; nextComma = ( commas.size() > commaPos ) ? commas[commaPos] : -1; } string record; while( pos < nextNewl && !ifs.eof() ) { char cc = ifs.get(); pos++; if( cc == '\"' ) { cc = ifs.get(); pos++; } if( ifs.good() ) record += cc; } writeCell( result, row, col, record ); ifs.get(); pos++; while( col+1 < cols ) { col++; writeCell( result, row, col, "" ); } row++; newlPos++; nextNewl = ( newls.size() > newlPos ) ? newls[newlPos] : -1; } if( ifs.bad() ) error = 1; } sheet readCSV( string filename, unsigned &error ) { error = 0; ifstream ifs( filename ); sheet fail( 0, 0 ); vector<long unsigned> commas; vector<long unsigned> newls; cout << "marka" << '\n'; csvMarkers( commas, newls, ifs, error ); if( error != 0 ) return fail; size_t rows; size_t cols; cout << "dim" << '\n'; csvDimensions2( rows, cols, commas, newls ); sheet result( rows, cols ); ifs.close(); ifs.open( filename ); cout << "dat" << '\n'; csvData2( commas, newls, result, rows, cols, ifs, error ); cout << "dun" << '\n'; if( error != 0 ) return fail; return result; } //Returns -1 if string is invalid coord decodeDimension( string dimension ) { coord failure; failure.x = -1; failure.y = -1; int width = 0; int height = 0; size_t lcount = 0; while( dimension[lcount] >= 'A' && dimension[lcount] <= 'Z' ) { if( lcount == dimension.size() ) { return failure; } lcount++; } string letters = dimension.substr( 0, lcount ); int value; for( size_t count = 0; count < lcount; count++ ) { width *= 26; value = letters[count] + 1 - 'A'; if( value < 1 || value > 26 ) { return failure; } width += value; } string numbers = dimension.substr( lcount ); stringstream converter( numbers ); if( !( converter >> height ) ) { return failure; } coord result; result.x = width; result.y = height; return result; } int getCommonStrings( vector<string> &commonStrings, const string &fileContents ) { string startTag("<t>"); string endTag("</t>"); size_t currentPos = fileContents.find( startTag ); size_t nextPos; size_t len; while( currentPos != string::npos ) { currentPos += 3; nextPos = fileContents.find( endTag, currentPos ); if( nextPos == string::npos ) { return -1; } len = nextPos - currentPos; string newString( fileContents.substr( currentPos, len ) ); commonStrings.push_back( newString ); currentPos = fileContents.find( startTag, currentPos ); } return 1; } int loadCommonStrings( vector<string> &commonStrings, unzFile xlsxFile ) { if( unzOpenCurrentFile( xlsxFile ) == UNZ_OK ) { unz_file_info xmlFileInfo; memset( &xmlFileInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( xlsxFile, &xmlFileInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string xmlFileName; xmlFileName.resize( xmlFileInfo.size_filename ); unzGetCurrentFileInfo( xlsxFile, &xmlFileInfo, &xmlFileName[0], xmlFileInfo.size_filename, NULL, 0, NULL, 0 ); if( xmlFileName.compare( SHARED_STRINGS_PATH ) == 0 ) { string xmlFileContents; uLong xmlFileSize = xmlFileInfo.uncompressed_size; unsigned long long maxBufferSize = 1; if( sizeof( unsigned long long ) == sizeof( unsigned ) ) { maxBufferSize = -1; } else { maxBufferSize <<= sizeof( unsigned ) * 8; maxBufferSize--; } if( xmlFileSize <= maxBufferSize ) { xmlFileContents.resize( xmlFileSize ); voidp xmlFileBuffer = &xmlFileContents[0]; if( unzReadCurrentFile( xlsxFile, xmlFileBuffer, xmlFileSize ) ) { if( getCommonStrings( commonStrings, xmlFileContents ) == 1 ) { return 1; } } } return -1; } } } return 0; } int sanitizeXMLStrings( vector<string> &strings ) { size_t currentPos; size_t endPos; size_t len; for( vector<string>::iterator it = strings.begin(); it != strings.end(); it++ ) { currentPos = it->find_first_of( '&' ); while( currentPos != string::npos ) { endPos = it->find_first_of( ';', currentPos ); if( endPos == string::npos ) { return 0; } len = endPos - currentPos + 1; string token = it->substr( currentPos, len ); if( len == 6 ) { if( token.compare( "&quot;" ) == 0 ) { it->replace( currentPos, 6, """" ); } else if( token.compare( "&apos;" ) == 0 ) { it->replace( currentPos, 6, "'" ); } else { return 0; } } else if( len == 5 ) { if( token.compare( "&amp;" ) == 0 ) { it->replace( currentPos, 5, "&" ); } else { return 0; } } else if( len == 4 ) { if( token.compare( "&lt;" ) == 0 ) { it->replace( currentPos, 4, "<" ); } else if( token.compare( "&gt;" ) == 0 ) { it->replace( currentPos, 4, ">" ); } else { return 0; } } else { return 0; } currentPos = it->find_first_of( '&', currentPos ); } } return 1; } int fileIn( const char * filepath, unzFile zipFile ) { if( unzOpenCurrentFile( zipFile ) == UNZ_OK ) { unz_file_info zipFileInfo; memset( &zipFileInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( zipFile, &zipFileInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string zipFileName; zipFileName.resize( zipFileInfo.size_filename ); unzGetCurrentFileInfo( zipFile, &zipFileInfo, &zipFileName[0], zipFileInfo.size_filename, NULL, 0, NULL, 0 ); unzCloseCurrentFile( zipFile ); int comparison = zipFileName.substr( 0, strlen( filepath ) ).compare( filepath ); if( comparison == 0 ) { return 1; } else { return 0; } } } return -1; } int fileIn( const char * filepath, unzFile zipFile, string &title ) { if( unzOpenCurrentFile( zipFile ) == UNZ_OK ) { unz_file_info zipFileInfo; memset( &zipFileInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( zipFile, &zipFileInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string zipFileName; zipFileName.resize( zipFileInfo.size_filename ); unzGetCurrentFileInfo( zipFile, &zipFileInfo, &zipFileName[0], zipFileInfo.size_filename, NULL, 0, NULL, 0 ); unzCloseCurrentFile( zipFile ); int comparison = zipFileName.substr( 0, strlen( filepath ) ).compare( filepath ); if( comparison == 0 ) { title = zipFileName; title = title.substr( title.find_last_of( '/' ) + 1 ); title.erase( title.find_last_of( '.' ) ); return 1; } else { return 0; } } } return -1; } int getSheetContents( vector< vector<sheetNode> > &spreadsheet, const vector<string> &commonStrings, const string &fileContents ) { size_t currentPosition; size_t endPosition; currentPosition = fileContents.find( "<d" ); currentPosition += 16; endPosition = fileContents.find_first_of( ':', currentPosition ); string topleft = fileContents.substr( currentPosition, endPosition - currentPosition ); currentPosition = endPosition + 1; endPosition = fileContents.find_first_of( '"', currentPosition ); string bottomright = fileContents.substr( currentPosition, endPosition - currentPosition ); coord lower = decodeDimension( bottomright ); coord upper = decodeDimension( topleft ); coord size; size.x = lower.x + 1 - upper.x; size.y = lower.y + 1 - upper.y; if( (int)lower.x == -1 || (int)upper.x == -1 || (int)lower.y == -1 || (int)upper.y == -1 || (int)size.x == 0 || (int)size.y == 0 ) { return 0; } sheetNode blankcell; vector<sheetNode> blankvector( size.x, blankcell ); spreadsheet.assign( size.y, blankvector ); currentPosition = fileContents.find( "<c ", endPosition ); string newDimension; coord newPosition; size_t nextType; size_t nextCell; while( currentPosition != string::npos ) { currentPosition += 6; endPosition = fileContents.find_first_of( '"', currentPosition ); newDimension = fileContents.substr( currentPosition, endPosition - currentPosition ); newPosition = decodeDimension( newDimension ); newPosition.x -= upper.x; newPosition.y -= upper.y; nextType = fileContents.find( " t=", endPosition ); nextCell = fileContents.find_first_of( '/', endPosition ); sheetNode * newCell; if( nextType > nextCell ) { newCell = new sheetNode(); } else { currentPosition = nextType + 4; char cellType = fileContents[currentPosition]; currentPosition = fileContents.find( "<v", currentPosition ); currentPosition += 3; endPosition = fileContents.find_first_of( '<', currentPosition ); string value = fileContents.substr( currentPosition, endPosition - currentPosition ); stringstream converter( value ); long double newValue; if( !( converter >> newValue ) ) { newValue = 0; } switch( cellType ) { case 's': newCell = new sheetNode( commonStrings[(int)newValue] ); break; case 'n': newCell = new sheetNode( newValue ); break; case 'b': if( newValue == 0 ) { newCell = new sheetNode( false ); } else { newCell = new sheetNode( true ); } break; default: newCell = new sheetNode(); break; } } spreadsheet[newPosition.y][newPosition.x] = *newCell; currentPosition = fileContents.find( "<c ", endPosition ); } return 1; } int readXMLSheet( vector< page > &sheetList, string title, const vector<string> &commonStrings, unzFile xlsxFile ) { if( unzOpenCurrentFile( xlsxFile ) == UNZ_OK ) { unz_file_info xmlFileInfo; memset( &xmlFileInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( xlsxFile, &xmlFileInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string xmlFileContents; uLong xmlFileSize = xmlFileInfo.uncompressed_size; unsigned long long maxBufferSize = 1; if( sizeof( unsigned long long ) == sizeof( unsigned ) ) { maxBufferSize = -1; } else { maxBufferSize <<= sizeof( unsigned ) * 8; maxBufferSize--; } if( xmlFileSize <= maxBufferSize ) { xmlFileContents.resize( xmlFileSize ); voidp xmlFileBuffer = &xmlFileContents[0]; vector< vector<sheetNode> > spreadsheet; int fileReadStatus = unzReadCurrentFile( xlsxFile, xmlFileBuffer, xmlFileSize ); if( fileReadStatus > 0 ) { if( getSheetContents( spreadsheet, commonStrings, xmlFileContents ) == 1 ) { page newsheet; newsheet.name = title; newsheet.contents = spreadsheet; sheetList.push_back( newsheet ); return 1; } } } } } return -1; } //Necessarily takes an already opened unzFile and leaves it open int getCommonStrings( vector<string> &commonStrings, unzFile xlsxFile ) { int commonStringsFound = 0; int fileAccessStatus = unzGoToFirstFile( xlsxFile ); while( fileAccessStatus == UNZ_OK && commonStringsFound == 0 ) { commonStringsFound = loadCommonStrings( commonStrings, xlsxFile ); fileAccessStatus = unzGoToNextFile( xlsxFile ); } if( commonStringsFound != 1 ) { return commonStringsFound; } if( !sanitizeXMLStrings( commonStrings ) ) { return -1; } return 1; } int getXMLSheets( string filename, vector< page > &sheetList, vector<string> commonStrings, unzFile xlsxFile ) { int fileAccessStatus = unzGoToFirstFile( xlsxFile ); while( fileAccessStatus == UNZ_OK ) { string title; if( fileIn( "xl/worksheets/", xlsxFile, title ) ) { string pageName = filename; pageName.resize( pageName.find_last_of('.') ); pageName = pageName + "_" + title; readXMLSheet( sheetList, pageName, commonStrings, xlsxFile ); } fileAccessStatus = unzGoToNextFile( xlsxFile ); } return 1; } vector< page > readXLSX( string filename ) { vector< page > falseResult; unzFile xlsxFile = unzOpen( filename.c_str() ); if( xlsxFile ) { vector<string> commonStrings; int commonStringsFound = getCommonStrings( commonStrings, xlsxFile ); if( commonStringsFound == 0 ) { return falseResult; } else if( commonStringsFound == -1 ) { return falseResult; } vector< page > sheetList; int dataFound = getXMLSheets(filename, sheetList, commonStrings, xlsxFile); if( dataFound != 1 ) { return falseResult; } return sheetList; } return falseResult; } vector< page > getFile( string fileName ) { unsigned error; FileType filetype = getType( fileName ); if( filetype == CSV ) { vector< page > csvSheet( 1, readCSV( fileName, error ) ); return csvSheet; } else if( filetype == XLSX ) { return readXLSX( fileName ); } vector< page > failure; return failure; } <file_sep><?php /*! * This class acts as a wrapper between our application and * the XCache var cache, allowing us to store variables in * RAM. */ class XCache { // Define some public variables for whether we should use // this class or not. public static $enabled = false; // Store some stats about the class. public static $access_time = 0; public static $hits = 0; public static $misses = 0; /*! * Initiate the cache so that we can use it elsewhere in * our application, otherwise every other call is bypassed by * a flag. */ public static function init() { self::$enabled = true; } /*! * Fetch a keyvalue from the variable cache, so that we can * mess around with some data! */ public static function fetch($key) { if(!self::$enabled) { return null; } $start = microtime(true); $data = xcache_get($key); $data = ($data) ? unserialize($data) : null; if(!is_null($data)) { self::$hits++; } else { self::$misses++; } $finish = microtime(true); self::$access_time += $finish - $start; return $data; } /*! * Store some data related to a key for a specified (or unspecified * amount of time). */ public static function store($key, $data, $ttl = 0) { if(!self::$enabled) { return false; } $data = serialize($data); return xcache_set($key, $data, $ttl); } /*! * Remove a key from the local variable cache, which is generally * used when we have data we want to update. */ public static function remove($key) { if(!self::$enabled) { return false; } return xcache_unset($key); } } ?><file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; header("content-type: application/json; charset=utf8"); $dataset = isset($_GET['dataset']) ? $_GET['dataset'] : null; $document = array(); foreach($_POST as $name => $value) { if($name == "dataset") continue; $document[$name] = $value; } $result = $rainhawk->insertData($dataset, $document); if(!$result) { echo json_encode(array( "Result" => "ERROR", "Message" => $rainhawk->error() )); exit; } echo json_encode(array( "Result" => "OK", "Record" => $result )); exit; ?> <file_sep>eco.charts.d3map = function() { return { title: 'Map', render: function(data, latitude, longitude, target) { console.log(target); var map = new google.maps.Map(target.node(), { zoom: 2, center: new google.maps.LatLng(0, 0), mapTypeId: google.maps.MapTypeId.TERRAIN }); // Create overlay var overlay = new google.maps.OverlayView(); // Add the container when the overlay is added // to the map overlay.onAdd = function() { var layer = d3.select(this.getPanes().overlayMouseTarget).append("div") .attr("class", "map-dot"); // Draw each marker as a separate SVG element overlay.draw = function() { var projection = this.getProjection(), padding = 10; var marker = layer.selectAll("svg") .data(data) .each(transform) //update existing markers .enter().append("svg:svg") .each(transform) .attr("class", "marker"); // Add a circle marker.append("svg:circle") .attr("r", 4.5) .attr("cx", padding) .attr("cy", padding); // Add a label // marker.data(json.data.results) // .on('mouseover', function(d) // { // d3.select(this).append("svg:text") // .attr("class", "tooltip") // .attr("x", padding+7) // .attr("y", padding) // .attr("dy", ".31em") // .text(function(d) { return d.name }); // }) // .on('mouseout', function(d) // { // d3.selectAll("text").remove(); // }); function transform(d) { d = new google.maps.LatLng(+d[latitude], +d[longitude]) d = projection.fromLatLngToDivPixel(d); return d3.select(this) .style("left", (d.x - padding) + "px") .style("top", (d.y - padding) + "px"); } }; }; // Bind overlay to map overlay.setMap(map); return this; } } } <file_sep><?php require_once "includes/core.php"; require_once "includes/check_login.php"; $dataset = isset($_GET['dataset']) ? htmlspecialchars($_GET['dataset']) : null; $datasetInfo = $rainhawk->fetchDataset($dataset); $fields = $datasetInfo['fields']; $colWidth = 100 / count($fields); ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Edit Data</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> <link rel="stylesheet" href="/js/jtable.2.3.1/themes/metro/blue/jtable.min.css" type="text/css"> <script src="/js/jtable.2.3.1/jquery.jtable.js"></script> <style type="text/css"> #dataTable { margin-left: 15px; margin-right: 15px; border-radius: 6px; overflow: hidden; } </style> <script> $(function() { $("#dataTable").jtable({ title: "Data", paging: true, pageSize: 50, sorting: true, defaultSorting: "name ASC", actions: { listAction: '/proxy/list_data.php?dataset=<?php echo $dataset; ?>', <?php if(in_array($user, $datasetInfo['write_access']) && $datasetInfo['rows'] > 0) { ?> createAction: '/proxy/insert_data.php?dataset=<?php echo $dataset; ?>', updateAction: '/proxy/update_data.php?dataset=<?php echo $dataset; ?>', deleteAction: '/proxy/delete_data.php?dataset=<?php echo $dataset; ?>' <?php } ?> }, fields: { <?php foreach($fields as $field) { ?> <?php if($field == "_id") continue; ?> '<?php echo $field; ?>': { title: '<?php echo $field; ?>', width: '<?php echo $colWidth; ?>%' }, <?php } ?> _id: { key: true, create: false, edit: false, list: false } } }).jtable("load"); }); </script> </head> <body> <?php require_once "includes/nav.php"; ?> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <h1><?php echo $datasetInfo['name'];?></h1> <p><?php echo $datasetInfo['description'];?></p> </div> </div> </div> </div> <div class="row"> <?php if($datasetInfo['rows'] > 0) { ?> <div id="dataTable"></div> <?php } else { ?> <div class="alert alert-info"> <strong>No data!</strong> There's no data here. Why don't you try <a class="alert-link" href="/upload.php?dataset=<?php echo $datasetInfo['name']; ?>">uploading</a> some? </div> <?php } ?> </div> </div> </body> </html><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_read_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to read from this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "min" => null, "max" => null, "average" => null, "sum" => null, ); /*! * Run some commands to calculate some aggregations for the dataset * depending on the query provided. */ // Check if we have a field_name or not. if(empty($data->field)) { echo json_beautify(json_render_error(404, "You didn't specify a field name to use in the calculations.")); exit; } // Set some local variables. $query = array(); // Check if we need to run a pre-query to match certain documents. if(!empty($data->query)) { $query[] = array( '$match' => $data->query ); } // Create the query that we need to run for the calculations. $query[] = array( '$group' => array( "_id" => null, "min" => array( '$min' => '$' . $data->field ), "max" => array( '$max' => '$' . $data->field ), "average" => array( '$avg' => '$' . $data->field ), "sum" => array( '$sum' => '$' . $data->field ) ) ); // Run the query. $result = $dataset->aggregate($query); // Check if it worked. if(!$result) { echo json_beautify(json_render_error(405, "An unexpected error occured while performing your query - are you sure you formatted it correctly?")); exit; } // Set the JSON output. $stats = $result[0]; $json['min'] = $stats['min']; $json['max'] = $stats['max']; $json['average'] = $stats['average']; $json['sum'] = $stats['sum']; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array(); /*! * Try and add the constraint to the field that was specified, but if none * were specified then try and automatically detect which ones to add. */ // Check if the field is set. if(!empty($data->field)) { // Check if the field can be constrained. if($data->field == "_id") { echo json_beautify(json_render_error(405, "You can't apply a constraint to the _id field.")); exit; } // Check if the field already has a constraint. if(isset($dataset->constraints[$data->field])) { echo json_beautify(json_render_error(406, "This field already has a constraint, please remove the current constraint before adding a new one.")); exit; } // Check if the datatype has been set. if(empty($data->type) || !in_array($data->type, array("string", "integer", "float", "timestamp", "latitude", "longitude"))) { echo json_beautify(json_render_error(407, "The data type that you've selected is not supported. We currently support: string, integer, float, timestamp, latitude, longitude.")); exit; } // Add the constraint to the field. $dataset->constraints[$data->field] = array( "type" => $data->type ); // Store the dataset information in the index table. \rainhawk\sets::update($dataset); // Return the added attribute to the JSON. $json['added'] = true; } else { // Get all the records to find all the fields. $rows = $dataset->find(array()); $fields = array(); // Iterate through the rows. foreach($rows as $row) { foreach($row as $field => $value) { if($field == "_id") continue; // Check if the field has already been detected or not. if(!isset($fields[$field])) { $fields[$field] = \rainhawk\data::detect($value); } else { $type = \rainhawk\data::detect($value); // Check if the field type is in-line. if($fields[$field] == $type) { continue; } else if($fields[$field] == \rainhawk\data::INTEGER && $type == \rainhawk\data::FLOAT) { $fields[$field] == \rainhawk\data::FLOAT; } else if($fields[$field] == \rainhawk\data::FLOAT && $type == \rainhawk\data::INTEGER) { continue; } else { $fields[$field] = "unknown"; } } } } // Strip the already-constrained fields. if(!empty($dataset->constraints)) { foreach($dataset->constraints as $field => $constraint) unset($fields[$field]); } // Check if there are any constraints to add. if(empty($fields)) { echo json_beautify(json_render_error(408, "No unconstrained fields were found during automatic detection.")); exit; } // Set the JSON array. $json['detected'] = array(); // Add the new constraints. foreach($fields as $field => $type) { if($type == "unknown") { // Set the JSON output. $json['detected'][$field] = array( "type" => "unknown" ); } else { // Set the constraint on the field. $dataset->constraints[$field] = array( "type" => $type ); // Store the dataset information in the index table. \rainhawk\sets::update($dataset); // Set the JSON output. $json['detected'][$field] = array( "type" => $type ); } } } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php require_once "includes/core.php"; require_once "includes/check_login.php"; ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Create Dataset</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> <style type="text/css"> .row .form-controls { margin-top: 40px; } </style> <script> rainhawk.apiKey = "<?php echo $mashape_key; ?>"; $(function() { $("form").submit(function(e) { var $submit = $(this).find("button[type=submit]"); var dataset = $("#datasetName").val(); var description = $("#datasetDescription").val(); $submit.attr("disabled", true); rainhawk.datasets.create(dataset, description, function(data) { $(".container:last").prepend($('<div class="alert alert-success fade in"></div>') .append($('<span><strong>Success!</strong> Dataset <a class="alert-link" href="/edit.php?dataset=' + data.name + '">' + data.name + '</a> successfully created.&nbsp;</span>')) .append($('<span>Now try <a class="alert-link" href="/upload.php?dataset=' + data.name + '">uploading</a> some data.</span>')) .append($('<button type="button" class="close pull-right" data-dismiss="alert" aria-hidden="true">&times;</button>')) ); }, function(message) { $(".container:last").prepend($('<div class="alert alert-danger fade in"></div>') .append($('<strong>Error!</strong>&nbsp;')) .append(message) .append($('<button type="button" class="close pull-right" data-dismiss="alert" aria-hidden="true">&times;</button>')) ); $submit.removeAttr("disabled"); }); return false; }); }); </script> </head> <body> <?php require_once "includes/nav.php"; ?> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <h1>Create a new dataset...</h1> <p>Get started here by entering a unique name for your dataset along with a description for what this dataset will hold.</p> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <form role="form"> <div class="form-group"> <label for="datasetName">Dataset Name:</label> <div class="input-group"> <span class="input-group-addon"><?php echo $user; ?>.</span> <input type="text" class="form-control" id="datasetName" name="datasetName" placeholder="Enter the name of the dataset..." required autofocus> </div> </div> <div class="form-group"> <label for="datasetDescription">Dataset Description:</label> <input type="text" class="form-control" id="datasetDescription" name="datasetDescription" placeholder="Enter a description for this dataset..." required> </div> <div class="form-controls"> <button type="submit" class="btn btn-default">Submit</button> <a href="/datasets.php" type="button" class="btn btn-danger">Back</a> </div> </form> </div> </div> </div> </div> </div> </body> </html> <file_sep>#include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> #include <typeinfo> #include <functional> #include "sadUtils.hpp" #include "sadReader.hpp" const char TEST_DELIM = '#'; const char* TESTING_PATH = "tests"; using namespace std; //////////////////////////////////////////////////////////////////////////////// //////// TEXT FUNCTIONS //////////////////////////////////////////////////////////////////////////////// bool convertBool( std::string &data, bool &v ) { std::string input = toUpper( data ); if( input == "TRUE" ) { v = true; return true; } if( input == "FALSE" ) { v = false; return true; } return false; } bool whitespace( char c ) { if( c == ' ' || c == '\n' || c == '\r' || c == '\t' ) return true; return false; } string toUpper( string input ) { string output = input; for( string::iterator it = output.begin(); it != output.end(); ++it ) { if( (*it >= 'a') && (*it <= 'z') ) { *it += 'A' - 'a'; } } return output; } string tab( unsigned size, char tabc, unsigned tabw ) { string output; for( unsigned it = 0; it < size*tabw; it++ ) output += tabc; return output; } //////////////////////////////////////////////////////////////////////////////// //////// TESTING FUNCTIONS //////////////////////////////////////////////////////////////////////////////// // All test files should be named after their function (i.e. the test for the // function "increment" should also be "increment") and must consist of the // following format: // # // <Test Data A1>#<Test Data A2>#...#<Test Data An> // <Test Data B1>#<Test Data B2>#...#<Test Data Bn> // ... // # // <Test Result A> // <Test Result B> // ... // # // // Where '#' = TEST_DELIM, and must not contain any other instances symbols. // // For loading test data, the "error" argument is set to the result of the // attempt: // 0: Success // 1: File I/O error // 2: Invalid test file // 3: EOF reached early template <class V> struct LoadTest { vector<V> operator() ( string fname, unsigned index, unsigned &error, unsigned &pof ) { pof = 0; char line[MAX_READ_SIZE]; vector<V> output; string filepath = TESTING_PATH; filepath += "/" + fname; // Simple file-access stuff ifstream ifs ( filepath.c_str() ); if( !ifs.good() ) { error = 1; return output; } ifs.getline( line, MAX_READ_SIZE ); pof++; if( ifs.good() ) { // Verifying that the file matches the format if( line[0] != TEST_DELIM ) { error = 2; return output; } // Loops through lines of test data ifs.getline( line, MAX_READ_SIZE ); pof++; while( line[0] != TEST_DELIM && ifs.good() ) { //Extract the indexed data into a string string data (line); size_t pos = 0; for( unsigned i = 0; i < index; i++ ) { pos = data.find( TEST_DELIM, pos ); if( pos == string::npos ) { error = 2; return output; } pos++; } data = data.substr( pos ); pos = data.find( TEST_DELIM ); if( pos != string::npos ) data = data.substr( 0, pos ); // The magic happens... V next; if( !convertData( data, next ) ) { error = 2; return output; } output.push_back( next ); ifs.getline( line, MAX_READ_SIZE ); pof++; } if( !ifs.fail() && line[0] == TEST_DELIM ) { error = 0; return output; } } if( ifs.fail() ) error = 1; else error = 3; return output; } }; template <class V> struct LoadResult { vector<V> operator() ( string fname, unsigned &error, unsigned &pof ) { pof = 0; char line[MAX_READ_SIZE]; vector<V> output; string filepath = TESTING_PATH; filepath += "/" + fname; // Simple file-access stuff ifstream ifs ( filepath.c_str() ); if( !ifs.good() ) { error = 1; return output; } ifs.getline( line, MAX_READ_SIZE ); pof++; if( ifs.good() ) { // Verifying that the file matches the format if( line[0] != TEST_DELIM ) { error = 2; return output; } // Loops through all of the test data, doing nothing ifs.getline( line, MAX_READ_SIZE ); pof++; while( line[0] != TEST_DELIM && ifs.good() ) { ifs.getline( line, MAX_READ_SIZE ); pof++; } if( ifs.good() ) { // Loops through all of the test results, adding them to the output ifs.getline( line, MAX_READ_SIZE ); pof++; while( line[0] != '#' && ifs.good() ) { V next; string data = line; if( !convertData( data, next ) ) { error = 2; return output; } output.push_back( next ); ifs.getline( line, MAX_READ_SIZE ); pof++; } // Confirm there are no stream errors, with the exception of EOF if( !ifs.fail() ) { error = 0; return output; } } } if( ifs.fail() ) error = 1; else error = 3; return output; } }; template <class T> vector<T> getData( LoadResult<T> loadResult, string fname, unsigned index, ostream &out, unsigned ind, unsigned &error ) { unsigned pof; vector<T> data = loadResult( fname, error, pof ); if( error != 0 ) { switch( error ) { case 1: if( pof == 0 ) { out << tab(ind) << "ERROR: I/O error while trying to open test " << " file." << '\n'; } else { out << tab(ind) << "ERROR: I/O error occured on line " << pof << " of test file." << '\n'; } break; case 2: out << tab(ind) << "ERROR: Invalid input on line " << pof << " of test file." << '\n'; break; case 3: out << tab(ind) << "ERROR: End of file reached early." << '\n'; break; // Should not conceivably happen default: out << tab(ind) << "ERROR: Unknown error code received while " << " reading test file." << '\n'; break; } } return data; } template <class T> vector<T> getData( LoadTest<T> loadTest, string fname, unsigned index, ostream &out, unsigned ind, unsigned &error ) { unsigned pof; vector<T> data = loadTest( fname, index, error, pof ); if( error != 0 ) { switch( error ) { case 1: if( pof == 0 ) { out << tab(ind) << "ERROR: I/O error while trying to open test " << " file." << '\n'; } else { out << tab(ind) << "ERROR: I/O error occured on line " << pof << " of test file." << '\n'; } break; case 2: out << tab(ind) << "ERROR: Invalid input on line " << pof << " of test file." << '\n'; break; case 3: out << tab(ind) << "ERROR: End of file reached early." << '\n'; break; // Should not conceivably happen default: out << tab(ind) << "ERROR: Unknown error code received while " << " reading test file." << '\n'; break; } } return data; } template <class Ret, class A> bool runFunctionTests( function<Ret(A)> f, string fname, ostream &out, unsigned ind ) { // Obtains the test data unsigned error; LoadResult<Ret> loadResult; vector<Ret> resultData = getData( loadResult, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<A> loadTestA; vector<A> testA = getData( loadTestA, fname, 0, out, ind, error ); if( error != 0 ) return false; // Checks the volume of test data for validity vector<size_t> failures; size_t size = resultData.size(); if( size != testA.size() ) { out << tab(ind) << "ERROR: Different test and result pool sizes." << '\n'; return false; } vector<Ret> testResults; for( size_t it = 0; it < size; it++ ) { testResults.push_back( f(testA[it]) ); } for( size_t it = 0; it < size; it++ ) { if( resultData[it] != testResults[it] ) failures.push_back( it ); } if( failures.size() == 0 ) { out << tab(ind) << "SUCCESS: All " << size << " tests passed." << '\n'; return true; } out << tab(ind) << "FAILURE: Function failed the following tests:" << '\n'; ind++; for( vector<size_t>::iterator it = failures.begin(); it != failures.end(); it++ ) { out << tab(ind) << *it << '\n'; } ind--; return false; } template <class Ret, class A, class B> bool runFunctionTests( function<Ret(A,B)> f, string fname, ostream &out, unsigned ind ) { // Obtains the test data unsigned error; LoadResult<Ret> loadResult; vector<Ret> resultData = getData( loadResult, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<A> loadTestA; vector<A> testA = getData( loadTestA, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<B> loadTestB; vector<B> testB = getData( loadTestB, fname, 1, out, ind, error ); if( error != 0 ) return false; // Checks the volume of test data for validity vector<size_t> failures; size_t size = resultData.size(); if( size != testA.size() ) { out << tab(ind) << "ERROR: Different test and result pool sizes." << '\n'; return false; } vector<Ret> testResults; for( size_t it = 0; it < size; it++ ) { testResults.push_back( f(testA[it],testB[it]) ); } for( size_t it = 0; it < size; it++ ) { if( resultData[it] != testResults[it] ) failures.push_back( it ); } if( failures.size() == 0 ) { out << tab(ind) << "SUCCESS: All " << size << " tests passed." << '\n'; return true; } out << tab(ind) << "FAILURE: Function failed the following tests:" << '\n'; ind++; for( vector<size_t>::iterator it = failures.begin(); it != failures.end(); it++ ) { out << tab(ind) << *it << '\n'; } ind--; return false; } template <class Ret, class A, class B, class C> bool runFunctionTests( function<Ret(A,B,C)> f, string fname, ostream &out, unsigned ind ) { // Obtains the test data unsigned error; LoadResult<Ret> loadResult; vector<Ret> resultData = getData( loadResult, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<A> loadTestA; vector<A> testA = getData( loadTestA, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<B> loadTestB; vector<B> testB = getData( loadTestB, fname, 1, out, ind, error ); if( error != 0 ) return false; LoadTest<C> loadTestC; vector<C> testC = getData( loadTestC, fname, 2, out, ind, error ); if( error != 0 ) return false; // Checks the volume of test data for validity vector<size_t> failures; size_t size = resultData.size(); if( size != testA.size() ) { out << tab(ind) << "ERROR: Different test and result pool sizes." << '\n'; return false; } vector<Ret> testResults; for( size_t it = 0; it < size; it++ ) { testResults.push_back( f(testA[it],testB[it],testC[it]) ); } for( size_t it = 0; it < size; it++ ) { if( resultData[it] != testResults[it] ) failures.push_back( it ); } if( failures.size() == 0 ) { out << tab(ind) << "SUCCESS: All " << size << " tests passed." << '\n'; return true; } out << tab(ind) << "FAILURE: Function failed the following tests:" << '\n'; ind++; for( vector<size_t>::iterator it = failures.begin(); it != failures.end(); it++ ) { out << tab(ind) << *it << '\n'; } ind--; return false; } template <class Ret, class A, class B, class C, class D > bool runFunctionTests( function<Ret(A,B,C,D)> f, string fname, ostream &out, unsigned ind ) { // Obtains the test data unsigned error; LoadResult<Ret> loadResult; vector<Ret> resultData = getData( loadResult, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<A> loadTestA; vector<A> testA = getData( loadTestA, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<B> loadTestB; vector<B> testB = getData( loadTestB, fname, 1, out, ind, error ); if( error != 0 ) return false; LoadTest<C> loadTestC; vector<C> testC = getData( loadTestC, fname, 2, out, ind, error ); if( error != 0 ) return false; LoadTest<D> loadTestD; vector<D> testD = getData( loadTestD, fname, 3, out, ind, error ); if( error != 0 ) return false; // Checks the volume of test data for validity vector<size_t> failures; size_t size = resultData.size(); if( size != testA.size() ) { out << tab(ind) << "ERROR: Different test and result pool sizes." << '\n'; return false; } vector<Ret> testResults; for( size_t it = 0; it < size; it++ ) { testResults.push_back( f(testA[it],testB[it],testC[it],testD[it]) ); } for( size_t it = 0; it < size; it++ ) { if( resultData[it] != testResults[it] ) failures.push_back( it ); } if( failures.size() == 0 ) { out << tab(ind) << "SUCCESS: All " << size << " tests passed." << '\n'; return true; } out << tab(ind) << "FAILURE: Function failed the following tests:" << '\n'; ind++; for( vector<size_t>::iterator it = failures.begin(); it != failures.end(); it++ ) { out << tab(ind) << *it << '\n'; } ind--; return false; } template <class Ret, class A, class B, class C, class D, class E> bool runFunctionTests( function<Ret(A,B,C,D,E)> f, string fname, ostream &out, unsigned ind ) { // Obtains the test data unsigned error; LoadResult<Ret> loadResult; vector<Ret> resultData = getData( loadResult, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<A> loadTestA; vector<A> testA = getData( loadTestA, fname, 0, out, ind, error ); if( error != 0 ) return false; LoadTest<B> loadTestB; vector<B> testB = getData( loadTestB, fname, 1, out, ind, error ); if( error != 0 ) return false; LoadTest<C> loadTestC; vector<C> testC = getData( loadTestC, fname, 2, out, ind, error ); if( error != 0 ) return false; LoadTest<D> loadTestD; vector<D> testD = getData( loadTestD, fname, 3, out, ind, error ); if( error != 0 ) return false; LoadTest<E> loadTestE; vector<E> testE = getData( loadTestE, fname, 4, out, ind, error ); if( error != 0 ) return false; // Checks the volume of test data for validity vector<size_t> failures; size_t size = resultData.size(); if( size != testA.size() ) { out << tab(ind) << "ERROR: Different test and result pool sizes." << '\n'; return false; } vector<Ret> testResults; for( size_t it = 0; it < size; it++ ) { testResults.push_back( f(testA[it],testB[it],testC[it],testD[it],testE[it]) ); } for( size_t it = 0; it < size; it++ ) { if( resultData[it] != testResults[it] ) failures.push_back( it ); } if( failures.size() == 0 ) { out << tab(ind) << "SUCCESS: All " << size << " tests passed." << '\n'; return true; } else { out << tab(ind) << "FAILURE: Function failed the following tests:" << '\n'; ind++; for( vector<size_t>::iterator it = failures.begin(); it != failures.end(); it++ ) { out << tab(ind) << *it << '\n'; } ind--; } return false; } <file_sep><?php require "framework/UnitTest.php"; require "../includes/kernel.php"; array_shift($argv); if(empty($argv)) { echo "Usage: php run.php Class\n"; exit; } if($argv[0] == "suite" || $argv[0] == "all") { $files = glob("test*.php"); $files = array_diff($files, array("testSuite.php")); foreach($files as $file) { $classes = get_declared_classes(); require_once $file; $diff = array_diff(get_declared_classes(), $classes); $class = reset($diff); $test = new $class; $test->exec(); } } else { foreach($argv as $class) { $class = str_replace("\\", "", $class); $file = "test" . $class . ".php"; $class = $class . "Test"; if(file_exists($file)) { require_once $file; $test = new $class; $test->exec(); } } } ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_read_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to read from this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "coefficients" => array() ); /*! * Pipe the command to our Python script to calculate the coefficients * of the polynomial using NumPy. */ $dataset = escapeshellarg($data->dataset); $degree = $data->degree; // Check that the two fields are set. if(!is_array($data->fields) || !(count($data->fields) == 2)) { echo json_beautify(json_render_error(404, "You didn't specify the two fields to use!")); exit; } // Set the fields. $field_one = escapeshellarg($data->fields[0]); $field_two = escapeshellarg($data->fields[1]); // Run the command. exec("python '../correlation/correlation.py' eco " . $dataset . " " . $field_one . " " . $field_two . " " . $degree, $output); // Check for empty output. if(empty($output)) { echo json_beautify(json_render_error(405, "Couldn't find a polyfit equation for the given datasets.")); exit; } // Output the coefficients. foreach($output as $line) { $data = json_decode($line, true); if(is_array($data)) { $json['coefficients'] = $data; } } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep>#include <string> #include <vector> #include "sadReader.hpp" #include "sadUtils.hpp" #include "sadTables.hpp" #include "sadWriter.hpp" using namespace std; const unsigned edges[4][6] = { { 0, 1, 2, 3, 4, 5 }, { 3, 4, 5, 6, 7, 8 }, { 0, 1, 3, 4, 6, 7 }, { 1, 2, 4, 5, 7, 8 } }; const unsigned corners[4][6] = { { 0, 1, 3, 4 }, { 1, 2, 4, 5 }, { 3, 4, 6, 7 }, { 4, 5, 7, 8 } }; item idProperty( vector<JType> adj ) { item r; // Header r.header = 0; if( adj[3] == STRING ) r.header++; if( adj[4] == STRING ) r.header += 2; if( adj[5] == STRING ) r.header++; // Edge for( size_t it = 0; it < 4; it++ ) { r.edge[it] = 0; if( adj[edges[it][0]] != NULLVALUE ) r.edge[it]++; if( adj[edges[it][1]] != NULLVALUE ) r.edge[it]++; if( adj[edges[it][2]] != NULLVALUE ) r.edge[it]++; if( adj[edges[it][3]] != NULLVALUE ) r.edge[it]++; if( adj[edges[it][4]] != NULLVALUE ) r.edge[it]++; if( adj[edges[it][5]] != NULLVALUE ) r.edge[it]++; } // Corner for( size_t it = 0; it < 4; it++ ) { r.corner[it] = 0; if( adj[corners[it][0]] != NULLVALUE ) r.corner[it]++; if( adj[corners[it][1]] != NULLVALUE ) r.corner[it]++; if( adj[corners[it][2]] != NULLVALUE ) r.corner[it]++; if( adj[corners[it][3]] != NULLVALUE ) r.corner[it]++; } // Tuple r.tuple = 0; for( size_t it = 0; it < 9; it++ ) if( adj[it] != NULLVALUE ) r.tuple++; // Vertical bridge r.vbridge[0] = 0; r.vbridge[1] = 0; r.vbridge[2] = 0; if( adj[6] != NULLVALUE ) { r.vbridge[0]++; r.vbridge[1]++; } if( adj[7] != NULLVALUE ) { r.vbridge[0]++; r.vbridge[1]++; r.vbridge[2]++; } if( adj[8] != NULLVALUE ) { r.vbridge[1]++; r.vbridge[2]++; } // Horizontal bridge r.hbridge = false; if( adj[3] != NULLVALUE && adj[5] != NULLVALUE && ( ( adj[0] != NULLVALUE && adj[2] != NULLVALUE ) || ( adj[6] != NULLVALUE && adj[8] != NULLVALUE ) ) ) { r.hbridge = true; } // End return r; } vector< vector<item> > propertyGrid( sheet sh ) { size_t rows = sh.rows(); size_t cols = sh.cols(); vector< vector<item> > properties; for( size_t row = 0; row < rows; row++ ) { vector<item> propertyrow; for( size_t col = 0; col < cols; col++ ) { vector<JType> adj; for( int x = row-1; x <= (int)row+1; x++ ) { for( int y = col-1; y <= (int)col+1; y++ ) { if( x<0 || x>(int)rows-1 || y<0 || y>(int)cols-1 ) adj.push_back( NULLVALUE ); else adj.push_back( sh[x][y].getType() ); } } propertyrow.push_back( idProperty( adj ) ); } properties.push_back( propertyrow ); } return properties; } int evalVBridge( const vector< vector<item> > &pgrid, size_t crow, size_t start, size_t end ) { int midN = 2; int edgeN = 1; int score = 0; score += (int)pgrid[crow][start].vbridge[2] - edgeN; score += (int)pgrid[crow][end].vbridge[0] - edgeN; for( size_t it = start + 1; it < end; it++ ) { score += (int)pgrid[crow][it].vbridge[1] - midN; } return score; } int evalTopRow( const vector< vector<item> > &pgrid, size_t crow, size_t start, size_t end ) { int edgeN = 4; int cornerN = 3; int score = 0; score += (int)pgrid[crow][start].corner[3] - cornerN; score += (int)pgrid[crow][end].corner[2] - cornerN; for( size_t it = start + 1; it < end; it++ ) { score += (int)pgrid[crow][it].edge[1] - edgeN; } return score; } trow evalRow( const vector< vector<item> > &pgrid, size_t crow, size_t start, size_t end ) { int tupleN = 6; int edgeN = 4; int cornerN = 3; trow thisrow; thisrow.mid = 0; thisrow.bot = 0; thisrow.mid += (int)pgrid[crow][start].edge[3] - edgeN; thisrow.mid += (int)pgrid[crow][end].edge[2] - edgeN; thisrow.bot += (int)pgrid[crow][start].corner[1] - cornerN; thisrow.bot += (int)pgrid[crow][end].corner[0] - cornerN; for( size_t it = start + 1; it < end; it++ ) { thisrow.mid += (int)pgrid[crow][it].tuple - tupleN; thisrow.bot += (int)pgrid[crow][it].edge[0] - edgeN; } return thisrow; } vector<tableRating> evalTableBody( const vector< vector<item> > &pgrid, vector< vector<bool> > &allowed, size_t x1, size_t x2, size_t y ) { size_t crow = y+1; bool remaining = true; unsigned population = ( ((x2-x1)*(x2-x1)) + (x2-x1) )/2; tableRating nothingness; nothingness.score = 0; nothingness.depth = 0; vector<tableRating> scores( population, nothingness ); while( crow < pgrid.size() && remaining ) { remaining = false; size_t selection = 0; for( size_t start = x1; start < x2; start++ ) { for( size_t end = start+1; end <= x2; end++ ) { if( allowed[start-x1][end-start-1] ) { trow thisrow = evalRow( pgrid, crow, start, end ); if( crow == y+1 ) { int bridgeScore = evalVBridge( pgrid, crow, start, end ); if( bridgeScore > thisrow.mid ) thisrow.mid = bridgeScore; } if( crow == y+2 ) { int topScore = evalTopRow( pgrid, crow, start, end ); if( topScore > thisrow.mid ) thisrow.mid = topScore; } if( thisrow.mid > 0 || thisrow.bot > 0 ) { if( thisrow.mid >= thisrow.bot ) { remaining = true; scores[selection].score += thisrow.mid; scores[selection].depth++; } else { allowed[start-x1][end-start-1] = false; scores[selection].score += thisrow.bot; scores[selection].depth++; } } else allowed[start-x1][end-start-1] = false; } selection++; } } crow++; } return scores; } // Only call when tbl.x1, tbl.x2, and tbl.y1 have been initialized bool idTable( const vector< vector<item> > &pgrid, size_t x1, size_t x2, size_t y, table &result ) { // Filter out headers at the bottom of the sheet if( pgrid.size() <= y+1 ) return false; // A diagonal grid representing each possible combination of x1 and x2 values vector< vector<bool> > allowed; for( size_t start = x1; start < x2; start++ ) { vector<bool> endpoints; for( size_t end = start+1; end <= x2; end++ ) { endpoints.push_back( true ); } allowed.push_back( endpoints ); } // Loops through each row, determining all the ways it may be valid. Ends // either at the end of the grid or when the last row has no more valid forms. vector<tableRating> scores = evalTableBody( pgrid, allowed, x1, x2, y ); int max = -1; unsigned current = 0; for( size_t start = x1; start < x2; start++ ) { for( size_t end = start+1; end <= x2; end++ ) { // end << "," << scores[current].depth << "] : " << scores[current].score << '\n'; if( scores[current].score > max ) { result.x1 = start; result.x2 = end; result.y1 = y; result.y2 = y + scores[current].depth; result.score = scores[current].score; max = scores[current].score; } current++; } } if( result.y1 != result.y2 ) return true; return false; } bool containedIn( table a, table b ) { if( a.x1 >= b.x1 && a.x2 <= b.x2 && a.y1 >= b.y1 && a.y2 <= b.y2 ) return true; return false; } vector<table> scanTables( const vector< vector<item> > &pgrid ) { vector<table> result; size_t rows = pgrid.size(); size_t cols = pgrid[0].size(); for( size_t row = 0; row < rows; row++ ) { table tbl; unsigned heads = 0; for( size_t col = 0; col < cols; col++ ) { if( pgrid[row][col].header >= 4 ) { // This shouldn't theoretically be possible at all given a valid grid. if( heads == 0 ) { tbl.x1 = col; tbl.y1 = row; } heads++; } else { if( heads > 0 ) { tbl.x2 = col; tbl.y2 = tbl.y1; bool contained = false; for( vector<table>::iterator it = result.begin(); it != result.end(); it++ ) { if( containedIn( tbl, *it ) ) contained = true; } if( !contained ) if( idTable( pgrid, tbl.x1, tbl.x2, tbl.y1, tbl ) ) { result.push_back( tbl ); } heads = 0; } else if( pgrid[row][col].header == 3 ) { tbl.x1 = col; tbl.y1 = row; heads++; } else heads = 0; } } } return result; } void printProp( vector< vector<item> > pg ) { for( size_t x = 0; x < pg.size(); x++ ) { for( size_t y = 0; y < pg[x].size(); y++ ) { cout << "[" << x << "," << y << "]: "; cout << "H: " << pg[x][y].header << ", "; cout << "E: " << pg[x][y].edge[0] << "," << pg[x][y].edge[1] << "," << pg[x][y].edge[2] << "," << pg[x][y].edge[3] << ", "; cout << "C: " << pg[x][y].corner[0] << "," << pg[x][y].corner[1] << "," << pg[x][y].corner[2] << "," << pg[x][y].corner[3] << ", "; cout << "T: " << pg[x][y].tuple << ", "; cout << "V: " << pg[x][y].vbridge[0] << "," << pg[x][y].vbridge[1] << "," << pg[x][y].vbridge[2]; cout << '\n'; } } } unsigned clashDegree( table a, table b ) { if( a.x1 > b.x2 || a.x2 < b.x1 ) return 0; else { if( a.y1 > b.y2 || a.y2 < b.y1 ) return 0; else return 1; } } void removeClashes( vector<table> &input ) { size_t current = 0; while( current < input.size() ) { size_t next = current + 1; while( next < input.size() ) { if( clashDegree( input[current], input[next] ) > 0 ) { if( input[next].score > input[current].score ) { input.erase( input.begin() + current ); current = 0; next = current + 1; } else input.erase( input.begin() + next ); } else next++; } current++; } } vector<table> getSheetTables( sheet sh ) { vector< vector<item> > pgrid = propertyGrid( sh ); vector<table> result = scanTables( pgrid ); removeClashes( result ); return result; } <file_sep>#ifndef SAD_TABLES #define SAD_TABLES struct item { unsigned header; unsigned edge[4]; unsigned corner[4]; unsigned tuple; unsigned vbridge[3]; bool hbridge; }; struct trow { long int mid; long int bot; }; struct table { size_t x1; size_t x2; size_t y1; size_t y2; long int score; }; struct tableRating { long int score; size_t depth; }; std::vector<table> getSheetTables( sheet sh ); #endif <file_sep>#ifndef SAD_UTILS #define SAD_UTILS #include <string> #include <sstream> #include <fstream> #include <vector> #include <functional> extern const char* TESTING_PATH; const unsigned MAX_READ_SIZE = 256; std::string tab( unsigned size, char tabc = ' ', unsigned tabw = 2 ); std::string toUpper( std::string input ); bool whitespace( char c ); // Templated Functions bool convertBool( std::string &data, bool &v ); // Generic string-to-data function // Only works with data types that can be converted by a stringstream template<class V> bool convertData( std::string &data, V &v ) { std::istringstream ss(data); ss >> v; if( ss.fail() || !ss.eof() ) return false; else return true; } // Generic testing function template <class Ret, class... Args> bool testFunction( std::function<Ret(Args...)> f, std::string fname, std::ostream &out, unsigned ind ) { int argc = sizeof...(Args); out << tab(ind) << "Testing function " << fname << "..." << '\n'; if( argc > 5 ) { out << tab(ind) << "ERROR: Too many arguments to function." << '\n'; return false; } if( argc < 1 ) { out << tab(ind) << "ERROR: Too few arguments to function." << '\n'; return false; } return runFunctionTests( f, fname, out, ind ); } #endif <file_sep>#include <iostream> #include <vector> #include <cstdio> #include <cstring> #include "sadReader.hpp" #include "sadTables.hpp" #include "sadWriter.hpp" using namespace std; int main( int argc, char * argv[] ) { if( argc == 1 ) { cout << "Usage: sadparser [filenames]" << '\n'; return 0; } else if( argc == 2 ) { if( strcmp( argv[1], "help" ) == 0 ) { cout << "Usage: sadparser [filenames]" << '\n'; return 0; } } for( int cfile = 1; cfile < argc; cfile++ ) { string filename = argv[cfile]; if( filename[0] == '-' ) { if( filename.compare("-n") == 0 ) { //Placeholder text continue; } else { cout << "Flag not recognized: \"" << filename << "\"" << '\n'; continue; } } cout << "Now reading file " << argv[cfile] << "..." << '\n'; cout << "Getting contents..." << '\n'; unsigned error = 0; vector<sheet> fileContents = readFile( filename, error ); if( error == 0 ) { cout << "Processing contents..." << '\n'; vector< vector<table> > tablesOfSheets; for( vector<sheet>::iterator it = fileContents.begin(); it != fileContents.end(); it++ ) { vector<table> tableList = getSheetTables( *it ); tablesOfSheets.push_back( tableList ); } cout << "Printing contents..." << '\n'; unsigned count = 0; for( size_t it = 0; it < fileContents.size(); it++ ) { string title = filename.substr( 0, filename.find_last_of('.') ); char * newFilename = new char[title.size()+5]; sprintf( newFilename, "%s-%02d", title.c_str(), count+1 ); string filetitle( newFilename ); vector<string> fileList = jsonFile( filetitle, fileContents[it], tablesOfSheets[it] ); for( size_t ot = 0; ot < fileList.size(); ot++ ) { cout << fileList[ot] << " created." << '\n'; } count++; } } else { switch( error ) { case 1: cout << "ERROR: Failure in file access operations." << '\n'; break; case 2: case 3: cout << "ERROR: Invalid file contents." << '\n'; break; default: cout << "ERROR: Unknown error code, something is wrong." << '\n'; break; } } } cout << "All done." << '\n'; return 0; } <file_sep><?php require_once "includes/core.php"; require_once "includes/check_login.php"; $datasetsInfo = $rainhawk->listDatasets(); ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Datasets</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> <script> $(function() { $(".confirm").confirm({ text: "Are you sure you wish to delete this dataset? This action is irreversible!", title: "Really?", confirmButton: "Delete" }); }); </script> </head> <body> <?php require_once "includes/nav.php"; ?> <div class="container"> <?php if(isset($_GET['deletefailed'])) { ?> <div class="row"> <div class="alert alert-danger fade in"> <strong>Error!</strong> Deletion failed <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> </div> </div> <?php } else if(isset($_GET['deleted'])) { ?> <div class="row"> <div class="alert alert-success fade in"> <strong>Gone!</strong> Dataset successfully deleted. <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> </div> </div> <?php } ?> <div class="row"> <table class="table"> <thead> <tr> <th>Name</th> <th>Description</th> <th>Records</th> <th>Fields</th> <th>Access</th> <th></th> <th></th> <th></th> <th></th> </tr> </head> <tbody> <?php foreach($datasetsInfo as $dataset) { ?> <tr> <td><a href="/properties.php?dataset=<?php echo $dataset['name']; ?>"><?php echo $dataset['name']; ?></a></td> <td><?php echo $dataset['description']; ?></td> <td><?php echo $dataset['rows']; ?></td> <td><?php echo count($dataset['fields']); ?></td> <td><?php echo in_array($user, $dataset['write_access']) ? "Write" : "Read"; ?></td> <td> <a href="/edit.php?dataset=<?php echo $dataset['name']; ?>" class="btn btn-info btn-sm"> <i class="fa fa-edit"></i>&nbsp; View </a> </td> <td> <a href="/visualise/?dataset=<?php echo $dataset['name']; ?>" class="btn btn-success btn-sm" <?php echo $dataset['rows'] == 0 ? "disabled" : null; ?>> <i class="fa fa-bar-chart-o"></i>&nbsp; Visualise </a> </td> <td> <a href="/upload.php?dataset=<?php echo $dataset['name']; ?>" class="btn btn-primary btn-sm" <?php echo !in_array($user, $dataset['write_access']) ? "disabled" : null; ?>> <i class="fa fa-cloud-upload"></i>&nbsp; Upload </a> </td> <td> <a href="/proxy/delete_dataset.php?dataset=<?php echo $dataset['name']; ?>" id="del<?php echo explode(".", $dataset['name'])[1]; ?>" class="btn btn-danger btn-sm confirm" <?php echo !in_array($user, $dataset['write_access']) ? "disabled" : null; ?>> <i class="fa fa-ban"></i>&nbsp; Delete </a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </body> </html> <file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; header("content-type: application/json; charset=utf8"); $dataset = isset($_GET['dataset']) ? $_GET['dataset'] : null; $idvalue = isset($_POST['_id']) ? $_POST['_id'] : null; $changes = array(); foreach($_POST as $name => $value) { if($name == "dataset") continue; if($name == "_id") continue; $changes[$name] = $value; } $query = array( "_id" => $idvalue ); $changes = array( '$set' => $changes ); $result = $rainhawk->updateData($dataset, $query, $changes); if(!$result) { echo json_encode(array( "Result" => "ERROR", "Message" => $rainhawk->error() )); exit; } echo json_encode(array( "Result" => "OK" )); exit; ?> <file_sep><?php require_once "includes/core.php"; if(isset($_POST['apiKey'])) { $mashape_key = trim($_POST['apiKey']); $rainhawk = new Rainhawk($mashape_key); $ping = $rainhawk->ping(); $user = null; if($ping) { $user = $ping['mashape_user']; } if(empty($user)) { header("Location: /login.php?fail"); exit; } else { $location = isset($_GET['dest']) ? urldecode($_GET['dest']) : "/datasets.php"; $_SESSION['apiKey'] = $mashape_key; $_SESSION['user'] = $user; header("Location: " . $location); exit; } } if(isset($_SESSION['apiKey']) && isset($_SESSION['user']) && !isset($_GET['logout'])) { header("Location: /datasets.php"); exit; } if(isset($_GET['logout'])) { session_unset(); } ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Login</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> </head> <body> <?php require_once "includes/nav.php"; ?> <div class="container"> <?php if(isset($_GET['dest'])) { ?> <div class="alert alert-danger"> <p>You need to be logged in to access this page!</p> </div> <?php } ?> <?php if(isset($_GET['fail'])) { ?> <div class="alert alert-danger"> <p>Your API key could not be validated with the service, please try again.</p> </div> <?php } ?> <?php if(isset($_GET['logout'])) { ?> <div class="alert alert-success"> <p>Successfully logged out.</p> </div> <?php } ?> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <h1>Login to manage your data!</h1> <p>Please insert your Mashape API key...</p> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <form action="login.php<?php echo isset($_GET['dest']) ? "?dest=" . $_GET['dest'] : null; ?>" role="form" method="post"> <div class="form-group <?php echo isset($_GET['fail']) ? "has-error" : null; ?>"> <label for="apiKey">API Key:</label> <input type="text" placeholder="Enter your API key here..." name="apiKey" class="form-control" autofocus> </div> <button type="submit" class="btn btn-default">Login</button> </form> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <h3><i class="fa fa-key"></i>&nbsp; Don't have an API key?</h3> <p>Register an API key for Project Rainhawk at <a href="https://www.mashape.com/sneeza/project-rainhawk">Mashape.com</a>.</p> </div> </div> </div> </div> </div> </body> </html> <file_sep>Guidelines for working on the frontend --- * All JavaScript and JS libraries should be placed in js/ . * All images in img/ . * Example visualizations showcasing the app will be placed in visualizations/example/ * Best to use the minified versions of the libraries. <file_sep>#include <string> #include <vector> #include "sadReader.hpp" #include "sadTables.hpp" std::vector<std::string> jsonFile( std::string filename, sheet &sh, std::vector<table> tbls ); <file_sep><?php /** * Project Rainhawk * * Simple PHP wrapper for the Rainhawk API, which provides simple JSON * encoded data for a variety of data sources with pre-defined * operations. * * @package Rainhawk * @license none */ class Rainhawk { /** * Store some constants for the different request methods. * * @var string */ const GET = "GET"; const POST = "POST"; const PUT = "PUT"; const DELETE = "DELETE"; const PUT_FILE = "PUTFILE"; /** * Store the base address for the API. * * @var string */ private $host = "https://sneeza-eco.p.mashape.com"; /** * Store the Mashape API key to use for authentication to the * API. Without this, no requests will succeed. * * @var string */ private $mashapeKey = null; /** * Store the last known error number, which is fetched from the * API meta response. * * @var integer */ private $errno = null; /** * Store the last known error message, which is also fetched from * the API data response. * * @var string */ private $error = null; /** * When the class is initialised, we have to store the Mashape key * in the class for all requests. * * @param string $mashapeKey The mashape key to use for all requests. * @return eco Our new class instance. */ public function __construct($mashapeKey) { $this->mashapeKey = $mashapeKey; } /** * Send a simple ping request to the API, which will respond with * the timestamp of the server's current time. * * @return array|bool Returns the data array on success, false on failure. */ public function ping() { $url = $this->host . "/ping"; $data = $this->sendRequest($url, self::GET); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * Fetch a list of available datasets, in no particular order, returned * as an array from the API. We only get back the datasets that we have * read or write access to. * * @return array|bool Returns the datasets on success, false on failure. */ public function listDatasets() { $url = $this->host . "/datasets"; $data = $this->sendRequest($url, self::GET); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['datasets']; } /** * Get the dataset information, including the total rows and field * names. We can also use this to check whether or not the dataset * exists. * * @param string $name The dataset name. * @return array|bool Returns the data array on success, false on failure. */ public function fetchDataset($name) { $url = $this->host . "/datasets/" . $name; $data = $this->sendRequest($url, self::GET); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * Create a new dataset, with a specified name and description. These * are both mandatory. * * @param string $name The dataset's name. * @param string $description The dataset's description. * @return array|bool Returns the data array on success, false on failure. */ public function createDataset($name, $description) { $postData = array( "name" => $name, "description" => $description ); $url = $this->host . "/datasets"; $data = $this->sendRequest($url, self::POST, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * Delete the specified dataset, provided you have write access to the * set. This operation cannot be reversed. * * @param string $name The dataset's name. * @return bool Returns the boolean on success, false on failure. */ public function deleteDataset($name) { $url = $this->host . "/datasets/" . $name; $data = $this->sendRequest($url, self::DELETE); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['deleted']; } /** * Run a select query, finding results from a dataset that match * certain conditions. Optionally, leave the query blank to return * all rows. * * @param string $name The dataset name to query. * @param array $query The query to run, in MongoDB format. * @param int $offset Apply an offset on the query, for pagination. * @param int $limit Apply a row limit on the query. * @param array $sort The sorting order, in array format. * @param array $fields The fields to return from the query. * @param array $exclude The fields to exclude from the results. * @return array|bool Returns the data array on success, false on failure. */ public function selectData($name, $query = null, $offset = 0, $limit = 0, $sort = null, $fields = null, $exclude = null) { $query_string = array( "query" => json_encode($query), "offset" => $offset, "limit" => $limit, "sort" => json_encode($sort), "fields" => json_encode($fields), "exclude" => json_encode($exclude) ); $url = $this->host . "/datasets/" . $name . "/data"; $data = $this->sendRequest($url, self::GET, $query_string); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * Insert is an alias of insertMulti, and we just manipulate the * parameters passed to wrap one row to look like an array of * rows. * * @param string $name The dataset to insert rows into. * @param array $row The row to insert. * @return array|bool Returns the data array on success, false on failure. */ public function insertData($name, $row) { return $this->insertMultiData($name, array($row))[0]; } /** * Insert multiple rows into a dataset. The API will return * a success parameter as well as the number of rows added * which we can use to verify our request. * * @param string $name The dataset to insert the rows into. * @param array $rows The rows to insert. * @return array|bool Returns the data array on success, false on failure. */ public function insertMultiData($name, $rows) { $postData = array( "rows" => json_encode($rows) ); $url = $this->host . "/datasets/" . $name . "/data"; $data = $this->sendRequest($url, self::POST, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['rows']; } /** * Update documents using a query, which can be used to match * multiple or single documents. The change is essentially just * a diff for the record, and the magic keyword \$unset can be * sent to remove a field totally. * * @param string $name The dataset to update documents in. * @param array $query The query to use to find documents to update. * @param array $changes The changes to make. * @return array|bool Returns the data array on success, false on failure. */ public function updateData($name, $query, $changes) { $postData = array( "query" => json_encode($query), "changes" => json_encode($changes) ); $url = $this->host . "/datasets/" . $name . "/data"; $data = $this->sendRequest($url, self::PUT, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['updated']; } /** * Delete documents from the database using a query to match * documents in a specified dataset. * * @param string $name The dataset that we should delete rows from. * @param array $query The query to match rows to delete. * @return array|bool Returns the data array on success, false on failure. */ public function deleteData($name, $query) { $postData = array( "query" => json_encode($query) ); $url = $this->host . "/datasets/" . $name . "/data"; $data = $this->sendRequest($url, self::DELETE, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['deleted']; } /** * Upload a data file to the specified dataset. We currently support lots * of different types of files including .ods, .csv, .txt and more. * * @param string $name The dataset to insert the data into. * @param string $file The path to the file to upload. * @return array|bool Returns the data array on success, false on failure. */ public function uploadData($name, $file) { $fp = fopen($file, "rb"); $size = filesize($file); $postData = array( "fp" => $fp, "size" => $size ); $url = $this->host . "/datasets/" . $name . "/upload/" . pathinfo($file, PATHINFO_EXTENSION); $data = $this->sendRequest($url, self::PUT_FILE, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * List the indexes that have been created on a dataset. We * should have at least one on _id by default. * * @param string $name The dataset that we should list indexes on. * @return array|bool Returns the indexes on success, false on failure. */ public function listIndexes($name) { $url = $this->host . "/datasets/" . $name . "/indexes"; $data = $this->sendRequest($url, self::GET); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['indexes']; } /** * Remove an index from the specified dataset, which works on a single * field and will return a bool. * * @param string $name The dataset to remove an index on. * @param string $field The field to remove the index on. * @return bool Returns true or false. */ public function removeIndex($name, $field) { $postData = array( "field" => $field ); $url = $this->host . "/datasets/" . $name . "/indexes"; $data = $this->sendRequest($url, self::DELETE, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['removed']; } /** * Create an index on the specified dataset, which currently * only works on a single field. * * @param string $name The dataset to create an index on. * @param string $field The field to index. A blank field will cause auto-indexing. * @return array|bool Returns the data array on success, false on failure. */ public function addIndex($name, $field = null) { $postData = array( "field" => $field ); $url = $this->host . "/datasets/" . $name . "/indexes"; $data = $this->sendRequest($url, self::POST, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return !empty($field) ? $json['data']['added'] : $json['data']['detected']; } /** * Get the dataset's access list, which requires read access to view. Here * we can see which usernames have been given access to read and write from * and to the dataset. * * @param string $name The dataset name. * @return array|bool Returns the data array on success, false on failure. */ public function listAccess($name) { $url = $this->host . "/datasets/" . $name . "/access"; $data = $this->sendRequest($url, self::GET); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * Give a user access to the specified dataset, which requires you to * send the type and the username in a POST request. * * @param string $name The dataset to create an index on. * @param string $username The username to give access to. * @param string|array $type The type of access to give, "read" and "write". * @return array|bool Returns the data array on success, false on failure. */ public function giveAccess($name, $username, $type) { $postData = array( "username" => $username, "type" => is_array($type) ? json_encode($type) : $type ); $url = $this->host . "/datasets/" . $name . "/access"; $data = $this->sendRequest($url, self::POST, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['added']; } /** * Remove a user's access from the specified dataset, which requires * you to have write access to the set. * * @param string $name The dataset to create an index on. * @param string $username The username to remove access from. * @param string|null $type The type of access to give, "read" and "write", or null for both. * @return array|bool Returns the data array on success, false on failure. */ public function removeAccess($name, $username, $type = null) { $postData = array( "username" => $username, "type" => $type ); $url = $this->host . "/datasets/" . $name . "/access"; $data = $this->sendRequest($url, self::DELETE, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['removed']; } /** * List the constraints currently applied to a dataset. These constraints * are run on the data being returned from any endpoint that shows dataset * data. * * @param string $name The dataset to list the constraints on. * @return array|bool Returns the constraints on success, false on failure. */ public function listConstraints($name) { $url = $this->host . "/datasets/" . $name . "/constraints"; $data = $this->sendRequest($url, self::GET); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['constraints']; } /** * Add constraints to fields within a dataset. If the field name and type * are both left blank then the system will automatically determine the * type of each field and apply the constraints itself. * * @param string $name The dataset to apply the constraints to. * @param string $field The field to constrain. * @param string $type The type to constrain to. * @return mixed Returns the constraints on success, false on failure. */ public function addConstraint($name, $field = null, $type = null) { $postData = array( "field" => $field, "type" => $type ); $url = $this->host . "/datasets/" . $name . "/constraints"; $data = $this->sendRequest($url, self::POST, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return !empty($field) && !empty($type) ? $json['data']['added'] : $json['data']['detected']; } /** * Remove a constraint from a field, which requires that the above has * already been run on a field (or multiple). * * @param string $name The dataset to remove the constraints from. * @param string $field The field to unconstrain. * @return bool Returns true or false. */ public function removeConstraint($name, $field) { $postData = array( "field" => $field ); $url = $this->host . "/datasets/" . $name . "/constraints"; $data = $this->sendRequest($url, self::DELETE, $postData); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['removed']; } /** * Calculate the linear regression of two fields of data inside a * dataset, to the n-th degree. * * @param string $name The dataset that we run calculations on. * @param array $fields The two fields to use. * @param int $degree The degree of the polynomial. * @return array|bool Returns the coefficients on success, false on failure. */ public function calcPolyfit($name, $fields, $degree = 2) { $query_string = array( "fields" => json_encode($fields), "degree" => $degree ); $url = $this->host . "/datasets/" . $name . "/calc/polyfit"; $data = $this->sendRequest($url, self::GET, $query_string); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']['coefficients']; } /** * Calculate some statistics about a set of data, which can be * limited to a subset of data in a dataset using a query or the * entire table. * * @param string $name The dataset that we run calculations on. * @param string $field The field to run the calculations on. * @param array $query The query to run, in MongoDB format. * @return array|bool Returns the stats on success, false on failure. */ public function calcStats($name, $field, $query = array()) { $query_string = array( "field" => $field, "query" => $query ); $url = $this->host . "/datasets/" . $name . "/calc/stats"; $data = $this->sendRequest($url, self::GET, $query_string); $json = $this->parseJson($data); if(!$json) { return false; } return $json['data']; } /** * Return the last known error code, which can be populated from * the API or a failed cURL request. * * @return integer The error code. */ public function errno() { return $this->errno; } /** * Return the last known error message, which can be populated * from the API or a failed cURL request. * * @return string The error message. */ public function error() { return $this->error; } /** * Private function to parse JSON into an array, also setting * the error code and message in the class if necessary. * * @param string $data The JSON string. * @return array|bool The decoded JSON data on success, or false on failure. */ private function parseJson($data) { $json = json_decode($data, true); if(!is_array($json)) { $this->errno = 402; $this->error = "Invalid JSON received from API."; return false; } if($json['meta']['code'] !== 200) { $this->errno = $json['meta']['code']; $this->error = $json['data']['message']; return false; } return $json; } /** * Private function to make a cURL request to the API using two * different methods to send the data - POST and GET. * * @param string $url The web address to fetch. * @param string $method GET, POST, PUT or DELETE. * @param string $params The query parameters or POST parameters. * @param integer $timeout The timeout to use for the request. * @return string The response data from the request. */ private function sendRequest($url, $method, $params = null, $timeout = 10) { $ch = curl_init(); if($method == self::GET && !empty($params)) { $url .= "?" . http_build_query($params); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, "Rainhawk / PHP Wrapper 1.0"); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Mashape-Authorization: " . $this->mashapeKey)); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if($method == self::POST) { curl_setopt($ch, CURLOPT_POST, true); if(!empty($params)) { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); } } else if($method == self::PUT || $method == self::DELETE) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if(!empty($params)) { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); } } else if($method == self::PUT_FILE) { curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_INFILE, $params['fp']); curl_setopt($ch, CURLOPT_INFILESIZE, $params['size']); } $result = curl_exec($ch); if(!$result) { $this->errno = curl_errno($ch); $this->error = curl_error($ch); } curl_close($ch); return $result; } } ?><file_sep>#include <iostream> #include <functional> #include <fstream> #include <string> #include <sstream> #include <vector> #include <cstring> #include "unzip.h" #include "sadUtils.hpp" #include "sadReader.hpp" using namespace std; const char* SHARED_STRINGS_PATH = "xl/sharedStrings.xml"; //////////////////////////////////////////////////////////////////////////////// //////// CELL MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////// cell::cell() { jType= NULLVALUE; } cell::cell( std::string newString ) { setValue( newString ); } cell::cell( long double newNumber ) { setValue( newNumber ); } cell::cell( bool newBool ) { setValue( newBool ); } void cell::setValue( std::string input ) { jType = STRING; strval = input; } void cell::setValue( long double input ) { jType = NUMBER; numval = input; } void cell::setValue( bool input ) { jType = BOOL; boolval = input; } JType cell::getType() { return jType; } string cell::getString() { if( jType == STRING ) return strval; return ""; } long double cell::getNumber() { if( jType == NUMBER ) return numval; return 0; } bool cell::getBool() { if( jType == BOOL ) return boolval; return false; } //////////////////////////////////////////////////////////////////////////////// //////// XMLNODE MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////// xmlNode::xmlNode( string input ) { name = input; attC = 0; childC = 0; contentC = 0; } void xmlNode::addAttribute( string attribute, string value ) { attC++; attributes.push_back( attribute ); values.push_back( value ); } void xmlNode::addChild( xmlNode* child ) { childC++; children.push_back( child ); } void xmlNode::addContent( string input ) { contentC++; content.push_back( input ); } string xmlNode::getName() { return name; } vector<string> xmlNode::getAttribute( size_t index ) { vector<string> attribute; if( index >= 0 && index < attC ) { attribute.push_back( attributes[index] ); attribute.push_back( values[index] ); } return attribute; } size_t xmlNode::attributeCount() { return attC; } xmlNode* xmlNode::getChild( size_t index ) { if( index >= 0 && index < childC ) return children[index]; return 0; } size_t xmlNode::childCount() { return childC; } std::string xmlNode::getContent( size_t index ) { if( index >= 0 && index < contentC ) return content[index]; return ""; } size_t xmlNode::contentCount() { return contentC; } //////////////////////////////////////////////////////////////////////////////// //////// SHEET MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////// sheet::sheet( size_t rows, size_t columns, string name ) : rowc(rows), colc(columns) { sName = name; cell blank; vector<cell> column( colc, blank ); contents.insert( contents.end(), rowc, column ); } size_t sheet::rows() { return rowc; } size_t sheet::cols() { return colc; } string sheet::name() { return sName; } //////////////////////////////////////////////////////////////////////////////// //////// CSV FILE READING //////////////////////////////////////////////////////////////////////////////// // Section ends with cc = " and ifs.peek() != " regardless of the // length/meaning of the quote. void skipQuotes( long unsigned &pos, istream &ifs, unsigned &error ) { char cc; cc = ifs.get(); pos++; if( cc != '\"' ) { while( ifs.good() && cc != '\"' ) { cc = ifs.get(); pos++; if( cc == '\"' && ifs.peek() == '\"' ) { ifs.get(); pos++; cc = ifs.get(); pos++; } } if( ifs.eof() ) { error = 2; return; } if( ifs.fail() ) { error = 1; return; } } } void writeCell( sheet &target, size_t row, size_t col, string record ) { if( record == "" ) return; long double number; if( convertData( record, number ) ) { target[row][col].setValue( number ); return; } bool boolean; if( convertBool( record, boolean ) ) { target[row][col].setValue( boolean ); return; } target[row][col].setValue( record ); } void csvMarkers( vector<long unsigned> &commas, vector<long unsigned> &newls, istream &ifs, unsigned &error ) { long unsigned pos = 0; char cc = ifs.get(); while( ifs.good() ) { if( cc == '\"' ) skipQuotes( pos, ifs, error ); if( error != 0 ) return; if( cc == ',' ) commas.push_back( pos ); if( cc == '\n' || cc == '\r' ) { newls.push_back( pos ); if( cc == '\r' && ifs.peek() == '\n' ) ifs.get(); } cc = ifs.get(); pos++; } if( ifs.bad() ) error = 1; } void csvDimensions( size_t &rows, size_t &cols, const vector<long unsigned> &commas, const vector<long unsigned> &newls ) { size_t max = newls.size(); size_t commaPos = 0; size_t newlPos = 0; long unsigned nextComma = ( commas.size() > 0 ) ? commas[0] : -1; long unsigned nextNewl = ( newls.size() > 0 ) ? newls[0] : -1; size_t dimensionPos = 0; vector<size_t> dimensions(1,1); while( newlPos < max ) { nextNewl = ( newls.size() > newlPos ) ? newls[newlPos] : -1; while( nextComma < nextNewl ) { dimensions[dimensionPos]++; commaPos++; nextComma = ( commas.size() > commaPos ) ? commas[commaPos] : -1; } dimensions.push_back(1); dimensionPos++; newlPos++; } rows = dimensions.size(); cols = 0; for( vector<size_t>::iterator it = dimensions.begin(); it != dimensions.end(); it++ ) { if( *it > cols ) cols = *it; } } void csvData( vector<long unsigned> &commas, vector<long unsigned> &newls, sheet &result, size_t rows, size_t cols, istream &ifs, unsigned &error ) { long unsigned pos = 0; size_t commaPos = 0; size_t newlPos = 0; long unsigned nextComma = ( commas.size() > 0 ) ? commas[0] : -1; long unsigned nextNewl = ( newls.size() > 0 ) ? newls[0] : -1; size_t row = 0; size_t col = 0; while( ifs.good() ) { col = 0; while( nextComma < nextNewl ) { if( ifs.peek() == '\n' ) ifs.get(); string record; while( pos < nextComma ) { char cc = ifs.get(); pos++; if( cc == '\"' ) { cc = ifs.get(); pos++; } record += cc; } writeCell( result, row, col, record ); ifs.get(); pos++; col++; commaPos++; nextComma = ( commas.size() > commaPos ) ? commas[commaPos] : -1; } string record; while( pos < nextNewl && !ifs.eof() ) { char cc = ifs.get(); pos++; if( cc == '\"' ) { cc = ifs.get(); pos++; } if( ifs.good() ) record += cc; } writeCell( result, row, col, record ); ifs.get(); pos++; while( col+1 < cols ) { col++; writeCell( result, row, col, "" ); } row++; newlPos++; nextNewl = ( newls.size() > newlPos ) ? newls[newlPos] : -1; } if( ifs.bad() ) error = 1; } sheet readCSV( string filename, unsigned &error ) { error = 0; ifstream ifs( filename ); sheet fail( 0, 0 ); vector<long unsigned> commas; vector<long unsigned> newls; csvMarkers( commas, newls, ifs, error ); if( error != 0 ) return fail; size_t rows; size_t cols; csvDimensions( rows, cols, commas, newls ); string name = filename.substr( 0, filename.find_last_of('.') ); sheet result( rows, cols, name ); ifs.close(); ifs.open( filename ); csvData( commas, newls, result, rows, cols, ifs, error ); if( error != 0 ) return fail; return result; } //////////////////////////////////////////////////////////////////////////////// //////// XML FILE READING //////////////////////////////////////////////////////////////////////////////// // WARNING: Currently there is no support for non-ascii (i.e. full unicode ) // characters, beware! // Returns true if c is a valid start to an xml name bool xmlNameStart( char c ) { if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == ':' || c == '_' ) { return true; } return false; } bool xmlName( char c ) { if( xmlNameStart(c) || c == '-' || c == '.' || (c >= '0' && c <= '9') ) { return true; } return false; } // Progresses the stream one xml text character forward, while skipping over // literal escape strings // Returns the xml text character char xmlChar( istream &ifs, unsigned &error ) { error = 0; char cc; try { cc = ifs.get(); if( cc == '&' ) { string text; cc = ifs.get(); while( cc != ';' ) { text += cc; if( text.size() > 4 ) { error = 2; return cc; } cc = ifs.get(); } if( text == "lt" ) return '<'; else if( text == "gt" ) return '>'; else if( text == "amp" ) return '&'; else if( text == "apos" ) return '\''; else if( text == "quot" ) return '\"'; else { error = 2; return cc; } } return cc; } catch( istream::failure e ) { if( ifs.fail() ) error = 1; else error = 3; ifs.clear(); } return cc; } // Takes a stream whose next character is the first character of the content // section of a tag, and sets the value of "text" to the content. // Note: Takes the stream to the start of the next tag (last character is '<') void xmlContent( string &text, istream &ifs, unsigned &error ) { //cout << "content" << '\n'; char cc; string input; while( ifs.peek() != '<' ) { cc = xmlChar( ifs, error ); if( error != 0 ) return; input += cc; } text = input; ifs.get(); } // Takes a stream whose next character is the first character of an attribute // name, and sets the value of "name" and "value" to the attribute values. // Note: Takes stream to the end of any following whitespace. // Extra note: Exception mask of stream should be set to catch all errors void xmlAttribute( string &name, string &value, istream &ifs, unsigned &error ) { //cout << "attribute" << '\n'; char delim; char cc; value = ""; cc = ifs.get(); while( xmlName(cc) ) { name += cc; cc = ifs.get(); } while( whitespace(cc) ) cc = ifs.get(); if( cc != '=' ) { error = 2; return; } cc = ifs.get(); while( whitespace(cc) ) cc = ifs.get(); if( cc != '"' && cc != '\'' ) { error = 2; return; } delim = cc; cc = ifs.get(); while( cc != delim ) { value += cc; cc = ifs.get(); } while( whitespace(ifs.peek()) ) cc = ifs.get(); error = 0; } void xmlTagName( string &name, istream &ifs, unsigned &error ) { //cout << "tagname" << '\n'; string input; input += ifs.get(); while( xmlName(ifs.peek()) ) input += ifs.get(); name = input; while( whitespace(ifs.peek()) ) ifs.get(); if( !ifs.good() ) { if( ifs.eof() ) error = 3; else error = 1; } } // Assumed position of stream at time of calling: // <tag-name abc... // ^ // (i.e. the first ifs.get() would return 'a') // // Guaranteed position at end of call: // xyz> abc... // ^ // (i.e. the next ifs.get() would return 'a') // // This is a fairly basic parser that only handles tags, content, and // attributes. Fortunately, that's all that -should- be required. In the event // that unaccounted-for input is encountered, the error code will be set // accordingly. // Error codes: // 0: Success // 1: File I/O error // 2: Unparsable file // 3: EOF reached early void xmlTag( xmlNode *result, istream &ifs, unsigned &error ) { //cout << "tag" << '\n'; error = 0; char cc; // Read tag internals while( xmlNameStart(ifs.peek()) ) { string name; string value; xmlAttribute( name, value, ifs, error ); result->addAttribute( name, value ); if( error != 0 ) return; } cc = ifs.get(); if( cc != '/' && cc != '>' ) { error = 2; return; } if( cc == '/' ) { cc = ifs.get(); //cout << "empty: " << cc << "->" << (char)ifs.peek() << '\n'; return; } string text; // Obtain content, including contained tags while( true ) { xmlContent( text, ifs, error ); result->addContent( text ); if( error != 0 ) return; if( ifs.peek() == '/' ) { cc = ifs.get(); while( cc != '>' ) cc = ifs.get(); while( whitespace(ifs.peek()) ) ifs.get(); return; } xmlTagName( text, ifs, error ); if( error != 0 ) return; xmlNode* child = new xmlNode( text ); xmlTag( child, ifs, error ); if( error != 0 ) return; result->addChild( child ); } } void xmlMetaTag( xmlNode *result, istream &ifs, unsigned &error ) { //cout << "metatag" << '\n'; try { error = 0; char cc; // Read tag internals while( xmlNameStart(ifs.peek()) ) { string name; string value; xmlAttribute( name, value, ifs, error ); result->addAttribute( name, value ); if( error != 0 ) return; } cc = ifs.get(); if( cc != '?' || ifs.peek() != '>' ) { error = 2; return; } ifs.get(); while( whitespace(ifs.peek()) ) ifs.get(); } catch( istream::failure e ) { if( ifs.fail() ) error = 1; else error = 3; ifs.clear(); } } void xmlDocument( xmlNode *result, string &content, unsigned &error ) { //cout << "document" << '\n'; char cc; istringstream ifs( content ); while( !ifs.eof() && whitespace(ifs.peek()) ) ifs.get(); while( !ifs.eof() ) { cc = ifs.get(); if( cc != '<' ) { error = 2; return; } string name; xmlNode* child; if( ifs.peek() == '?' ) { ifs.get(); xmlTagName( name, ifs, error ); if( error != 0 ) return; child = new xmlNode( name ); xmlMetaTag( child, ifs, error ); if( error != 0 ) return; } else { xmlTagName( name, ifs, error ); if( error != 0 ) return; child = new xmlNode( name ); xmlTag( child, ifs, error ); if( error != 0 ) return; } result->addChild( child ); while( !ifs.eof() && whitespace(ifs.peek()) ) ifs.get(); } error = 0; } void printXMLTree( xmlNode* root, ostream &out, unsigned ind = 0 ) { out << tab(ind) << root->getName() << ":" << '\n'; ind++; for( size_t it = 0; it < root->attributeCount(); it++ ) { vector<string> attribute = root->getAttribute(it); out << tab(ind) << attribute[0] << "=""" << attribute[1] << """" << '\n'; } string content = root->getContent(0); if( content != "" ) out << tab(ind) << content << '\n'; for( size_t it = 0; it < root->childCount(); it++ ) { xmlNode* child = root->getChild(it); printXMLTree( child, out, ind ); // Due to the way nodes are formatted, there should always be n children and // n+1 contents content = root->getContent(it+1); if( content != "" ) out << tab(ind) << content << '\n'; } } // Returns true if the current file of "zipFile" begins with "title". This is // used both for identifying files in a directory as well as exact files. // Sets title to the full file name and path bool fileMatch( unzFile uzf, string &title, unsigned &error ) { if( unzOpenCurrentFile( uzf ) == UNZ_OK ) { unz_file_info uzfInfo; memset( &uzfInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( uzf, &uzfInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string uzfName; uzfName.resize( uzfInfo.size_filename ); unzGetCurrentFileInfo( uzf, &uzfInfo, &uzfName[0], uzfInfo.size_filename, NULL, 0, NULL, 0 ); unzCloseCurrentFile( uzf ); string uzfNameCut = uzfName.substr( 0, title.size() ); if( uzfNameCut == title ) { title = uzfName; return true; } return false; } } error = 1; return false; } //Returns a list of the filenames of every file in the archive vector<string> getArchiveFiles( unzFile uzf, unsigned &error ) { vector<string> result; int fileAccessStatus = unzGoToFirstFile( uzf ); while( fileAccessStatus == UNZ_OK ) { if( unzOpenCurrentFile( uzf ) == UNZ_OK ) { unz_file_info uzfInfo; memset( &uzfInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( uzf, &uzfInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string uzfName; uzfName.resize( uzfInfo.size_filename ); unzGetCurrentFileInfo( uzf, &uzfInfo, &uzfName[0], uzfInfo.size_filename, NULL, 0, NULL, 0 ); unzCloseCurrentFile( uzf ); result.push_back( uzfName ); } } else { error = 1; return result; } fileAccessStatus = unzGoToNextFile( uzf ); } return result; } string loadArchiveFile( unzFile uzf, string filename, unsigned &error ) { int fileAccessStatus = unzGoToFirstFile( uzf ); while( fileAccessStatus == UNZ_OK ) { if( fileMatch( uzf, filename, error ) ) { if( unzOpenCurrentFile( uzf ) == UNZ_OK ) { unz_file_info archiveFileInfo; memset( &archiveFileInfo, 0, sizeof( unz_file_info ) ); if( unzGetCurrentFileInfo( uzf, &archiveFileInfo, NULL, 0, NULL, 0, NULL, 0 ) == UNZ_OK ) { string archiveFileContents; uLong archiveFileSize = archiveFileInfo.uncompressed_size; unsigned long maxBufferSize = -1; if( archiveFileSize <= maxBufferSize ) { archiveFileContents.resize( archiveFileSize ); voidp archiveFileBuffer = &archiveFileContents[0]; if( unzReadCurrentFile( uzf, archiveFileBuffer, archiveFileSize ) ) { return archiveFileContents; } } } } error = 1; return ""; } if( error != 0 ) return ""; fileAccessStatus = unzGoToNextFile( uzf ); } error = 2; return ""; } vector<string> loadSharedStrings( xmlNode* ss ) { vector<string> result; xmlNode* parent = ss->getChild(1); size_t childC = parent->childCount(); for( size_t it = 0; it < childC; it++ ) { xmlNode* sharedString = parent->getChild(it)->getChild(0); result.push_back( sharedString->getContent(0) ); } return result; } void decodeDimension( string dimension, unsigned &x, unsigned &y ) { int width = 0; size_t lcount = 0; while( dimension[lcount] >= 'A' && dimension[lcount] <= 'Z' ) lcount++; string letters = dimension.substr( 0, lcount ); int value; for( size_t count = 0; count < lcount; count++ ) { width *= 26; value = letters[count] + 1 - 'A'; width += value; } string numbers = dimension.substr( lcount ); x = width; convertData( numbers, y ); } sheet loadWorksheet( string title, xmlNode* ws, const vector<string> &ss ) { xmlNode* top = ws->getChild(1); size_t child = 0; xmlNode* bottom = top->getChild(0); while( bottom->getName() != "dimension" ) { child++; bottom = top->getChild(child); } vector<string> dimensions = bottom->getAttribute(0); unsigned cols; unsigned rows; decodeDimension( dimensions[1].substr( dimensions[1].find(':') + 1), cols, rows ); sheet result( rows, cols, title ); while( bottom->getName() != "sheetData" ) { child++; bottom = top->getChild(child); } for( size_t row = 0; row < bottom->childCount(); row++ ) { xmlNode* rowHead = bottom->getChild(row); for( size_t col = 0; col < rowHead->childCount(); col++ ) { xmlNode* colHead = rowHead->getChild(col); unsigned cellX; unsigned cellY; decodeDimension( colHead->getAttribute(0)[1], cellX, cellY ); cellX--; cellY--; string typeString = colHead->getAttribute(2)[1]; string value = colHead->getChild(0)->getContent(0); if( typeString == "s" ) { size_t index; convertData( value, index ); writeCell( result, cellY, cellX, ss[index] ); } else writeCell( result, cellY, cellX, value ); } } return result; } vector<sheet> readXLSX( string filename, unsigned &error ) { vector<sheet> result; unzFile uzf = unzOpen( filename.c_str() ); if( uzf ) { vector<string> commonStrings; string sharedStringsContent = loadArchiveFile( uzf, "xl/sharedStrings.xml", error ); if( error != 0 ) return result; xmlNode* sharedStringsXML = new xmlNode( "sharedstrings" ); xmlDocument( sharedStringsXML, sharedStringsContent, error ); if( error != 0 ) return result; vector<string> sharedStringList = loadSharedStrings( sharedStringsXML ); if( error != 0 ) return result; string worksheetPath = "xl/worksheets/"; vector<string> archiveFiles = getArchiveFiles( uzf, error ); if( error != 0 ) return result; for( vector<string>::iterator it = archiveFiles.begin(); it != archiveFiles.end(); it++ ) { string filepath = it->substr( 0, it->find_last_of('/')+1 ); if( filepath == worksheetPath ) { string contents = loadArchiveFile( uzf, *it, error ); if( error != 0 ) return result; xmlNode* worksheetXML = new xmlNode( "worksheet" ); xmlDocument( worksheetXML, contents, error ); if( error != 0 ) return result; string title = filename.substr( filename.find_last_of('/')+1 ); title = title.substr( 0, title.find_last_of('.') ); sheet worksheet = loadWorksheet( title, worksheetXML, sharedStringList ); result.push_back( worksheet ); } } return result; } error = 1; return result; } //////////////////////////////////////////////////////////////////////////////// //////// CORE FUNCTIONS //////////////////////////////////////////////////////////////////////////////// FileType getFileType( string filename ) { size_t pos = filename.find_last_of( '.' ); if( pos == string::npos ) return UNDEF; string file = toUpper( filename.substr( pos + 1 ) ); if( file.compare( "CSV" ) == 0 ) return CSV; if( file.compare( "ODS" ) == 0 ) return ODS; if( file.compare( "XLSX" ) == 0 ) return XLSX; return UNDEF; } vector<sheet> readFile( string filename, unsigned &error ) { FileType filetype = getFileType( filename ); vector<sheet> result; switch( filetype ) { case CSV: result.push_back( readCSV( filename, error ) ); return result; break; case XLSX: return readXLSX( filename, error ); break; case ODS: default: error = 1; return result; break; } } //////////////////////////////////////////////////////////////////////////////// //////// TESTING //////////////////////////////////////////////////////////////////////////////// // void testUtilities( ostream &out, unsigned &testsRun, unsigned &testsPassed, // unsigned ind = 0 ) // { // testsRun = 0; // testsPassed = 0; // //Begin testing // out << tab(ind) << "Initiating Utility Function Testing Protocols:" << '\n'; // ind++; // function<int(int)> fAdd = add; // testFunction<int,int>( fAdd, "add", out, ind ); // function<string(string)> fToUpper = toUpper; // testsRun++; // if( testFunction( fToUpper, "toUpper", out, ind ) ) testsPassed++; // ind--; // //End of tests // } // // void testCore( ostream &out, unsigned &testsRun, unsigned &testsPassed, // unsigned ind = 0 ) // { // testsRun = 0; // testsPassed = 0; // //Begin testing // out << tab(ind) << "Initiating Core Function Testing Protocols:" << '\n'; // ind++; // function<FileType(string)> fGetFileType = getFileType; // testsRun++; // if( testFunction( fGetFileType, "getFileType", out, ind ) ) testsPassed++; // //End of tests // ind--; // } // void printSheet( sheet sh, ostream &out, unsigned ind ) { size_t rows = sh.rows(); size_t cols = sh.cols(); for( size_t row = 0; row < rows; row++ ) { out << tab(ind); for( size_t col = 0; col < cols; col++ ) { JType celltype = sh[row][col].getType(); switch( celltype ) { case STRING: out << "[S:" << sh[row][col].getString() << "]"; break; case BOOL: out << "[B:" << sh[row][col].getBool() << "]"; break; case NUMBER: out << "[N:" << sh[row][col].getNumber() << "]"; break; default: out << "[NULL]"; break; } } out << '\n'; } } <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array(); /*! * Try and remove the index from the dataset provided the field has already * been specified. */ // Check if the field is set. if(empty($data->field)) { echo json_beautify(json_render_error(404, "You didn't specify the field to remove the index on.")); exit; } // Check if the _id field has been speciifed. if($data->field == "_id") { echo json_beautify(json_render_error(405, "You can't remove the index on the _id field.")); exit; } // Get the current indexes. $indx = $dataset->fetch_indexes(); $indexes = array(); // Set the indexes properly. foreach($indx as $index) { $indexes[] = array_keys($index['key'])[0]; } // Check if the index has already been set. if(!in_array($data->field, $indexes)) { echo json_beautify(json_render_error(406, "The field you specified does not have an index.")); exit; } // Remove the index. if(!$dataset->remove_index($data->field)) { echo json_beautify(json_render_error(407, "There was an unknown problem removing the index you specified.")); exit; } // Set the output. $json['removed'] = true; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep># -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "debian_squeeze_amd64" config.vm.box_url = "http://ergonlogic.com/files/boxes/debian-current.box" config.vm.define :rainhawk do |t| end config.vm.network :forwarded_port, guest: 80, host: 8080 config.vm.network :forwarded_port, guest: 443, host: 8443 config.vm.network :forwarded_port, guest: 27017, host: 27017 config.vm.provider :virtualbox do |v| v.customize ["modifyvm", :id, "--memory", "2048"] end config.vm.provision :puppet do |puppet| puppet.manifests_path = ".puppet/manifests" puppet.manifest_file = "main.pp" puppet.module_path = ".puppet/modules" puppet.options = ["--verbose"] end end <file_sep>'use strict'; eco.charts.d3piechart = function() { return { title: 'Pie Chart', options : { width : 1400, height : 700, margin : { top: 30, left: 80 } }, render: function(data, xValue, yValue, target) { var options = this.options; var width = options.width, height = options.height, maxRadius = Math.min(width, height)/2; var color = d3.scale.category20b(); //holds whether an element is being viewed var viewToggle = false; var arc = d3.svg.arc() .outerRadius(maxRadius) .innerRadius(0); var pie = d3.layout.pie() .sort(null) .value(function(d) { return d[yValue]; }); var svg = target.append("svg") .attr("width", width + options.margin.top) .attr("height", height + options.margin.left) .attr("class", "pie-chart") .append("g") .attr("transform", "translate(" + ((width / 2) + options.margin.left) + "," + ((height / 2) + options.margin.top) + ")"); data.forEach(function(d) { d[yValue] = +d[yValue]; }); var g = svg.selectAll(".pie-chart-arc") .data(pie(data)) .enter().append("g") .attr("class", "pie-chart-arc"); g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data[xValue]); }) .attr("opacity", 0.9) .on("mouseover", mouseover) .on("mouseout", mouseout) .on("click", mouseclick); g.append("text") .attr("transform", function(d) { d.outerRadius = maxRadius; d.innerRadius = maxRadius/2; return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")"; }) .attr("dy", ".35em") .style("text-anchor", "middle") .text(function(d) { return d.data[xValue]; }); function mouseover(d) { d3.selectAll("[class=pie-header-text]").remove(); svg.append("g") .append("text") .attr("x", 25) .attr("y", 50) .attr("class", "pie-header-text") .attr("fill", "#483D8B") .attr("transform", "translate(-" + (width / 2 + options.margin.left) + ",-" + (height / 2 + options.margin.top) + ")") .text(d["data"][xValue] + ": " + d["data"][yValue]); d3.select(this) .transition() .duration(100) .attr("opacity", 1); } function mouseout(d) { if (!viewToggle) { d3.selectAll("path") .transition() .duration(200) .attr("opacity", 0.9); } } function mouseclick(d) { //select all but the selected element var selectedElement = this; d3.selectAll("path") .filter(function(d) { return (this !== selectedElement); }) .transition() .duration(150) .attr("opacity", 0.4); viewToggle = !viewToggle; if (!viewToggle) mouseout(d); } // Calculates the arc angle then converts from radians to degrees. function angle(d) { var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90; return a > 90 ? a - 180 : a; } } } } <file_sep>#ifndef FILEREADER #define FILEREADER #include <string> #include <vector> using namespace std; enum FileType { CSV, XLSX, UNDEF, ODS }; enum JType { STRING, NUMBER, OBJECT, ARRAY, BOOL, NULLVALUE }; //TODO: Fix value storage; only data of one type (string, number, and //boolean) needs to be stored for any given instantiation, making it //inefficient to allocate memory for all of them at once class sheetNode { public: sheetNode(); sheetNode( string newString ); sheetNode( long double newNumber ); sheetNode( bool newBool ); JType getType(); string getString(); long double getNumber(); bool getBool(); private: JType jType; string strval; long double numval; bool boolval; }; typedef struct { string name; vector< vector<sheetNode> > contents; } page; vector< page > getFile( string fileName ); string pageString( page spreadsheet ); #endif <file_sep>CXX = g++ CPPFLAGS = -std=c++0x -g -Wall -Iunzip ZPATH = unzip PARSE_SRCS = sadTables.cpp sadReader.cpp sadUtils.cpp sadWriter.cpp sadParser.cpp PARSE_OBJS = $(PARSE_SRCS:%.cpp=%.o) ABS_UNZ_OBJS = miniunz.o unzip.o ioapi.o libz.a UNZ_OBJS = $(ABS_UNZ_OBJS:%=$(ZPATH)/%) default: sadparser sadparser: $(PARSE_OBJS) $(UNZ_OBJS) $(CXX) $(CPPFLAGS) -o $@ $(PARSE_OBJS) $(UNZ_OBJS) $(PARSE_OBJS): %.o: %.cpp $(CXX) $(CPPFLAGS) -c $< $(UNZ_OBJS): cd unzip && $(MAKE) clean: $(RM) sadparser *.o *~ cd unzip && $(MAKE) clean $(RM) examples/*.json <file_sep><?php use Rainhawk\Sets; use Rainhawk\Dataset; class RainhawkSetsTest extends UnitTest { public $class = "Rainhawk\Sets"; public function __before() { app::$username = "test"; rainhawk::select_database("tests"); return $this; } public function testCreate() { $dataset = new Dataset(app::$username, "testset"); $dataset->description = "Test dataset."; $dataset->read_access[] = app::$username; $dataset->write_access[] = app::$username; $this->assertEquals(sets::create($dataset), true); } public function testUpdate() { $dataset = new Dataset(app::$username, "testset"); $this->assertEquals(sets::update($dataset), true); } public function testExists() { $this->assertEquals(sets::exists(app::$username, "testset"), true); } public function testFetchMetadata() { $metadata = sets::fetch_metadata(app::$username, "testset"); $description = $metadata['description']; $this->assertEquals($description, "Test dataset."); } public function testSetsForUser() { $sets = sets::sets_for_user(app::$username); $datasets = array(); foreach($sets as $set) { $datasets[] = $set; } $this->assertEquals($datasets[0]['description'], "Test dataset."); } public function testRemove() { $dataset = new Dataset(app::$username, "testset"); $this->assertEquals(sets::remove($dataset), true); } } ?><file_sep>'use strict'; eco.charts.d3linegraph = function() { return { title: 'Steam Graph', options : { width : 1500, height : 700, margin : { top: 100, left: 50, bottom: 50, right: 50 } }, render: function(data, xValue, yValue, target) { //store data before wrapping var dd = data; //wrap the data data = [{"values":data}]; var options = this.options; var width = options.width, height = options.height; var margin = options.margin; var yScale = d3.scale.linear() .domain([0, d3.max(dd, function(d) { return +d[yValue]; })]) .range([height-margin.bottom, margin.top]); var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .ticks(20); var yAxisR = d3.svg.axis() .scale(yScale) .orient("right") .ticks(20); var xScale = d3.scale.linear() .domain([0,d3.max(dd, function(d) { return +d[xValue]; })]) .range([margin.left,width-margin.right]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var stack = d3.layout.stack() .offset("zero") .values(function(d) { return d.values; }); var colorScale = d3.scale.category20b(); var area = d3.svg.area() .x(function(d) { return xScale(d[xValue]); }) .y0(function(d) { return yScale(d.y0); }) .y1(function(d) { return yScale(d.y0 + d[yValue]); }); var svg = target.append("svg") .attr("width", width) .attr("height", height); //draw horizontal lines svg.selectAll("horizontalGrid") .data(yScale.ticks(20)) .enter() .append("line") .attr( { "x1" : margin.left, "x2" : width - margin.right, "y1" : function(d){ return yScale(d);}, "y2" : function(d){ return yScale(d);}, "shape-rendering" : "crispEdges", "stroke" : "grey", "stroke-width" : "1px" }); svg.selectAll("path") .data(stack(data)) .enter().append("path") .attr("class", "layer") .attr("d", function(d) { return area(d.values); }) .style("fill", function() { return colorScale(Math.random())}); //left axis svg.append("g") .attr("class", "y axis") .call(yAxis) .attr("transform", "translate("+margin.left+",0)") .append("text") .attr("transform", "rotate(-90)") .attr("y", -40) .attr("x", -height/2) .attr("dy", ".21em") .style("text-anchor", "end") .style("font", "12px Helvetica") .text(yValue); //right axis svg.append("g") .attr("class", "y axis") .call(yAxisR) .attr("transform", "translate("+(width-margin.right)+",0)") svg.append("g") .attr("class", "x axis") .call(xAxis) .attr("transform", "translate(0,"+(height-margin.bottom)+")") .append("text") .attr("transform", "translate("+(width/2)+",35)") .style("text-anchor", "end") .style("font", "12px Helvetica") .text(xValue); d3.select("path") .on("mousemove", mousemove) .on("click", mouseclick); function mousemove() { var posX = (d3.mouse(this)[0] - margin.left - 1); var posY = (height+margin.top - 151) - d3.mouse(this)[1]; var xmouseScale = d3.scale.linear() .range([0, d3.max(dd, function(d) { return +d[xValue]; })]) .domain([0, width-margin.left-margin.right]); var ymouseScale = d3.scale.linear() .range([0, d3.max(dd, function(d) { return +d[yValue]; })]) .domain([0, height-margin.top-margin.bottom-3]); d3.selectAll("[class=steam-text]").remove(); svg.append("g") .append("text") .attr("x", 25) .attr("y", 50) .attr("class", "steam-text") .attr("fill", "#483D8B") .text(xValue + ": " + Math.round(xmouseScale(posX)) + ", " + yValue + ": " + Math.round(ymouseScale(posY))); }; function mouseclick() { d3.select(this) .style("fill", function() { return colorScale(Math.random())}); }; } } } <file_sep>'use strict'; /* controllers */ // to do: Get data from our api, make it all faster angular.module('eco.controllers', []) .controller('ecoCtrl', function ($scope, $http, dataService) { /* TO DO: If one option is null or two or more are the same throw error. When Visualize button is pressed, check that all parameters are != null. */ // selected radio button $scope.selectedVizType = {id:1}; // has the user requested to visualise a certain dataset? if (window.location.search == '') { $scope.selectedDataset = ''; } else { $scope.selectedDataset = window.location.search.slice(1).split('=')[1]; } // the fields for the selected dataset $scope.fields = []; // current user's api key $scope.apiKey = apiKey; // reinitialize $scope.vizTypes here $scope.getFields = function() { $http({ method: 'GET', url: 'https://sneeza-eco.p.mashape.com/datasets/'+$scope.selectedDataset+'/data', headers: { 'X-Mashape-Authorization' : $scope.apiKey } }). success(function(json) { $scope.fields = []; if(json.data["rows"] != undefined) { $.each(json.data["results"][0], function(key, val) { if (key!='_id') { $scope.fields.push(key); } }); } else { return null; }; }) } // (don't have this be a function so it only runs once) $scope.getDatasetNames = function() { // todo: get user's API key from cookie $http({ method: 'GET', url: 'https://sneeza-eco.p.mashape.com/datasets', headers: { 'X-Mashape-Authorization' : $scope.apiKey } }). success(function(json) { // attach the data to the scope $scope.datasets = []; $.each(json.data.datasets, function(key,val) { // var datasetName = val.name.split('.')[1]; var datasetName = val.name; $scope.datasets.push(datasetName); }); // clean the error messages $scope.error = ''; }). error(function (data, status) { if (status === 404) { $scope.error = 'Datasets not found'; } else { $scope.error = 'Error: ' + status; } }); }; // check to see that no parameter is empty $scope.checkParameters = function() { // if ($scope.valid == false) { // alert("Invalid options"); // } $scope.validParams = true; for (var field in $scope.vizTypes[$scope.selectedVizType.id].options) { if ($scope.vizTypes[$scope.selectedVizType.id].options[field] === null) { $scope.validParams = false; console.log("Invalid parameters!"); return; } } }; // send visualization options to the service and vis type. // Do this when the 'visualize' is clicked but in the future, // validate the options made accordingly. $scope.sendVizOptionsToService = function() { console.log('Sending options to service!'); dataService.selectedVizType = $scope.selectedVizType.id; dataService.vizOptions = $scope.vizTypes; } // $scope.validParams = true; // get the datasets immediately $scope.getDatasetNames(); // when a new dataset is selected from the dropdown get its fields $scope.$watch('selectedDataset', function() { if ($scope.selectedDataset != '') { $scope.getFields(); dataService.selectedDataset = $scope.selectedDataset; dataService.getSelectedDataset(); $scope.currentData = dataService.getData($scope.selectedDataset, $scope.apiKey); } // reinitialize parameter options $scope.vizTypes = eco.charts(); }); $scope.$watch('selectedVizType.id', function() { $scope.validParams = true; }); $scope.$watch('vizTypes', function() { $scope.checkParameters(); }) });<file_sep>#ifndef FILE_READER #define FILE_READER #include <string> #include <iostream> #include <vector> extern const char* SHARED_STRINGS_PATH; const long unsigned MAX_BUFFER_SIZE = 65536; enum FileType : unsigned { UNDEF = 0, CSV = 1, XLSX = 2, ODS = 3 }; enum JType : unsigned { NULLVALUE = 0, STRING = 1, NUMBER = 2, BOOL = 3, OBJECT = 4, ARRAY = 5 }; class xmlNode { public: xmlNode( std::string input ); void addAttribute( std::string attribute, std::string value ); void addChild( xmlNode* child ); void addContent( std::string input ); size_t attributeCount(); size_t childCount(); size_t contentCount(); std::vector<std::string> getAttribute( size_t index ); xmlNode* getChild( size_t index ); std::string getContent( size_t index ); std::string getName(); private: std::string name; size_t attC; std::vector<std::string> attributes; std::vector<std::string> values; size_t childC; std::vector<xmlNode*> children; size_t contentC; std::vector<std::string> content; }; class cell { public: cell(); cell( std::string newString ); cell( long double newNumber ); cell( bool newBool ); void setValue( std::string input ); void setValue( long double input ); void setValue( bool input ); JType getType(); std::string getString(); long double getNumber(); bool getBool(); private: JType jType; std::string strval; long double numval; bool boolval; }; // Access elements with sheet[x][y], where x is the row and y is the col class sheet { public: sheet( size_t rows, size_t columns, std::string name = "sheet" ); std::vector<cell>& operator [](size_t idx) { return contents[idx]; } const std::vector<cell>& operator [](size_t idx) const { return contents[idx]; } size_t rows(); size_t cols(); std::string name(); private: std::string sName; size_t rowc; size_t colc; std::vector< std::vector<cell> > contents; }; std::vector<sheet> readFile( std::string filename, unsigned &error ); void printSheet( sheet sh, std::ostream &out, unsigned ind = 0 ); #endif <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define our output by filling up the JSON array with the variables * from the dataset object. */ if(!$dataset->remove()) { echo json_beautify(json_render_error(404, "There was a problem while trying to remove this dataset.")); exit; } // Set the JSON. $json = array( "deleted" => true ); /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; $dataset = isset($_GET['dataset']) ? htmlspecialchars($_GET['dataset']) : null; $access = $rainhawk->listAccess($dataset); $readList = $access['read_access']; $writeList = $access['write_access']; $accessList = array_unique(array_merge($readList, $writeList)); if(!in_array($user, $writeList)) { header("Location: /properties.php?dataset=" . $dataset . "&nowrite"); exit; } $currentUsers = (array)$_POST['currentUser']; $newUsers = (array)$_POST['newUser']; $errors = array(); foreach($currentUsers as $username => $access) { $result = ""; $types = array(); if(isset($access['read'])) $types[] = "read"; if(isset($access['write'])) $types[] = "write"; foreach($types as $type) { if($type == "read" && !in_array($username, $readList)) { $result = $rainhawk->giveAccess($dataset, $username, "read"); } else if($type == "write" && !in_array($username, $writeList)) { $result = $rainhawk->giveAccess($dataset, $username, "write"); } else { $result = true; } if(!$result) { $errors[] = $rainhawk->error(); } } } foreach($readList as $username) { if(!isset($currentUsers[$username]['read'])) { $result = $rainhawk->removeAccess($dataset, $username, "read"); if(!$result) { $errors[] = $rainhawk->error(); } } } foreach($writeList as $username) { if(!isset($currentUsers[$username]['write'])) { $result = $rainhawk->removeAccess($dataset, $username, "write"); if(!$result) { $errors[] = $rainhawk->error(); } } } foreach($newUsers as $key => $newUser) { $result = ""; $types = array(); if(isset($newUser['read'])) $types[] = "read"; if(isset($newUser['write'])) $types[] = "write"; if(in_array($newUser["user"], array_keys($currentUsers))) { $errors[] = "User " . $newUser['user'] . " already has permissions assigned"; } else { var_dump($dataset); var_dump($newUser['user']); var_dump($types); $result = $rainhawk->giveAccess($dataset, $newUser['user'], $types); } if(!$result) { $errors[] = $rainhawk->error(); } } if(empty($errors)) { header("Location: /properties.php?dataset=" . $dataset); exit; } ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can write to the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "deleted" => 0 ); /*! * Run the delete command directly in MongoDB, but be careful that * they're not accidentally sending an empty query to delete all * documents. */ // Set some local variables. $query = !empty($data->query) ? $data->query : array(); // Change the MongoID if we have one. foreach($query as $key => $value) { if($key == "_id") { try { $mongoid = new MongoID($value); } catch(Exception $e) { $mongoid = null; } $query[$key] = $mongoid; } } // Run the delete query. $deleted = $dataset->delete($query); // Check if the query failed. if(!is_int($deleted)) { echo json_beautify(json_render_error(405, "An unexpected error occured while performing your query - are you sure you formatted all the parameters correctly?")); exit; } // Set the JSON. $json['deleted'] = $deleted; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php /*! * This class is a very, very simple OO style wrapper for the * cURL extension for PHP. It also offers a quick-access * function to fetch a URL in one-line. */ class cURL { // Define a global variable that can be overridden. public static $timeout = 6; public static $user_agent = null; /*! * Pass all of the functions on with an OO style to the * base extension below. */ public static function init() { return curl_init(); } public static function setopt($ch, $type, $value) { return curl_setopt($ch, $type, $value); } public static function getinfo($ch, $type) { return curl_getinfo($ch, $type); } public static function exec($ch) { return curl_exec($ch); } public static function errno($ch) { return curl_errno($ch); } public static function error($ch) { return curl_error($ch); } public static function close($ch) { return curl_close($ch); } /*! * Quick access function to fetch a URL with an optional * timeout, which overrides the class 'timeout' variable. * We also set a user agent with the version string provided * by the app. */ public static function get($url, $timeout = null, $headers = array()) { $ch = self::init(); self::setopt($ch, CURLOPT_URL, $url); self::setopt($ch, CURLOPT_USERAGENT, self::$user_agent); self::setopt($ch, CURLOPT_TIMEOUT, ($timeout) ? $timeout : self::$timeout); self::setopt($ch, CURLOPT_HTTPHEADER, $headers); self::setopt($ch, CURLOPT_FOLLOWLOCATION, true); self::setopt($ch, CURLOPT_RETURNTRANSFER, true); self::setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // self::setopt($ch, CURLOPT_ENCODING, "gzip"); $result = self::exec($ch); self::close($ch); return $result; } /*! * Quick access function to fetch a URL with an optional * timeout, which overrides the class 'timeout' variable. * We also set a user agent with the version string provided * by the app. */ public static function post($url, $post_data = array(), $timeout = null, $headers = array()) { $ch = self::init(); self::setopt($ch, CURLOPT_URL, $url); self::setopt($ch, CURLOPT_USERAGENT, self::$user_agent); self::setopt($ch, CURLOPT_TIMEOUT, ($timeout) ? $timeout : self::$timeout); self::setopt($ch, CURLOPT_HTTPHEADER, $headers); self::setopt($ch, CURLOPT_FOLLOWLOCATION, true); self::setopt($ch, CURLOPT_RETURNTRANSFER, true); self::setopt($ch, CURLOPT_SSL_VERIFYPEER, false); self::setopt($ch, CURLOPT_POST, true); self::setopt($ch, CURLOPT_POSTFIELDS, $post_data); // self::setopt($ch, CURLOPT_ENCODING, "gzip"); $result = self::exec($ch); self::close($ch); return $result; } /*! * Quick access function to perform a HEAD request on a URL * and send us back the last_modified header as a timestamp. */ public static function get_last_modified($url, $timestamp, $timeout = null) { $ch = self::init(); self::setopt($ch, CURLOPT_URL, $url); self::setopt($ch, CURLOPT_USERAGENT, self::$user_agent); self::setopt($ch, CURLOPT_TIMEOUT, ($timeout) ? $timeout : self::$timeout); self::setopt($ch, CURLOPT_FOLLOWLOCATION, true); self::setopt($ch, CURLOPT_RETURNTRANSFER, true); self::setopt($ch, CURLOPT_SSL_VERIFYPEER, false); self::setopt($ch, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); self::setopt($ch, CURLOPT_TIMEVALUE, $timestamp); self::setopt($ch, CURLOPT_FILETIME, true); // self::setopt($ch, CURLOPT_ENCODING, "gzip"); $result = self::exec($ch); $code = self::getinfo($ch, CURLINFO_HTTP_CODE); $last_modified = self::getinfo($ch, CURLINFO_FILETIME); if($code == 200) { $result = array( "last_modified" => $last_modified, "result" => $result ); } else { $result = false; } self::close($ch); return $result; } } ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can write to the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define our output by filling up the JSON array with the variables * from the dataset object. */ $json = array( "rows" => array() ); /*! * Add the specified row(s) to the Mongo collection, ignoring any * fields and just straight up dumping the values. */ $rows = array(); // Check for some actual documents. if(!empty($data->row)) { $rows[] = $data->row; } else if(!empty($data->rows)) { foreach($data->rows as $row) $rows[] = $row; } else { echo json_beautify(json_render_error(404, "There were no rows passed to the endpoint to insert.")); exit; } // Insert the rows of data into the dataset. $rows = $dataset->insert_multi($rows); // Check that it was a success. if(!$rows) { echo json_beautify(json_render_error(404, "An unknown error occured while inserting your data into the dataset.")); exit; } // Set the JSON output. foreach($rows as $row) { if(isset($row['_id'])) { $_id = (string)$row['_id']; unset($row['id']); $row = array("_id" => $_id) + $row; } foreach($row as $field => $value) { if(isset($dataset->constraints[$field])) { $row[$field] = \rainhawk\data::check($dataset->constraints[$field]['type'], $value); } } $json['rows'][] = $row; } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep>#ifndef TABLEPROCESSOR #define TABLEPROCESSOR #include "JSONWriter.h" #include "readFile.h" #include <vector> vector< vector<JSONObject> > processData( vector< vector<sheetNode> > spreadsheet ); #endif <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to upload data to * the dataset, which requires the dataset name and prefix. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Fetch the input file, 8kB at a time, saving it to a temporary file so that * we can run it through the parser. */ // Check that the type has been set. if(empty($data->type)) { echo json_beautify(json_render_error(404, "You specified a type that we don't support. Currently we support: csv, xlsx, ods.")); exit; } // Set a temporary location for the file. $file = "/tmp/upload_" . sprintf("%07d", rand(1, 1000000)) . "." . $data->type; $fp = fopen($file, "w"); // Check if the user sent a file or not. if(!$input = fopen("php://input", "r")) { echo json_beautify(json_render_error(405, "You didn't send any file contents to process.")); exit; } // Read the data and write it to the file, 8kB at a time. while($data = fread($input, 1024 * 8)) { fwrite($fp, $data); } // Close the file pointers. fclose($fp); fclose($input); // Check if the file is empty or not. if(filesize($file) == 0) { unlink($file); echo json_beautify(json_render_error(406, "The contents of the file you uploaded is empty.")); exit; } /*! * Once we've uploaded the file, send it to the parser for processing. */ // Run the parser command. exec("cd ../parser/ && ./sadparser '" . $file . "' 2>&1", $result); // Check for any errors. if(!empty($result)) { foreach($result as $line) { if(stripos($line, "invalid") !== false) { echo json_beautify(json_render_error(407, "There was a problem while processing your data - your data could not be read. Currently we only support: csv, xlsx.")); exit; } else if(stripos($line, "could not") !== false) { echo json_beautify(json_render_error(408, "There was a problem while processing your data - we seem to be having technical difficulties with our parser. Please try again later.")); exit; } else if(stripos($line, "error") !== false) { echo json_beautify(json_render_error(409, "There was a problem while processing your data - make sure that your file contains valid data.")); exit; } } } // Remove the temporary file. unlink($file); // Find the generated JSON files. $files = scandir("/tmp"); $file = pathinfo($file, PATHINFO_FILENAME); // Iterate through the /tmp directory to find them. foreach($files as $tmp_file) { if(stripos($tmp_file, $file) !== false && pathinfo($tmp_file, PATHINFO_EXTENSION) == "json") { $tmp_file = "/tmp/" . $tmp_file; $rows = json_decode(file_get_contents($tmp_file), true); $rows = $rows['data'] ?: []; // Check if the rows were empty. if(empty($rows)) { echo json_beautify(json_render_error(409, "One or more of the specified documents contained no data.")); exit; } // Insert the rows of data into the dataset. $rows = $dataset->insert_multi($rows); // Check that it was a success. if(!$rows) { echo json_beautify(json_render_error(409, "An unknown error occured while inserting your data into the dataset.")); exit; } // Set the JSON output. foreach($rows as $row) { if(isset($row['_id'])) { $_id = (string)$row['_id']; unset($row['id']); $row = array("_id" => $_id) + $row; } foreach($row as $field => $value) { if(isset($dataset->constraints[$field])) { $row[$field] = \rainhawk\data::check($dataset->constraints[$field]['type'], $value); } } $json['rows'][] = $row; } // Delete JSON. unlink($tmp_file); } } // Check if the number of rows inserted was zero. if(!isset($json['rows']) || empty($json['rows'])) { echo json_beautify(json_render_error(410, "After parsing the uploaded file we couldn't find any data.")); exit; } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep>#include "JSONWriter.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <stdexcept> using namespace std; ///////////////////////////////////////////////////// // JSONObject Implementation JSONObject::JSONObject() { fields = 0; } int JSONObject::fieldCount() { return fields; } string JSONObject::getName( unsigned pos ) { if( pos >= 0 && pos < fields ) { return names[pos]; } else { return NULL; } } string JSONObject::getValue( unsigned pos ) { if( pos >= 0 && pos < fields ) { return values[pos]; } else { return NULL; } } void JSONObject::addPair( string name ) { names.push_back(name); //if( jasdksjdfkvj ) values.push_back("0"); //else values.push_back("null"); values.push_back("null"); fields++; } void JSONObject::addPair( string name, long double value ) { names.push_back(name); ostringstream converter; converter << value; values.push_back(converter.str()); fields++; } void JSONObject::addPair( string name, const char * value ) { string stringValue = value; addPair( name, stringValue ); } void JSONObject::addPair( string name, string &value ) { names.push_back(name); values.push_back(value); fields++; } void JSONObject::addPair( string name, bool value ) { names.push_back(name); if( value ) { values.push_back("true"); } else { values.push_back("false"); } fields++; } // End of JSONObject Implementation ///////////////////////////////////////////////////// string JSONString( JSONObject object ) { string document = "{\n"; unsigned count = 0; unsigned max = object.fieldCount(); while( count < max ) { document += "\t"; document += "\""; document += object.getName(count); document += "\": "; string value = object.getValue(count); document += value; count++; if( count < max ) { document += ","; } document += '\n'; } document += "}"; return document; } //Inputs: // string name: A path and filename for the new file in which // the JSON document will be stored. // vector<JSONObject> objects: A vector containing the JSON objects that the // new document contains. //Output: An integer representing the success of the operation. Values are: // 0: Successful operation // 1: File I/O error int createJDocument( string name, vector<JSONObject> objects ) { ofstream ofs( name ); if( !ofs.good() ) { return 1; } ofs << "["; for( vector<JSONObject>::iterator it = objects.begin(); it != objects.end(); it++ ) { if(it != objects.begin()) ofs << ",\n"; ofs << JSONString( *it ); } ofs << "]"; ofs.close(); return 0; } <file_sep>eco.charts.d3barchart = function() { return { title: 'Bar Chart', options : { width : 1400, height : 600, margin : { top: 70, right: 20, bottom: 140, left: 80 } }, render: function(data, xValue, yValue, target) { var options = this.options, width = options.width, height = options.height; var margin = { top: options.margin.top, bottom: options.margin.bottom, left: options.margin.left, right: options.margin.right }; //holds whether an element is being viewed var viewToggle = false; var xCount = 0; for (k in data) if (data.hasOwnProperty(k)) xCount++; console.log(xCount); // count the number of rows in the dataset for xValue. // xCount = ...; var xScale = d3.scale.ordinal() .domain(d3.range(xCount)) .rangeRoundBands([0, width], .1); // get the max value of the column for yValue. // yMax = ...; // CHANGE THIS var yScale = d3.scale.linear() .domain([0, d3.max(data, function(d) { return +d[yValue]; })]) .range([height, 0]); var colorScale = d3.scale.category20b(); var svg = target .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .attr("class", "bar-chart") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // make the number of ticks customizable var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .ticks(10); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var bar = svg.selectAll("g") .data(data, function(d) { return d[yValue]; }) .enter() .append("g"); bar.append("rect") .attr ({ x : function(d,i) { return xScale(i); }, y : function(d) { return yScale(d[yValue]); }, height: function(d) { return height - yScale(d[yValue]); }, width: xScale.rangeBand(), fill: function(d,i) { return colorScale(i); }, opacity: 0.9 }) .on ({ mouseover : mouseover, mouseout : mouseout, click : mouseclick }); // add labels bar.append("text") .attr("class", "bar-text") .attr("text", "middle") .attr("dy", ".35em") .attr("height", 10) .attr("width", 20) .attr('transform', function(d,i) { return d3.transform('translate(' + (xScale(i) + (xScale.rangeBand()/2)) + ',' + (height + 5) + ') rotate(90)').toString(); }) .text(function(d) { console.log(d);return d[xValue]; }); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", -40) .attr("x", -height/2) .attr("dy", ".21em") .style("text-anchor", "end") .style("font", "12px Helvetica") .text(yValue); function mouseover(d) { var xPos = d3.select(this).attr("x"); var yPos = d3.select(this).attr("y"); //text showing x and y values d3.selectAll("[class=bar-header-text]").remove(); svg.append("g") .append("text") .attr("x", 25 - margin.left) .attr("y", 50 - margin.top) .attr("class", "bar-header-text") .attr("fill", "#483D8B") .text(d[xValue] + ": " + d[yValue]); d3.select(this) .transition() .duration(100) .attr("opacity", 1); } function mouseout(d) { if (!viewToggle) { d3.selectAll("rect") .transition() .duration(200) .attr("opacity", 0.9); } } function mouseclick(d) { //select all but the selected element var selectedElement = this; d3.selectAll("rect") .filter(function(d) { return (this !== selectedElement); }) .transition() .duration(150) .attr("opacity", 0.4); viewToggle = !viewToggle; if (!viewToggle) mouseout(d); } return this; } } }; <file_sep>CC=cc CFLAGS=-O3 UNZ_OBJS = miniunz.o unzip.o ioapi.o libz.a .c.o: $(CC) -c $(CFLAGS) $*.c all: $(UNZ_OBJS) %.o: %.c $(CC) $(CFLAGS) -c $< clean: $(RM) -f *.o *~ all <file_sep>Elgar's Coding Orchestra ===================== Our totally unnamed project is still pretty sparse. We currently have a server set up at spe.sneeza.me, and all members of our group have an account on that server with sudo access. Your default password will be '<PASSWORD>' which you can change by running the passwd command. Project Page --------------------- We currently have a public facing website located at: ``` http://project.spe.sneeza.me/ ``` Our API --------------------- You can find detailed documentation about how to use the API on [Mashape](https://www.mashape.com/sneeza/project-rainhawk#!documentation). The API is free to use while it's still in active pre-release development. Mashape have many wrappers for different languages which can be used to make calls to the API using an authorization key, so they'll help you get started. We are currently in the process of developing more complex and native wrapper classes for different languages, to interface with the API directly and take care of all the error handling for you. Please check back here for more info in the near future. Developing With Vagrant --------------------- In order to develop with Vagrant, you need to do the following: 1. Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads). 2. Clone this repository somewhere on your machine. ```bash git clone https://github.com/zacoppotamus/elgarscodingorchestra.git ``` 3. Navigate into the cloned directory and start Vagrant. This may take a while to run, so you can move to the next steps while it's downloading all of the necessary files. ```bash cd elgarscodingorchestra && vagrant up ``` 4. Add the following records to your `/etc/hosts` or `%systemroot%\system32\drivers\etc\hosts` file: ```bash 127.0.0.1 rainhawk.dev api.rainhawk.dev ``` 5. Once step 3 has completed provisioning, navigate your browser to [rainhawk.dev:8080](http://rainhawk.dev:8080) and you'll be able to access the project website. 6. To get access to the dev machine, use the following command from anywhere in the directory. This will create an SSH tunnel into the virtual machine, where `/vagrant` is a syncronised folder to the git directory. ```bash vagrant ssh ``` Unit Tests + Test Cases --------------------- There are two different types of test cases that can be run - unit tests and procedural tests. To run all of the unit tests for the API, navigate to `/api/tests` and execute: ```bash $ php run.php suite Rainhawk . OK (1 tests, 0 assertions) 0.00 seconds Rainhawk\Data ... ..... ....... ... ``` If you wish to run a single unit test, or more than one then execute: ```bash $ php run.php Rainhawk\Data Rainhawk\Data ... ..... ....... ... .... .... ... ..... OK (34 tests, 0 assertions) 0.00 seconds ``` If you wish to test the different wrappers then you can navigate to `/wrappers/{lang}/tests.x`. To run the PHP tests, execute `php tests.php` and to run the Javascript tests open the `tests.html` file in your web browser. <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->name) || empty($data->description)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } if(!preg_match("/^[a-zA-Z0-9\-\_]+$/", $data->name)) { echo json_beautify(json_render_error(402, "The dataset name you passed contains disallowed characters!")); exit; } /*! * Come up with a new prefix to use for the dataset, by generating * a 6 character string and checking that it hasn't already been * used. Now we can just use their username. */ $data->prefix = app::$username; $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check if you already have a dataset with this name. if($dataset->exists) { echo json_beautify(json_render_error(403, "You already have a dataset with this name!")); exit; } /*! * Now that we have our prefix and name, we can create the new * dataset and return the details to the user. */ $dataset->prefix = $data->prefix; $dataset->name = $data->name; $dataset->description = $data->description; // Give this user read and write access. $dataset->read_access[] = app::$username; $dataset->write_access[] = app::$username; // Perform the creation command. if(!rainhawk\sets::create($dataset)) { echo json_beautify(json_render_error(404, "There was a problem while trying to create your dataset - please try again later.")); exit; } // Get a new reference to the dataset. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Create an index on _id to force-create the set. if(!$dataset->add_index("_id")) { echo json_beautify(json_render_error(405, "There was a problem while trying to create your dataset - please try again later.")); exit; } /*! * Define our output by filling up the JSON array with the variables * from the dataset object. */ $json = array( "name" => $dataset->prefix . "." . $dataset->name, "description" => $dataset->description, "rows" => $dataset->rows, "fields" => array_keys($dataset->fields), "constraints" => $dataset->constraints, "read_access" => $dataset->read_access, "write_access" => $dataset->write_access ); /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep>#include <vector> #include <fstream> #include <sstream> #include <string> #include "sadUtils.hpp" #include "sadWriter.hpp" #include "sadReader.hpp" #include "sadTables.hpp" using namespace std; string jsonDocument( sheet &sh, table tbl ) { vector<string> fieldNames; string output; unsigned ind = 0; output += tab(ind) + "{\n"; ind++; output += tab(ind) + "\"data\" : [\n"; ind++; for( size_t col = tbl.x1; col <= tbl.x2; col++ ) { fieldNames.push_back( sh[tbl.y1][col].getString() ); } for( size_t row = tbl.y1+1; row <= tbl.y2; row++ ) { output += tab(ind) + "{\n"; ind++; for( size_t col = tbl.x1; col <= tbl.x2; col++ ) { output += tab(ind) + "\""; output += fieldNames[col-tbl.x1]; output += "\" : "; JType type = sh[row][col].getType(); ostringstream converter; switch( type ) { case STRING: output += "\""; output += sh[row][col].getString(); output += "\""; break; case NUMBER: converter << sh[row][col].getNumber(); output += converter.str(); break; case BOOL: if( sh[row][col].getBool() ) output += "true"; else output += "false"; break; case NULLVALUE: output += "null"; break; default: break; } if( col != tbl.x2 ) output += ','; output += '\n'; } ind--; output += tab(ind) + "}"; if( row != tbl.y2 ) output += ','; output += "\n"; } ind--; output += tab(ind) + "]\n"; ind--; output += tab(ind) + "}"; return output; } vector<string> jsonFile( string filename, sheet &sh, vector<table> tbls ) { vector<string> outputs; for( size_t it = 0; it < tbls.size(); it++ ) { string output = filename + "-" + to_string(it) + ".json"; ofstream ofs( output.c_str() ); ofs << jsonDocument( sh, tbls[it] ); ofs.close(); outputs.push_back( output ); } return outputs; } <file_sep>eco.charts.d3bubblechart = function() { return { title : 'Bubble Chart', options : { width : 1500, height : 800, margin : { top: 100, right: 20, bottom: 30, left: 80 } }, render : function(data, xValue, yValue, maxRadius, target) { options = this.options; var width = options.width, height = options.height; var color = d3.scale.category20b(); var maxElement = d3.max(d3.values(data),function(i){ return +i[yValue]; }); var minElement = d3.min(d3.values(data),function(i){ return +i[yValue]; }); var scale = d3.scale.linear() .range([10, height/15]) .domain([minElement, maxElement]); var scalingFactor = (height/10)/maxElement; var svg = target.append("svg") .attr("class", "bubble-chart"); var force = d3.layout.force() .nodes(data) .size([width, height]) .gravity(0.01) .charge(-1000/data.length) .start(); var nodes = svg.selectAll(".bubble-chart-node") .data(force.nodes()) .enter() .append("g") .attr("class", "bubble-chart-node") .on("mouseover", mouseover) .on("mouseout", mouseout) .call(force.drag); nodes.append("circle") .attr("r", function(data) { return scale(data[yValue]); }) .attr("fill", function(d, i) { return color(i); }); force.on("tick", function() { callCollisions(); svg.selectAll("circle") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); svg.on("mousemove", function() { force.resume(); }); function mouseover(d) { d3.select(this) .select("circle") .transition() .duration(150) .attr("r", function(data) { return scale(data[yValue]) * 1.2; }); d3.selectAll("[class=bubble-text]").remove(); svg.append("g") .append("text") .attr("x", 25) .attr("y", 50) .attr("class", "bubble-text") .attr("fill", "#483D8B") .text(d[xValue] + ": " + d[yValue]); callCollisions(d); }; function mouseout() { d3.select("bubble-chart-tooltip").classed("hidden", true); d3.select(this) .select("circle") .transition() .duration(150) .attr("r", function(data) { return scale(data[yValue]); }); }; function collide(node,ex) { var r = scale(node[yValue]) * ex + 20, nx1 = node["x"] - r, nx2 = node["x"] + r, ny1 = node["y"] - r, ny2 = node["y"] + r; return function(quad, x1, y1, x2, y2) { if (quad.point && (quad.point !== node)) { var x = node["x"] - quad.point.x, y = node["y"] - quad.point.y, l = Math.sqrt(x * x + y * y), r = (scale(node[yValue]) + scale(quad.point[yValue])) * ex; if (l < r) { l = (l - r) / l * .5; node["x"] -= x *= l; node["y"] -= y *= l; quad.point.x += x; quad.point.y += y; } } return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1; }; }; function callCollisions(selected) { var nn = nodes[0]; var n = nn.length; var i = -1, j = -1; var cords = new Array(); function f(d,j) { cords[j] = d[j]["__data__"]; }; while (++j < n) f(nn,j); var q = d3.geom.quadtree(cords); while (++i < n) { if (selected != null) { if (cords[i].index == selected.index) q.visit(collide(cords[i],1.1)) else q.visit(collide(cords[i],1)); } else q.visit(collide(cords[i],1)); }; } } } } <file_sep>#include <vector> #include <string> #include <iostream> #include "readFile.h" #include "JSONWriter.h" using namespace std; typedef struct { unsigned y; unsigned x1; unsigned x2; } header; typedef struct { unsigned x1; unsigned y1; unsigned x2; unsigned y2; } table; vector<header> detectRows( vector< vector<sheetNode> > spreadsheet ) { unsigned currentPos; unsigned stringCount; unsigned height = 0; vector<header> headers; header newHeader; for( vector< vector<sheetNode> >::iterator outIt = spreadsheet.begin(); outIt != spreadsheet.end(); outIt++ ) { currentPos = 0; stringCount = 0; for( vector<sheetNode>::iterator inIt = outIt->begin(); inIt != outIt->end(); inIt++ ) { if( inIt->getType() == STRING ) { stringCount++; } else { if( stringCount > 1 ) { newHeader.y = height; newHeader.x1 = currentPos - stringCount; newHeader.x2 = currentPos - 1; headers.push_back( newHeader ); } stringCount = 0; } currentPos++; } if( stringCount > 1 ) { newHeader.x2 = currentPos - 1; newHeader.x1 = currentPos - 1 - stringCount ; headers.push_back( newHeader ); } height++; } return headers; } bool containedIn( vector<table> tables, header row ) { //Assumes that the row is always at the same height or lower on the //spreadsheet than the lowest table in tables //This is the case in intended use as tables are added to the list in //vertical descending order and the row always represents the latest table for( vector<table>::iterator it = tables.begin(); it != tables.end(); it++ ) { if( ( row.x1 >= it->x1 ) && ( row.x2 <= it->x2 ) ) { if( row.y <= it->y2 ) { return true; } } } return false; } int area( table square ) { int size = ( square.x2 + 1 - square.x1 ) * ( square.y2 + 1 - square.y1 ); return size; } void printBoolGrid( vector< vector<bool> > grid ) { for( vector< vector<bool> >::iterator outIt = grid.begin(); outIt != grid.end(); outIt++ ) { for( vector<bool>::iterator inIt = outIt->begin(); inIt != outIt->end(); inIt++ ) { cout << *inIt << " "; } cout << '\n'; } cout << '\n'; } table getTable( vector< vector<sheetNode> > spreadsheet, header row ) { table newTable; table maxTable; maxTable.x1 = 0; maxTable.x2 = 0; maxTable.y1 = 0; maxTable.y2 = 0; unsigned cX; unsigned cY; bool blank; vector< vector<bool> > checkedCells; vector<bool> newRow( row.x2 - row.x1 + 1, false ); for( unsigned count = row.x1; count <= row.x2; count++ ) { blank = false; cY = row.y; newTable.x1 = count; newTable.y1 = cY; while( !blank ) { cY++; if( cY - row.y > checkedCells.size() ) { checkedCells.push_back( newRow ); } if( spreadsheet[cY][count].getType() == NULLVALUE ) { blank = true; } } for( unsigned count2 = cY-1; count2 > row.y; count2-- ) { cX = count; if( !checkedCells[count2 - row.y - 1][cX - row.x1] ) { checkedCells[count2 - row.y - 1][cX - row.x1] = true; blank = false; while( !blank ) { cX++; checkedCells[count2 - row.y - 1][cX - row.x1] = true; if( spreadsheet[count2][cX].getType() == NULLVALUE ) { blank = true; } } newTable.x2 = cX-1; newTable.y2 = count2; if( area(newTable) > area(maxTable) ) { maxTable = newTable; } } } } return maxTable; } bool collisionTables( table first, table second ) { if( first.x2 < second.x1 || first.x1 > second.x2 ) { return false; } if( first.y2 < second.y1 || first.y1 > second.y2 ) { return false; } return true; } void collisionScan( vector<table> &tables ) { for( vector<table>::iterator outIt = tables.begin(); outIt != tables.end(); outIt++ ) { for( vector<table>::iterator inIt = outIt + 1; inIt != tables.end(); inIt++ ) { if( collisionTables( *outIt, *inIt ) ) { if( area( *inIt ) <= area( *outIt ) ) { inIt = tables.erase( inIt ); inIt--; } else { outIt = tables.erase( outIt ); outIt--; break; } } } } } vector<table> contentScan( vector< vector<sheetNode> > spreadsheet, vector<header> headers ) { vector<table> tables; table newTable; for( vector<header>::iterator it = headers.begin(); it != headers.end(); it++ ) { if( !containedIn( tables, *it ) ) { newTable = getTable( spreadsheet, *it ); if( newTable.y2 - newTable.y1 > 1 ) { tables.push_back( newTable ); } } } return tables; } //Only clears spaces and tabs string clearWhiteSpace( string target ) { size_t start = 0; size_t end = target.size() - 1; while( target[start] == ' ' || target[start] == '\t' ) start++; while( target[end] == ' ' || target[end] == '\t' ) end--; if( start != 0 || end != target.size() - 1 ) { if( start >= end || end == string::npos ) return ""; string result = target; cout << '"' << result << "\", " << start << ", " << end << '\n'; result.resize( end + 1 ); return result.substr( start ); } return target; } vector<JSONObject> encodeTable( vector< vector<sheetNode> > spreadsheet, table data ) { unsigned cX; unsigned cY = data.y1 + 1; string nameval; string strval; long double numval; bool boolval; JType datatype; vector<JSONObject> result; while( cY <= data.y2 ) { JSONObject next; cX = data.x1; while( cX <= data.x2 ) { nameval = spreadsheet[data.y1][cX].getString(); datatype = spreadsheet[cY][cX].getType(); switch( datatype ) { case STRING: strval = spreadsheet[cY][cX].getString(); strval = clearWhiteSpace( strval ); strval = "\"" + strval + "\""; next.addPair( nameval, strval ); break; case NUMBER: numval = spreadsheet[cY][cX].getNumber(); next.addPair( nameval, numval ); break; case OBJECT: case ARRAY: break; case BOOL: boolval = spreadsheet[cY][cX].getBool(); next.addPair( nameval, boolval ); break; case NULLVALUE: next.addPair( nameval ); break; } cX++; } result.push_back( next ); cY++; } return result; } vector< vector<JSONObject> > encodeTables( vector< vector<sheetNode> > spreadsheet, vector<table> tables ) { vector< vector<JSONObject> > result; for( vector<table>::iterator it = tables.begin(); it != tables.end(); it++ ) { vector<JSONObject> nextObject( encodeTable( spreadsheet, *it ) ); result.push_back( nextObject ); } return result; } vector< vector<JSONObject> > processData( vector< vector<sheetNode> > spreadsheet ) { //Padding the spreadsheet to prevent out-of-bounds access errors during //table scanning sheetNode nullcell; vector<sheetNode> nullrow( spreadsheet[0].size()+1, nullcell ); for( vector< vector<sheetNode> >::iterator it = spreadsheet.begin(); it != spreadsheet.end(); it++ ) { it->push_back( nullcell ); } spreadsheet.push_back( nullrow ); vector<header> initialHeaders( detectRows( spreadsheet ) ); vector<table> initialTables( contentScan( spreadsheet, initialHeaders ) ); collisionScan( initialTables ); vector< vector<JSONObject> > result( encodeTables( spreadsheet, initialTables ) ); return result; } <file_sep>#ifndef FILEWRITER #define FILEWRITER #include <vector> #include <string> using namespace std; class JSONObject { public: JSONObject(); void addPair( string name, const char * value ); void addPair( string name, string &value ); void addPair( string name, long double value ); void addPair( string name, bool value ); void addPair( string name ); string getName( unsigned pos ); string getValue( unsigned pos ); int fieldCount(); private: unsigned fields; std::vector<string> names; std::vector<string> values; }; string JSONString( JSONObject object ); int createJDocument( string name, vector<JSONObject> objects ); #endif <file_sep><?php /*! * This class allows us to connect to a network cache storage * to access globally shared objects. We use this for User, * Trade and other classes. */ class Redis { // Define some public variables for connections. public static $host = "127.0.0.1"; public static $port = 6379; public static $enabled = false; // Store some stats about the class. public static $access_time = 0; public static $hits = 0; public static $misses = 0; public static $hit = array(); public static $missed = array(); // Define some private variables. private static $timeout = 6; private static $persistent = false; private static $socket = null; /*! * Connect to the Redis server using the defined host and port, * using fsockopen as a data stream. Optionally, accept a toggle * for using persistent connections. */ public static function connect($host = null, $port = null, $persistent = false) { if($host) self::$host = $host; if($port) self::$port = $port; $timeout = self::$timeout; $flags = STREAM_CLIENT_CONNECT; if($persistent) { $flags |= STREAM_CLIENT_PERSISTENT; } self::$enabled = true; self::$persistent = $persistent; self::$socket = stream_socket_client(self::$host . ":" . self::$port, $errno, $error, $timeout, $flags); } /*! * Close the socket so that we can free up the resource. If we're * using persistent connections, then ignore the request. */ public static function close() { if(self::$socket && !self::$persistent) { fclose(self::$socket); } return false; } /*! * Define a function for fetching a variable from the Redis store, * which stores statistics about the usage of the class. */ public static function fetch($key) { if(!self::$socket || !self::$enabled) { return null; } $start = microtime(true); $data = self::send_command(array("GET", $key)); if(!is_null($data)) { self::$hits++; self::$hit[] = $key; $data = unserialize($data); } else { self::$misses++; self::$missed[] = $key; } $finish = microtime(true); self::$access_time += $finish - $start; return $data; } /*! * Define a function for fetching multiple variables from the cache * in one request, reducing network overhead for simple things. */ public static function fetch_multi() { if(!self::$socket || !self::$enabled) { return null; } $args = func_get_args(); if(count($args) == 1 && is_array($args[0])) { $args = array_values($args[0]); } $start = microtime(true); $data = self::send_command(array_merge(array("MGET"), $args)); $results = array(); $i = 0; foreach($data as $d) { if(!is_null($d)) { self::$hits++; self::$hit[] = $args[$i]; $d = unserialize($d); } else { self::$misses++; self::$missed[] = $args[$i]; } $results[$args[$i]] = $d; $i++; } $finish = microtime(true); self::$access_time += $finish - $start; return $results; } /*! * Define a function for fetching a variable from the Redis store, * which stores statistics about the usage of the class. */ public static function store($key, $data, $ttl = 0) { if(!self::$socket || !self::$enabled) { return false; } $data = serialize($data); $args = ($ttl == 0) ? array("SET", $key, $data) : array("SETEX", $key, $ttl, $data); return self::send_command($args); } /*! * Delete a key from the Redis cache, which is pretty useful for * invalidating cache records. */ public static function remove($key) { if(!self::$enabled) { return false; } return self::send_command(array("DEL", $key)); } /*! * Run a single FLUSHALL command on the Redis server to clear * the entire cache. */ public static function flushall() { if(!self::$enabled) { return false; } return self::send_command(array("FLUSHALL")); } /*! * Send the command to the socket specified at the start of * the class. */ private static function send_command($args) { $command = "*" . count($args) . "\r\n"; foreach($args as $argument) { $command .= "$" . strlen($argument) . "\r\n"; $command .= $argument . "\r\n"; } fwrite(self::$socket, $command); return self::parse_response(); } /*! * Parse the response given to us by Redis, depending on the * format specified. */ private static function parse_response() { $line = fgets(self::$socket); list($type, $result) = array($line[0], substr($line, 1, strlen($line) - 3)); if($type == "-") { return null; } else if($type == "$") { if($result == "-1") { return null; } else { $read = 0; $size = intval($result); $result = null; if($size > 0) { do { $block_size = ($size - $read) > 1024 ? 1024 : ($size - $read); $line = fread(self::$socket, $block_size); $read += strlen($line); $result .= $line; } while ($read < $size); } fread(self::$socket, 2); return $result; } } else if($type == "*") { $count = (int)$result; $result = array(); for($i = 0; $i < $count; $i++) { $result[] = self::parse_response(); } } return $result; } }<file_sep><?php // Include the necessary classes. include("classes/app.class.php"); include("classes/curl.class.php"); include("classes/redis.class.php"); include("classes/xcache.class.php"); include("classes/rainhawk/rainhawk.class.php"); include("classes/rainhawk/dataset.class.php"); include("classes/rainhawk/sets.class.php"); include("classes/rainhawk/data.class.php"); /*! * Set the timezone properly. */ date_default_timezone_set("UTC"); /*! * Make a new instance of App, which is a global singleton that * we can use to get vital information about the application's * current state and some global variables. In this block, we * define all the required variables depending on what machine * we're running on. */ app::$development = (file_exists("/vagrant") || stripos($_SERVER['HTTP_HOST'], "dev") !== false); app::$debug = (isset($_GET['d3bug'])); app::$maintenance = false; app::$version = "γ"; app::$init_time = microtime(true); app::$stack = array( "redis" => array( "host" => "127.0.0.1", "port" => 6379 ), "mongodb" => array( "host" => "127.0.0.1", "port" => 27017, "database" => "eco" ) ); if(!app::$development) { app::$root_path = "/home/www/spe.sneeza.me/"; } else { app::$debug = true; app::$root_path = "/vagrant/www/"; } if(app::$debug) { ini_set("display_errors", 1); error_reporting(E_ALL & ~E_NOTICE); } /*! * Create a new instance of the cache, depending on which deployment * we're on. We need one instance of xcache, which is our local * cache, and one instance of redis, which is our global cache. */ xcache::init(); redis::connect(app::$stack['redis']['host'], app::$stack['redis']['port']); /*! * Set the user agent to be used in the cURL singleton. */ curl::$timeout = 6; curl::$user_agent = "ECO " . app::$version . "; spe.sneeza.me;"; /*! * Connect to MongoDB so that we can run queries on different data * sets that have been imported. */ rainhawk::connect(app::$stack['mongodb']['host'], app::$stack['mongodb']['port']); rainhawk::select_database(app::$stack['mongodb']['database']); /*! * Check if the Mashape key has been set, and if not then use a * default key so we don't break direct integration with our test * services. */ app::$username = isset($_SERVER['HTTP_X_MASHAPE_USER']) ? trim(strtolower($_SERVER['HTTP_X_MASHAPE_USER'])) : "global"; ?><file_sep>'use strict'; // Use shared services here as a way to share data between controllers, or between // controller/directive angular.module('eco.services', []) .factory('dataService', function($http, $q) { var dataService = {}; dataService.currentData = ''; dataService.selectedDataset = ''; dataService.selectedVizType; dataService.vizOptions = ''; // get data for the selected dataset // TODO check for empty datasets dataService.sayhey = function(name) { console.log('Hi, '+name); }; dataService.getData = function(datasetName, apikey) { // this happens asynchronously var promise = $http({ method: 'GET', url: 'https://sneeza-eco.p.mashape.com/datasets/'+datasetName+'/data', headers: { 'X-Mashape-Authorization' : apikey } }). success(function(json) { console.log('Done getting data from ' + datasetName + ' and injecting to controller'); dataService.currentData = json.data.results; }); return promise; } /* dataService.getDatasetNames = function(apiKey) { // todo: get user's API key from cookie var datasets; var promise = $http({ method: 'GET', url: 'https://sneeza-eco.p.mashape.com/datasets', headers: { 'X-Mashape-Authorization' : apiKey } }). success(function(json) { // attach the data to the scope var datasets = []; console.log(json); $.each(json.data.datasets, function(key,val) { var datasetName = val.name.split('.')[1]; dataService.datasets.push(datasetName); }); }); console.log(datasets); return datasets; };*/ dataService.getSelectedDataset = function() { console.log('Selected Dataset: ' + this.selectedDataset); return this.selectedDataset; }; dataService.getCurrentData = function() { console.log('Current Data: ' + this.currentData); return this.currentData; }; dataService.getSelectedVizType = function() { console.log('Selected Visualisation Type is: ' + this.selectedVizType); return this.selectedVizType; }; return dataService; });<file_sep><?php require_once "rainhawk.php"; require_once "redis.php"; // Start session handling. session_start(); // Get the user's information. $mashape_key = isset($_SESSION['apiKey']) ? $_SESSION['apiKey'] : null; $user = isset($_SESSION['user']) ? $_SESSION['user'] : null; // Set up the Rainhawk wrapper. $rainhawk = new Rainhawk($mashape_key); // Connect to our Redis cache. redis::connect("127.0.0.1", 6379); ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array(); /*! * Try and add the access to the dataset as the user has specified, * which will always work even if the access already exists. */ // Check if the type is set. if(empty($data->type)) { echo json_beautify(json_render_error(404, "You didn't specify the type of access to give.")); exit; } // Check if the username is set. if(empty($data->username)) { echo json_beautify(json_render_error(404, "You didn't specify the user to give access to.")); exit; } // If the type is JSON, decode it into an array. $data->type = json_decode($data->type, true) ?: $data->type; // Iterate through the type or types set and apply them. if(is_string($data->type)) { // Make sure the type is valid. if(!in_array($data->type, array("read", "write"))) { echo json_beautify(json_render_error(405, "You didn't specify a valid type of access to give.")); exit; } // Check if the user already has that access. if(in_array($data->username, $dataset->{$data->type . "_access"})) { echo json_beautify(json_render_error(406, "The user you specified already has " . $data->type . " access to this dataset.")); exit; } // Give the user access. $dataset->{$data->type . "_access"}[] = $data->username; $dataset->{$data->type . "_access"} = array_unique($dataset->{$data->type . "_access"}); } else { // Iterate through the types. foreach($data->type as $type) { // Make sure the type is valid. if(!in_array($type, array("read", "write"))) { echo json_beautify(json_render_error(405, "You didn't specify a valid type of access to give.")); exit; } // Check if the user already has that access. if(in_array($data->username, $dataset->{$type . "_access"})) { echo json_beautify(json_render_error(406, "The user you specified already has " . $type . " access to this dataset.")); exit; } // Give the user access. $dataset->{$type . "_access"}[] = $data->username; $dataset->{$type . "_access"} = array_unique($dataset->{$type . "_access"}); } } // Store the dataset information in the index table. \rainhawk\sets::update($dataset); // Return the added attribute to the JSON. $json['added'] = true; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep>function printDatasets() { $(document).ready(function() { $.getJSON("//api.spe.sneeza.me/datasets", function(data) { $.each(data.data.datasets, function(key,val) { // No description field yet. var description = val.description; var size = val.rows; var tr = $('<tr><td id="dataset"><a href="dataset.html">'+val.name+'</a></td><td>'+description+'</td><td>'+size+'</td></tr>'); $('table').append(tr); }) }) }); } function vizPrintDatasets() { $(document).ready(function() { $.getJSON("//api.spe.sneeza.me/datasets", function(data) { $.each(data.data.datasets, function(key,val) { var rb = $('<div class="row"><div class="btn-group" data-toggle="buttons"><label class="btn btn-default btn-block"><input type="radio" name="options" id="option">'+val.name+'</label></div></div>'); $('#datasets').append(rb); }) }) $(document).on('mousedown', '.btn', function() { $(this).button(); }) }); } function printDataset() { $(document).ready(function() { // Update to GET value dataset = window.location.search.slice(1); $.getJSON("http://api.spe.sneeza.me/datasets/"+dataset, function(result){ $.each(result.data.fields[0], function(k, header){ $('.table').append("<th>" + k + "</th>"); }); $.each(result.data.fields, function(i, row){ var tr; $.each(row, function(j, col){ tr = tr + "<td>" + col + "</td>"; }); $('.table').append("<tr>" + tr + "</tr>"); }); }); }); } <file_sep><?php // Show errors all the time. error_reporting(E_ALL & ~E_NOTICE); ini_set("display_errors", 1); // Set the header content type including charset. include("includes/classes/route.class.php"); header("content-type: application/json; charset=utf8"); header("access-control-allow-origin: *"); header("access-control-allow-headers: *"); /*! * Add all of the possible routes to the class, including * API paths and stuff. */ // Set the data object. $data = new stdClass; // Create a main endpoint. route::get("/", function() use($data) { include("main.php"); }); // Create an endpoint for the ping command. route::get("/ping", function() use($data) { include("ping.php"); }); // Create an endpoint to list all available datasets. route::get("/datasets", function() use($data) { include("datasets.php"); }); // Create an endpoint to create a new dataset. route::post("/datasets", function() use($data) { $data->name = isset($_POST['name']) ? strtolower(trim($_POST['name'])) : null; $data->description = isset($_POST['description']) ? trim($_POST['description']) : null; include("datasets/create.php"); }); // Create an endpoint to get the info about a dataset. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; include("datasets/info.php"); }); // Create an endpoint to get the info about a dataset. route::delete("/datasets/(\w+|\-+)\.(\w+|\-+)", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; include("datasets/remove.php"); }); // Create an endpoint to perform a query on a dataset. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)/data", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->query = isset($_GET['query']) ? json_decode($_GET['query'], true) : null; $data->offset = isset($_GET['offset']) && intval($_GET['offset']) >= 0 ? intval($_GET['offset']) : 0; $data->limit = isset($_GET['limit']) && intval($_GET['limit']) >= 1 ? intval($_GET['limit']) : null; $data->sort = isset($_GET['sort']) ? json_decode($_GET['sort'], true) : null; $data->fields = isset($_GET['fields']) ? json_decode($_GET['fields'], true) : null; $data->exclude = isset($_GET['exclude']) ? json_decode($_GET['exclude'], true) : null; include("datasets/data.php"); }); // Create an endpoint to insert new data into the dataset. route::post("/datasets/(\w+|\-+)\.(\w+|\-+)/data", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->row = isset($_POST['row']) ? json_decode($_POST['row'], true) : null; $data->rows = isset($_POST['rows']) ? json_decode($_POST['rows'], true) : null; include("datasets/data/insert.php"); }); // Create an endpoint to update data in the dataset. route::put("/datasets/(\w+|\-+)\.(\w+|\-+)/data", function($prefix, $name) use($data) { parse_str(file_get_contents("php://input"), $_PUT); $data->prefix = $prefix; $data->name = $name; $data->query = isset($_PUT['query']) ? json_decode($_PUT['query'], true) : null; $data->changes = isset($_PUT['changes']) ? json_decode($_PUT['changes'], true) : null; include("datasets/data/update.php"); }); // Create an endpoint to delete data from the dataset. route::delete("/datasets/(\w+|\-+)\.(\w+|\-+)/data", function($prefix, $name) use($data) { parse_str(file_get_contents("php://input"), $_DELETE); $data->prefix = $prefix; $data->name = $name; $data->query = isset($_DELETE['query']) ? json_decode($_DELETE['query'], true) : null; include("datasets/data/delete.php"); }); // Create an endpoint to insert new data into the dataset. route::put("/datasets/(\w+|\-+)\.(\w+|\-+)/upload/(\w+|\-+)", function($prefix, $name, $type) use($data) { $data->prefix = $prefix; $data->name = $name; $data->type = in_array(strtolower($type), array("csv", "xlsx", "ods")) ? strtolower($type) : null; include("datasets/upload.php"); }); // Create an endpoint to list the constraints on a dataset. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)/constraints", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; include("datasets/constraints.php"); }); // Create an endpoint to add a constraint to a dataset. route::post("/datasets/(\w+|\-+)\.(\w+|\-+)/constraints", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->field = isset($_POST['field']) ? trim($_POST['field']) : null; $data->type = isset($_POST['type']) ? trim(strtolower($_POST['type'])) : null; include("datasets/constraints/add.php"); }); // Create an endpoint to remove a constraint on a dataset. route::delete("/datasets/(\w+|\-+)\.(\w+|\-+)/constraints", function($prefix, $name) use($data) { parse_str(file_get_contents("php://input"), $_DELETE); $data->prefix = $prefix; $data->name = $name; $data->field = isset($_DELETE['field']) ? trim($_DELETE['field']) : null; include("datasets/constraints/remove.php"); }); // Create an endpoint to list the indexes on a dataset. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)/indexes", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; include("datasets/indexes.php"); }); // Create an endpoint to add an index to a dataset. route::post("/datasets/(\w+|\-+)\.(\w+|\-+)/indexes", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->field = isset($_POST['field']) ? trim($_POST['field']) : null; include("datasets/indexes/add.php"); }); // Create an endpoint to remove an index from a dataset. route::delete("/datasets/(\w+|\-+)\.(\w+|\-+)/indexes", function($prefix, $name) use($data) { parse_str(file_get_contents("php://input"), $_DELETE); $data->prefix = $prefix; $data->name = $name; $data->field = isset($_DELETE['field']) ? trim($_DELETE['field']) : null; include("datasets/indexes/remove.php"); }); // Create an endpoint to list the access to a dataset. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)/access", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; include("datasets/access.php"); }); // Create an endpoint to add access to a dataset. route::post("/datasets/(\w+|\-+)\.(\w+|\-+)/access", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->type = isset($_POST['type']) ? $_POST['type'] : null; $data->username = isset($_POST['username']) ? trim(strtolower($_POST['username'])) : null; include("datasets/access/add.php"); }); // Create an endpoint to remove access to a dataset. route::delete("/datasets/(\w+|\-+)\.(\w+|\-+)/access", function($prefix, $name) use($data) { parse_str(file_get_contents("php://input"), $_DELETE); $data->prefix = $prefix; $data->name = $name; $data->type = isset($_DELETE['type']) && in_array($_DELETE['type'], array("read", "write")) ? trim(strtolower($_DELETE['type'])) : null; $data->username = isset($_DELETE['username']) ? trim(strtolower($_DELETE['username'])) : null; include("datasets/access/remove.php"); }); // Create an endpoint for the polyfit calculations. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)/calc/polyfit", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->fields = isset($_GET['fields']) ? json_decode($_GET['fields'], true) : null; $data->degree = isset($_GET['degree']) && $_GET['degree'] > 0 && $_GET['degree'] <= 20 ? (int)$_GET['degree'] : 2; include("datasets/calc/polyfit.php"); }); // Create an endpoint for the stats calculations. route::get("/datasets/(\w+|\-+)\.(\w+|\-+)/calc/stats", function($prefix, $name) use($data) { $data->prefix = $prefix; $data->name = $name; $data->field = isset($_GET['field']) ? trim($_GET['field']) : null; $data->query = isset($_GET['query']) ? json_decode($_GET['query'], true) : null; include("datasets/calc/stats.php"); }); /*! * Perform the routing request. */ route::parse(); include("main.php"); exit; ?> <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array(); /*! * Try and add the access to the dataset as the user has specified, * which will always work even if the access already exists. */ // Check if the field is set. if(empty($data->field)) { echo json_beautify(json_render_error(404, "You didn't specify the field to remove the constraint on.")); exit; } // Remove the constraint from the field. unset($dataset->constraints[$data->field]); // Store the dataset information in the index table. \rainhawk\sets::update($dataset); // Set the output. $json['removed'] = true; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_read_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to read from this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "rows" => 0, "offset" => $data->offset, "results" => array() ); /*! * Perform our 'find' query based on the information fed to the * API. We have to check if some parameters are set/valid here. */ $query = array(); $fields = array(); // Check if we have a query or not. if(!empty($data->query)) { $query = $data->query; } // Check if any field names were sent. if(!empty($data->fields)) { if(is_array($data->fields)) { foreach($data->fields as $field_name) { $fields[$field_name] = true; } if(!isset($fields['_id'])) { $fields['_id'] = false; } } else { echo json_beautify(json_render_error(404, "You didn't specify the field names to return correctly, they should be in the form: ['field1', 'field2'].")); exit; } } // Check if we need to exclude fields. if(!empty($data->exclude)) { if(is_array($data->exclude)) { foreach($data->exclude as $field_name) { $fields[$field_name] = false; } } else { echo json_beautify(json_render_error(405, "You didn't specify the field names to exclude correctly, they should be in the form: ['field1', 'field2'].")); exit; } } // Change the MongoID if we have one. foreach($query as $key => $value) { if($key == "_id") { try { $mongoid = new MongoID($value); } catch(Exception $e) { $mongoid = null; } $query[$key] = $mongoid; } } // Run the query. $query = $dataset->find($query, $fields); // Check if the query failed. if(!$query) { echo json_beautify(json_render_error(406, "An unexpected error occured while performing your query - are you sure you formatted all the parameters correctly?")); exit; } // Get the number of rows the query matches. $json['rows'] = $query->count(); // Sort the query using the provided query. if(isset($data->sort)) { try { $query = $query->sort($data->sort); } catch(Exception $e) {} } // Set the offset if we have one. if($data->offset > 0) { $query = $query->skip($data->offset); } // If we have a row limit, apply it. if(isset($data->limit)) { $query = $query->limit($data->limit); $json['limit'] = $data->limit; } // Iterate through the results and populate the output. foreach($query as $row) { if(isset($row['_id'])) { $_id = (string)$row['_id']; unset($row['id']); $row = array("_id" => $_id) + $row; } foreach($row as $field => $value) { if(isset($dataset->constraints[$field])) { $row[$field] = \rainhawk\data::check($dataset->constraints[$field]['type'], $value); } } $json['results'][] = $row; } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_read_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to read from this dataset.")); exit; } /*! * Define our output by filling up the JSON array with the variables * from the dataset object. */ $json = array( "name" => $dataset->prefix . "." . $dataset->name, "description" => $dataset->description, "rows" => $dataset->rows, "fields" => array_keys($dataset->fields), "constraints" => $dataset->constraints, "read_access" => $dataset->read_access, "write_access" => $dataset->write_access ); /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep>import json # To convert to JSON import sys # To get arguments import warnings # To suppress numpy warnings import numpy # To calculate correlation from pymongo import MongoClient # To communicate with MongoDB warnings.simplefilter('ignore', numpy.RankWarning) def graphEquation(xPoints, yPoints, degree): x = numpy.array(xPoints) y = numpy.array(yPoints) poly = numpy.polyfit(x, y, degree) return poly.tolist() def query(databaseName, collectionName, xName, yName, degree): client = MongoClient('spe.sneeza.me', 27017) db = client[databaseName] collection = db[collectionName] xPoints = [p[xName] for p in collection.find()] yPoints = [p[yName] for p in collection.find()] equation = graphEquation(xPoints, yPoints, degree) print json.dumps(equation) return json.dumps(equation) def main(): if(len(sys.argv) == 6): return query(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) else: print "Usage: correlation.py databaseName collectionName xFieldName yFieldName degree" if __name__ == "__main__": main() <file_sep>New logic for our application --- This here is going to be the new logic for the frontend part of our project, using AngularJS. Even though its use is not needed as much in other sections of the website it is almost mandatory in the 'custom visualizations' part of the project and would greatly benefit the modularity of our application if it were also used when editing datasets (if we have time). Dependencies ---- ~~To get dependencies run ```bower install```.~~ Site is deployed automatically, so no point yet. To-Do ---- * The most important thing: Generating a visualization, maybe in the same, maybe in a different page. * Write a gruntfile/makefile for this and then the whole frontend. * Think of how to implement limitations in the data fields. * Refactor! PS ---- I know I broke the guidelines (several of them), but I couldn't think of another way to show how the app is going to be structured from now on without putting it in a separate folder! js/,img/,css/ is so 2010 :P. <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_read_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to read from this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "indexes" => array() ); /*! * Fetch the indexes from the dataset, and list them back to the * user in a friendly format. */ // Get a list of indexes. $indexes = $dataset->fetch_indexes(); // Check if the listing failed. if(!$indexes) { echo json_beautify(json_render_error(404, "There was a problem while fetching the indexes.")); exit; } // Return them into the JSON array. foreach($indexes as $index) { $json['indexes'][] = array_keys($index['key'])[0]; } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; $dataset = isset($_GET['dataset']) ? $_GET['dataset'] : null; $result = $rainhawk->deleteDataset($dataset); if($result) { header("Location: /datasets.php?deleted"); exit; } else { header("Location: /datasets.php?deletefailed"); exit; } ?> <file_sep><?php require_once "includes/core.php"; require_once "includes/check_login.php"; $dataset = isset($_GET['dataset']) ? htmlspecialchars($_GET['dataset']) : null; $datasetInfo = $rainhawk->fetchDataset($dataset); ?> <!DOCTYPE html> <html lang="en-GB"> <head> <title>Project Rainhawk - Upload Data</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <?php require_once "includes/meta.php"; ?> <style type="text/css"> .row .form-controls { margin-top: 40px; } </style> <script> rainhawk.apiKey = "<?php echo $mashape_key; ?>"; var file; $(function() { $('form').submit(uploadDataset); $('input[type=file]').change(prepareUpload); }); function prepareUpload(event) { file = event.target.files[0]; } function verifyDataset(name, success) { var url = 'https://sneeza-eco.p.mashape.com/datasets/' + name; $.ajax({ url: url, type: "GET", success: function(data) { if(data.meta.code === 200) { success(); } else { errormsg("Dataset does not exist or you do not have write access. Try creating a dataset using the <a class='alert-link' href='create.php'>create</a> interface.") } }, error: function(data) { return false; }, beforeSend: function(xhr) { xhr.setRequestHeader("X-Mashape-Authorization", "<?php echo $mashape_key; ?>"); } }); } function uploadDataset(event) { if($('#datasetName').length) { var name = $('#datasetName').val(); } else { name = '<?php echo $dataset ?>'; } verifyDataset(name, function() { $('#btnSubmit').button('loading'); var type = $('#datasetType').val(); var url = 'https://sneeza-eco.p.mashape.com/datasets/' + name + "/upload/" + type; $.ajax({ url: url, type: 'PUT', processData: false, contentType: false, data: file, datatype: 'json', success: function(data) { if(data.meta.code === 200) { successmsg(name); } else { errormsg(data.data.message); } }, error: function(err) { errormsg(JSON.stringify(err)); }, beforeSend: function(xhr) { xhr.setRequestHeader("X-Mashape-Authorization", "<?php echo $mashape_key; ?>"); } }); }); return false; } function errormsg(message) { $(".container:last").prepend( "<div class='alert alert-danger fade in'>"+ "<strong>Error!</strong> " + message + "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>"+ "</div>"); $('#btnSubmit').button('reset'); } function successmsg(name) { $(".container:last").prepend( "<div class='alert alert-success fade in'>"+ "<strong>Done!</strong> Data successfully uploaded to dataset <a class='alert-link' href='/properties.php?dataset="+name+"'>"+name+"</a>. "+ "Now try <a class='alert-link' href='/visualise/?dataset="+name+"'>visualising</a> the data."+ "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>"+ "</div>"); $('#btnSubmit').button('reset'); } </script> </head> <body> <?php require_once "includes/nav.php"; ?> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <h1>Upload data!</h1> <p>Select a file to upload into the relevant dataset...</p> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <form role="form"> <div class="form-group"> <label for="datasetName">Dataset Name:</label> <?php if(isset($dataset)) { ?> <p class="form-control-static"><?php echo $dataset; ?></p> <?php } else { ?> <input type="text" class="form-control" id="datasetName" name="datasetName" placeholder='Enter your dataset name here...' required autofocus> <?php } ?> </div> <div class="form-group"> <label for="datasetFile">Type:</label> <select class="form-control" id="datasetType"> <option value="csv">csv</option> <option value="xlsx">xlsx</option> <option value="ods">ods</option> </select> </div> <div class="form-group"> <label for="datasetFile">File</label> <input type="file" id="datasetFile" name="datasetFile"> </div> <div class="form-controls"> <button id="btnSubmit" type="submit" data-loading-text="Uploading..." class="btn btn-default">Upload</button> <a href="/datasets.php" type="button" class="btn btn-danger">Back</a> </div> </form> </div> </div> </div> </div> </div> </body> </html><file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; $dataset = isset($_GET['dataset']) ? htmlspecialchars($_GET['dataset']) : null; $datasetInfo = $rainhawk->fetchDataset($dataset); $fields = $datasetInfo['fields']; $constraints = $datasetInfo['constraints']; $errors = array(); if(isset($_GET['autoapply'])) { $result = $rainhawk->addConstraint($dataset); } else { foreach($_POST['constraint'] as $field => $constraint) { if($constraints[$field] != $constraint) { if(isset($constraints[$field])) { $result = $rainhawk->removeConstraint($dataset, $field); if(isset($result['message'])) { $errors[] = $result['message']; } } if($constraint != "none") { $result = $rainhawk->addConstraint($dataset, $field, $constraint); if(isset($result['message'])) { $errors[] = $result['message']; } } } } } header("Location: /properties.php?dataset=" . $dataset); exit; ?> <file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; header("content-type: application/json; charset=utf8"); $dataset = isset($_GET['dataset']) ? $_GET['dataset'] : null; $query = isset($_GET['query']) ? json_decode($_GET['query']) : null; $limit = isset($_GET['jtPageSize']) ? (int)$_GET['jtPageSize'] : null; $offset = isset($_GET['jtStartIndex']) ? (int)$_GET['jtStartIndex'] : 0; $fields = isset($_GET['fields']) ? json_decode($_GET['fields']) : null; $exclude = isset($_GET['exclude']) ? json_decode($_GET['exclude']) : null; $sort = isset($_GET['jtSorting']) ? $_GET['jtSorting'] : null; if(isset($sort)) { list($field, $order) = explode(" ", $sort); $sort = array($field => ($order == "ASC" ? 1 : -1)); } $records = array(); $results = $rainhawk->selectData($dataset, $query, $offset, $limit, $sort, $fields, $exclude); if(!$results) { echo json_encode(array( "Result" => "Fail", "Message" => $rainhawk->error() )); exit; } foreach($results['results'] as $row) { $records[] = $row; } echo json_encode(array( "Result" => "OK", "Records" => $records, "TotalRecordCount" => $results["rows"] )); exit; ?> <file_sep>'use strict'; angular.module('eco', [ 'eco.controllers', 'eco.directives', 'eco.services', 'ngRoute', 'ui.bootstrap' ]) .config(function($routeProvider, $locationProvider) { // configure routes $routeProvider // route for the final visualization .when('/visualization', { templateUrl: 'visualization.html', controller: 'ecoCtrl', }) // is '/' when starting server within newlogic/ .when('/', { templateUrl: 'customize.html', controller: 'ecoCtrl' // resolve: { // // controller won't be instantiated before all // // dependencies are resolved // 'dataService':function(dataService) { // return dataService.getData(); // } // } }); $locationProvider.html5Mode(true); }); <file_sep><?php // Include the Rainhawk class. include("rainhawk.class.php"); header("content-type: text/plain; charset=utf8"); // Create a debugging function. function debug($message) { echo "[+] " . $message . "\n"; } // Create a failure logging function. function failed($message) { global $errors; $errors++; echo "[!] " . $message . "\n"; } // Create the new instance. $rainhawk = new Rainhawk("eSQpirMYxjXUs8xIjjaUo72gutwDJ4CP"); $started = microtime(true); $username = null; $name = "phpwrapper"; $errors = 0; // Create an array of the tests. $tests = array( /** * Test #1: Ping the API. */ function() use($rainhawk) { global $username; debug("Checking that the API is online..."); $ping = $rainhawk->ping(); if($ping == false) { failed("Could not ping the service - " . $rainhawk->error()); } else { $username = $ping['mashape_user']; debug("--> Server time offset: " . (time() - $ping['server_time'])); debug("--> Found username: " . $username); } }, /** * Test #2: List the datasets, delete the dataset if it already exists, * create a dataset and then get information on the dataset. */ function() use($rainhawk) { global $username, $name; debug("Fetching a list of the datasets that we have access to..."); $datasets = $rainhawk->listDatasets(); if($datasets == false) { failed("Could not list the datasets - " . $rainhawk->error()); } else { debug("--> Found a list of datasets."); foreach($datasets as $dataset) { if($dataset['name'] == $username . "." . $name) { debug("--> Found " . $dataset['name'] . ", cleaning up..."); $rainhawk->deleteDataset($dataset['name']); } } } debug("Creating the test dataset, '" . $name . "'..."); $dataset = $rainhawk->createDataset($name, "An example dataset from the PHP class for testing."); if($dataset == false) { failed("Could not create the dataset - " . $rainhawk->error()); } else { debug("--> " . json_encode($dataset)); } $name = $username . "." . $name; debug("Fetching the information for the new dataset..."); $dataset = $rainhawk->fetchDataset($name); if($dataset == false) { failed("Could not fetch the dataset - " . $rainhawk->error()); } else { debug("--> " . json_encode($dataset)); } }, /** * Test #3: Add one row of data, add another two rows of data and upload * a file to the dataset. */ function() use($rainhawk) { global $name; debug("Adding one row of data to the dataset..."); $row = array( "name" => "John", "age" => 20, "weight" => 320.2, "role" => "content" ); $inserted = $rainhawk->insertData($name, $row); if($inserted == false) { failed("Could not insert one row of data - " . $rainhawk->error()); } else { debug("--> " . json_encode($inserted)); } debug("Adding two rows of data in batch to the dataset..."); $rows = array( array( "name" => "Jane", "age" => 24, "weight" => 220.4, "role" => "owner" ), array( "name" => "Bob", "age" => 36, "weight" => 320.6, "role" => "manager" ) ); $inserted = $rainhawk->insertMultiData($name, $rows); if($inserted == false) { failed("Could not insert two rows of data in batch - " . $rainhawk->error()); } else { debug("--> " . json_encode($inserted)); } debug("Uploading some rows of data to the dataset from a .csv..."); $file = "../test_data.csv"; $uploaded = $rainhawk->uploadData($name, $file); if($uploaded == false) { failed("Could not upload the data into the dataset - " . $rainhawk->error()); } else { debug("--> " . json_encode($uploaded)); } }, /** * Test #4: Detect the constraints that should be applied to the data, and * then remove one of the constraints and list the constraints. */ function() use($rainhawk) { global $name; debug("Automatically detecting constraints and applying them..."); $constraints = $rainhawk->addConstraint($name); if($constraints == false) { failed("Could not detect the constraints - " . $rainhawk->error()); } else { debug("--> " . json_encode($constraints)); } debug("Removing the constraint on 'role'..."); $removed = $rainhawk->removeConstraint($name, "role"); if($removed == false) { failed("Could not remove the constraint on 'role' - " . $rainhawk->error()); } else { debug("--> Removed: " . json_encode($removed)); } debug("Listing all constraints being applied to the dataset..."); $constraints = $rainhawk->listConstraints($name); if($constraints == false) { failed("Could not list the constraints - " . $rainhawk->error()); } else { debug("--> " . json_encode($constraints)); } }, /** * Test #5: Add an index to all of the fields on the dataset, remove one * of the indexes and then list them. */ function() use($rainhawk) { global $name; debug("Adding indexes to all of the relevant fields automatically..."); $indexes = $rainhawk->addIndex($name); if($indexes == false) { failed("Could not add the indexes - " . $rainhawk->error()); } else { debug("--> " . json_encode($indexes)); } debug("Removing the index on 'name'..."); $removed = $rainhawk->removeIndex($name, "name"); if($removed == false) { failed("Could not remove the index on 'name' - " . $rainhawk->error()); } else { debug("--> Removed: " . json_encode($removed)); } debug("Listing all indexes currently on the dataset..."); $indexes = $rainhawk->listIndexes($name); if($indexes == false) { failed("Could not list the indexes - " . $rainhawk->error()); } else { debug("--> " . json_encode($indexes)); } }, /** * Test #6: Select data from the dataset and then delete all of the data. */ function() use($rainhawk) { global $name; debug("Selecting some of the data..."); $query = array( "role" => "content" ); $select = $rainhawk->selectData($name, $query); if($select == false) { failed("Could not run the select query - " . $rainhawk->error()); } else { debug("--> " . json_encode($select)); } debug("Removing all of the data..."); $deleted = $rainhawk->deleteData($name, array()); if($deleted == false) { failed("Could not delete the data - " . $rainhawk->error()); } else { debug("--> Deleted: " . json_encode($deleted)); } }, /** * Test #7: Delete the dataset and clean up. */ function() use($rainhawk) { global $name; debug("Removing our test dataset..."); $deleted = $rainhawk->deleteDataset($name); if($deleted == false) { failed("Could not delete dataset - " . $rainhawk->error()); } else { debug("--> Deleted: " . json_encode($deleted)); } } ); // Run the tests. foreach($tests as $callable) { $callable(); } // Finish up and exit. debug("Done! All tests completed in " . number_format(microtime(true) - $started, 2) . " second(s)."); // Check for any failures. if($errors > 0) { failed("--> " . $errors . " operation(s) failed."); } // Finish execution. exit; ?><file_sep>/** * Project Rainhawk * * Simple PHP wrapper for the Rainhawk API, which provides simple JSON * encoded data for a variety of data sources with pre-defined * operations. * * @package Rainhawk * @license none */ var rainhawk = { /** * Set the base URL for the API. * * @var {string} */ host: "https://sneeza-eco.p.mashape.com", /** * Store the user's Mashape API key. * * @var {string} */ apiKey: null, /** * Create an object that can be used for communicating at an HTTP level * with the API. */ http: { /** * Store the supported methods for communicating with the API, which * are only the standard HTTP protocol methods. */ methods: { get: "GET", post: "POST", put: "PUT", del: "DELETE" }, /** * Method to create a new instance of a HTTP request using the above * factories. Each one is tested in turn until a valid object is received * at which point we can send the result back. * * @return {object} */ createRequest: function(method, url) { var request = new XMLHttpRequest(); if("withCredentials" in request) { request.open(method, url, true); return request; } else if(typeof XDomainRequest != "undefined") { request = new XDomainRequest(); request.open(method, url); return request; } return; }, /** * Send a HTTP request to the specified endpoint so that we can get * some data back and process requests. * * @param {object} options * @return {httprequest} */ send: function(options, success, failure) { if(!options.params) options.params = {}; if(!options.timeout) options.timeout = 10000; var request; var params; if(rainhawk.objectSize(options.params) > 0) { params = ""; for(var key in options.params) { params += key + "=" + encodeURIComponent(options.params[key]) + "&"; } params = params.substring(0, params.length - 1); if(options.method == this.methods.get) { options.url = options.url + "?" + params; params = null; } } request = this.createRequest(options.method, options.url); request.timeout = options.timeout; request.setRequestHeader("X-Mashape-Authorization", rainhawk.apiKey); if(params && !options.hasOwnProperty("file")) { request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } else if(options.method == this.methods.put && options.hasOwnProperty("file")) { params = options.file; } request.onload = function(e) { if(request.status == 200) { var json = JSON.parse(request.responseText); if(json.hasOwnProperty("meta") && json.hasOwnProperty("data") && json.meta.code == 200) { success(json); } else { failure(json.hasOwnProperty("data") && json.data.hasOwnProperty("message") ? json.data.message : "Invalid JSON received from API."); } } else { failure(request.statusText ? request.statusText : "An unknown error occured while performing the request."); } }; request.onerror = function(e) { failure(request.statusText ? request.statusText : "An unknown error occured while performing the request."); }; request.send(params); return request; } }, /** * Send a simple ping request to the API, which will respond with * the timestamp of the server's current time. * * @param {function} success * @param {function} error */ ping: function(success, error) { var url = rainhawk.host + "/ping"; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get }, function(json) { success(json.data); }, error); }, /** * Operations specific to datasets go in here. */ datasets: { /** * List the datasets that the current user can access (either read or * write) and some basic information about them. * * @param {function} success * @param {function} error */ list: function(success, error) { var url = rainhawk.host + "/datasets"; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get }, function(json) { success(json.data.datasets); }, error); }, /** * Fetch some information about a specific dataset, returning an array * of data that can be used to gather more insight into what the dataset * currently looks like. * * @param {string} name * @param {function} success * @param {function} error */ info: function(name, success, error) { var url = rainhawk.host + "/datasets/" + name; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get }, function(json) { success(json.data); }, error); }, /** * Create a new dataset using the POST method on the same endpoint as * above, sending only the name of the dataset and not the username as * well. * * @param {string} name * @param {string} description * @param {function} success * @param {function} error */ create: function(name, description, success, error) { var url = rainhawk.host + "/datasets"; var params = {name: name, description: description}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.post, params: params }, function(json) { success(json.data); }, error); }, /** * Remove a dataset using the DELETE method on the dataset's endpoint * * @param {string} name * @param {function} success * @param {function} error */ delete: function(name, success, error) { var url = rainhawk.host + "/datasets/" + name; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.del }, function(json) { success(json.data.deleted); }, error); } }, /** * Operations specific to data points go here. */ data: { /** * Fetch some data from the dataset, optionally specifying a query to * filter the rows that will be returned. * * @param {string} name * @param {object} options * @param {function} success * @param {function} error */ select: function(name, options, success, error) { if(!options) options = {}; var url = rainhawk.host + "/datasets/" + name + "/data"; var params = { query: options.hasOwnProperty("query") ? JSON.stringify(options.query) : null, offset: options.hasOwnProperty("offset") ? options.offset : 0, limit: options.hasOwnProperty("limit") ? options.limit : 0, sort: options.hasOwnProperty("sort") ? JSON.stringify(options.sort) : null, field: options.hasOwnProperty("field") ? JSON.stringify(options.field) : null, exclude: options.hasOwnProperty("exclude") ? JSON.stringify(options.exclude) : null }; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get, params: params }, function(json) { success(json.data); }, error); }, /** * Insert a single row of data into the specified dataset, which is * just an alias for insertMulti providing an array of one row instead. * * @param {string} name * @param {object} row * @param {function} success * @param {function} error */ insert: function(name, row, success, error) { return this.insertMulti(name, [row], function(rows) { success(rows[0]); }, error); }, /** * Insert multiple rows of data into the specified dataset, which calls * the API with an array of objects which are sent in batch. * * @param {string} name * @param {array} rows * @param {function} success * @param {function} error */ insertMulti: function(name, rows, success, error) { var url = rainhawk.host + "/datasets/" + name + "/data"; var params = {rows: JSON.stringify(rows)}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.post, params: params }, function(json) { success(json.data.rows); }, error); }, /** * Run an update query on the specified dataset, using the query to * match rows and then the changes object to specify the changes to * make. * * @param {string} name * @param {object} query * @param {object} changes * @param {function} success * @param {function} error */ update: function(name, query, changes, success, error) { var url = rainhawk.host + "/datasets/" + name + "/data"; var params = {query: JSON.stringify(query), changes: JSON.stringify(changes)}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.put, params: params }, function(json) { success(json.data.updated); }, error); }, /** * Delete the specified rows of data from the dataset. This is a * destructive operation and cannot be undone, so use it wisely. * * @param {string} name * @param {object} query * @param {function} success * @param {function} error */ delete: function(name, query, success, error) { var url = rainhawk.host + "/datasets/" + name + "/data"; var params = {query: JSON.stringify(query)}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.del, params: params }, function(json) { success(json.data.deleted); }, error); }, /** * Upload data into the specified dataset, using a File object * which can be obtained from a form input field of type file. * * @param {string} name * @param {file} file * @param {function} success * @param {function} error */ upload: function(name, file, type, success, error) { var url = rainhawk.host + "/datasets/" + name + "/upload/" + type; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.put, file: file }, function(json) { success(json.data.rows); }, error); }, /** * Calculations are performed on data so we group the relevant endpoints * inside a sub-object. */ calc: { /** * Calculate the coefficients of a line of best fit through certain * data points inside a dataset. * * @param {string} name * @param {array} fields * @param {int} degree * @param {function} success * @param {function} error */ polyfit: function(name, fields, degree, success, error) { var url = rainhawk.host + "/datasets/" + name + "/calc/polyfit"; var params = {fields: JSON.stringify(fields)}; if(degree) params.degree = degree; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get, params: params }, function(json) { success(json.data.coefficients); }, error); }, /** * Calculate the means and other statistical data for certain data * within a dataset. This method is mostly for convenience but can * also be useful for other things. * * @param {string} name * @param {array} fields * @param {object} query * @param {function} success * @param {function} error */ stats: function(name, field, query, success, error) { var url = rainhawk.host + "/datasets/" + name + "/calc/stats"; var params = {field: field, query: JSON.stringify(query)}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get, params: params }, function(json) { success(json.data); }, error); } } }, /** * Operations specific to manipulate the indexes on a dataset. */ indexes: { /** * Generate a list of indexes that exist on a dataset which are * currently being applied to a dataset. * * @param {string} name * @param {function} success * @param {function} error */ list: function(name, success, error) { var url = rainhawk.host + "/datasets/" + name + "/indexes"; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get }, function(json) { success(json.data.indexes); }, error); }, /** * Create an index on the specified fields so that queries on those * fields can be much faster and more efficient. * * @param {string} name * @param {string} field * @param {function} success * @param {function} error */ add: function(name, field, success, error) { var url = rainhawk.host + "/datasets/" + name + "/indexes"; var params = {}; if(field) params.field = field; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.post, params: params }, function(json) { if(field) { success(json.data.added); } else { success(json.data.detected); } }, error); }, /** * Delete an index from the specified dataset on the specified fields, * which requires that the indexes already exist. * * @param {string} name * @param {array} field * @param {function} success * @param {function} error */ remove: function(name, field, success, error) { var url = rainhawk.host + "/datasets/" + name + "/indexes"; var params = { field: field }; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.del, params: params }, function(json) { success(json.data.removed); }, error); } }, /** * Operations specific to access allowed to/on a dataset. */ access: { /** * List the access that's currently available to a dataset, giving two * arrays - one for the users that have read access and another for those * who have write access. * * @param {string} name * @param {function} success * @param {function} error */ list: function(name, success, error) { var url = rainhawk.host + "/datasets/" + name + "/access"; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get }, function(json) { success(json.data); }, error); }, /** * Give a user certain access levels to a dataset, provided an array or * string of types of access. * * @param {string} name * @param {string} username * @param {string|array} type * @param {function} success * @param {function} error */ give: function(name, username, type, success, error) { var url = rainhawk.host + "/datasets/" + name + "/access"; var params = { username: username, type: typeof type == "string" ? type : JSON.stringify(type) }; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.post, params: params }, function(json) { success(json.data.added); }, error); }, /** * Remove access from a user to the specified dataset, which uses a * string to represent either "read" or "write". * * @param {string} name * @param {string} username * @param {string} type * @param {function} success * @param {function} error */ remove: function(name, username, type, success, error) { var url = rainhawk.host + "/datasets/" + name + "/access"; var params = {username: username, type: type}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.del, params: params }, function(json) { success(json.data.removed); }, error); } }, /** * Operations specific to constraints applied to datasets. */ constraints: { /** * List the constraints that are currently being applied to a dataset, * which are essentially masks on fields. Currently supported: string, * array, integer, float, timestamp, latitude, longitude. * * @param {string} name * @param {function} success * @param {function} error */ list: function(name, success, error) { var url = rainhawk.host + "/datasets/" + name + "/constraints"; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.get }, function(json) { success(json.data.constraints); }, error); }, /** * Add a constraint on a field within a dataset, specifying the type * of data that should appear in that field as well as the field name. * * @param {string} name * @param {string} field * @param {string} type * @param {function} success * @param {function} error */ add: function(name, field, type, success, error) { var url = rainhawk.host + "/datasets/" + name + "/constraints"; var params = {}; if(field) params.field = field; if(type) params.type = type; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.post, params: params }, function(json) { if(field) { success(json.data.added); } else { success(json.data.detected); } }, error); }, /** * Remove the constraint from a field in a dataset, which unmasks the * data being returned from queries. * * @param {string} name * @param {string} field * @param {function} success * @param {function} error */ remove: function(name, field, success, error) { var url = rainhawk.host + "/datasets/" + name + "/constraints"; var params = {field: field}; return rainhawk.http.send({ url: url, method: rainhawk.http.methods.del, params: params }, function(json) { success(json.data.removed); }, error); } }, /** * Support function to allow the library to count the size of an object, * which JS doesn't have native support for. * * @param {object} obj * @return {int} */ objectSize: function(obj) { var size = 0, key; for(key in obj) { if(obj.hasOwnProperty(key)) size++; } return size; } }; <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(JSON_ERROR_NOMETHOD); exit; ?><file_sep><?php /** * Rainhawk * * The main class for our Rainhawk framework, providing an * interface from the application to the MongoDB database layer * so that we can grab data. * * @package Rainhawk */ class Rainhawk { /** * Store a connection instance for our database layer. * * @var MongoClient */ private static $connection; /** * Store a reference for our MongoDatabase instance. * * @var MongoDatabase */ private static $database; /** * Connect to the specified MongoDB server, which defaults to localhost on * Mongo's default port of 27017 (coincidentally also Valve's Source server * IP range but w/e). * * @param string $host The hostname or IP of the Mongo server. * @param integer $port The port that the server is running on. * @return bool Whether the connection was a success or not. */ public static function connect($host = "127.0.0.1", $port = 27017) { return (self::$connection = new MongoClient("mongodb://" . $host . ":" . $port . "/")); } /** * Grab a reference to a MongoDatabase object so that we can grab collection * objects to pass through to child classes. * * @param string $database The name of the database. * @return bool Whether the database was selected or not. */ public static function select_database($database) { return (self::$database = self::$connection->selectDB($database)); } /** * Grab a reference to a MongoCollection object provided a name. * * @param string $name The name of the collection. * @return MongoCollection The object. */ public static function select_collection($name) { return self::$database->selectCollection($name); } } ?><file_sep><nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <a href="/" class="navbar-brand">Project<strong>Rainhawk</strong><?php echo $user ? " / " . htmlspecialchars($user, ENT_QUOTES) : null; ?></a> </div> <ul class="nav navbar-nav navbar-right"> <?php if($user) { ?> <li> <div> <a class="btn btn-default navbar-btn" href="/create.php"><i class="fa fa-file"></i>&nbsp; Create Dataset</a> </div> </li> <li> <div> <a class="btn btn-default navbar-btn" href="/datasets.php"><i class="fa fa-bars"></i>&nbsp; Browse Datasets</a> </div> </li> <li> <div> <a class="btn btn-default navbar-btn" href="/login.php?logout"><i class="fa fa-user"></i>&nbsp; Log Out</a> </div> </li> <?php } else { ?> <li> <div> <a class="btn btn-default navbar-btn" href="/login.php"><i class="fa fa-user"></i>&nbsp; Login</a> </div> </li> <?php } ?> </ul> </div> </nav><file_sep><?php // Define the headers. header("content-type: text/plain; charset=utf8"); chdir("/var/www"); // Define the commands to be run. $commands = array( "whoami", "/usr/bin/git clean -d -f", "/usr/bin/git reset --hard", "/usr/bin/git pull", "/usr/bin/git status", "/usr/bin/git submodule sync", "/usr/bin/git submodule update", "/usr/bin/git submodule status", "cd /var/www/parser && /usr/bin/make clean", "cd /var/www/parser && /usr/bin/make" ); // Run them all. foreach($commands as $command) { echo "$ {$command}\n"; $output = shell_exec("export PATH=/usr/local/bin:/usr/bin:/bin; " . $command . " 2>&1"); echo "{$output}\n"; } ?> <file_sep><?php use Rainhawk\Data; class RainhawkDataTest extends UnitTest { public $class = "Rainhawk\Data"; public function testCheckString() { $this->assertEquals(data::check(data::STRING, "test"), "test"); $this->assertEquals(data::check(data::STRING, "2"), "2"); $this->assertEquals(data::check(data::STRING, array()), null); } public function testCheckInteger() { $this->assertEquals(data::check(data::INTEGER, 2), 2); $this->assertEquals(data::check(data::INTEGER, 2.2), null); $this->assertEquals(data::check(data::INTEGER, "2"), 2); $this->assertEquals(data::check(data::INTEGER, "2.5ab"), null); $this->assertEquals(data::check(data::INTEGER, array()), null); } public function testCheckFloat() { $this->assertEquals(data::check(data::FLOAT, 2), 2); $this->assertEquals(data::check(data::FLOAT, 2.2), 2.2); $this->assertEquals(data::check(data::FLOAT, "2"), 2); $this->assertEquals(data::check(data::FLOAT, "2.2"), 2.2); $this->assertEquals(data::check(data::FLOAT, ".5"), 0.5); $this->assertEquals(data::check(data::FLOAT, "5.1.2"), null); $this->assertEquals(data::check(data::FLOAT, array()), null); } public function testCheckTimestamp() { $this->assertEquals(data::check(data::TIMESTAMP, 2), null); $this->assertEquals(data::check(data::TIMESTAMP, "19 July 2002"), strtotime("19 July 2002")); $this->assertEquals(data::check(data::TIMESTAMP, "1335939007"), strtotime("1335939007")); } public function testCheckLatitude() { $this->assertEquals(data::check(data::LATITUDE, 2), null); $this->assertEquals(data::check(data::LATITUDE, "123.123"), null); $this->assertEquals(data::check(data::LATITUDE, "38.898556"), 38.898556); $this->assertEquals(data::check(data::LATITUDE, "0.2123123"), null); } public function testCheckLongitude() { $this->assertEquals(data::check(data::LONGITUDE, 2), null); $this->assertEquals(data::check(data::LONGITUDE, "-77.037852"), -77.037852); $this->assertEquals(data::check(data::LONGITUDE, "38.898556"), 38.898556); $this->assertEquals(data::check(data::LONGITUDE, "0.2123123"), null); } public function testCheckArray() { $this->assertEquals(data::check(data::ARR, 13), null); $this->assertEquals(data::check(data::ARR, (object)array(1)), array(1)); $this->assertEquals(data::check(data::ARR, array(1, 2)), array(1, 2)); } public function testDetect() { $this->assertEquals(data::detect("test"), data::STRING); $this->assertEquals(data::detect("1"), data::INTEGER); $this->assertEquals(data::detect("1.2"), data::FLOAT); $this->assertEquals(data::detect("-1.4"), data::FLOAT); $this->assertEquals(data::detect(array(1)), data::ARR); } } ?><file_sep><?php require_once "../includes/core.php"; require_once "../includes/check_login.php"; header("content-type: application/json; charset=utf8"); $dataset = isset($_GET['dataset']) ? $_GET['dataset'] : null; $idValue = isset($_POST['_id']) ? $_POST['_id'] : null; $query = array( "_id" => $idValue ); $result = $rainhawk->deleteData($dataset, $query); if(!$result) { echo json_encode(array( "Result" => "ERROR", "Message" => $rainhawk->error() )); exit; } echo json_encode(array( "Result" => "OK" )); exit; ?> <file_sep><?php if(empty($mashape_key) || empty($user)) { header("Location: /login.php?dest=" . urlencode($_SERVER['REQUEST_URI'])); exit; } ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check if the user provided enough information to create the new * dataset, including the name and description. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array(); /*! * Try and add the indexes to the dataset as the user has specified, * which will always work even if the index already exists. */ // Check if the fields are set. if(!empty($data->field)) { // Check if the field can be indexed. if($data->field == "_id") { echo json_beautify(json_render_error(404, "The _id field is always indexed by default.")); exit; } // Get the current indexes. $indx = $dataset->fetch_indexes(); $indexes = array(); // Set the indexes properly. foreach($indx as $index) { $indexes[] = array_keys($index['key'])[0]; } // Check if the index has already been set. if(in_array($data->field, $indexes)) { echo json_beautify(json_render_error(405, "The field you specified already has an index.")); exit; } // Add the index. if(!$dataset->add_index($data->field)) { echo json_beautify(json_render_error(406, "There was an unknown problem adding the index you specified.")); exit; } // Set the JSON response. $json['added'] = true; } else { // Find the fields to index and the indexes. $fields = app::find_index_names(array_keys($dataset->fields)); $indx = $dataset->fetch_indexes(); $indexes = array(); // Set the indexes properly. foreach($indx as $index) { $indexes[] = array_keys($index['key'])[0]; } // Remove the fields that already have indexes. foreach($fields as $index => $field) { if(in_array($field, $indexes)) unset($fields[$index]); } // Check if the fields are empty. if(empty($fields)) { echo json_beautify(json_render_error(404, "We couldn't find any fields to add indexes to.")); exit; } // Start buffering the response. $json['detected'] = array(); // Add indexes to each of the fields. foreach($fields as $field) { if(!$dataset->add_index($field)) { echo json_beautify(json_render_error(405, "There was an unknown problem adding one of the indexes.")); exit; } // Set the response. $json['detected'][] = $field; } } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can read from the dataset. if(!$dataset->have_read_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to read from this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "read_access" => array(), "write_access" => array() ); /*! * Fetch the access arrays from the dataset, and list them back to * the user in a friendly format. */ // Return the read_access keys into the JSON. foreach($dataset->read_access as $username) { $json['read_access'][] = $username; } // Return the write_access keys into the JSON. foreach($dataset->write_access as $username) { $json['write_access'][] = $username; } /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php /** * @package UnitTest */ class UnitTest { /** * @var string */ protected $class; /** * @var integer */ protected $passed = 0; /** * @var integer */ protected $failed = 0; /** * @var integer */ protected $started; /** * @param mixed $value * @param mixed $expected * @return mixed */ public function assertEquals($value, $expected) { return $this->outputTestResult($value == $expected); } /** * @param mixed $value * @return mixed */ public function assert($value) { return $this->outputTestResult($value); } /** * @param boolean $passes * @return mixed */ public function outputTestResult($passes) { if($passes) { $this->passed++; echo "."; } else { $this->failed++; echo "F"; } } /** * @return UnitTest */ public function __before() { return $this; } /** * @return void */ public function exec() { $this->started = microtime(true); $this->__before(); echo $this->class . "\n\n"; foreach(get_class_methods($this) as $method) { if(stripos($method, "assert") !== false || in_array($method, array("outputTestResult", "exec", "__before"))) { continue; } else { $this->$method(); echo "\n"; } } echo "\n"; echo ($this->failed == 0 ? "OK" : "FAILED") . " (" . ($this->passed + $this->failed) . " tests, " . $this->failed . " assertions)\n"; echo number_format(microtime(true) - $this->started, 2) . " seconds\n"; return; } } ?><file_sep><?php /*! * This class allows us to connect to a network cache storage * to access globally shared objects. We use this for User, * Trade and other classes. */ class MongoCLI { // Hold the host and port in variables. public static $host = "127.0.0.1"; public static $port = 27017; // Private connection variable for Mongo. private static $conn = null; private static $database = null; private static $datasets = null; /*! * Create a new instance of the native Mongo driver, which we're * essentially wrapping with this class. We don't need to worry about * usernames or passwords. */ public static function connect($host = null, $port = null) { if($host) self::$host = $host; if($port) self::$port = $port; self::$conn = new MongoClient("mongodb://" . self::$host . ":" . self::$port . "/"); if(self::$conn) { return true; } return false; } /*! * Select the database to use within the Mongo instance, so we can * separate out our application's logic. */ public static function select_database($database) { try { self::$database = self::$conn->selectDB($database); } catch(Exception $e) { return false; } return true; } /*! * Select the collection to be used for storing/retreiving the data. * If the collection doesn't exist, Mongo will create one for us. */ public static function select_collection($collection) { try { return self::$database->selectCollection($collection); } catch(Exception $e) { return false; } } /*! * Check if a collection exists so that we can prevent people creating * two sets with the same name. */ public static function collection_exists($name) { $datasets = self::datasets(); $matches = $datasets->find(array("name" => $name)); return ($matches->count() > 0); } /*! * Check that a user has access to a specific collection by validating * their ownership with the datasets table. */ public static function can_access_collection($name) { $datasets = self::datasets(); $matches = $datasets->find(array("name" => $name, "accessors" => app::$mashape_key)); return ($matches->count() > 0); } /*! * Get the statistics for a collection given it's label, which is * provided by the user. */ public static function get_collection_info($label) { // } /*! * Get a list of all of the available collections in the database. * This is useful for a variety of reasons. */ public static function get_collections_for_key($mashape_key) { $datasets = self::select_collection("system.datasets"); return $datasets->find(array("owners" => $mashape_key)); } /*! * Create a new collection in the database using the specified name * and optional parameters. */ public static function create_collection($name, $mashape_key) { $internal_name = $mashape_key . "." . $name; $collection = self::$database->createCollection($internal_name); if($collection) { $datasets = self::select_collection("system.datasets"); $datasets->insert(array( "name" => "tes034923", "label" => $name, "created" => time(), "rows" => 0, "fields" => array(), "have_access" => array($mashape_key) )); } return false; } /*! * Private function for getting a handler to the datasets collection * so that we can check which tables exist. */ private static function datasets() { if(isset(self::$datasets)) { return self::$datasets; } return self::select_collection("system.datasets"); } /*! * A public function to generate a safe name for a dataset, so that users * can't access system sets or other user's sets. */ public static function safe_name($name) { return "data." . $name; } } <file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Define our server_time timestamp and set it as the JSON output * to be sent back to the client. */ $json = array( "server_time" => time(), "mashape_user" => app::$username ); /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?><file_sep><?php include("includes/kernel.php"); include("includes/api/core.php"); /*! * Check that the parameters have all been set and sent to the script, * including the prefix and the name. */ if(empty($data->prefix) || empty($data->name)) { echo json_beautify(json_render_error(401, "You didn't pass one or more of the required parameters.")); exit; } /*! * Check to see if the dataset exists, and that we have access to it. * We need to use the prefix and the name of the dataset to get a * reference to it. */ // Create a new dataset object. $dataset = new rainhawk\dataset($data->prefix, $data->name); // Check that the dataset exists. if(!$dataset->exists) { echo json_beautify(json_render_error(402, "The dataset you specified does not exist.")); exit; } // Check that we can write to the dataset. if(!$dataset->have_write_access(app::$username)) { echo json_beautify(json_render_error(403, "You don't have access to write to this dataset.")); exit; } /*! * Define an empty array to store the results of whatever we need * to send back. */ $json = array( "updated" => 0 ); /*! * Check that the two required parameters are set, so that we can * ensure that no data gets erroneously removed. */ // Check the query is set. if(empty($data->query)) { echo json_beautify(json_render_error(404, "You can't use a catch-all query for update statements, dummy.")); exit; } // Check the changes aren't empty. if(empty($data->changes)) { echo json_beautify(json_render_error(405, "You didn't specify any changes to make.")); exit; } // Set some local variables. $query = $data->query; $changes = $data->changes; // Change the MongoID if we have one. foreach($query as $key => $value) { if($key == "_id") { try { $mongoid = new MongoID($value); } catch(Exception $e) { $mongoid = null; } $query[$key] = $mongoid; } } // Run the update query. $updated = $dataset->update($query, $changes); // Check if the query failed. if(!is_int($updated)) { echo json_beautify(json_render_error(406, "An unexpected error occured while performing your query - are you sure you formatted all the parameters correctly?")); exit; } // Set the output. $json['updated'] = $updated; /*! * Output our JSON payload for use in whatever needs to be using * it. */ echo json_beautify(json_render(200, $json)); exit; ?>
0a871335cc57eef2de345c265d46f9f9bcc3a953
[ "Ruby", "JavaScript", "Markdown", "Makefile", "Python", "PHP", "C++" ]
93
PHP
zacoppotamus/ElgarsCodingOrchestra
347bd77d31eab0c42efb3ec53289319729bbe701
9b360d1ae7af8a9edebd50118a30acf20eda7342
refs/heads/master
<repo_name>tomasmparra/GaeaPeople-iMagazine<file_sep>/js/headerScript.js const menuIcon1 = document.getElementById('menuIconWrapper1'); const slideOutMenu11 = document.getElementById('slideOutMenu1'); menuIcon1.addEventListener('click', function() { if (slideOutMenu11.style.opacity == "1"){ slideOutMenu11.style.opacity = '0' ; slideOutMenu11.style.pointerEvents = 'none'; } else { slideOutMenu11.style.opacity = '1' ; slideOutMenu11.style.pointerEvents = 'auto'; } }) const menuIcon2 = document.getElementById('menuIconWrapper2'); const slideOutMenu22 = document.getElementById('slideOutMenu2'); menuIcon2.addEventListener('click', function() { if (slideOutMenu22.style.opacity == "1") { slideOutMenu22.style.opacity = '0' ; slideOutMenu22.style.pointerEvents = 'none'; }else { slideOutMenu22.style.opacity = '1' ; slideOutMenu22.style.pointerEvents = 'auto'; } })
8da376fc0b434f2fd45d5da34d3df6a961588821
[ "JavaScript" ]
1
JavaScript
tomasmparra/GaeaPeople-iMagazine
cef8a667e44a8cbeebbcee2f547061b36a672213
1fdc89e667d375c67c62fdf90d58de458543e3c8
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author it354f715 */ @Entity @Table(name = "DECKS") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Decks.findAll", query = "SELECT d FROM Decks d"), @NamedQuery(name = "Decks.findById", query = "SELECT d FROM Decks d WHERE d.id = :id"), @NamedQuery(name = "Decks.findByDeckname", query = "SELECT d FROM Decks d WHERE d.deckname = :deckname"), @NamedQuery(name = "Decks.findByUserid", query = "SELECT d FROM Decks d WHERE d.userid = :userid"), @NamedQuery(name = "Decks.findByClassid", query = "SELECT d FROM Decks d WHERE d.classid = :classid")}) public class Decks implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "DECKNAME") private String deckname; @Basic(optional = false) @NotNull @Column(name = "USERID") private int userid; @Column(name = "CLASSID") private Integer classid; public Decks() { } public Decks(Integer id) { this.id = id; } public Decks(Integer id, String deckname, int userid) { this.id = id; this.deckname = deckname; this.userid = userid; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDeckname() { return deckname; } public void setDeckname(String deckname) { this.deckname = deckname; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public Integer getClassid() { return classid; } public void setClassid(Integer classid) { this.classid = classid; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Decks)) { return false; } Decks other = (Decks) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entities.Decks[ id=" + id + " ]"; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities.service; import entities.Decks; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; /** * * @author it354f715 */ @Stateless @Path("entities.decks") public class DecksFacadeREST extends AbstractFacade<Decks> { @PersistenceContext(unitName = "MyFlashCardWSPU") private EntityManager em; public DecksFacadeREST() { super(Decks.class); } @POST @Override @Consumes({"application/xml", "application/json"}) public void create(Decks entity) { super.create(entity); } @PUT @Path("{id}") @Consumes({"application/xml", "application/json"}) public void edit(@PathParam("id") Integer id, Decks entity) { super.edit(entity); } @DELETE @Path("{id}") public void remove(@PathParam("id") Integer id) { super.remove(super.find(id)); } @GET @Path("{id}") @Produces({"application/xml", "application/json"}) public Decks find(@PathParam("id") Integer id) { return super.find(id); } @GET @Override @Produces({"application/xml", "application/json"}) public List<Decks> findAll() { return super.findAll(); } @GET @Path("findAllOrderByDeckname") @Produces({"application/xml", "application/json"}) public List<Decks> findAllOrderByDeckname() { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d ORDER BY d.deckname"); return q.getResultList(); } @GET @Path("findByClassid/{classid}") @Produces({"application/xml", "application/json"}) public List<Decks> findByClassid(@PathParam("classid") String classid) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d WHERE d.classid = " + classid + " ORDER BY d.deckname"); return q.getResultList(); } @GET @Path("findByClassnumber/{classnumber}") @Produces({"application/xml", "application/json"}) public List<Decks> findByClassnumber(@PathParam("classnumber") String classnumber) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d JOIN Assignments a ON d.id = a.deckid JOIN Classes c ON a.classid = c.id WHERE c.classnumber = :classnumber ORDER BY d.deckname"); q.setParameter("classnumber", classnumber); return q.getResultList(); } @GET @Path("findByUsername/{username}") @Produces({"application/xml", "application/json"}) public List<Decks> findByUsername(@PathParam("username") String username) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d JOIN Users u ON d.userid = u.id WHERE u.username = :username ORDER BY d.deckname"); q.setParameter("username", username); return q.getResultList(); } @GET @Path("findByUseridAndClassidAndDeckname/{userid}/{classid}/{deckname}") @Produces({"application/xml", "application/json"}) public List<Decks> findByUseridAndDecknameAndClassid(@PathParam("deckname") String deckname, @PathParam("classid") String classid, @PathParam("userid") String userid) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d WHERE lower(d.deckname) = lower(:deckname) AND d.classid = " + classid + " AND d.userid = " + userid); q.setParameter("deckname", deckname); return q.getResultList(); } @GET @Path("findByClassnmae/{classname}") @Produces({"application/xml", "application/json"}) public List<Decks> findByClassname(@PathParam("classname") String classname) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d JOIN Assignments a ON d.id = a.deckid JOIN Classes c ON a.classid = c.id WHERE lower(c.classname) LIKE lower(concat('%', :classname, '%')) ORDER BY d.deckname"); q.setParameter("classname", classname); return q.getResultList(); } @GET @Path("byDeckname/{deckname}") @Produces({"application/xml", "application/json"}) public List<Decks> findByWord(@PathParam("deckname") String deckname) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d WHERE lower(d.deckname) = lower(:deckname)"); q.setParameter("deckname", deckname); return q.getResultList(); } @GET @Path("findByKeyword/{keyword}") @Produces({"application/xml", "application/json"}) public List<Decks> findBykeyword(@PathParam("keyword") String keyword) { Query q = em.createQuery("SELECT DISTINCT d FROM Decks d JOIN Cards c ON d.id = c.deckid WHERE lower(c.answer) LIKE lower(concat('%', :keyword, '%')) OR lower(c.question) LIKE lower(concat('%', :keyword, '%')) ORDER BY d.deckname"); q.setParameter("keyword", keyword); return q.getResultList(); } @GET @Path("{from}/{to}") @Produces({"application/xml", "application/json"}) public List<Decks> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) { return super.findRange(new int[]{from, to}); } @GET @Path("count") @Produces("text/plain") public String countREST() { return String.valueOf(super.count()); } @Override protected EntityManager getEntityManager() { return em; } }
cff67823876266fa3399328df4f6b4485eb409ed
[ "Java" ]
2
Java
Suguru-Tokuda/MyFlashCardWS
75366b93b2f05576bd8998501c9d310734273aad
2c39b85c18a2a0113c92d87fd48d29f8b14bb120
refs/heads/master
<repo_name>GamingMaster2000/BPUsageMeter<file_sep>/js/methods/gm2k300.js // JavaScript Document function gm2k300(){ this.uid = 'gm2k300'; this.name = 'GM2K 3.0.0'; this.priority = 10; this.enabled = true; this.accountId = ''; this.serviceId = ''; this.Run = function() { UsageGadget.logger.LogMessage("INFO", "Running method: " + this.name); var that = this; var servicesPage = new WebLoading(UsageGadget.logger); servicesPage.onsuccess = function(responseText){that.ServicesPageLoaded(responseText);}; servicesPage.onfail = function(){that.FailedPageLoading();}; servicesPage.url = 'https://www.my.telstra.com.au/myaccount/overview'; servicesPage.LoadPage(); } this.FailedPageLoading = function() { UsageGadget.logger.LogMessage("WARNING", "Failed to load the webpage."); UsageGadget.CheckNextMethod(); } this.ServicesPageLoaded = function(responseText) { try{ var overviewPage = document.createElement('div'); overviewPage.innerHTML = responseText; var internetRows = overviewPage.getElementsByTagName("a"); var urlOfUsage = 'internet-daily-usage.json'; for(var i = 0; i < internetRows.length; i++){ try{ if(internetRows[i].getElementsByTagName('i').length < 1) continue; if(internetRows[i].getElementsByTagName('i')[0].innerHTML == UsageGadget.username){ var url = internetRows[i].href; var regex = new RegExp("accountId=([a-zA-Z0-9]+).*?serviceId=([a-zA-Z0-9]+)", "g"); var details = regex.exec(url); this.accountId = details[1]; this.serviceId = details[2]; break; } }catch(err){ } } //Throw an error if details not found. //Sometimes caused it to get stuck on 'REFRESHING' if(this.accountId == '' || this.serviceId == ''){ UsageGadget.logger.LogMessage("ERROR", "Couldn't find accountId or serviceId."); UsageGadget.CheckNextMethod(); return; } var that = this; var detailsPage = new WebLoading(UsageGadget.logger); detailsPage.onsuccess = function(responseText){that.DetailsLoaded(responseText);}; detailsPage.onfail = function(){that.FailedPageLoading();}; detailsPage.url = 'https://www.my.telstra.com.au/myaccount/internet-daily-usage.json?accountId=' + this.accountId + '&serviceId=' + this.serviceId; detailsPage.LoadPage(); }catch(err){ UsageGadget.logger.LogMessage("ERROR", "Couldn't find accountId or serviceId."); UsageGadget.CheckNextMethod(); return; } } this.DetailsLoaded = function(responseText) { UsageGadget.logger.LogMessage("INFO", "Getting usage info and passing it to the gadget to display!"); try{ var usageInfo = JSON.parse(responseText); var data = new DataToDisplay(); var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; data.totalUsage = usageInfo.result.totalUsage; data.allowance = usageInfo.result.allowanceUsage; //Sometimes the start/end dates are wrong (Turns out it's to do with timezones) //Try a messy (but more accurate) way first but //fall back to Telstra provided values if necessary try{ var Period = /^\(([0-9]+ [a-z]+) - ([0-9]+ [a-z]+)\)$/i.exec(usageInfo.result.headerDateRange); var startParts = /([0-9]+) ([a-z]+)/i.exec(Period[1]); var endParts = /([0-9]+) ([a-z]+)/i.exec(Period[2]); if(monthNames[(new Date()).getMonth()] == 'Jan' && startParts[2] == 'Dec'){ startParts.push((new Date()).getFullYear() - 1); }else{ startParts.push((new Date()).getFullYear()); } if(monthNames[(new Date()).getMonth()] == 'Dec' && endParts[2] == 'Jan'){ endParts.push((new Date()).getFullYear() + 1); }else{ endParts.push((new Date()).getFullYear()); } data.startDate = (new Date(startParts[1] + " " + startParts[2] + " " + startParts[3])).getTime(); data.endDate = (new Date(endParts[1] + " " + endParts[2] + " " + endParts[3])).getTime(); }catch(err){ data.startDate = usageInfo.result.startDate; data.endDate = usageInfo.result.endDate; } //Try to avoid some Telstra issues. if(data.allowance > 0){ System.Gadget.Settings.write("lastGoodAllowance", data.allowance); System.Gadget.Settings.write("lastGoodStart", data.startDate); System.Gadget.Settings.write("lastGoodEnd", data.endDate); }else{ data.allowance = System.Gadget.Settings.read("lastGoodAllowance"); data.startDate = System.Gadget.Settings.read("lastGoodStart"); data.endDate = System.Gadget.Settings.read("lastGoodEnd"); } var unratedUsage = 0; try{ for(var i = 0; i < usageInfo.result.usageList.length; i++){ unratedUsage += usageInfo.result.usageList[i].unratedUsage; } }catch(err){ UsageGadget.logger.LogMessage("ERROR", "Couldn't get 'Unrated Usage'. Error: " + err.message); } data.unratedUsage = unratedUsage; data.flyoutData = this.BuildFlyoutPage(usageInfo, data); data.raw = responseText; UsageGadget.DisplayData(data); }catch(err){ UsageGadget.logget.LogMessage("ERROR", "Error getting the usage data. Message: " + err.message); } } this.BuildFlyoutPage = function (usageInfo, data) { var usageGb = usageInfo.result.totalUsage / 1000; var unratedGb = data.unratedUsage / 1000; var allowanceGb = usageInfo.result.allowanceUsage / 1000; var maxYLabel = (usageInfo.result.maxYAxis > 1000 ? usageInfo.result.maxYAxis / 1000 + 'GB' : usageInfo.result.maxYAxis + 'MB'); var halfYLabel = (usageInfo.result.maxYAxis / 2 > 1000 ? usageInfo.result.maxYAxis / 2 / 1000 + 'GB' : usageInfo.result.maxYAxis / 2 + 'MB'); var output = ' <div style="margin-bottom: 10px;">\ <h5>PLAN DETAILS</h5>\ <table width="100%" class="font" style="margin-top: 5px;">\ <tr>\ <td width="25%" style="font-weight: bold;">Current Account Usage</td>\ <td>' + usageGb + 'GB (+ ' + unratedGb + 'GB Unrated Usage)</td>\ </tr>\ <tr>\ <td style="font-weight:bold">Current Usage Allowance</td>\ <td>' + allowanceGb + 'GB</td>\ </tr>\ <tr>\ <td style="font-weight:bold">Account Usage Status</td>\ <td>' + (usageInfo.result.speedSlowed ? 'Slowed' : 'In Allowance') + '</td>\ </tr>\ <tr>\ <td style="font-weight:bold">Current Bill Period</td>\ <td>' + usageInfo.result.headerDateRange.substring(1, usageInfo.result.headerDateRange.length - 1) + '</td>\ </tr>\ </table>\ </div>'; output += ' <div style="margin-top:10px;">\ <table class="breakdown_table">\ <thead>\ <tr>\ <td>Date</td>\ <td>Download (MB)</td>\ <td>Upload (MB)</td>\ <td>Total (MB)</td>\ <td>Unmetered (MB)</td>\ <td>Unrated (MB)</td>\ </tr>\ </thead>\ <tbody>'; var row = 0; for(var i = 0; i < usageInfo.result.usageList.length; i++){ output += ' <tr class="row' + (row++ % 2) + '">\ <td>' + usageInfo.result.usageList[i].usageDisplayDate + '</td>\ <td>' + usageInfo.result.usageList[i].downloadUsage + '</td>\ <td>' + usageInfo.result.usageList[i].uploadUsage + '</td>\ <td>' + usageInfo.result.usageList[i].totalUsage + '</td>\ <td>' + usageInfo.result.usageList[i].freeUsage + '</td>\ <td>' + usageInfo.result.usageList[i].unratedUsage + '</td>\ </tr>'; } output += ' </tbody>\ <tfoot style="font-weight: bold;">\ <tr>\ <td>Total</td>\ <td>' + usageInfo.result.downloadUsage + '</td>\ <td>' + usageInfo.result.uploadUsage + '</td>\ <td>' + usageInfo.result.totalUsage + '</td>\ <td>' + usageInfo.result.freeUsage + '</td>\ <td>' + data.unratedUsage + '</td>\ </tr>\ </tfoot>\ </table>\ </div>'; return output; } }<file_sep>/js/Logger.js // JavaScript Document function Logger() { this.opened = false; this.logger = null; this.user = ''; //Open Log File this.Open = function(){ if(this.opened){ //Log opened. Close the current log before continuing. this.Close(); } //Open a log file try{ var fso = new ActiveXObject("Scripting.FileSystemObject"); try{ this.logger = fso.OpenTextFile(System.Gadget.path + "\\logs\\log_" + this.user + ".txt", 8, true, 0); this.opened = true; }catch(err){ this.opened = false; } }catch(err){ this.opened = false; } } //Close Log File this.Close = function(){ if(this.opened){ this.logger.Close(); this.opened = false; } } //Log a Message this.LogMessage = function(prefix, message){ if(this.opened){ var currentdate = new Date(); var datetime = currentdate.getDate() + "/" + (currentdate.getMonth()+1) + "/" + currentdate.getFullYear() + " " + (currentdate.getHours() < 10 ? "0" : "") + currentdate.getHours() + ":" + (currentdate.getMinutes() < 10 ? "0" : "") + currentdate.getMinutes() + ":" + (currentdate.getSeconds() < 10 ? "0" : "") + currentdate.getSeconds(); this.logger.WriteLine("[" + datetime + " " + prefix + "] " + message); } } }<file_sep>/README.md # BPUsageMeter Bigpond Usage Meter Windows Gadget Windows Gadget to monitor Bigpond Usage. "Pre-compiled" versions are currently found at http://www.gm2k.net/gadgets/bpusagemeter/ To install these repository files for a "bleeding edge build" you can either: Copy them to the folder your gadget is currently installed in (usually %LocalAppData%\Microsoft\Windows Sidebar\Gadgets\BPUsageMeter.gadget) OR You can download these files, Place them in a zip file and rename that file so the extension is .gadget. This will allow you to install the gadget like you would any other.<file_sep>/js/styles/Classic.js // JavaScript Document function Classic(){ this.uid = 'style_classic'; this.timeTransition = 2; this.Name = 'Classic'; this.priority = 10; this.flyoutData = null; this.initialise = function(firstRun){ if(firstRun){ var dockedCSS=document.createElement("link"); dockedCSS.setAttribute("rel", "stylesheet"); dockedCSS.setAttribute("type", "text/css"); dockedCSS.setAttribute("href", "css/style_docked.css"); dockedCSS.setAttribute("id", "styleDocked"); dockedCSS.setAttribute("title", "docked"); var undockedCSS=document.createElement("link"); undockedCSS.setAttribute("rel", "stylesheet"); undockedCSS.setAttribute("type", "text/css"); undockedCSS.setAttribute("href", "css/style_undocked.css"); undockedCSS.setAttribute("id", "styleUndocked"); undockedCSS.setAttribute("title", "undocked"); undockedCSS.setAttribute("disabled", true); document.getElementsByTagName("head")[0].appendChild(dockedCSS); document.getElementsByTagName("head")[0].appendChild(undockedCSS); } var that = this; System.Gadget.Flyout.file = "classic_flyout.html"; System.Gadget.onUndock = function(){that.CheckDockState()}; System.Gadget.onDock = function(){that.CheckDockState()}; document.body.innerHTML = ' <div id="mainheader">BIGPOND USAGE</div>\ <div id="container">\ <span id="usageOverlay">\ <div id="usageBlock">\ <div id="barEmpty1">\ <div id="bar1" class="barFill"><img src="img/1x1pix_trans.gif" width="1" height="1"></div>\ </div>\ <div id="usageheader">\ <div style="float:left">USAGE</div>\ <div style="float:right" id="percentUsed">0%</div>\ </div>\ <div class="font">\ <div id="usage" style="float:right;">0 / 0GB</div>\ </div>\ </div>\ </span>\ <span id="monthOverlay">\ <div id="monthBlock">\ <div id="barEmpty2">\ <div id="bar2" class="barFill"><img src="img/1x1pix_trans.gif" width="1" height="1"></div>\ </div>\ <div id="monthheader">\ <div style="float:left">MONTH</div>\ <div style="float:right" id="percentMonth">0%</div>\ </div>\ <div class="font">\ <div id="monthRemaining" style="float:right;">0 DAYS</div>\ </div>\ </div>\ </span>\ <div id="controlBlock">\ <div class="icon icon-paper" onMouseOver="UsageGadget.style.SetIconColour(\'details\', \'over\')" onMouseOut="UsageGadget.style.SetIconColour(\'details\', \'normal\')" onClick="UsageGadget.style.OpenFlyout();">\ <div id="icon-details" class="icon-details"><img src="img/1x1pix_trans.gif" width="9" height="9"></div>\ <div id="icon-details-box" class="icon-details-box"><img src="img/1x1pix_trans.gif" width="1" height="1"></div>\ </div>\ <div class="icon icon-down" onMouseOver="UsageGadget.style.SetIconColour(\'refresh\', \'over\')" onMouseOut="UsageGadget.style.SetIconColour(\'refresh\', \'normal\')" onClick="UsageGadget.retrieveData();">\ <div id="icon-refresh" class="icon-refresh"><img src="img/1x1pix_trans.gif" width="9" height="9"></div>\ <div id="icon-refresh-triangle" class="icon-refresh-triangle"><img src="img/1x1pix_trans.gif" width="1" height="1"></div>\ <div id="icon-refresh-line" class="icon-refresh-line"><img src="img/1x1pix_trans.gif" width="1" height="1"></div>\ </div>\ <div id="lastUpdated" class="font10"" style="float:right;"></div>\ </div>\ </div>\ <div class="font10" id="accountName">' + (System.Gadget.Settings.read('displayAccount') ? System.Gadget.Settings.read('bigpondUsername') : '') + '</div>'; if (System.Gadget.docked) this.setTheme("docked"); else this.setTheme("undocked"); this.SetColours(); this.CheckDockState(); } this.SetColours = function() { var bgColor = System.Gadget.Settings.read("bgcolor"); var borderColor = System.Gadget.Settings.read("bordercolor"); var textColor = System.Gadget.Settings.read("textcolor"); var barTextColor = System.Gadget.Settings.read("bartextcolor"); var bar1color = System.Gadget.Settings.read("bar1color"); var bar2color = System.Gadget.Settings.read("bar2color"); var baremptycolor = System.Gadget.Settings.read("baremptycolor"); var iconcolorload = System.Gadget.Settings.read("iconcolor"); var hideDividers = System.Gadget.Settings.read("hideDividers"); document.body.style.backgroundColor = bgColor; document.body.style.borderColor = borderColor; document.getElementById("usageBlock").style.borderTopColor = (hideDividers) ? bgColor : borderColor; document.getElementById("monthBlock").style.borderTopColor = (hideDividers) ? bgColor : borderColor; document.getElementById("controlBlock").style.borderTopColor = (hideDividers) ? bgColor : borderColor; document.getElementById("bar1").style.backgroundColor = bar1color; document.getElementById("bar2").style.backgroundColor = bar2color; document.getElementById("barEmpty1").style.backgroundColor = baremptycolor; document.getElementById("barEmpty2").style.backgroundColor = baremptycolor; document.getElementById("mainheader").style.color = textColor; document.getElementById("usage").style.color = textColor; document.getElementById("monthremaining").style.color = textColor; document.getElementById("lastupdated").style.color = textColor; document.getElementById("usageheader").style.color = barTextColor; document.getElementById("monthheader").style.color = barTextColor; document.getElementById("accountName").style.color = textColor; iconcolour = iconcolorload ? iconcolorload : "#000000"; iconcolourover = bar1color ? bar1color : "#FF6600"; this.SetIconColour("details", "normal"); this.SetIconColour("refresh", "normal"); } this.CheckDockState = function() { System.Gadget.beginTransition(); if (System.Gadget.docked) { this.setTheme("docked"); var useHeight = 120; if(System.Gadget.Settings.read("displayAccount")){ useHeight = 131; } with (document.body.style) { width = 130; height = useHeight; } } else { this.setTheme("undocked"); var useHeight = 185; if(System.Gadget.Settings.read("displayAccount")){ useHeight = 201; } with (document.body.style) { width = 200; height = useHeight; } } System.Gadget.endTransition(System.Gadget.TransitionType.morph, this.timeTransition); } this.SetStatus = function(status) { document.getElementById("lastUpdated").innerHTML = status; } this.GetStatus = function() { return document.getElementById("lastUpdated").innerHTML; } this.setTheme = function(theme) { var styleUndocked = document.getElementById("styleUndocked"); var styleDocked = document.getElementById("styleDocked"); switch(theme) { case "docked": styleUndocked.disabled = true; styleDocked.disabled = false; break; case "undocked": styleUndocked.disabled = false; styleDocked.disabled = true; break; } } this.LoadSettings = function(settingsContainer) { var scriptNode = document.createElement('script'); scriptNode.setAttribute('src', "jscolor/jscolor.js"); scriptNode.setAttribute('type', "text/javascript"); document.getElementsByTagName('head')[0].appendChild(scriptNode); var bar1color = System.Gadget.Settings.read("bar1color") ? System.Gadget.Settings.read("bar1color") : "#FF6600"; var bar2color = System.Gadget.Settings.read("bar2color") ? System.Gadget.Settings.read("bar2color") : "#3399CC"; var baremptycolor = System.Gadget.Settings.read("baremptycolor") ? System.Gadget.Settings.read("baremptycolor") : "#CCCCCC"; var bgcolor = System.Gadget.Settings.read("bgcolor") ? System.Gadget.Settings.read("bgcolor") : "#FFFFFF"; var bordercolor = System.Gadget.Settings.read("bordercolor") ? System.Gadget.Settings.read("bordercolor") : "#000000"; var textcolor = System.Gadget.Settings.read("textcolor") ? System.Gadget.Settings.read("textcolor") : "#000000"; var bartextcolor = System.Gadget.Settings.read("bartextcolor") ? System.Gadget.Settings.read("bartextcolor") : "#FFFFFF"; var iconcolor = System.Gadget.Settings.read("iconcolor") ? System.Gadget.Settings.read("iconcolor") : "#000000"; var dividerDiv = document.createElement('div'); dividerDiv.className = 'row'; dividerDiv.innerHTML = '<div class="label"><strong>Hide Dividers:</strong></div>\ <div class="field">Yes <input type="radio" name="hideDividers" value="1" ' + (System.Gadget.Settings.read("hideDividers") ? 'CHECKED' : '') + '> \ No<input type="radio" name="hideDividers" value="0" ' + (!System.Gadget.Settings.read("hideDividers") ? 'CHECKED' : '') + '></div>'; settingsContainer.appendChild(dividerDiv); var mouseOverDiv = document.createElement('div'); mouseOverDiv.className = 'row'; mouseOverDiv.innerHTML = ' <div class="row">\ <div class="label"><strong>Mouseover Details:</strong></div>\ <div class="field">\ Yes <input type="radio" name="mouseoverDetails" value="1" ' + (System.Gadget.Settings.read("mouseoverDetails") ? 'CHECKED' : '') + '> \ No<input type="radio" name="mouseoverDetails" value="0" ' + (!System.Gadget.Settings.read("mouseoverDetails") ? 'CHECKED' : '') + '>\ </div>\ </div>'; settingsContainer.appendChild(mouseOverDiv); var mixedUnitsDiv = document.createElement('div'); mixedUnitsDiv.className = 'row'; mixedUnitsDiv.innerHTML = ' <div class="row">\ <div class="label"><strong>Use Mixed Units:</strong></div>\ <div class="field">\ Yes <input type="radio" name="mixedUnits" value="1" ' + (System.Gadget.Settings.read("mixedUnits") ? 'CHECKED' : '') + '> \ No<input type="radio" name="mixedUnits" value="0" ' + (!System.Gadget.Settings.read("mixedUnits") ? 'CHECKED' : '') + '>\ </div>\ </div>'; settingsContainer.appendChild(mixedUnitsDiv); var blankRow = document.createElement('div'); blankRow.className = 'row'; blankRow.innerHTML = '<br /><hr style="border:none; border-top:1px dotted black; height:1px;">'; settingsContainer.appendChild(blankRow); var resetColours = document.createElement('strong'); resetColours.innerHTML = 'Colours:&nbsp;&nbsp;'; settingsContainer.appendChild(resetColours); var resetLink = document.createElement('a'); resetLink.innerHTML = "Reset"; resetLink.href = '#'; var that = this; resetLink.onclick = function(){that.resetColours(); return false;}; settingsContainer.appendChild(resetLink); var colourTable = document.createElement('div'); colourTable.innerHTML = '<table width=100% cellpadding=1 callspacing=0 border=0>\ <tr class="font">\ <td>Bar 1</td>\ <td>Bar 2</td>\ <td>Bar Empty</td>\ <td>Background</td>\ </tr>\ <tr>\ <td><input class="color {hash:true}" id="bar1color" value="' + bar1color + '" size="6"></td>\ <td><input class="color {hash:true}" id="bar2color" value="' + bar2color + '" size="6"></td>\ <td><input class="color {hash:true}" id="baremptycolor" value="' + baremptycolor + '" size="6"></td>\ <td><input class="color {hash:true}" id="bgcolor" value="' + bgcolor + '" size="6"></td>\ </tr>\ <tr class="font">\ <td>Border</td>\ <td>Text</td>\ <td>Bar Text</td>\ <td>Icons</td>\ </tr>\ <tr>\ <td><input class="color {hash:true}" id="bordercolor" value="' + bordercolor + '" size="6"></td>\ <td><input class="color {hash:true}" id="textcolor" value="' + textcolor + '" size="6"></td>\ <td><input class="color {hash:true}" id="bartextcolor" value="' + bartextcolor + '" size="6"></td>\ <td><input class="color {hash:true}" id="iconcolor" value="' + iconcolor + '" size="6"></td>\ </tr>\ </table>'; settingsContainer.appendChild(colourTable); } this.ValidateSettings = function(event) { } this.SaveSettings = function(event) { System.Gadget.Settings.write("hideDividers", Radio_Value_Get(document.getElementById('hideDividers'))); System.Gadget.Settings.write("mouseoverDetails", Radio_Value_Get(document.getElementById('mouseoverDetails'))); System.Gadget.Settings.write("mixedUnits", Radio_Value_Get(document.getElementById('mixedUnits'))); System.Gadget.Settings.write("bar1color", bar1color.value); System.Gadget.Settings.write("bar2color", bar2color.value); System.Gadget.Settings.write("baremptycolor", baremptycolor.value); System.Gadget.Settings.write("bgcolor", bgcolor.value); System.Gadget.Settings.write("bordercolor", bordercolor.value); System.Gadget.Settings.write("textcolor", textcolor.value); System.Gadget.Settings.write("bartextcolor", bartextcolor.value); System.Gadget.Settings.write("iconcolor", iconcolor.value); } this.resetColours = function() { document.getElementById("bar1color").value = "#FF6600"; document.getElementById("bar1color").style.backgroundColor = "#FF6600"; document.getElementById("bar1color").style.color = "#FFFFFF"; document.getElementById("bar2color").value = "#3399CC"; document.getElementById("bar2color").style.backgroundColor = "#3399CC"; document.getElementById("bar2color").style.color = "#000000"; document.getElementById("baremptycolor").value = "#CCCCCC"; document.getElementById("baremptycolor").style.backgroundColor = "#CCCCCC"; document.getElementById("baremptycolor").style.color = "#000000"; document.getElementById("bgcolor").value = "#FFFFFF"; document.getElementById("bgcolor").style.backgroundColor = "#FFFFFF"; document.getElementById("bgcolor").style.color = "#000000"; document.getElementById("bordercolor").value = "#000000"; document.getElementById("bordercolor").style.backgroundColor = "#000000"; document.getElementById("bordercolor").style.color = "#FFFFFF"; document.getElementById("textcolor").value = "#000000"; document.getElementById("textcolor").style.backgroundColor = "#000000"; document.getElementById("textcolor").style.color = "#FFFFFF"; document.getElementById("bartextcolor").value = "#FFFFFF"; document.getElementById("bartextcolor").style.backgroundColor = "#FFFFFF"; document.getElementById("bartextcolor").style.color = "#000000"; document.getElementById("iconcolor").value = "#000000"; document.getElementById("iconcolor").style.backgroundColor = "#000000"; document.getElementById("iconcolor").style.color = "#FFFFFF"; } this.FormatUsage = function(info, targetUnits){ var unitSuffix = ['', 'MB', 'GB', 'TB', 'PB', 'EB', 'YB']; for(var i = 0; i < unitSuffix.length; i++){ if(info[1] == unitSuffix[i]){ info[1] = i; } if(targetUnits && targetUnits == unitSuffix[i]){ targetUnits = i; } } while((targetUnits && info[1] != targetUnits) || (!targetUnits && info[0] >= 1000)){ info[0] /= 1000; info[1]++; } info[1] = unitSuffix[info[1]]; } this.DisplayData = function(data) { try{ var usageAccuracy = System.Gadget.Settings.read("usageAccuracy"); var remainingAccuracy = System.Gadget.Settings.read("remainingAccuracy"); var usageDisplay = [(System.Gadget.Settings.read("usageDisplay") ? data.allowance - data.totalUsage : data.totalUsage), "MB"]; var quotaDisplay = [data.allowance, "MB"]; //In MB if(System.Gadget.Settings.read("mixedUnits")){ //Mix Units this.FormatUsage(usageDisplay); this.FormatUsage(quotaDisplay); }else{ //Don't mix the units, just make them GB this.FormatUsage(usageDisplay, "GB"); this.FormatUsage(quotaDisplay, "GB"); } quotaDisplay[0] = roundNumber(quotaDisplay[0], 3); //At most 3 decimal places. //Dynamically find max number of decimal places. Not fixed because more decimal places where possible is better //Particularly if usage is over 1Tb. 3 decimal places makes it accurate to nearest GB. //If possible want accuracy to nearest MB var dPs = 10 - quotaDisplay[0].toString().length + (quotaDisplay[0] - Math.floor(quotaDisplay[0]) > 0 ? 1 : 0) - parseInt(usageDisplay[0]).toString().length; usageDisplay[0] = roundNumber(usageDisplay[0], Math.max(0, dPs)); if(usageDisplay[1] == quotaDisplay[1]) usageDisplay[1] = ''; //Usage Bar document.getElementById("usage").innerHTML = usageDisplay[0] + usageDisplay[1] + " \/ " + quotaDisplay[0] + quotaDisplay[1]; if(System.Gadget.Settings.read("usageDisplay")){ document.getElementById("bar1").style.width = Math.max((data.allowance - data.totalUsage) / data.allowance * 100, 0) + "%"; document.getElementById("percentUsed").innerHTML = Math.min(roundNumber((data.allowance - data.totalUsage) / data.allowance * 100, usageAccuracy), 100) + "%"; }else{ document.getElementById("bar1").style.width = Math.min(data.totalUsage / data.allowance * 100, 100) + "%"; document.getElementById("percentUsed").innerHTML = Math.max(roundNumber(data.totalUsage / data.allowance * 100, usageAccuracy), 0) + "%"; } //Month Bar var today = new Date(); var startDate = new Date(data.startDate); startDate.setHours(0); startDate.setMinutes(0); startDate.setSeconds(0); var endDate = new Date(data.endDate + 24*60*60*1000); endDate.setHours(0); endDate.setMinutes(0); endDate.setSeconds(0); var monthRemaining = (endDate.getTime()-today.getTime())/(1000*60*60*24); var monthPassed = (today.getTime()-startDate.getTime())/(1000*60*60*24); var daysInMonth = (endDate.getTime()-startDate.getTime())/(1000*60*60*24); var daysPassed = daysInMonth - (endDate.getTime()-today.getTime())/(1000*60*60*24); document.getElementById("monthRemaining").innerHTML = (roundNumber(monthRemaining, remainingAccuracy)) + (monthRemaining == 1 ? " DAY" : " DAYS"); document.getElementById("bar2").style.width = Math.min(monthPassed / daysInMonth * 100 , 100) + "%"; document.getElementById("percentMonth").innerHTML = roundNumber(monthPassed / daysInMonth * 100, usageAccuracy) + "%"; //Mouseover details var perDayRemaining = [Math.max(0, (data.allowance - data.totalUsage) / ((monthRemaining < 1) ? 1 : monthRemaining)), "MB"]; this.FormatUsage(perDayRemaining); perDayRemaining[0] = Math.round(perDayRemaining[0] * 1000) / 1000; //Sets to 3 decimal places (regardless of unit) perDayRemaining = perDayRemaining[0] + " " + perDayRemaining[1]; var surplusDeficit = ["0", "MB", "Surplus"]; if ((data.allowance / daysInMonth * daysPassed) >= data.totalUsage) surplusDeficit = [(data.allowance / daysInMonth * daysPassed) - data.totalUsage, "MB", "Surplus"]; else surplusDeficit = [data.totalUsage - (data.allowance / daysInMonth * daysPassed), "MB", "Deficit"]; this.FormatUsage(surplusDeficit); surplusDeficit[0] = Math.round(surplusDeficit[0] * 1000) / 1000; //Sets to 3 decimal places (regardless of unit) if(System.Gadget.Settings.read("mouseoverDetails")){ document.getElementById("mainheader").setAttribute("title", UsageGadget.username); document.getElementById("usageOverlay").setAttribute("title", surplusDeficit[2] + ": " + surplusDeficit[0] + " " + surplusDeficit[1]); document.getElementById("monthOverlay").setAttribute("title", "Per Day Remaining: " + perDayRemaining); } this.flyoutData = ' <div style="margin-bottom: 5px;">\ <h5>USAGE</h5>\ <table width="100%" class="font" style="margin-top: 5px;">\ <tr>\ <td width="25%" style="font-weight: bold;">Per Day Remaining</td>\ <td>' + perDayRemaining + '</td>\ </tr>\ <tr>\ <td style="font-weight:bold">' + surplusDeficit[2] + '</td>\ <td>' + surplusDeficit[0] + " " + surplusDeficit[1] + '</td>\ </tr>\ </table>\ </div>'; this.flyoutData += data.flyoutData; }catch(err){ this.flyoutData = err.message; } } this.SetIconColour = function(iconname, status) { if (iconname == "details") { if (status == "over") { document.getElementById("icon-details").style.borderColor = iconcolourover; document.getElementById("icon-details-box").style.backgroundColor = iconcolourover; } else { document.getElementById("icon-details").style.borderColor = iconcolour; document.getElementById("icon-details-box").style.backgroundColor = iconcolour; } } else if (iconname == "refresh") { if (status == "over") { document.getElementById("icon-refresh").style.borderColor = iconcolourover; document.getElementById("icon-refresh-triangle").style.borderTopColor = iconcolourover; document.getElementById("icon-refresh-line").style.backgroundColor = iconcolourover; } else { document.getElementById("icon-refresh").style.borderColor = iconcolour; document.getElementById("icon-refresh-triangle").style.borderTopColor = iconcolour; document.getElementById("icon-refresh-line").style.backgroundColor = iconcolour; } } } this.OpenFlyout = function () { if (this.flyoutData) { System.Gadget.Flyout.show = !System.Gadget.Flyout.show; System.Gadget.Flyout.document.parentWindow.content = this.flyoutData; } } }<file_sep>/js/common.js // JavaScript Document function LoadJSFiles(path, arrayToStore){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var folder = fso.GetFolder(path); var fc = new Enumerator(folder.files); for(; !fc.atEnd();fc.moveNext()){ try{ var fileref = document.createElement('script') fileref.setAttribute("type","text/javascript") fileref.setAttribute("src", fc.item()) document.getElementsByTagName("head")[0].appendChild(fileref) var classname = fc.item() + ""; classname = classname.toString().replace(path + "\\", "").replace(".js", ""); arrayToStore.push(new window[classname]()); }catch(err){ } } //If priority isn't defined it'll fail gracefully try{ arrayToStore.sort(function(a, b){return a.priority-b.priority}); }catch(err){ } } function Radio_Value_Get(radioObj) { if(!radioObj) return ""; var radioLength = radioObj.length; if(radioLength == undefined) if(radioObj.checked) return radioObj.value; else return ""; for(var i = 0; i < radioLength; i++) { if(radioObj[i].checked) { return radioObj[i].value; } } return ""; } function roundNumber(num, dec) { var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); return result; }<file_sep>/js/settings/General.js // JavaScript Document function General(){ this.id = 'general'; this.name = 'General'; this.priority = 10; //Lower number == Higher priority this.usernameField = null; this.passwordField = null; this.refreshIntervalField = null; this.overrideQuotaField = null; this.Initialise = function () { this.usernameField = document.createElement('input'); this.usernameField.type = 'text'; this.usernameField.id = "bigpondUsername"; this.usernameField.title = "Username"; this.usernameField.size = 20; this.usernameField.value = System.Gadget.Settings.read("bigpondUsername"); this.passwordField = document.createElement('input'); this.passwordField.type = '<PASSWORD>'; this.passwordField.id = '<PASSWORD>'; this.passwordField.title = 'Password'; this.passwordField.size = 20; this.passwordField.value = System.Gadget.Settings.read("<PASSWORD>"); this.refreshIntervalField = document.createElement('input'); this.refreshIntervalField.type = 'text'; this.refreshIntervalField.id = 'refreshInterval'; this.refreshIntervalField.title = 'Refresh Interval'; this.refreshIntervalField.size = 20; this.refreshIntervalField.value = (System.Gadget.Settings.read("refreshInterval") ? System.Gadget.Settings.read("refreshInterval") : 60); this.overrideQuotaField = document.createElement('input'); this.overrideQuotaField.type = 'text'; this.overrideQuotaField.id = 'overrideQuota'; this.overrideQuotaField.title = 'Override Quota'; this.overrideQuotaField.size = 20; this.overrideQuotaField.value = System.Gadget.Settings.read("overrideQuota"); } this.CreateRow = function(label, input) { var rowDiv = document.createElement('div'); rowDiv.className = 'row'; var labelDiv = document.createElement('div'); labelDiv.className = 'label'; labelDiv.innerHTML = "<strong>" + label + ":</strong>"; var fieldDiv = document.createElement('div'); fieldDiv.className = 'field'; fieldDiv.appendChild(input); rowDiv.appendChild(labelDiv); rowDiv.appendChild(fieldDiv); return rowDiv; } this.Display = function (tabContent) { var node = document.createElement('div'); node.appendChild(this.CreateRow('Username', this.usernameField)); node.appendChild(this.CreateRow('Password', this.passwordField)); node.appendChild(this.CreateRow('Refresh Interval (mins)', this.refreshIntervalField)); node.appendChild(this.CreateRow('Override Quota (GB)', this.overrideQuotaField)); //I.E. handles radio buttons stupidly so just manually handle them var radioButtons = document.createElement('div'); radioButtons.className = 'row'; radioButtons.innerHTML = ' <div class="label"><strong>Usage Display:</strong></div>\ <div class="field"> Used <input type="radio" name="usageDisplay" value="0"' + (!System.Gadget.Settings.read("usageDisplay") ? 'CHECKED' : '') + '> \ Remaining <input type="radio" name="usageDisplay" value="1"' + (System.Gadget.Settings.read("usageDisplay") ? 'CHECKED' : '') + '>\ </div>'; node.appendChild(radioButtons); var unratedButtons = document.createElement('div'); unratedButtons.className = 'row'; unratedButtons.innerHTML = ' <div class="label"><strong>Unrated as Metered:</strong></div>\ <div class="field"> Yes <input type="radio" name="includeUnrated" value="1"' + (System.Gadget.Settings.read("includeUnrated") ? 'CHECKED' : '') + '> \ No <input type="radio" name="includeUnrated" value="0"' + (!System.Gadget.Settings.read("includeUnrated") ? 'CHECKED' : '') + '>\ </div>'; node.appendChild(unratedButtons); tabContent.appendChild(node); } this.ValidateSettings = function (event) { //validate fields if (this.usernameField.value == "") { UsageGadgetSettings.SetStatus('Please enter your username!'); event.cancel = true; return; } if(this.usernameField.value.indexOf("@") < 0){ UsageGadgetSettings.SetStatus('Please enter your full username. E.g. <EMAIL>'); event.cancel = true; return; } if (this.passwordField.value == "") { UsageGadgetSettings.SetStatus("Please enter your password!"); event.cancel = true; return; } if (/^-?\d+$/.test(this.refreshIntervalField.value) == false || this.refreshIntervalField.value < 15) { UsageGadgetSettings.SetStatus("Refresh interval must be a whole number >= 15!"); event.cancel = true; return; } if (this.overrideQuotaField.value) { if (/^\d+(\.\d{1,1})?$/.test(this.overrideQuotaField.value) == false || this.overrideQuotaField.value < 1) { UsageGadgetSettings.SetStatus("Override Quota must be a number >= 1!"); event.cancel = true; return; } } } this.SaveSettings = function(event) { System.Gadget.Settings.write("bigpondUsername", this.usernameField.value.toLowerCase()); System.Gadget.Settings.write("bigpondPassword", <PASSWORD>.<PASSWORD>Field.value); System.Gadget.Settings.write("refreshInterval", this.refreshIntervalField.value); System.Gadget.Settings.write("overrideQuota", this.overrideQuotaField.value); System.Gadget.Settings.write("usageDisplay", Radio_Value_Get(document.getElementsByName('usageDisplay'))); System.Gadget.Settings.write("includeUnrated", Radio_Value_Get(document.getElementsByName('includeUnrated'))); } }<file_sep>/js/settings/Appearance.js // JavaScript Document function Appearance(){ this.id = 'appearance'; this.name = 'Appearance'; this.priority = 20; this.styles = []; this.style = null; this.Initialise = function () { LoadJSFiles(System.Gadget.path + "\\js\\styles", this.styles); var stylename = System.Gadget.Settings.read("style"); this.style = this.styles[0]; //Sets a default just in case one can't be found for(var i = 0; i < this.styles.length; i++){ if(this.styles[i].uid == stylename){ this.style = this.styles[i]; break; } } } this.Display = function (tabContent) { var container = document.createElement('div'); container.innerHTML = '<strong>Select Style:</strong> '; var selector = document.createElement('select'); selector.id = 'styleSelect'; container.appendChild(selector); container.appendChild(document.createElement('hr')); for(var i = 0; i < this.styles.length; i++){ //Add option to the style selector var option = document.createElement('option'); option.value = this.styles[i].uid; option.text = this.styles[i].Name; var styleSettings = document.createElement('div'); styleSettings.id = 'appearance_' + this.styles[i].uid + '_settings'; container.appendChild(styleSettings); if(this.styles[i].uid == this.style.uid){ option.selected = true; }else{ styleSettings.style.display = "none"; } selector.add(option); //Load any style settings that may be there! try{ this.styles[i].LoadSettings(styleSettings); }catch(err){ } } var that = this; selector.onchange = function(){that.ShowStyleSettings(this)}; tabContent.appendChild(container); } this.ShowStyleSettings = function(selector) { var uid = selector.options[selector.selectedIndex].value; for(var i = 0; i < this.styles.length; i++){ document.getElementById('appearance_' + this.styles[i].uid + '_settings').style.display = "none"; if(uid == this.styles[i].uid) document.getElementById('appearance_' + this.styles[i].uid + '_settings').style.display = ''; } } this.ValidateSettings = function(event) { for(var i = 0; i < this.styles.length; i++){ this.styles[i].ValidateSettings(event); if(event.cancel) return; } } this.SaveSettings = function(event) { var selector = document.getElementById('styleSelect'); System.Gadget.Settings.write("style", selector.options[selector.selectedIndex].value); for(var i = 0; i < this.styles.length; i++){ this.styles[i].SaveSettings(event); } } }<file_sep>/js/settings/Misc.js // JavaScript Document function Misc(){ this.id = 'misc'; this.name = 'Misc'; this.priority = 30; this.Initialise = function () { } this.Display = function (tabContent) { var node = document.createElement('div'); var useErrorLog = System.Gadget.Settings.read("useErrorLog"); var displayAccount = System.Gadget.Settings.read("displayAccount"); var use12hourtime = System.Gadget.Settings.read("use12hourtime"); var hideFailedMessages = System.Gadget.Settings.read("hideFailedMessages"); var usageAccuracy = (System.Gadget.Settings.read("usageAccuracy") ? System.Gadget.Settings.read("usageAccuracy") : 0); var remainingAccuracy = (System.Gadget.Settings.read("remainingAccuracy") ? System.Gadget.Settings.read("remainingAccuracy") : 1); node.innerHTML = ' <div class="row">\ <div class="label">\ <strong>Log Errors & Debug Messages:</strong>\ </div>\ <div class="field">\ Yes <input type="radio" name="logErrors" value="1" ' + (useErrorLog ? 'CHECKED' : '') + '> \ No<input type="radio" name="logErrors" value="0" ' + (!useErrorLog ? 'CHECKED' : '') + '>\ </div>\ </div>\ <div class="row">\ <div class="field">\ <a href="' + System.Gadget.path + '\\logs\\">Open Log Folder</a>\ </div>\ </div>\ <div class="row">\ <div class="label">\ <strong>Display Account Name:</strong>\ </div>\ <div class="field">\ Yes <input type="radio" name="displayAccount" value="1" ' + (displayAccount ? 'CHECKED' : '') + '> \ No<input type="radio" name="displayAccount" value="0" ' + (!displayAccount ? 'CHECKED' : '') + '>\ </div>\ </div>\ <div class="row">\ <div class="label">\ <strong>Use 12 hour time:</strong>\ </div>\ <div class="field">\ Yes <input type="radio" name="use12hourtime" value="1" ' + (use12hourtime ? 'CHECKED' : '') + '> \ No<input type="radio" name="use12hourtime" value="0" ' + (!use12hourtime ? 'CHECKED' : '') + '>\ </div>\ </div>\ <div class="row">\ <div class="label">\ <strong>Only "As of" Label:</strong>\ </div>\ <div class="field">\ Yes <input type="radio" name="hideFailedMessages" value="1" ' + (hideFailedMessages ? 'CHECKED' : '') + '> \ No<input type="radio" name="hideFailedMessages" value="0" ' + (!hideFailedMessages ? 'CHECKED' : '') + '>\ </div>\ </div>\ <div class="row"><br></div>\ <div class="row">\ <strong>Value Accuracy (Decimal Places):</strong><br>\ <table>\ <tr class="font">\ <td>Usage/Month</td>\ <td>Days Remaining</td>\ </tr>\ <tr>\ <td><input type="text" id="usageAccuracy" size=20 value="' + usageAccuracy + '"></td>\ <td><input type="text" id="remainingAccuracy" size=20 value="' + remainingAccuracy + '"></td>\ </tr>\ </table>\ </div>'; tabContent.appendChild(node); } this.ValidateSettings = function(event) { if(document.getElementById('usageAccuracy').value){ IsFound = /^-?\d+$/.test(document.getElementById('usageAccuracy').value); if(IsFound == false || document.getElementById('usageAccuracy').value < 0){ UsageGadgetSettings.SetStatus("Usage/Month Accuracy must be a number 0 or greater."); event.cancel = true; return; } } if(document.getElementById('remainingAccuracy').value){ IsFound = /^-?\d+$/.test(document.getElementById('remainingAccuracy').value); if(IsFound == false || document.getElementById('remainingAccuracy').value < 0){ UsageGadgetSettings.SetStatus("Remaining Time Accuracy must be a number 0 or greater."); event.cancel = true; return; } } } this.SaveSettings = function(event) { System.Gadget.Settings.write("useErrorLog", Radio_Value_Get(document.getElementById('logErrors'))); System.Gadget.Settings.write("displayAccount", Radio_Value_Get(document.getElementById('displayAccount'))); System.Gadget.Settings.write("use12hourtime", Radio_Value_Get(document.getElementById('use12hourtime'))); System.Gadget.Settings.write("hideFailedMessages", Radio_Value_Get(document.getElementById('hideFailedMessages'))); System.Gadget.Settings.write("usageAccuracy", document.getElementById('usageAccuracy').value); System.Gadget.Settings.write("remainingAccuracy", document.getElementById('remainingAccuracy').value); } }<file_sep>/js/methods/gm2k201.js // JavaScript Document // JavaScript Document function gm2k201(){ this.uid = 'gm2k201'; this.name = 'GM2K 2.0.1'; this.priority = 20; this.enabled = true; this.accountId = ''; this.serviceId = ''; this.Run = function() { UsageGadget.logger.LogMessage("INFO", "Running method: " + this.name); //Older methods require a different login page so we need to login "again" UsageGadget.logger.LogMessage("INFO", "This method requires a different login page so we're calling that now."); var that = this; var loginPage = new WebLoading(UsageGadget.logger); loginPage.method = 'POST'; loginPage.headers.push(new RequestHeader('Content-Type', 'application/x-www-form-urlencoded')); loginPage.postdata = "username=" + UsageGadget.username + "&password=" + UsageGadget.password; loginPage.onsuccess = function(responseText){that.LoginOK(responseText);}; loginPage.onfail = function(){that.FailedPageLoading();}; loginPage.url = 'https://signon.bigpond.com/login'; loginPage.waitFor200 = false; loginPage.LoadPage(); } this.LoginOK = function(responseText) { var loginOK = /Your username\/password combination is incorrect or incomplete/.exec(responseText); if (loginOK == "Your username/password combination is incorrect or incomplete"){ //Shouldn't actually get here since the details should be correct before getting here UsageGadget.logger.LogMessage("ERROR", "Logging in failed. Username or Password is incorrect."); UsageGadget.CheckNextMethod(); return; } var that = this; var servicesPage = new WebLoading(UsageGadget.logger); servicesPage.onsuccess = function(responseText){that.ServicesPageLoaded(responseText);}; servicesPage.onfail = function(){that.FailedPageLoading();}; servicesPage.url = 'https://myaccount.bigpond.com/MyServices.do'; servicesPage.LoadPage(); } this.FailedPageLoading = function() { UsageGadget.logger.LogMessage("WARNING", "Failed to load the webpage."); UsageGadget.CheckNextMethod(); } this.ServicesPageLoaded = function(responseText) { try{ UsageGadget.logger.LogMessage("INFO", "'My Services' page loaded. Loading usage page. Method: " + this.name); var doc = document.createElement('div'); doc.innerHTML = responseText; var pTags = doc.getElementsByTagName("p"); var usageURL = ''; for(var i = 0; i < pTags.length; i++){ if(pTags[i].innerHTML == 'Username: ' + UsageGadget.username){ if(/view usage/ig.exec(pTags[i].parentNode.innerHTML)){ var linkItems = pTags[i].parentNode.getElementsByTagName('a'); for(var j = 0; j < linkItems.length; j++) if(linkItems[j].innerHTML == 'View usage'){ usageURL = linkItems[j].href.replace("x-gadget://", ""); break; } } } } if(usageURL == ''){ UsageGadget.logger.LogMessage("ERROR", "Couldn't find usage URL."); UsageGadget.CheckNextMethod(); return; } usageURL = "https://myaccount.bigpond.com" + usageURL; var that = this; var detailsPage = new WebLoading(UsageGadget.logger); detailsPage.onsuccess = function(responseText){that.DetailsLoaded(responseText);}; detailsPage.onfail = function(){that.FailedPageLoading();}; detailsPage.url = usageURL; detailsPage.LoadPage(); }catch(err){ UsageGadget.logger.LogMessage("ERROR", "Couldn't find usage URL. Message: " + err.message); UsageGadget.CheckNextMethod(); } } this.DetailsLoaded = function(responseText) { UsageGadget.logger.LogMessage("INFO", "Getting usage info and passing it to the gadget to display!"); try{ var data = new DataToDisplay(); var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var result = 1; var Usage = /<tr class=\"trStyleTotal\">[^`]+?<!-- total usage shown as bold -->[^`]+?>([0-9\-]+)<\/b>/i.exec(responseText); var Quota = /Monthly Allowance[^`]+?([0-9:]+\s*(?:G|M|h))/i.exec(responseText); var Period = /<tbody>[^`]+?<!-- date column -->[^`]+?>([0-9]{2} [A-Za-z]{3} [0-9]{4})<[^`]+>([0-9]{2} [A-Za-z]{3} [0-9]{4})[^`]+<\/tbody>/i.exec(responseText); if(Usage != null) data.totalUsage = (Usage[1] == '-' ? 0 : Usage[1]); else result = 0; if(Quota != null){ var allowanceDetails = /([0-9]+)\s*(G|M)/.exec(Quota[1]); data.allowance = allowanceDetails[1] * (allowanceDetails[2] == 'G' ? 1000 : 1); }else result = 0; if(Period != null){ var startParts = /([0-9]+) ([a-z]+)/i.exec(Period[1]); var endParts = /([0-9]+) ([a-z]+)/i.exec(Period[2]); if(monthNames[(new Date()).getMonth()] == 'Jan' && startParts[2] == 'Dec'){ startParts.push((new Date()).getFullYear() - 1); }else{ startParts.push((new Date()).getFullYear()); } if(monthNames[(new Date()).getMonth()] == 'Dec' && endParts[2] == 'Jan'){ endParts.push((new Date()).getFullYear() + 1); }else{ endParts.push((new Date()).getFullYear()); } data.startDate = (new Date(startParts[1] + " " + startParts[2] + " " + startParts[3])).getTime(); data.endDate = (new Date(endParts[1] + " " + endParts[2] + " " + endParts[3])).getTime(); }else result = 0; if(result == 0){ UsageGadget.logger.LogMessage("WARNING", "Required usage information wasn't found. Page is probably not compatible with method " + this.name + ". Trying next method."); UsageGadget.CheckNextMethod(); return; } data.unratedUsage = 0; try{ var UnratedUsage = /<tr class="trStyleTotal">[^`]+<td>([^`]+)<\/td>[^`]+?<\/tr>[^`]+?<\/tfoot>/i.exec(responseText); data.unratedUsage = UnratedUsage[1]; }catch(err){ } data.flyoutData = this.BuildFlyoutPage(responseText, data); data.raw = responseText; UsageGadget.DisplayData(data); }catch(err){ UsageGadget.logger.LogMessage("ERROR", "Error getting the usage data. Message: " + err.message); UsageGadget.CheckNextMethod(); } } this.BuildFlyoutPage = function (content, data) { try{ content = content.replace(/\/res\/images/gi, "img"); var pageTable = /<h5>Volume based usage meter table<\/h5>[\s]*(<table class[^`]+?>[^`]+<\/table>)/.exec(content); var accountDetails = /<table[^`]+?>([^`]+?Monthly Allowance[^`]+?)<\/table>/i.exec(content); accountDetails[1] = accountDetails[1].replace(/<a[^`]+?<\/a>/gi, ""); accountDetails[1] = accountDetails[1].replace(/class="[^`]+?"/gi, ""); accountDetails[1] = "<table class=\"accountTable\">" + accountDetails[1] + "</table>"; var pageHTML = "<h5>PLAN DETAILS</h5>" + accountDetails[1] + "<div class=\"spacer\"></div>" + pageTable[1]; return pageHTML; }catch(err){ return ''; } } }
43cabe3708bc47c65d73c33b897900f3da8a2f35
[ "JavaScript", "Markdown" ]
9
JavaScript
GamingMaster2000/BPUsageMeter
5f2f07abac1c54b4cc8173fbda2901ec80fb8d62
480599fabfdb50d81d97570f4ca5ef5d5322938e
refs/heads/main
<repo_name>learn-with-aws/Lambda_Boto3<file_sep>/stop_start_ec2_instances.py import json import boto3 data = boto3.client('ec2') def lambda_handler(event, context): instances = data.describe_instances(Filters=[{'Name': 'tag:env', 'Values': ['wc_testserver']}]) instances_list = [] for instance in instances['Reservations']: for instance_id in instance['Instances']: instances_list.append(instance_id['InstanceId']) print (instances_list) # Stop EC2 instances data.stop_instances(InstanceIds=instances_list) print ("The above instance got stopped") # Start Ec2 Instances #data.start_instances(InstanceIds=instances_list) #print ("The above instance got started") <file_sep>/secret_manager.py import boto3 import json secret_name = "dev/ocp" region_name = "us-east-1" # Create a Secrets Manager client session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name ) get_secret_value_response = client.get_secret_value(SecretId=secret_name) secret = get_secret_value_response['SecretString'] dictData = json.loads(secret) #print(dictData) print(dictData['host']) print(dictData['port']) <file_sep>/stop_ec2_instances_without_specific_tags.py ## Stop the Server if they don't have any tags. #### Steps - Create a Lambda and setup a cloudwatch event pattren. Select EC2 service type and event. import json import boto3 data = boto3.client('ec2') def lambda_handler(event, context): instances = data.describe_instances(Filters=[{'Name': 'tag:env', 'Values': ['wc_testserver']}]) instances_list = [] for instance in instances['Reservations']: for instance_id in instance['Instances']: instances_list.append(instance_id['InstanceId']) print (instances_list) data.stop_instances(InstanceIds=instances_list) #data.stop_instances(InstanceIds=instances_list) print ("The above instance got start")
312467382dc85355077fce09f496fb91de13377d
[ "Python" ]
3
Python
learn-with-aws/Lambda_Boto3
c3353de63cceea9b888fbaf4f6da66e5a4471370
f51f43b283aa00300b8c3874495953a6a2eff63d
refs/heads/master
<repo_name>ebru-c-7/my-portfolio<file_sep>/src/components/Tools.js import React from "react"; const Tools = (props) => { return props.data.map((tool, i) => ( <img src={tool.logo} alt={tool.name} key={i} style={{ width: "2rem" }} title={tool.name} /> )); }; export default Tools; <file_sep>/src/components/CustomCard.js import React from "react"; import Card from "react-bootstrap/Card"; import Tools from "./Tools"; import logo from "../assets/projects/logo.png"; const CustomCard = (props) => { return ( <div className="card-container"> {props.data.map((pro, i) => ( <Card bg="light" text="dark" className="custom-card" key={i}> <Card.Img variant="top" className="project-logo" src={pro.logo || logo} /> <Card.Body> <Card.Title>{pro.name}</Card.Title> <Card.Text>{pro.description}</Card.Text> </Card.Body> <Card.Footer> {!!pro.codeURL && <Card.Link target="blank" href={pro.codeURL}>Code</Card.Link>} {!!pro.link && <Card.Link target="blank" href={pro.link}>Live</Card.Link>} {!!pro.document && <Card.Link target="blank" href={pro.document}>Doc</Card.Link>} </Card.Footer> <Card.Footer> <Tools data={pro.tools} /> </Card.Footer> </Card> ))} </div> ); }; export default CustomCard; <file_sep>/src/components/About.js import React from "react"; import Modal from "react-bootstrap/Modal"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faLinkedinIn, faGithub } from "@fortawesome/free-brands-svg-icons"; import { faEnvelope } from "@fortawesome/free-solid-svg-icons"; import profile from "../assets/profile-ebru-c-7.jpg"; const About = (props) => { return ( <React.Fragment> <Modal.Header closeButton> <Modal.Title>who am I?</Modal.Title> </Modal.Header> <Modal.Body> <img src={profile} alt="profile" className="about-profile" /> <p> I have provided the advisory and audit (post-control) services at EY Turkey to the global clients for almost 6 years after graduation. However, at the end of this long and fruitful career, I have decided to pursue a different path and started to work to become a web developer after leaving EY as the "Global Trade Manager". </p> <p> I have completed the double major program with MIS department in the university and participated in the system design and management of multiple projects to get my degree. </p> <p> In the projects I have created, React, Jquery, Bootstrap, CSS3, HTML5 for Frontend; Node.js (REST API) for Backend are used (Check out{" "} <code onClick={props.change.bind(null, "skills")}>my skills</code>{" "} section here). </p> <p> Also, you can take a look at the projects on{" "} <code onClick={props.change.bind(null, "my-projects")}> my projects </code>{" "} section. </p> </Modal.Body> <Modal.Footer> <Modal.Header> <b>Contact: </b> </Modal.Header> <Modal.Body> <a className="about-social" target="blank" rel="noopener noreferrer" href={"https://www.linkedin.com/in/ebru-%C3%A7akmak-1b62b133/"} > <FontAwesomeIcon style={{ fontSize: "1.3rem" }} icon={faLinkedinIn} /> </a> <a className="about-social" href={`mailto:<EMAIL>`}> <FontAwesomeIcon style={{ fontSize: "1.3rem" }} icon={faEnvelope} /> </a> <a className="about-social" target="blank" rel="noopener noreferrer" href={"https://github.com/ebru-c-7/"} > <FontAwesomeIcon style={{ fontSize: "1.3rem" }} icon={faGithub} />{" "} </a> </Modal.Body> </Modal.Footer> </React.Fragment> ); }; export default About; <file_sep>/src/components/Container.js import React, { useState } from "react"; import rocket from "../assets/icons/rocket-solid.svg"; import code from "../assets/icons/laptop-code-solid.svg"; import cap from "../assets/icons/graduation-cap-solid.svg"; import tools from "../assets/icons/tools-solid.svg"; import MenuItem from "./MenuItem"; import CustomModal from "./CustomModal"; const Container = () => { const [modal, setModal] = useState(null); const modalHandler = (section) => setModal(section); const modalCloseHandler = () => setModal(null); return ( <React.Fragment> <div className="App"> <MenuItem class="App-top" logo={rocket} alt="about-me" modalHandler={modalHandler} > About Me </MenuItem> <div className="App-middle"> <MenuItem logo={code} alt="my-projects" modalHandler={modalHandler}> My Projects </MenuItem> <MenuItem logo={cap} alt="education-certificates" modalHandler={modalHandler} > Education & {"\n"} Certificates </MenuItem> </div> <MenuItem class="App-bottom" logo={tools} alt="skills" modalHandler={modalHandler} > My Skills </MenuItem> </div> <CustomModal change={modalHandler} type={modal} close={modalCloseHandler} /> </React.Fragment> ); } export default Container; <file_sep>/src/components/Projects.js import React, { useState } from "react"; import axios from "../utility/axios"; import Modal from "react-bootstrap/Modal"; import CustomCard from "./CustomCard"; const Projects = (props) => { const [list, setList] = useState(null); const loadProjects = async () => { const projects = await axios.get("/projectList.json"); setList(projects.data); }; if (!list) { loadProjects(); } let content = list ? ( <React.Fragment> <Modal.Header closeButton> <Modal.Title>My Projects</Modal.Title> </Modal.Header> <Modal.Body> <CustomCard data={list} /> </Modal.Body> </React.Fragment> ) : null; return content; }; export default Projects; <file_sep>/src/components/CustomFigure.js import React from "react"; import Figure from "react-bootstrap/Figure"; const CustomFigure = (props) => { let figuresElement = props.data.map((el, i) => ( <Figure key={i}> <Figure.Image alt="tool" src={el.logo} /> <Figure.Caption>{el.description}</Figure.Caption> </Figure> )); return ( <section> <h6>{props.children}</h6> <div className="figure-container">{figuresElement}</div> </section> ); }; export default CustomFigure; <file_sep>/src/components/Skills.js import React, { useState } from "react"; import axios from "../utility/axios"; import Modal from "react-bootstrap/Modal"; import CustomFigure from "./CustomFigure"; const Skills = (props) => { const [list, setList] = useState(null); const loadSkills = async () => { const skills = await axios.get("/skillsList.json"); setList(skills.data); }; if (!list) { loadSkills(); } let content = list ? (<React.Fragment> <Modal.Header closeButton> <Modal.Title>My Skills</Modal.Title> </Modal.Header> <Modal.Body> <CustomFigure data={list && list.project}>My Project-Based Skills</CustomFigure> <hr /> <CustomFigure data={list && list.basic}>General Knowledge</CustomFigure> </Modal.Body> </React.Fragment>) : null; return content; }; export default Skills;
a411d98e214bc2a46c11839c7ec975087bb1f813
[ "JavaScript" ]
7
JavaScript
ebru-c-7/my-portfolio
a6a1c54b8912fae51d824111028370dcdc87393a
c398a837df7ad101dc6355c84612085bd17b72ab
refs/heads/master
<repo_name>thinkful-ei-quail/johna-bookmarks-app<file_sep>/src/bookmarks.js import $ from 'jquery'; import api from './bookmarksApi.js'; import store from './bookmarksStore.js'; import trashIcon from './trash.png'; const ifRating = (val, fallback) => ((val >= 1) && (val <= 5)) ? val : fallback; const bookmarkIdFrom$Target = $target => $target.closest('li').data('id'); // IMPORTANT -- :indeterminate selector only works if these are wrapped by a form // any call site that isn't naturally inside a form needs to wrap this result w/ <form></form> const generateRatingEditorHtml = current => `<div class="stars"> <input name="rating" type="radio" ${(current===1)?'checked ':''}value="1" aria-label="1 Star"> <input name="rating" type="radio" ${(current===2)?'checked ':''}value="2" aria-label="2 Stars"> <input name="rating" type="radio" ${(current===3)?'checked ':''}value="3" aria-label="3 Stars"> <input name="rating" type="radio" ${(current===4)?'checked ':''}value="4" aria-label="4 Stars"> <input name="rating" type="radio" ${(current===5)?'checked ':''}value="5" aria-label="5 Stars"> <button class="no-rating" aria-label="No rating" type="button"><span>Reset</span></button> </div>`; const generateNewBookmarkFormHtml = expanded => `<form id="new-bookmark-form" class="${expanded?'':'collapsed'}" role="dialog" aria-modal="true" aria-labelledby="new-bookmark-form-title"><h2 id="new-bookmark-form-title" >Add new bookmark</h2><input name="url" class="http" placeholder="http://samplelink.code/toInfinityAndBeyond"><input placeholder="Title" name="title">${generateRatingEditorHtml()}<textarea placeholder="Add a description (optional)" id="desc"></textarea><input type="reset" id="cancel-add" value="Cancel"><input type="submit" value="Create"> </form>`; const generateBookmarkHtml = (id, title, url, desc, rating, expanded) => { const ratingText = ifRating(rating,''); return `<li data-id="${id}" ><h2 class="bookmark"><button aria-controls="expanded-${id}" aria-expanded="${expanded}" class="bookmark-header" id="header-${id}"><span class="header-rating" aria-label="${ratingText?ratingText+' stars':''}" data-rating="${ratingText}">${ratingText?'★':''}</span>${title}</button></h2><div aria-labelledby="header-${id}" id="expanded-${id}" class="bookmark-details ${expanded?'expanded':'collapsed'}" ><div><form>${generateRatingEditorHtml(rating)}</form><a href="${url}">Visit Site</a></div><button aria-label="Delete bookmark" class="bookmark-killer" ><img src="${trashIcon}"></button><p>${typeof(desc) === 'string' ? desc : ''}</p></div></li>`; }; const generateBookmarkListHtml = bookmarks => bookmarks.map(b => generateBookmarkHtml(b.id, b.title, b.url, b.desc, b.rating, b.expanded)).join(''); const generateFilterHtml = current => `<select id="filter"> <option${(current===0)?' selected':''}>No filter</option> <option${(current===1)?' selected':''}>1 Star or better</option> <option${(current===2)?' selected':''}>2 Star or better</option> <option${(current===3)?' selected':''}>3 Star or better</option> <option${(current===4)?' selected':''}>4 Star or better</option> <option${(current===5)?' selected':''}>5 Star only</option> </select>`; const render = () => { const minStarRating = store.filter(); const err = store.error(); const errText = err ? err : ''; let bookmarks = store.getAllBookmarks(); let emptyViewMessage; if(minStarRating) { bookmarks = bookmarks.filter(bookmark => bookmark.rating >= minStarRating); emptyViewMessage = '<li><p class="error">None of your bookmarks match the current filter.</p></li>'; } else { emptyViewMessage = `<li><p class="error">You don't have any bookmarks yet. Why not create one?</p></li>`; } $('main').html(`<div id="controls"><button id="add"><span>+ Add</span></button>${ generateFilterHtml(store.filter())}</div>${generateNewBookmarkFormHtml(store.adding())}<p class="error">${errText}</p><ul>${(bookmarks.length > 0) ? generateBookmarkListHtml(bookmarks) : emptyViewMessage}</ul>`); store.error(null); }; const renderRatingEditor = where => { where.replaceWith(generateRatingEditorHtml()); }; const onAddClicked = () => { store.adding(!store.adding()); render(); }; const onAddFormSubmitted = e => { e.preventDefault(); const form = e.target; const rating = form.rating.value; api.insert(store.encodedUserName(), { title: form.title.value, url: form.url.value, desc: form.desc.value, rating: ifRating(rating)}) .then(bookmark => store.addBookmark(bookmark)) .then(() => store.adding(false)) .catch(err => store.error(err)) .finally(render); }; const onFilterChanged = e => { store.filter(e.target.selectedIndex); render(); }; const onHeaderClicked = e => { expand(bookmarkIdFrom$Target($(e.target)), true); }; const onBookmarkKillerClicked = e => { const id = bookmarkIdFrom$Target($(e.target)); api.delete(store.encodedUserName(), id) .then(() => store.deleteBookmark(id)) .catch(err => store.error(err)) .finally(render); }; const onBookmarkRated = e => { const $target = $(e.target); const rating = +$target.val(); const id = bookmarkIdFrom$Target($target); api.update(store.encodedUserName(), id, { rating }) .then(() => store.findBookmark(id).rating = rating) .catch(err => store.error(err)) .finally(render); }; const onZeroRatingClicked = e => { const $target = $(e.target); if($target.closest('#new-bookmark-form')) // for the adder, no api calls yet; just re-render the editor renderRatingEditor($target.closest('.stars')); else { // the api doesn't seem to allow an existing rating to be nulled or zeroed; we'll hide this feature with css /* const bookmark = store.findBookmark(bookmarkIdFrom$Target($target)); api.update(store.encodedUserName(), bookmark.id, { rating: 0 }) .then(() => bookmark.rating = 0) .catch(err => store.error(err)) .finally(render); */ } }; const expand = (linkedBookmarkId, toggle) => { const linked = store.findBookmark(linkedBookmarkId); if(linked) { linked.expanded = toggle ? !linked.expanded : true; render(); $(`#header-${linkedBookmarkId}`)[0].scrollIntoView(); } }; export default { init: function(linkedBookmarkId) { api.getAll(store.encodedUserName()) .then(bookmarks => bookmarks.forEach(bookmark => store.addBookmark(bookmark))) .then(() => this.expand(linkedBookmarkId)) .catch(err => store.error(err)) .finally(render); const $bodyElement = $('body'); $bodyElement.on('click', '#add', onAddClicked); $bodyElement.on('input', '#filter', onFilterChanged); $bodyElement.on('click', '#cancel-add', onAddClicked); $bodyElement.on('submit', '#new-bookmark-form', onAddFormSubmitted); $bodyElement.on('change', 'li .stars input', onBookmarkRated); $bodyElement.on('click', '.no-rating', onZeroRatingClicked); $bodyElement.on('click', '.bookmark-header', onHeaderClicked); $bodyElement.on('click', '.bookmark-killer', onBookmarkKillerClicked); }, expand, };<file_sep>/src/bookmarksStore.js const Bookmark = function() { this.id = null; this.title = 'New Bookmark'; this.url = 'https://'; this.desc = null; this.rating = null; this.expanded = false; }; const store = { adding: false, bookmarks: [], error: null, filter: 0, user: null, }; export default { assignUser: (encodedUser, decodedUser) => store.user = { encodedUser, decodedUser }, decodedUserName: () => store.user.decodedUser, encodedUserName: () => store.user.encodedUser, error: err => (err!==undefined) ? (store.error = err) : store.error, addBookmark: bookmark => store.bookmarks.unshift(Object.assign(new Bookmark(), bookmark)), adding: bool => (bool!==undefined) ? (store.adding = bool) : store.adding, deleteBookmark: id => store.bookmarks.splice(store.bookmarks.findIndex(bookmark => bookmark.id === id), 1), filter: level => (level!==undefined) ? (store.filter = level) : store.filter, findBookmark: id => store.bookmarks.find(bookmark => bookmark.id === id), getAllBookmarks: () => store.bookmarks, };<file_sep>/README.md Bookmarks App Live Example: <https://thinkful-ei-quail.github.io/johna-bookmarks-app/> Required Implemented Features: * I can add bookmarks to my bookmark list. Bookmarks contain: * title * url link * description * rating (1-5) * I can see a list of my bookmarks when I first open the app * All bookmarks in the list default to a "condensed" view showing only title and rating * I can click on a bookmark to display the "detailed" view * Detailed view expands to additionally display description and a "Visit Site" link * I can remove bookmarks from my bookmark list * I receive appropriate feedback when I cannot submit a bookmark * I can select from a dropdown (a &lt;select> element) a "minimum rating" to filter the list by all bookmarks rated at or above the chosen selection Bonus Implemented Features: * I can change the rating of an existing bookmark * I can view and/or change any user's bookmarks by changing the query portion of the URL. For example, JaneLane's bookmarks are at <https://thinkful-ei-quail.github.io/johna-bookmarks-app/?JaneLane> * I can link to a specific bookmark using the fragment identifier (hash sign); for example, if JaneLane had a bookmark with id 1, I could link to it with <https://thinkful-ei-quail.github.io/johna-bookmarks-app/?JaneLane#header-1>. When the page loads, the requested bookmark is expanded and scrolled into view.
59c8239aee40af236697ee35fd5a86d20685fdae
[ "JavaScript", "Markdown" ]
3
JavaScript
thinkful-ei-quail/johna-bookmarks-app
d22fa33e69fb774086b7e918592709454db0da49
13cbbfa0aa1ca280152f6e7a31cf9bd9c941f92e
refs/heads/master
<file_sep><?php use Doctrine\ORM\Tools\Setup; use Doctrine\ORM\EntityManager; use WWII\Config\ConfigManager; use WWII\Service\ServiceManager; use WWII\Service\ServiceManagerInterface; if (!isset($loader)) { $loader = include(__DIR__ . "/../autoload.php"); } $loader->set("WWII\\Domain", __DIR__ . '/domain/src/'); $loader->register(true); $loader->set("WWII\\Application", __DIR__ . '/application/src/'); $loader->register(true); $loader->set("WWII\\Console", __DIR__ . '/console/src/'); $loader->register(true); $loader->set("WWII\Common", __DIR__ . '/common/src'); $loader->register(true); $loader->set("WWII\\", __DIR__ . '/core/src/'); $loader->register(true); $isDevMode = true; $configManager = ConfigManager::getInstance(); $config = Setup::createXMLMetadataConfiguration($configManager->get('doctrine_mappings'), $isDevMode); $connection = $configManager->get('database'); $entityManager = EntityManager::create($connection, $config); $platform = $entityManager->getConnection()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); $serviceManager = new ServiceManager(); $serviceManager->setConfigManager($configManager); <file_sep><?php // BEGIN: TITIP error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT); $includePaths = array( __DIR__ . '/../../vendor', __DIR__ . '/../../vendor/wwii', ); set_include_path(get_include_path() . PATH_SEPARATOR . implode(PATH_SEPARATOR, $includePaths)); function __autoload($className) { if ($className === 'PEAR_Error') { return; } include($className . '.php'); } include_once('init_autoload.php'); if (isset($_GET['bypass']) || isset($_GET['print'])) { ob_start(); session_start(); require_once('bootstrap.php'); ob_end_flush(); return; } // END: TITIP ob_start(); require_once("./libs/sesschk.php"); require_once("./libs/lib_konci.php"); include_once("./libs/myfunctions.php"); include_once("./libs/agent.php"); header('Content-type: text/html; charset=utf-8'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <meta name="author" content="<NAME>" /> <title> <?php include("./includes/title.php");?> </title> <link href="./styles/arina.css" rel="stylesheet" type="text/css"/> <link href="./styles/form.css" rel="stylesheet" type="text/css"/> <link href="./styles/topmenu.css" rel="stylesheet" type="text/css"/> <link href="./styles/leftmenu2.css" rel="stylesheet" type="text/css"/> <script src="./libs/leftmenu2.js" type="text/javascript"></script> <?php sessionBreak($_SESSION['arinaSess']); ?> </head> <?php //$agent->init(); ?> <body> <div id="head"> <div class="left">PT. <NAME> </div> <div class="right">Online Reporting System</div> </div> <div id="container"> <div id="left"> <div class="boxed"> <div class="title"> <?php include("./includes/cp.php");?> </div> <?php include("./includes/leftmenu.php"); ?> </div> </div> <div id="content"> <div id="topnavcontainer"> <?php include("./includes/topmenu.php"); ?> </div> <div id="thecontent"> <h3><?php echo $pageTitle;?></h3> <!-- CONTENT FILTER /--> <?php if (! isset($_GET['c'])||$_GET['c']=="") { include("./includes/home.php"); } elseif ($_GET['sub']=="svlk") { //echo "<script type=text/javascript>"; //echo "window.location.href = http://192.168.0.1:8080/tri_svlk"; //echo "</script>"; header('location:http://192.168.0.1:8080/tri_svlk'); } else { if (! file_exists("./includes/controller.php")) { include("./includes/404.php"); } else { //~echo '<img src="./images/icons/$_GET[c].png" width="64"' echo '<img src="./images/icons/wwii.jpg" width="150"' . ' height="50" align="right" style="padding: 20px;margin-top: -60px" />'; //~echo "$_GET[c]"; include("./includes/controller.php"); } } ?> </div> </div> </div> </body> </html> <?php ob_end_flush(); ?> <file_sep><?php class DoctrineCLI { protected $entityManagers = array(); protected $activeEntityManager = null; protected $commands = array(); protected $specialCommands = array(); public function __construct() { $this->entityManagers[0]['key'] = '1'; $this->entityManagers[0]['name'] = 'MySQL Entity Manager'; $this->entityManagers[0]['active'] = true; $this->entityManagers[1]['key'] = '2'; $this->entityManagers[1]['name'] = 'MsSQL Entity Manager'; $this->entityManagers[1]['active'] = false; $this->commands[0]['key'] = '1'; $this->commands[0]['name'] = 'Validate schema'; $this->commands[1]['key'] = '2'; $this->commands[1]['name'] = 'Dump Update Schema SQL'; $this->commands[2]['key'] = '3'; $this->commands[2]['name'] = 'Execute Update Schema SQL'; $this->specialCommands[0]['key'] = 'b'; $this->specialCommands[0]['name'] = 'Back'; $this->specialCommands[1]['key'] = 'x'; $this->specialCommands[1]['name'] = 'Exit'; } public function run() { $this->displayMessages($this->getWelcomeMessages()); while (true) { if ($this->activeEntityManager == null) { $message = $this->getPreSelectMessages() . $this->getSelectMessages() . $this->getSpecialCommandMessages(false) . $this->getInputMessages(); $input = $this->getInput($message); $this->translateInput($input); } else { $message = $this->getPreCommandMessages() . $this->getCommandMessages() . $this->getSpecialCommandMessages(true) . $this->getInputMessages(); $input = $this->getInput($message); $this->translateInput($input); } } } protected function getWelcomeMessages() { $message = PHP_EOL . 'Welcome to Doctrine Custom CLI.' . PHP_EOL . PHP_EOL; return $message; } protected function getPreSelectMessages() { $message = 'Select an Entity Manager:' . PHP_EOL; return $message; } protected function getSelectMessages() { $message = ''; foreach ($this->entityManagers as $entityManager) { $message .= $entityManager['key'] . '. ' . $entityManager['name'] . PHP_EOL; } return $message; } protected function getPreCommandMessages() { $message = 'Active Entity Manager: ' . $this->activeEntityManager['name'] . PHP_EOL; return $message; } protected function getCommandMessages() { $message = ''; foreach ($this->commands as $command) { $message .= $command['key'] . '. ' . $command['name'] . PHP_EOL; } return $message; } protected function getSpecialCommandMessages($includeBack = true) { $message = ''; foreach ($this->specialCommands as $command) { if ($includeBack || (!$includeBack && $command['key'] != 'b')) { $message .= $command['key'] . '. ' . $command['name'] . PHP_EOL; } } return $message; } protected function getInputMessages() { $message = PHP_EOL . 'Choice : '; return $message; } protected function getMaintenanceMessages($target) { $message = $target['name'] . ' is under maintenance.' . PHP_EOL . PHP_EOL; return $message; } protected function getErrorMessages() { $message = 'Wrong choice...' . PHP_EOL . PHP_EOL; return $message; } protected function displayMessages($messages) { fwrite(STDOUT, $messages); } protected function getInput($message) { $this->displayMessages($message); $input = chop(fgets(STDIN)); fwrite(STDOUT, PHP_EOL); return $input; } protected function translateInput($input) { if (empty($this->activeEntityManager)) { switch ($input) { case '1': case '2': $activeEntityManager = null; foreach ($this->entityManagers as $entityManager) { if ($entityManager['key'] == $input) { if ($entityManager['active']) { $activeEntityManager = $entityManager; } else { $this->displayMessages($this->getMaintenanceMessages($entityManager)); return; } } } if ($activeEntityManager == null) { $this->displayMessages($this->getErrorMessages()); } else { $this->activeEntityManager = $activeEntityManager; } break; case 'x': $this->terminate(); break; default: $this->displayMessages($this->getErrorMessages()); break; } } else { chdir(dirname(__FILE__)); switch ($input) { case '1': $this->displayMessages('Please wait...' . PHP_EOL); $this->displayMessages('==========================================================' . PHP_EOL . PHP_EOL); system('doctrine.php.bat orm:validate-schema'); $this->displayMessages(PHP_EOL . '==========================================================' . PHP_EOL . PHP_EOL); break; case '2': $this->displayMessages('Please wait...' . PHP_EOL); $this->displayMessages('==========================================================' . PHP_EOL); system('doctrine.php.bat orm:schema-tool:update --dump-sql'); $this->displayMessages('==========================================================' . PHP_EOL . PHP_EOL); break; case '3': $this->displayMessages('Please wait...' . PHP_EOL); $this->displayMessages('==========================================================' . PHP_EOL); system('doctrine.php.bat orm:schema-tool:update --force'); $this->displayMessages('==========================================================' . PHP_EOL . PHP_EOL); break; case 'b': $this->activeEntityManager = null; break; case 'x': $this->terminate(); break; } } } protected function terminate($code = 0) { fwrite(STDOUT, 'Teriminating...' . PHP_EOL); $this->activeEntityManager = null; sleep(1); exit($code); } } $cli = new DoctrineCLI(); $cli->run(); <file_sep><?php // Include the Console_CommandLine package. require_once 'Console/CommandLine.php'; require_once __DIR__ . '/../wwii/bootstrap.php'; $config = include __DIR__ . '/../wwii/console/config/config.default.php'; $parser = new Console_CommandLine(array( 'description' => 'WWII Console Application v-1.0.0', 'version' => '1.0.0' )); $parser->addOption('verbose', array( 'short_name' => '-v', 'long_name' => '--verbose', 'action' => 'StoreTrue', 'description' => 'turn on verbose output' )); foreach ($config['console']['commands'] as $strCommand => $arrayCommand) { $command = $parser->addCommand($strCommand, array( 'description' => $arrayCommand['description'] )); if (isset($arrayCommand['options']) && ! empty($arrayCommand['options'])) { foreach ($arrayCommand['options'] as $strOption => $arrayOption) { $command->addOption($strOption, $arrayOption); } } if (isset($arrayCommand['arguments']) && ! empty($arrayCommand['arguments'])) { foreach ($arrayCommand['arguments'] as $strArgument => $arrayArgument) { $command->addArgument($strArgument, $arrayArgument); } } } try { $result = $parser->parse(); $controllerName = $result->command_name; if (! empty($result->command)) { $controller = new $config['console']['commands'][$controllerName]['controller']( $serviceManager, $entityManager ); $options = null; if (isset($result->command->options)) { $options = $result->command->options; } $args = null; if (isset($result->command->args)) { $args = $result->command->args; } $controller->run($options, $args); } } catch (\Exception $e) { $parser->displayError($e->getMessage()); } <file_sep><?php include(__DIR__ . '/init_autoload.php'); if (php_sapi_name() === 'cli') { return false; } $application = new \WWII\Application(); $application->setEntityManager($entityManager); $application->run();
d22822bfd63af33c1ce6f6aebb224533e3ba3f01
[ "PHP" ]
5
PHP
rendyep/wwii-root
de668aedc9854d5998ab8cef5f7c2ddc3495451f
8eb44ff38250dcda286da0cc2c8820d7a4a9119b
refs/heads/master
<repo_name>Gastonm123/2048<file_sep>/main.py from juego import Juego import pyglet from pyglet.gl import * from pyglet import clock from pyglet.window import key from numeros import numeros window = pyglet.window.Window() clock.set_fps_limit(60) j = Juego() j.ant = j.tablero.copy() @window.event def on_key_press(symbol, modifiers): if symbol == key.B: j.tablero = j.ant j.ant = j.tablero.copy() if symbol == key.LEFT: j.moveLeft() elif symbol == key.RIGHT: j.moveRigth() elif symbol == key.UP: j.moveUp() elif symbol == key.DOWN: j.moveDown() @window.event def on_draw(): clock.tick() mapa = j.tablero mx = window.width // 2 my = window.height // 2 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glLoadIdentity() glBegin(GL_QUADS) glColor3f(0.3,0.3,0.3) glVertex2f(mx-90, my+90) glVertex2f(mx+95, my+90) glVertex2f(mx+95, my-95) glVertex2f(mx-90, my-95) glEnd() corrimiento_y = 85 for linea in mapa: corrimiento_x = -85 for pieza in linea: corner_x = mx + corrimiento_x corner_y = my + corrimiento_y glBegin(GL_QUADS) glColor3f(*numeros[str(pieza)]) glVertex2f(corner_x, corner_y) glVertex2f(corner_x+40, corner_y) glVertex2f(corner_x+40, corner_y-40) glVertex2f(corner_x, corner_y-40) glEnd() if pieza != 0: label = pyglet.text.Label( str(pieza), font_name='Times New Roman', font_size=10, x=corner_x+20, y=corner_y-20, anchor_x='center', anchor_y='center' ) label.draw() label.delete() corrimiento_x += 45 corrimiento_y -= 45 #print score corner_x = mx + 115 corner_y = my + 150 glColor3f(0.5, 0.1, 0.1) glBegin(GL_QUADS) glVertex2f(corner_x, corner_y) glVertex2f(corner_x+100, corner_y) glVertex2f(corner_x+100, corner_y-20) glVertex2f(corner_x, corner_y-20) glEnd() label = pyglet.text.Label( 'Score: ' + str(j.score), font_name='Times New Roman', font_size=10, x=corner_x+10, y=corner_y-10, anchor_x='left', anchor_y='center' ) label.draw() label.delete() pyglet.app.run()<file_sep>/juego.py from __future__ import print_function from random import randint import numpy as np class Juego: def __init__(self): self.tablero = np.array([[0 for i in range(4)] for j in range(4)]) self.state = True self.win = False self.score = 0 self.putPiece() def putPiece(self): posLibres = [] for i, linea in enumerate(self.tablero): for j, pieza in enumerate(linea): if pieza == 0: posLibres.append((i, j)) if len(posLibres) == 0: self.state = False else: pick = posLibres[ randint(0, len(posLibres)-1) ] ficha = 2 * randint(1, 2) self.tablero[pick[0]][pick[1]] = ficha self.score += ficha def moveLeft(self): #primero colapso las piezas iguales tablero = self.tablero.copy() for linea in self.tablero: anterior = 0 for j, pieza in enumerate(linea): if pieza == 0: pass elif anterior == 0: anterior = (j, pieza) elif anterior[1] == pieza: linea[j] = 0 linea[anterior[0]] = 2 * pieza self.score += linea[anterior[0]] anterior = 0 else: anterior = (j, pieza) #muevo las piezas for linea in self.tablero: piezas = [0 for i in range(4)] cont = 0 for pieza in linea: if pieza == 0: pass else: piezas[cont] = pieza cont += 1 for i, pieza in enumerate(piezas): linea[i] = pieza if not np.array_equal(self.tablero, tablero): self.putPiece() def moveRigth(self): tablero = self.tablero.copy() for linea in self.tablero: anterior = 0 for j, pieza in reversed(list(enumerate(linea))): if pieza == 0: pass elif anterior == 0: anterior = (j, pieza) elif anterior[1] == pieza: linea[j] = 0 linea[anterior[0]] = 2 * pieza self.score += linea[anterior[0]] anterior = 0 else: anterior = (j, pieza) #muevo las piezas for linea in self.tablero: piezas = [0 for i in range(4)] cont = 3 for pieza in reversed(linea): if pieza == 0: pass else: piezas[cont] = pieza cont -= 1 for i, pieza in enumerate(piezas): linea[i] = pieza if not np.array_equal(self.tablero, tablero): self.putPiece() def moveUp(self): #primero colapso las piezas iguales tablero = self.tablero.copy() for linea in self.tablero.T: anterior = 0 for j, pieza in enumerate(linea): if pieza == 0: pass elif anterior == 0: anterior = (j, pieza) elif anterior[1] == pieza: linea[j] = 0 linea[anterior[0]] = 2 * pieza self.score += linea[anterior[0]] anterior = 0 else: anterior = (j, pieza) #muevo las piezas for linea in self.tablero.T: piezas = [0 for i in range(4)] cont = 0 for pieza in linea: if pieza == 0: pass else: piezas[cont] = pieza cont += 1 for i, pieza in enumerate(piezas): linea[i] = pieza if not np.array_equal(self.tablero, tablero): self.putPiece() def moveDown(self): tablero = self.tablero.copy() for linea in self.tablero.T: anterior = 0 for j, pieza in reversed(list(enumerate(linea))): if pieza == 0: pass elif anterior == 0: anterior = (j, pieza) elif anterior[1] == pieza: linea[j] = 0 linea[anterior[0]] = 2 * pieza self.score += linea[anterior[0]] anterior = 0 else: anterior = (j, pieza) #muevo las piezas for linea in self.tablero.T: piezas = [0 for i in range(4)] cont = 3 for pieza in reversed(linea): if pieza == 0: pass else: piezas[cont] = pieza cont -= 1 for i, pieza in enumerate(piezas): linea[i] = pieza if not np.array_equal(self.tablero, tablero): self.putPiece() def show(self): for linea in self.tablero: for pieza in linea: print(pieza, end=", ") print('')
1e4365412d379479406f01d2c8c7bc8345ff6e47
[ "Python" ]
2
Python
Gastonm123/2048
2f35fc46f1871667357db80cfa3ac6fddc31d152
d35d34ed4c8ec4c469473ed5b3d9ddfa82fffcdb
refs/heads/main
<repo_name>bwaldvogel/mongo-java-server<file_sep>/h2-backend/src/main/java/de/bwaldvogel/mongo/H2MongoServer.java package de.bwaldvogel.mongo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.backend.h2.H2Backend; public class H2MongoServer extends MongoServer { private static final Logger log = LoggerFactory.getLogger(H2MongoServer.class); public static void main(String[] args) { final MongoServer mongoServer; if (args.length == 1) { String fileName = args[0]; mongoServer = new H2MongoServer(fileName); } else { mongoServer = new H2MongoServer(); } mongoServer.bind("localhost", 27017); Runtime.getRuntime().addShutdownHook(new Thread(() -> { log.info("shutting down {}", mongoServer); mongoServer.shutdownNow(); })); } public H2MongoServer() { super(H2Backend.inMemory()); } public H2MongoServer(String fileName) { super(new H2Backend(fileName)); } } <file_sep>/postgresql-backend/src/main/java/de/bwaldvogel/mongo/backend/postgresql/JsonConverter.java package de.bwaldvogel.mongo.backend.postgresql; import java.io.IOException; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.bwaldvogel.mongo.bson.BinData; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.LegacyUUID; import de.bwaldvogel.mongo.bson.ObjectId; import de.bwaldvogel.mongo.exception.MongoServerException; final class JsonConverter { private static final ObjectMapper objectMapper = objectMapper(); private JsonConverter() { } private static ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), DefaultTyping.JAVA_LANG_OBJECT, JsonTypeInfo.As.PROPERTY); objectMapper.addMixIn(LegacyUUID.class, LegacyUUIDJsonMixIn.class); objectMapper.addMixIn(BinData.class, BinDataJsonMixIn.class); objectMapper.registerSubtypes(ObjectId.class); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); SimpleModule module = new SimpleModule(); module.addAbstractTypeMapping(Set.class, LinkedHashSet.class); module.addAbstractTypeMapping(Map.class, LinkedHashMap.class); objectMapper.registerModule(module); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); objectMapper.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, true); objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true); return objectMapper; } static String toJson(Object object) { ObjectWriter writer = objectMapper.writer(); try { return writer.writeValueAsString(object); } catch (JsonProcessingException e) { throw new MongoServerException("Failed to serialize value to JSON", e); } } static Document fromJson(String json) throws IOException { ObjectReader reader = objectMapper.reader(); return reader.forType(Document.class).readValue(json); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/NumericUtils.java package de.bwaldvogel.mongo.backend; import java.math.BigDecimal; import de.bwaldvogel.mongo.bson.Decimal128; public class NumericUtils { @FunctionalInterface public interface BigDecimalCalculation { BigDecimal apply(BigDecimal a, BigDecimal b); } @FunctionalInterface public interface DoubleCalculation { double apply(double a, double b); } @FunctionalInterface public interface LongCalculation { long apply(long a, long b); } private static Number calculate(Number a, Number b, LongCalculation longCalculation, DoubleCalculation doubleCalculation, BigDecimalCalculation bigDecimalCalculation) { if (a instanceof Decimal128 || b instanceof Decimal128) { BigDecimal result = bigDecimalCalculation.apply(toBigDecimal(a), toBigDecimal(b)); return new Decimal128(result); } else if (a instanceof Double || b instanceof Double) { return Double.valueOf(doubleCalculation.apply(a.doubleValue(), b.doubleValue())); } else if (a instanceof Float || b instanceof Float) { double result = doubleCalculation.apply(a.doubleValue(), b.doubleValue()); return Float.valueOf((float) result); } else if (a instanceof Long || b instanceof Long) { return Long.valueOf(longCalculation.apply(a.longValue(), b.longValue())); } else if (a instanceof Integer || b instanceof Integer) { long result = longCalculation.apply(a.longValue(), b.longValue()); int intResult = (int) result; if (intResult == result) { return Integer.valueOf(intResult); } else { return Long.valueOf(result); } } else if (a instanceof Short || b instanceof Short) { long result = longCalculation.apply(a.longValue(), b.longValue()); short shortResult = (short) result; if (shortResult == result) { return Short.valueOf(shortResult); } else { return Long.valueOf(result); } } else { throw new UnsupportedOperationException("cannot calculate on " + a + " and " + b); } } private static BigDecimal toBigDecimal(Number value) { return Decimal128.fromNumber(value).toBigDecimal(); } public static Number addNumbers(Number one, Number other) { return calculate(one, other, Long::sum, Double::sum, BigDecimal::add); } public static Number subtractNumbers(Number one, Number other) { return calculate(one, other, (a, b) -> a - b, (a, b) -> a - b, BigDecimal::subtract); } public static Number multiplyNumbers(Number one, Number other) { return calculate(one, other, (a, b) -> a * b, (a, b) -> a * b, BigDecimal::multiply); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/UnsetStageTest.java package de.bwaldvogel.mongo.backend.aggregation.stage; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; class UnsetStageTest { @Test void testUnset() throws Exception { assertThat(unset("field1", json("_id: 1, field1: 'value1'"), json("_id: 2, field1: 'value1', field2: 'value2'"), json("_id: 3, field2: 'value2'"), json("_id: 4"))) .containsExactly( json("_id: 1"), json("_id: 2, field2: 'value2'"), json("_id: 3, field2: 'value2'"), json("_id: 4") ); } @Test void testUnsetMultipleFields() throws Exception { assertThat(unset(List.of("field1", "field2"), json("_id: 1, field1: 'value1'"), json("_id: 2, field1: 'value1', field2: 'value2'"), json("_id: 3, field2: 'value2', field3: 'value3'"), json("_id: 4, field3: 'value3'"), json("_id: 5"))) .containsExactly( json("_id: 1"), json("_id: 2"), json("_id: 3, field3: 'value3'"), json("_id: 4, field3: 'value3'"), json("_id: 5") ); } @Test void testUnsetWithSubdocument() throws Exception { assertThat(unset("fields.field1", json("_id: 1, fields: { field1: 'value1' }"), json("_id: 2, fields: { field1: 'value1', field2: 'value2' }"), json("_id: 3, fields: { field2: 'value2' }"), json("_id: 4, fields: { }"), json("_id: 5"))) .containsExactly( json("_id: 1, fields: { }"), json("_id: 2, fields: { field2: 'value2' }"), json("_id: 3, fields: { field2: 'value2' }"), json("_id: 4, fields: { }"), json("_id: 5") ); } @Test void testIllegalUnset() throws Exception { assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnsetStage("")) .withMessage("[Error 40352] Invalid $unset :: caused by :: FieldPath cannot be constructed with empty string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnsetStage(List.of(123, 456))) .withMessage("[Error 31120] $unset specification must be a string or an array containing only string values"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnsetStage(123)) .withMessage("[Error 31120] $unset specification must be a string or an array containing only string values"); } private List<Document> unset(Object input, Document... documents) { return new UnsetStage(input).apply(Stream.of(documents)).collect(Collectors.toList()); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/GraphLookupStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.FailedToParseException; public class GraphLookupStage extends AbstractLookupStage { private static final String START_WITH = "startWith"; private static final String CONNECT_FROM_FIELD = "connectFromField"; private static final String CONNECT_TO_FIELD = "connectToField"; private static final String MAX_DEPTH = "maxDepth"; private static final String DEPTH_FIELD = "depthField"; private static final Set<String> CONFIGURATION_KEYS; static { CONFIGURATION_KEYS = new HashSet<>(); CONFIGURATION_KEYS.add(FROM); CONFIGURATION_KEYS.add(START_WITH); CONFIGURATION_KEYS.add(CONNECT_FROM_FIELD); CONFIGURATION_KEYS.add(CONNECT_TO_FIELD); CONFIGURATION_KEYS.add(AS); CONFIGURATION_KEYS.add(MAX_DEPTH); CONFIGURATION_KEYS.add(DEPTH_FIELD); } private final String connectFromField; private final String connectToField; private final String asField; private final Integer maxDepth; private final String depthField; private final MongoCollection<?> collection; public GraphLookupStage(Document configuration, MongoDatabase mongoDatabase) { String from = readStringConfigurationProperty(configuration, FROM); collection = mongoDatabase.resolveCollection(from, false); readStringConfigurationProperty(configuration, FROM); readVariableConfigurationProperty(configuration, START_WITH); connectFromField = readStringConfigurationProperty(configuration, CONNECT_FROM_FIELD); connectToField = readStringConfigurationProperty(configuration, CONNECT_TO_FIELD); asField = readStringConfigurationProperty(configuration, AS); maxDepth = readOptionalIntegerConfigurationProperty(configuration, MAX_DEPTH); depthField = readOptionalStringConfigurationProperty(configuration, DEPTH_FIELD); ensureAllConfigurationPropertiesAreKnown(configuration, CONFIGURATION_KEYS); } @Override public String name() { return "$graphLookup"; } Integer readOptionalIntegerConfigurationProperty(Document configuration, String name) { Object value = configuration.get(name); if (value == null) { return null; } if (value instanceof Integer) { return (Integer) value; } throw new FailedToParseException("'" + name + "' option to \" + stageName + \" must be a integer, but was type " + Utils.describeType(value)); } String readOptionalStringConfigurationProperty(Document configuration, String name) { Object value = configuration.get(name); if (value == null) { return null; } if (value instanceof String) { return (String) value; } throw new FailedToParseException("'" + name + "' option to \" + stageName + \" must be a string, but was type " + Utils.describeType(value)); } void readVariableConfigurationProperty(Document configuration, String name) { Object value = configuration.get(name); if (value == null) { throw new FailedToParseException("missing '" + name + "' option to $graphLookup stage specification: " + configuration); } if (value instanceof String) { return; } throw new FailedToParseException("'" + name + "' option to $graphLookup must be a string, but was type " + Utils.describeType(value)); } @Override public Stream<Document> apply(Stream<Document> stream) { return stream.map(this::connectRemoteDocument); } private Document connectRemoteDocument(Document document) { Object value = document.get(connectFromField); List<Document> documentList = new ArrayList<>(); findLinkedDocuments(0, documentList, value); Document result = document.clone(); result.put(asField, documentList); return result; } private List<Document> findLinkedDocuments(long depth, final List<Document> linked, Object value) { if (maxDepth != null && depth > maxDepth) { return linked; } if (value instanceof List) { return ((List<?>) value).stream() .flatMap(item -> findLinkedDocuments(depth + 1, linked, item).stream()) .collect(toList()); } Document query = new Document(connectToField, value); List<Document> newlyLinkedDocuments = collection.handleQueryAsStream(query).collect(toList()); for (Document newDocument : newlyLinkedDocuments) { Object newValue = newDocument.get(connectFromField); if (depthField != null) { newDocument.put(depthField, depth); } linked.add(0, newDocument); findLinkedDocuments(depth + 1, linked, newValue); } return linked; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/IndexBuildFailedException.java package de.bwaldvogel.mongo.exception; import java.util.UUID; import de.bwaldvogel.mongo.MongoCollection; public class IndexBuildFailedException extends MongoServerError { private static final long serialVersionUID = 1L; public IndexBuildFailedException(MongoServerError e, MongoCollection<?> collection) { super(e.getCode(), e.getCodeName(), "Index build failed: " + UUID.randomUUID() + ": " + "Collection " + collection.getFullName() + " ( " + collection.getUuid() + " ) :: caused by :: " + e.getMessageWithoutErrorCode(), e); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/TerminalStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.stream.Stream; import de.bwaldvogel.mongo.bson.Document; public abstract class TerminalStage implements AggregationStage { abstract void applyLast(Stream<Document> stream); @Override public final Stream<Document> apply(Stream<Document> stream) { applyLast(stream); return Stream.empty(); } } <file_sep>/memory-backend/src/main/java/de/bwaldvogel/mongo/backend/memory/MemoryCollection.java package de.bwaldvogel.mongo.backend.memory; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.AbstractSynchronizedMongoCollection; import de.bwaldvogel.mongo.backend.CollectionOptions; import de.bwaldvogel.mongo.backend.CursorRegistry; import de.bwaldvogel.mongo.backend.DocumentWithPosition; import de.bwaldvogel.mongo.backend.QueryResult; import de.bwaldvogel.mongo.bson.Document; public class MemoryCollection extends AbstractSynchronizedMongoCollection<Integer> { private final List<Document> documents = new ArrayList<>(); private final Queue<Integer> emptyPositions = new LinkedList<>(); private final AtomicInteger dataSize = new AtomicInteger(); public MemoryCollection(MongoDatabase database, String collectionName, CollectionOptions options, CursorRegistry cursorRegistry) { super(database, collectionName, options, cursorRegistry); } @Override protected void updateDataSize(int sizeDelta) { dataSize.addAndGet(sizeDelta); } @Override protected int getDataSize() { return dataSize.get(); } @Override protected Integer addDocumentInternal(Document document) { Integer position = emptyPositions.poll(); if (position == null) { position = Integer.valueOf(documents.size()); } if (position.intValue() == documents.size()) { documents.add(document); } else { documents.set(position.intValue(), document); } return position; } @Override protected QueryResult matchDocuments(Document query, Document orderBy, int numberToSkip, int limit, int batchSize, Document fieldSelector) { Iterable<Document> documents = iterateAllDocuments(orderBy); Stream<Document> documentStream = StreamSupport.stream(documents.spliterator(), false); return matchDocumentsFromStream(documentStream, query, orderBy, numberToSkip, limit, batchSize, fieldSelector); } private Iterable<Document> iterateAllDocuments(Document orderBy) { DocumentIterable documentIterable = new DocumentIterable(this.documents); if (isNaturalDescending(orderBy)) { return documentIterable.reversed(); } else { return documentIterable; } } @Override public synchronized int count() { return documents.size() - emptyPositions.size(); } @Override public synchronized boolean isEmpty() { return documents.isEmpty() || super.isEmpty(); } @Override protected Integer findDocumentPosition(Document document) { int position = documents.indexOf(document); if (position < 0) { return null; } return Integer.valueOf(position); } @Override protected Stream<DocumentWithPosition<Integer>> streamAllDocumentsWithPosition() { return IntStream.range(0, documents.size()) .filter(position -> !emptyPositions.contains(position)) .mapToObj(index -> new DocumentWithPosition<>(documents.get(index), index)); } @Override protected void removeDocument(Integer position) { documents.set(position.intValue(), null); emptyPositions.add(position); } @Override protected Document getDocument(Integer position) { return documents.get(position.intValue()); } @Override protected void handleUpdate(Integer position, Document oldDocument, Document newDocument) { // noop } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/MissingTest.java package de.bwaldvogel.mongo.backend; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class MissingTest { @Test void testIsNullOrMissing() throws Exception { assertThat(Missing.isNullOrMissing(null)).isTrue(); assertThat(Missing.isNullOrMissing(Missing.getInstance())).isTrue(); assertThat(Missing.isNullOrMissing("value")).isFalse(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/BsonTimestamp.java package de.bwaldvogel.mongo.bson; import java.time.Instant; import java.util.Objects; public final class BsonTimestamp implements Bson, Comparable<BsonTimestamp> { private static final long serialVersionUID = 1L; private final long value; protected BsonTimestamp() { this(0); } public BsonTimestamp(long value) { this.value = value; } public BsonTimestamp(Instant instant, int increment) { value = (instant.getEpochSecond() << 32) | (increment & 0xFFFFFFFFL); } public long getValue() { return value; } public int getTime() { return (int) (value >> 32); } public int getInc() { return (int) value; } @Override public String toString() { return "BsonTimestamp[value=" + getValue() + ", seconds=" + getTime() + ", inc=" + getInc() + "]"; } @Override public int compareTo(BsonTimestamp other) { return Long.compareUnsigned(value, other.value); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BsonTimestamp other = (BsonTimestamp) o; return this.value == other.value; } @Override public int hashCode() { return Objects.hashCode(value); } } <file_sep>/memory-backend/src/test/java/de/bwaldvogel/mongo/backend/memory/MemoryBackendAggregationTest.java package de.bwaldvogel.mongo.backend.memory; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.backend.AbstractAggregationTest; class MemoryBackendAggregationTest extends AbstractAggregationTest { @Override protected MongoBackend createBackend() throws Exception { return new MemoryBackend(clock); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/AddFieldsStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.Map.Entry; import java.util.stream.Stream; import de.bwaldvogel.mongo.backend.Missing; import de.bwaldvogel.mongo.backend.aggregation.Expression; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; public class AddFieldsStage implements AggregationStage { private final Document addFields; public AddFieldsStage(Document addFields) { if (addFields.isEmpty()) { throw new MongoServerError(40177, "Invalid $addFields :: caused by :: specification must have at least one field"); } this.addFields = addFields; } @Override public String name() { return "$addFields"; } @Override public Stream<Document> apply(Stream<Document> stream) { return stream.map(this::projectDocument); } Document projectDocument(Document document) { Document clone = document.clone(); putRecursively(clone, addFields); return clone; } private void putRecursively(Document target, Document source) { for (Entry<String, Object> entry : source.entrySet()) { String key = entry.getKey(); Object value = Expression.evaluateDocument(entry.getValue(), target); if (value instanceof Document) { Document subDocument = (Document) target.compute(key, (k, oldValue) -> { if (!(oldValue instanceof Document)) { return new Document(); } else { return oldValue; } }); putRecursively(subDocument, (Document) value); } else { if (value instanceof Missing) { target.remove(key); } else { target.put(key, value); } } } } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Expression.java package de.bwaldvogel.mongo.backend.aggregation; import static de.bwaldvogel.mongo.backend.Missing.isNeitherNullNorMissing; import static de.bwaldvogel.mongo.backend.Missing.isNullOrMissing; import static de.bwaldvogel.mongo.backend.Utils.describeType; import static de.bwaldvogel.mongo.bson.Json.toJsonValue; import static java.util.Arrays.asList; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.time.DateTimeException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoField; import java.time.temporal.IsoFields; import java.time.temporal.TemporalAccessor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import java.util.Objects; import java.util.OptionalDouble; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; import java.util.regex.Pattern; import de.bwaldvogel.mongo.backend.Assert; import de.bwaldvogel.mongo.backend.BsonType; import de.bwaldvogel.mongo.backend.CollectionUtils; import de.bwaldvogel.mongo.backend.LinkedTreeSet; import de.bwaldvogel.mongo.backend.Missing; import de.bwaldvogel.mongo.backend.NumericUtils; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.backend.ValueComparator; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.ObjectId; import de.bwaldvogel.mongo.exception.BadValueException; import de.bwaldvogel.mongo.exception.ConversionFailureException; import de.bwaldvogel.mongo.exception.ErrorCode; import de.bwaldvogel.mongo.exception.FailedToOptimizePipelineError; import de.bwaldvogel.mongo.exception.FailedToParseException; import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.UnsupportedConversionError; public enum Expression implements ExpressionTraits { $abs { @Override Object apply(List<?> expressionValue, Document document) { return Utils.normalizeNumber(evaluateNumericValue(expressionValue, Math::abs)); } }, $add { @Override Object apply(List<?> expressionValue, Document document) { boolean returnDate = false; Number sum = 0; for (Object value : expressionValue) { Object number = value; if (isNullOrMissing(number)) { return null; } if (!(number instanceof Number) && !(number instanceof Instant)) { throw new MongoServerError(16554, name() + " only supports numeric or date types, not " + describeType(number)); } if (number instanceof Instant) { Instant instant = (Instant) number; number = instant.toEpochMilli(); returnDate = true; } sum = NumericUtils.addNumbers(sum, (Number) number); } if (returnDate) { return Instant.ofEpochMilli(sum.longValue()); } return sum; } }, $and { @Override Object apply(List<?> expressionValue, Document document) { for (Object value : expressionValue) { if (!Utils.isTrue(value)) { return false; } } return true; } }, $anyElementTrue { @Override Object apply(List<?> expressionValue, Document document) { Object valueInCollection = requireSingleValue(expressionValue); if (!(valueInCollection instanceof Collection)) { throw new MongoServerError(17041, name() + "'s argument must be an array, but is " + describeType(valueInCollection)); } Collection<?> collectionInCollection = (Collection<?>) valueInCollection; for (Object value : collectionInCollection) { if (Utils.isTrue(value)) { return true; } } return false; } }, $allElementsTrue { @Override Object apply(List<?> expressionValue, Document document) { Object parameter = requireSingleValue(expressionValue); if (!(parameter instanceof Collection)) { throw new MongoServerError(17040, name() + "'s argument must be an array, but is " + describeType(parameter)); } Collection<?> collectionInCollection = (Collection<?>) parameter; for (Object value : collectionInCollection) { if (!Utils.isTrue(value)) { return false; } } return true; } }, $arrayElemAt { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); if (parameters.isAnyNull()) { return null; } Object firstValue = parameters.getFirst(); Object secondValue = parameters.getSecond(); if (!(firstValue instanceof List<?>)) { throw new MongoServerError(28689, name() + "'s first argument must be an array, but is " + describeType(firstValue)); } if (!(secondValue instanceof Number)) { throw new MongoServerError(28690, name() + "'s second argument must be a numeric value, but is " + describeType(secondValue)); } List<?> collection = (List<?>) firstValue; int index = ((Number) secondValue).intValue(); if (index < 0) { index = collection.size() + index; } if (index < 0 || index >= collection.size()) { return Missing.getInstance(); } else { return collection.get(index); } } }, $arrayToObject { @Override Object apply(List<?> expressionValues, Document document) { Object values = requireSingleValue(expressionValues); if ((!(values instanceof Collection))) { throw new FailedToOptimizePipelineError(40386, name() + " requires an array input, found: " + describeType(values)); } Document result = new Document(); for (Object keyValueObject : (Collection<?>) values) { if (keyValueObject instanceof List) { List<?> keyValue = (List<?>) keyValueObject; if (keyValue.size() != 2) { throw new FailedToOptimizePipelineError(40397, name() + " requires an array of size 2 arrays,found array of size: " + keyValue.size()); } Object keyObject = keyValue.get(0); if (!(keyObject instanceof String)) { throw new FailedToOptimizePipelineError(40395, name() + " requires an array of key-value pairs, where the key must be of type string. Found key type: " + describeType(keyObject)); } String key = (String) keyObject; Object value = keyValue.get(1); result.put(key, value); } else if (keyValueObject instanceof Document) { Document keyValue = (Document) keyValueObject; if (keyValue.size() != 2) { throw new FailedToOptimizePipelineError(40392, name() + " requires an object keys of 'k' and 'v'. Found incorrect number of keys:" + keyValue.size()); } if (!(keyValue.containsKey("k") && keyValue.containsKey("v"))) { throw new FailedToOptimizePipelineError(40393, name() + " requires an object with keys 'k' and 'v'. Missing either or both keys from: " + keyValue.toString(true)); } Object keyObject = keyValue.get("k"); if (!(keyObject instanceof String)) { throw new FailedToOptimizePipelineError(40394, name() + " requires an object with keys 'k' and 'v', where the value of 'k' must be of type string. Found type: " + describeType(keyObject)); } String key = (String) keyObject; Object value = keyValue.get("v"); result.put(key, value); } else { throw new FailedToOptimizePipelineError(40398, "Unrecognised input type format for " + name() + ": " + describeType(keyValueObject)); } } return result; } }, $avg { @Override Double apply(List<?> expressionValue, Document document) { Collection<?> values = getValues(expressionValue); OptionalDouble averageValue = values.stream() .filter(Number.class::isInstance) .map(Number.class::cast) .mapToDouble(Number::doubleValue) .average(); if (averageValue.isPresent()) { return Double.valueOf(averageValue.getAsDouble()); } else { return null; } } }, $ceil { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, Math::ceil); } }, $cmp { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue); } }, $concat { @Override Object apply(List<?> expressionValue, Document document) { StringBuilder result = new StringBuilder(); for (Object value : expressionValue) { if (isNullOrMissing(value)) { return null; } if (!(value instanceof String)) { throw new MongoServerError(16702, name() + " only supports strings, not " + describeType(value)); } result.append(value); } return result.toString(); } }, $concatArrays { @Override Object apply(List<?> expressionValue, Document document) { List<Object> result = new ArrayList<>(); for (Object value : expressionValue) { if (isNullOrMissing(value)) { return null; } if (!(value instanceof Collection<?>)) { throw new MongoServerError(28664, name() + " only supports arrays, not " + describeType(value)); } result.addAll((Collection<?>) value); } return result; } }, $cond { @Override Object apply(Object expressionValue, Document document) { // document values need to be evaluated lazily List<Object> values = new ArrayList<>(); if (!(expressionValue instanceof Collection)) { values.add(expressionValue); } else { values.addAll(((Collection<?>) expressionValue)); } return apply(values, document); } @Override Object apply(List<?> expressionValue, Document document) { final Object ifExpression; final Object thenExpression; final Object elseExpression; if (expressionValue.size() == 1 && CollectionUtils.getSingleElement(expressionValue) instanceof Document) { Document condDocument = (Document) CollectionUtils.getSingleElement(expressionValue); List<String> requiredKeys = asList("if", "then", "else"); for (String requiredKey : requiredKeys) { if (!condDocument.containsKey(requiredKey)) { throw new MongoServerError(17080, "Missing '" + requiredKey + "' parameter to " + name()); } } for (String key : condDocument.keySet()) { if (!requiredKeys.contains(key)) { throw new MongoServerError(17083, "Unrecognized parameter to " + name() + ": " + key); } } ifExpression = condDocument.get("if"); thenExpression = condDocument.get("then"); elseExpression = condDocument.get("else"); } else { requireCollectionInSize(expressionValue, 3); ifExpression = expressionValue.get(0); thenExpression = expressionValue.get(1); elseExpression = expressionValue.get(2); } if (Utils.isTrue(evaluate(ifExpression, document))) { return evaluate(thenExpression, document); } else { return evaluate(elseExpression, document); } } }, $convert { @Override Object apply(List<?> expression, Document document) { Object expressionValue = CollectionUtils.getSingleElement(expression); if (!(expressionValue instanceof Document)) { throw new FailedToParseException(name() + " expects an object of named arguments but found: " + describeType(expressionValue)); } Document convertDocument = (Document) expressionValue; List<String> supportedKeys = asList("input", "to", "onError", "onNull"); for (String key : convertDocument.keySet()) { if (!supportedKeys.contains(key)) { throw new FailedToParseException(name() + " found an unknown argument: " + key); } } List<String> requiredParameters = asList("input", "to"); for (String requiredParameter : requiredParameters) { if (!convertDocument.containsKey(requiredParameter)) { throw new FailedToParseException("Missing '" + requiredParameter + "' parameter to " + name()); } } Object to = convertDocument.get("to"); if (to == null) { return null; } Object inputValue = convertDocument.get("input"); if (inputValue == null && convertDocument.containsKey("onNull")) { return convertDocument.get("onNull"); } final BsonType bsonType = getBsonType(to); return convert(inputValue, bsonType, document, convertDocument); } private BsonType getBsonType(Object to) { try { if (to instanceof String) { return BsonType.forString((String) to); } else if (to instanceof Integer) { return BsonType.forNumber((Integer) to); } else if (to instanceof Number) { throw new IllegalArgumentException("In $convert, numeric 'to' argument is not an integer"); } else { throw new IllegalArgumentException("$convert's 'to' argument must be a string or number, but is " + describeType(to)); } } catch (BadValueException e) { throw new FailedToOptimizePipelineError(ErrorCode.BadValue, "Unknown type name: " + to); } catch (IllegalArgumentException e) { throw new FailedToOptimizePipelineError(ErrorCode.FailedToParse, e.getMessage()); } } private Object convert(Object inputValue, BsonType bsonType, Document document, Document convertDocument) { try { switch (bsonType) { case DOUBLE: return $toDouble.apply(inputValue, document); case STRING: return $toString.apply(inputValue, document); case OBJECT_ID: return $toObjectId.apply(inputValue, document); case BOOL: return $toBool.apply(inputValue, document); case DATE: return $toDate.apply(inputValue, document); case INT: return $toInt.apply(inputValue, document); case LONG: return $toLong.apply(inputValue, document); case OBJECT: case ARRAY: case BIN_DATA: case NULL: case REGEX: case TIMESTAMP: case DECIMAL128: case MIN_KEY: case MAX_KEY: default: throw new UnsupportedOperationException("Unsupported conversion to type " + bsonType); } } catch (MongoServerError e) { if (e.hasCode(ErrorCode.ConversionFailure)) { if (convertDocument.containsKey("onError")) { return convertDocument.get("onError"); } } throw e; } } }, $dayOfMonth { @Override Object apply(List<?> expressionValue, Document document) { return evaluateDate(expressionValue, LocalDate::getDayOfMonth, document); } }, $dayOfWeek { @Override Object apply(List<?> expressionValue, Document document) { return evaluateDate(expressionValue, date -> date.getDayOfWeek().getValue(), document); } }, $dayOfYear { @Override Object apply(List<?> expressionValue, Document document) { return evaluateDate(expressionValue, LocalDate::getDayOfYear, document); } }, $dateToString { @Override Object apply(Object expressionValue, Document document) { Document dateToStringDocument = requireDocument(expressionValue, 18629); // validate mandatory 'date' expression parameter if (!dateToStringDocument.containsKey("date")) { throw new MongoServerError(18628, "Missing 'date' parameter to " + name()); } // validate unsupported parameters List<String> supportedKeys = asList("date", "format", "timezone", "onNull"); for (String key : dateToStringDocument.keySet()) { if (!supportedKeys.contains(key)) { throw new MongoServerError(18534, "Unrecognized parameter to " + name() + ": " + key); } } // validate optional 'format' parameter String format = "%Y-%m-%dT%H:%M:%S.%LZ"; Object formatDocument = dateToStringDocument.get("format"); if (formatDocument != null) { if (!(formatDocument instanceof String)) { throw new MongoServerError(18533, name() + " requires that 'format' be a string, found: " + describeType(formatDocument) + " with value " + formatDocument.toString()); } format = (String) formatDocument; } // validate optional 'timezone' parameter ZoneId timezone = ZoneId.of("UTC"); Object timezoneValue = Expression.evaluate(dateToStringDocument.get("timezone"), document); if (timezoneValue != null) { try { timezone = ZoneId.of(timezoneValue.toString()); } catch (DateTimeException e) { throw new MongoServerError(40485, name() + " unrecognized time zone identifier: " + timezoneValue); } } // optional parameter 'onNull' Object onNullValue = Expression.evaluate(dateToStringDocument.get("onNull"), document); // get zoned date time Object dateExpression = dateToStringDocument.get("date"); Object dateValue = Expression.evaluate(dateExpression, document); if (Missing.isNullOrMissing(dateValue)) { return onNullValue; } if (!(dateValue instanceof Instant)) { throw new MongoServerError(16006, "can't convert from " + describeType(dateValue) + " to Date"); } ZonedDateTime dateTime = ZonedDateTime.ofInstant((Instant) dateValue, timezone); // format return dateTime.format(builder(format).toFormatter()); } private DateTimeFormatterBuilder builder(String format) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); for (String part : format.split("(?=%.)")) { boolean hasFormatSpecifier = true; if (part.equals("%")) { // empty format specifier throw new MongoServerError(18535, "Unmatched '%' at end of $dateToString format string"); } else if (part.startsWith("%d")) { builder.appendValue(ChronoField.DAY_OF_MONTH, 2); } else if (part.startsWith("%G")) { builder.appendValue(ChronoField.YEAR, 4); } else if (part.startsWith("%H")) { builder.appendValue(ChronoField.HOUR_OF_DAY, 2); } else if (part.startsWith("%j")) { builder.appendValue(ChronoField.DAY_OF_YEAR, 3); } else if (part.startsWith("%L")) { builder.appendValue(ChronoField.MILLI_OF_SECOND, 3); } else if (part.startsWith("%m")) { builder.appendValue(ChronoField.MONTH_OF_YEAR, 2); } else if (part.startsWith("%M")) { builder.appendValue(ChronoField.MINUTE_OF_HOUR, 2); } else if (part.startsWith("%S")) { builder.appendValue(ChronoField.SECOND_OF_MINUTE, 2); } else if (part.startsWith("%w")) { throw new MongoServerError(18536, "Not yet supported format character '%w' in $dateToString format string"); } else if (part.startsWith("%u")) { builder.appendValue(ChronoField.DAY_OF_WEEK, 1); } else if (part.startsWith("%U")) { throw new MongoServerError(18536, "Not yet supported format character '%U' in $dateToString format string"); } else if (part.startsWith("%V")) { builder.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2); } else if (part.startsWith("%Y")) { builder.appendValue(ChronoField.YEAR, 4); } else if (part.startsWith("%z")) { builder.appendOffset("+HHMM", "+0000"); } else if (part.startsWith("%Z")) { throw new MongoServerError(18536, "Not yet supported format character '%Z' in $dateToString format string"); } else if (part.startsWith("%%")) { builder.appendLiteral("%"); } else if (part.startsWith("%")) { // invalid format specifier throw new MongoServerError(18536, "Invalid format character '" + part + "' in $dateToString format string"); } else { // literals (without format specifier) hasFormatSpecifier = false; builder.appendLiteral(part); } // append literals (after format specifier) if (hasFormatSpecifier && part.length() > 2) { builder.appendLiteral(part.substring(2)); } } return builder; } @Override Object apply(List<?> expressionValue, Document document) { throw new UnsupportedOperationException("must not be invoked"); } }, $divide { @Override Object apply(List<?> expressionValue, Document document) { TwoNumericParameters parameters = requireTwoNumericParameters(expressionValue, 16609); if (parameters == null) { return null; } double a = parameters.getFirstAsDouble(); double b = parameters.getSecondAsDouble(); if (Double.compare(b, 0.0) == 0) { throw new MongoServerError(16608, "can't " + name() + " by zero"); } return a / b; } }, $eq { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue, v -> v == 0); } }, $exp { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, Math::exp); } }, $filter { @Override Object apply(Object expressionValue, Document document) { Document filterExpression = requireDocument(expressionValue, 28646); List<String> requiredKeys = asList("input", "cond"); for (String requiredKey : requiredKeys) { if (!filterExpression.containsKey(requiredKey)) { throw new MongoServerError(28648, "Missing '" + requiredKey + "' parameter to " + name()); } } for (String key : filterExpression.keySet()) { if (!asList("input", "cond", "as").contains(key)) { throw new MongoServerError(28647, "Unrecognized parameter to " + name() + ": " + key); } } Object input = evaluate(filterExpression.get("input"), document); Object as = evaluate(filterExpression.getOrDefault("as", "this"), document); if (!(as instanceof String) || Objects.equals(as, "")) { throw new MongoServerError(16866, "empty variable names are not allowed"); } if (Missing.isNullOrMissing(input)) { return null; } if (!(input instanceof Collection)) { throw new MongoServerError(28651, "input to " + name() + " must be an array not " + describeType(input)); } Collection<?> inputCollection = (Collection<?>) input; String key = "$" + as; Document documentForCondition = document.clone(); Assert.isFalse(documentForCondition.containsKey(key), () -> "Document already contains '" + key + "'"); List<Object> result = new ArrayList<>(); for (Object inputValue : inputCollection) { Object evaluatedInputValue = evaluate(inputValue, document); documentForCondition.put(key, evaluatedInputValue); if (Utils.isTrue(evaluate(filterExpression.get("cond"), documentForCondition))) { result.add(evaluatedInputValue); } } return result; } @Override Object apply(List<?> expressionValue, Document document) { throw new UnsupportedOperationException("must not be invoked"); } }, $floor { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, a -> toIntOrLong(Math.floor(a))); } }, $gt { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue, v -> v > 0); } }, $gte { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue, v -> v >= 0); } }, $hour { @Override Object apply(List<?> expressionValue, Document document) { return evaluateTime(expressionValue, LocalTime::getHour, document); } }, $ifNull { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); Object expression = parameters.getFirst(); if (isNeitherNullNorMissing(expression)) { return expression; } else { return parameters.getSecond(); } } }, $in { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); Object needle = parameters.getFirst(); Object haystack = parameters.getSecond(); if (!(haystack instanceof Collection)) { throw new MongoServerError(40081, name() + " requires an array as a second argument, found: " + describeType(haystack)); } return ((Collection<?>) haystack).contains(needle); } }, $indexOfArray { @Override Object apply(List<?> expressionValue, Document document) { Object first = assertTwoToFourArguments(expressionValue); if (first == null) { return null; } if (!(first instanceof List<?>)) { throw new MongoServerError(40090, name() + " requires an array as a first argument, found: " + describeType(first)); } List<?> elementsToSearchIn = (List<?>) first; Range range = indexOf(expressionValue, elementsToSearchIn.size()); elementsToSearchIn = elementsToSearchIn.subList(range.getStart(), range.getEnd()); int index = elementsToSearchIn.indexOf(expressionValue.get(1)); if (index >= 0) { return index + range.getStart(); } return index; } }, $indexOfBytes { @Override Object apply(List<?> expressionValue, Document document) { return evaluateIndexOf(expressionValue, this::toList, 40091, 40092); } private List<Byte> toList(String input) { List<Byte> bytes = new ArrayList<>(); for (byte value : input.getBytes(StandardCharsets.UTF_8)) { bytes.add(value); } return bytes; } }, $indexOfCP { @Override Object apply(List<?> expressionValue, Document document) { return evaluateIndexOf(expressionValue, this::toList, 40093, 40094); } private List<Character> toList(String input) { List<Character> characters = new ArrayList<>(); for (char value : input.toCharArray()) { characters.add(value); } return characters; } }, $isArray { @Override Object apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); return (value instanceof List); } }, $literal { @Override Object apply(Object expressionValue, Document document) { return expressionValue; } @Override Object apply(List<?> expressionValue, Document document) { throw new UnsupportedOperationException("must not be invoked"); } }, $ln { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, Math::log); } }, $log { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, Math::log); } }, $log10 { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, Math::log10); } }, $lt { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue, v -> v < 0); } }, $lte { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue, v -> v <= 0); } }, $map { @Override Object apply(Object expressionValue, Document document) { Document filterExpression = requireDocument(expressionValue, 16878); List<String> requiredKeys = asList("input", "in"); for (String requiredKey : requiredKeys) { if (!filterExpression.containsKey(requiredKey)) { throw new MongoServerError(16882, "Missing '" + requiredKey + "' parameter to " + name()); } } for (String key : filterExpression.keySet()) { if (!asList("input", "in", "as").contains(key)) { throw new MongoServerError(16879, "Unrecognized parameter to " + name() + ": " + key); } } Object input = evaluate(filterExpression.get("input"), document); Object as = evaluate(filterExpression.getOrDefault("as", "this"), document); if (!(as instanceof String) || Objects.equals(as, "")) { throw new MongoServerError(16866, "empty variable names are not allowed"); } if (Missing.isNullOrMissing(input)) { return null; } if (!(input instanceof Collection)) { throw new MongoServerError(16883, "input to " + name() + " must be an array not " + describeType(input)); } Collection<?> inputCollection = (Collection<?>) input; String key = "$" + as; Document documentForCondition = document.clone(); Assert.isFalse(documentForCondition.containsKey(key), () -> "Document already contains '" + key + "'"); List<Object> result = new ArrayList<>(); for (Object inputValue : inputCollection) { Object evaluatedInputValue = evaluate(inputValue, document); documentForCondition.put(key, evaluatedInputValue); result.add(evaluate(filterExpression.get("in"), documentForCondition)); } return result; } @Override Object apply(List<?> expressionValue, Document document) { throw new UnsupportedOperationException("must not be invoked"); } }, $reduce { @Override Object apply(Object expressionValue, Document document) { Document reduceExpression = requireDocument(expressionValue, 40075); List<String> requiredKeys = asList("input", "initialValue", "in"); for (String requiredKey : requiredKeys) { if (!reduceExpression.containsKey(requiredKey)) { throw new MongoServerError(40079, "Missing '" + requiredKey + "' parameter to " + name()); } } for (String key : reduceExpression.keySet()) { if (!asList("input", "initialValue", "in").contains(key)) { throw new MongoServerError(40076, "Unrecognized parameter to " + name() + ": " + key); } } Object input = evaluate(reduceExpression.get("input"), document); Object initialValue = evaluate(reduceExpression.get("initialValue"), document); if (Missing.isNullOrMissing(input)) { return null; } if (!(input instanceof Collection)) { throw new MongoServerError(40080, "input to " + name() + " must be an array not " + describeType(input)); } Collection<?> inputCollection = (Collection<?>) input; final String thisKey = "$this"; final String valueKey = "$value"; Document documentForReduce = document.clone(); Assert.isFalse(documentForReduce.containsKey(thisKey), () -> "Document already contains '" + thisKey + "'"); Assert.isFalse(documentForReduce.containsKey(valueKey), () -> "Document already contains '" + valueKey + "'"); Object result = initialValue; for (Object inputValue : inputCollection) { Object evaluatedInputValue = evaluate(inputValue, document); documentForReduce.put(thisKey, evaluatedInputValue); documentForReduce.put(valueKey, result); result = evaluate(reduceExpression.get("in"), documentForReduce); } return result; } @Override Object apply(List<?> expressionValue, Document document) { throw new UnsupportedOperationException("must not be invoked"); } }, $max { @Override Object apply(List<?> expressionValue, Document document) { Collection<?> values = getValues(expressionValue); return values.stream() .filter(Missing::isNeitherNullNorMissing) .max(ValueComparator.asc()) .orElse(null); } }, $mergeObjects { @Override Object apply(List<?> expressionValue, Document document) { Document result = new Document(); for (Object value : expressionValue) { if (isNullOrMissing(value)) { continue; } if (!(value instanceof Document)) { throw new MongoServerError(40400, "$mergeObjects requires object inputs, but input " + toJsonValue(value) + " is of type " + describeType(value)); } result.merge((Document) value); } return result; } }, $min { @Override Object apply(List<?> expressionValue, Document document) { Collection<?> values = getValues(expressionValue); return values.stream() .filter(Missing::isNeitherNullNorMissing) .min(ValueComparator.asc()) .orElse(null); } }, $minute { @Override Object apply(List<?> expressionValue, Document document) { return evaluateTime(expressionValue, LocalTime::getMinute, document); } }, $mod { @Override Object apply(List<?> expressionValue, Document document) { TwoNumericParameters parameters = requireTwoNumericParameters(expressionValue, 16611); if (parameters == null) { return null; } double a = parameters.getFirstAsDouble(); double b = parameters.getSecondAsDouble(); return a % b; } }, $month { @Override Object apply(List<?> expressionValue, Document document) { return evaluateDate(expressionValue, date -> date.getMonth().getValue(), document); } }, $multiply { @Override Number apply(List<?> expressionValue, Document document) { TwoNumericParameters parameters = requireTwoNumericParameters(expressionValue, 16555); if (parameters == null) { return null; } Number first = parameters.getFirst(); Number second = parameters.getSecond(); return NumericUtils.multiplyNumbers(first, second); } }, $ne { @Override Object apply(List<?> expressionValue, Document document) { return evaluateComparison(expressionValue, v -> v != 0); } }, $not { @Override Object apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); return !Utils.isTrue(value); } }, $objectToArray { @Override List<Document> apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (!(value instanceof Document)) { throw new MongoServerError(ErrorCode._40390, name() + " requires a document input, found: " + describeType(value)); } List<Document> result = new ArrayList<>(); for (Entry<String, Object> entry : ((Document) value).entrySet()) { Document keyValue = new Document(); keyValue.append("k", entry.getKey()); keyValue.append("v", entry.getValue()); result.add(keyValue); } return result; } }, $or { @Override Object apply(List<?> expressionValue, Document document) { for (Object value : expressionValue) { if (Utils.isTrue(value)) { return true; } } return false; } }, $pow { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); if (parameters.isAnyNull()) { return null; } Object base = parameters.getFirst(); Object exponent = parameters.getSecond(); if (!(base instanceof Number)) { throw new MongoServerError(28762, name() + "'s base must be numeric, not " + describeType(base)); } if (!(exponent instanceof Number)) { throw new MongoServerError(28763, name() + "'s exponent must be numeric, not " + describeType(exponent)); } double a = ((Number) base).doubleValue(); double b = ((Number) exponent).doubleValue(); return Math.pow(a, b); } }, $rand { @Override Object apply(List<?> expressionValue, Document document) { if (expressionValue.size() > 1) { throw new MongoServerError(3040501, name() + " does not currently accept arguments"); } else if (expressionValue.size() == 1) { Object parameter = expressionValue.get(0); if (!(parameter instanceof Document)) { throw new MongoServerError(10065, "invalid parameter: expected an object (" + name() + ")"); } Document params = (Document) parameter; if (!params.isEmpty()) { throw new MongoServerError(3040501, name() + " does not currently accept arguments"); } } return random.nextDouble(); } }, $range { @Override Object apply(List<?> expressionValue, Document document) { if (expressionValue.size() < 2 || expressionValue.size() > 3) { throw new MongoServerError(28667, "Expression " + name() + " takes at least 2 arguments, and at most 3, but " + expressionValue.size() + " were passed in."); } Object first = expressionValue.get(0); Object second = expressionValue.get(1); int start = toInt(first, 34443, 34444, "starting value"); int end = toInt(second, 34445, 34446, "ending value"); final int step; if (expressionValue.size() > 2) { Object third = expressionValue.get(2); step = toInt(third, 34447, 34448, "step value"); if (step == 0) { throw new MongoServerError(34449, name() + " requires a non-zero step value"); } } else { step = 1; } List<Integer> values = new ArrayList<>(); if (step > 0) { for (int i = start; i < end; i += step) { values.add(i); } } else { for (int i = start; i > end; i -= Math.abs(step)) { values.add(i); } } return values; } private int toInt(Object object, int errorCodeIfNotANumber, int errorCodeIfNonInt, String errorMessage) { if (!(object instanceof Number)) { throw new MongoServerError(errorCodeIfNotANumber, name() + " requires a numeric " + errorMessage + ", found value of type: " + describeType(object)); } Number number = (Number) object; int value = number.intValue(); if (number.doubleValue() != value) { throw new MongoServerError(errorCodeIfNonInt, name() + " requires a " + errorMessage + " that can be represented as a 32-bit integer, found value: " + number); } return value; } }, $reverseArray { @Override Object apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (isNullOrMissing(value)) { return null; } if (!(value instanceof Collection<?>)) { throw new MongoServerError(34435, "The argument to " + name() + " must be an array, but was of type: " + describeType(value)); } List<?> list = new ArrayList<>((Collection<?>) value); Collections.reverse(list); return list; } }, $second { @Override Object apply(List<?> expressionValue, Document document) { return evaluateTime(expressionValue, LocalTime::getSecond, document); } }, $setDifference { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); if (parameters.isAnyNull()) { return null; } Object first = parameters.getFirst(); Object second = parameters.getSecond(); if (!(first instanceof Collection)) { throw new MongoServerError(17048, "both operands of " + name() + " must be arrays. First argument is of type: " + describeType(first)); } if (!(second instanceof Collection)) { throw new MongoServerError(17049, "both operands of " + name() + " must be arrays. First argument is of type: " + describeType(second)); } Set<Object> result = new LinkedTreeSet<>((Collection<?>) first); result.removeAll((Collection<?>) second); return result; } }, $setEquals { @Override Object apply(List<?> expressionValue, Document document) { if (expressionValue.size() < 2) { throw new MongoServerError(17045, name() + " needs at least two arguments had: " + expressionValue.size()); } Set<?> objects = null; for (Object value : expressionValue) { if (!(value instanceof Collection)) { throw new MongoServerError(17044, "All operands of " + name() + " must be arrays. One argument is of type: " + describeType(value)); } Set<?> setValue = new LinkedTreeSet<>((Collection<?>) value); if (objects == null) { objects = setValue; } else { if (!objects.containsAll(setValue) || !setValue.containsAll(objects)) { return false; } } } return true; } }, $setIntersection { @Override Object apply(List<?> expressionValue, Document document) { Set<?> result = null; for (Object value : expressionValue) { if (isNullOrMissing(value)) { return null; } if (!(value instanceof Collection)) { throw new MongoServerError(17047, "All operands of " + name() + " must be arrays. One argument is of type: " + describeType(value)); } Collection<?> values = (Collection<?>) value; if (result == null) { result = new LinkedTreeSet<>(values); } else { result.retainAll(values); } } if (result == null) { return Collections.emptySet(); } return result; } }, $setIsSubset { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); Object first = parameters.getFirst(); Object second = parameters.getSecond(); if (!(first instanceof Collection<?>)) { throw new MongoServerError(17046, "both operands of " + name() + " must be arrays. First argument is of type: " + describeType(first)); } if (!(second instanceof Collection<?>)) { throw new MongoServerError(17042, "both operands of " + name() + " must be arrays. Second argument is of type: " + describeType(second)); } Set<?> one = new LinkedTreeSet<>((Collection<?>) first); Set<?> other = new LinkedTreeSet<>((Collection<?>) second); return other.containsAll(one); } }, $setUnion { @Override Object apply(List<?> expressionValue, Document document) { Set<Object> result = new TreeSet<>(ValueComparator.asc()); for (Object value : expressionValue) { if (isNullOrMissing(value)) { return null; } if (!(value instanceof Collection<?>)) { throw new MongoServerError(17043, "All operands of " + name() + " must be arrays. One argument is of type: " + describeType(value)); } result.addAll((Collection<?>) value); } return result; } }, $size { @Override Object apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); Collection<?> collection = requireArray(17124, value); return collection.size(); } }, $slice { @Override Object apply(List<?> expressionValue, Document document) { if (expressionValue.size() < 2 || expressionValue.size() > 3) { throw new MongoServerError(28667, "Expression " + name() + " takes at least 2 arguments, and at most 3, but " + expressionValue.size() + " were passed in."); } Object first = expressionValue.get(0); if (isNullOrMissing(first)) { return null; } if (!(first instanceof List)) { throw new MongoServerError(28724, "First argument to " + name() + " must be an array, but is of type: " + describeType(first)); } List<?> list = (List<?>) first; Object second = expressionValue.get(1); if (!(second instanceof Number)) { throw new MongoServerError(28725, "Second argument to " + name() + " must be a numeric value, but is of type: " + describeType(second)); } final List<?> result; if (expressionValue.size() > 2) { Object third = expressionValue.get(2); if (!(third instanceof Number)) { throw new MongoServerError(28725, "Third argument to " + name() + " must be numeric, but is of type: " + describeType(third)); } Number number = (Number) third; if (number.intValue() < 0) { throw new MongoServerError(28729, "Third argument to " + name() + " must be positive: " + third); } int position = ((Number) second).intValue(); final int offset; if (position >= 0) { offset = Math.min(position, list.size()); } else { offset = Math.max(0, list.size() + position); } result = list.subList(offset, Math.min(offset + number.intValue(), list.size())); } else { int n = ((Number) second).intValue(); if (n >= 0) { result = list.subList(0, Math.min(n, list.size())); } else { result = list.subList(Math.max(0, list.size() + n), list.size()); } } return result; } }, $split { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); Object string = parameters.getFirst(); Object delimiter = parameters.getSecond(); if (isNullOrMissing(string)) { return null; } if (!(string instanceof String)) { throw new MongoServerError(40085, name() + " requires an expression that evaluates to a string as a first argument, found: " + describeType(string)); } if (!(delimiter instanceof String)) { throw new MongoServerError(40086, name() + " requires an expression that evaluates to a string as a second argument, found: " + describeType(delimiter)); } String[] values = ((String) string).split(Pattern.quote((String) delimiter), -1); return List.of(values); } }, $subtract { @Override Object apply(List<?> expressionValue, Document document) { TwoParameters parameters = requireTwoParameters(expressionValue); Object one = parameters.getFirst(); Object other = parameters.getSecond(); if (isNullOrMissing(one) || isNullOrMissing(other)) { return null; } if (one instanceof Number && other instanceof Number) { return NumericUtils.subtractNumbers((Number) one, (Number) other); } if (one instanceof Instant) { // subtract two instants (returns the difference in milliseconds) if (other instanceof Instant) { return ((Instant) one).toEpochMilli() - ((Instant) other).toEpochMilli(); } // subtract milliseconds from instant if (other instanceof Number) { return Instant.ofEpochMilli(((Instant) one).toEpochMilli() - ((Number) other).longValue()); } } throw new MongoServerError(16556, "cant " + name() + " a " + describeType(one) + " from a " + describeType(other)); } }, $sum { @Override Object apply(List<?> expressionValue, Document document) { if (expressionValue.size() == 1) { Object singleValue = CollectionUtils.getSingleElement(expressionValue); if (singleValue instanceof Collection<?>) { return apply(singleValue, document); } } Number sum = 0; for (Object value : expressionValue) { if (value instanceof Number) { sum = NumericUtils.addNumbers(sum, (Number) value); } } return sum; } }, $sqrt { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, Math::sqrt); } }, $strLenBytes { @Override Object apply(List<?> expressionValue, Document document) { String string = requireSingleStringValue(expressionValue); return string.getBytes(StandardCharsets.UTF_8).length; } }, $strLenCP { @Override Object apply(List<?> expressionValue, Document document) { String string = requireSingleStringValue(expressionValue); return string.length(); } }, $substr { @Override Object apply(List<?> expressionValue, Document document) { return $substrBytes.apply(expressionValue, document); } }, $substrBytes { @Override Object apply(List<?> expressionValue, Document document) { requireCollectionInSize(expressionValue, 3); String value = convertToString(expressionValue.get(0)); if (value == null || value.isEmpty()) { return ""; } byte[] bytes = value.getBytes(StandardCharsets.UTF_8); Object startValue = expressionValue.get(1); if (!(startValue instanceof Number)) { throw new FailedToOptimizePipelineError(16034, name() + ": starting index must be a numeric type (is BSON type " + describeType(startValue) + ")"); } int startIndex = Math.max(0, ((Number) startValue).intValue()); startIndex = Math.min(bytes.length, startIndex); Object lengthValue = expressionValue.get(2); if (!(lengthValue instanceof Number)) { throw new FailedToOptimizePipelineError(16035, name() + ": length must be a numeric type (is BSON type " + describeType(lengthValue) + ")"); } int length = ((Number) lengthValue).intValue(); if (length < 0) { length = bytes.length - startIndex; } length = Math.min(bytes.length, length); return new String(bytes, startIndex, length, StandardCharsets.UTF_8); } }, $substrCP { @Override Object apply(List<?> expressionValue, Document document) { requireCollectionInSize(expressionValue, 3); String value = convertToString(expressionValue.get(0)); if (value == null || value.isEmpty()) { return ""; } Object startValue = expressionValue.get(1); if (!(startValue instanceof Number)) { throw new FailedToOptimizePipelineError(34450, name() + ": starting index must be a numeric type (is BSON type " + describeType(startValue) + ")"); } int startIndex = Math.max(0, ((Number) startValue).intValue()); startIndex = Math.min(value.length(), startIndex); Object lengthValue = expressionValue.get(2); if (!(lengthValue instanceof Number)) { throw new FailedToOptimizePipelineError(34452, name() + ": length must be a numeric type (is BSON type " + describeType(lengthValue) + ")"); } int length = ((Number) lengthValue).intValue(); if (length < 0) { length = value.length() - startIndex; } int endIndex = Math.min(value.length(), startIndex + length); return value.substring(startIndex, endIndex); } }, $toBool { @Override Boolean apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (Missing.isNullOrMissing(value)) { return null; } else if (value instanceof Number) { Number number = (Number) value; return number.doubleValue() != 0.0; } else if (value instanceof Boolean) { return (Boolean) value; } else { return true; } } }, $toDate { private final DateTimeFormatter YEAR_MONTH = DateTimeFormatter.ofPattern("yyyy-MM", Locale.ROOT); private final DateTimeFormatter OFFSET_DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]XXXX", Locale.ROOT); @Override Instant apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (Missing.isNullOrMissing(value)) { return null; } else if (value instanceof Long || value instanceof Double) { Number number = (Number) value; return Instant.ofEpochMilli(number.longValue()); } else if (value instanceof Instant) { return (Instant) value; } else if (value instanceof String) { String dateString = (String) value; try { return Instant.parse(dateString); } catch (DateTimeParseException e1) { try { return LocalDate.parse(dateString).atStartOfDay(ZoneOffset.UTC).toInstant(); } catch (DateTimeParseException e2) { try { return ZonedDateTime.parse(dateString, OFFSET_DATE_TIME).toInstant(); } catch (DateTimeParseException e3) { try { TemporalAccessor temporalAccessor = YEAR_MONTH.parse(dateString); int year = temporalAccessor.get(ChronoField.YEAR); int month = temporalAccessor.get(ChronoField.MONTH_OF_YEAR); return LocalDate.of(year, month, 1).atStartOfDay(ZoneOffset.UTC).toInstant(); } catch (DateTimeParseException e) { throw new ConversionFailureException("Error parsing date string '" + dateString + "';"); } } } } } else { throw new UnsupportedConversionError(value, Instant.class); } } }, $toDouble { @Override Double apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (Missing.isNullOrMissing(value)) { return null; } else if (value instanceof Number) { Number number = (Number) value; return number.doubleValue(); } else if (value instanceof Boolean) { Boolean booleanValue = (Boolean) value; return booleanValue.booleanValue() ? 1.0 : 0.0; } else if (value instanceof Instant) { Instant instant = (Instant) value; return (double) instant.toEpochMilli(); } else if (value instanceof String) { String string = (String) value; try { return Double.valueOf(string); } catch (NumberFormatException e) { throw new ConversionFailureException("Failed to parse number '" + value + "' in $convert with no onError value: Did not consume whole number."); } } else { throw new UnsupportedConversionError(value, Double.class); } } }, $toInt { @Override Integer apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (Missing.isNullOrMissing(value)) { return null; } else if (value instanceof Number) { Number number = (Number) value; return number.intValue(); } else if (value instanceof Boolean) { Boolean booleanValue = (Boolean) value; return booleanValue.booleanValue() ? 1 : 0; } else if (value instanceof String) { String string = (String) value; try { return Integer.valueOf(string); } catch (NumberFormatException e) { throw new ConversionFailureException("Failed to parse number '" + value + "' in $convert with no onError value."); } } else { throw new UnsupportedConversionError(value, Integer.class); } } }, $toLong { @Override Long apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (Missing.isNullOrMissing(value)) { return null; } else if (value instanceof Number) { Number number = (Number) value; return number.longValue(); } else if (value instanceof Boolean) { Boolean booleanValue = (Boolean) value; return booleanValue.booleanValue() ? 1L : 0L; } else if (value instanceof Instant) { Instant instant = (Instant) value; return instant.toEpochMilli(); } else if (value instanceof String) { String string = (String) value; try { return Long.valueOf(string); } catch (NumberFormatException e) { throw new ConversionFailureException("Failed to parse number '" + value + "' in $convert with no onError value."); } } else { throw new UnsupportedConversionError(value, Long.class); } } }, $toLower { @Override Object apply(List<?> expressionValue, Document document) { return evaluateString(expressionValue, String::toLowerCase); } }, $toObjectId { @Override ObjectId apply(List<?> expressionValue, Document document) { Object value = requireSingleValue(expressionValue); if (Missing.isNullOrMissing(value)) { return null; } else if (value instanceof String) { String string = (String) value; try { return new ObjectId(string); } catch (RuntimeException e) { throw new ConversionFailureException("Failed to parse objectId '" + value + "' in $convert with no onError value."); } } else { throw new UnsupportedConversionError(value, ObjectId.class); } } }, $toUpper { @Override Object apply(List<?> expressionValue, Document document) { return evaluateString(expressionValue, String::toUpperCase); } }, $toString { @Override String apply(List<?> expressionValue, Document document) { return evaluateString(expressionValue, Function.identity()); } }, $trunc { @Override Object apply(List<?> expressionValue, Document document) { return evaluateNumericValue(expressionValue, a -> toIntOrLong(a.longValue())); } }, $year { @Override Object apply(List<?> expressionValue, Document document) { return evaluateDate(expressionValue, LocalDate::getYear, document); } }; private static final Set<String> KEYWORD_EXPRESSIONS = new HashSet<>(asList("$$PRUNE", "$$KEEP", "$$DESCEND")); private static final SecureRandom random = new SecureRandom(); private static Collection<?> getValues(List<?> expressionValue) { Collection<?> values = expressionValue; if (expressionValue.size() == 1) { if (expressionValue.get(0) instanceof Collection) { values = (Collection<?>) expressionValue.get(0); } } return values; } Object apply(Object expressionValue, Document document) { List<Object> evaluatedValues = new ArrayList<>(); if (!(expressionValue instanceof Collection)) { evaluatedValues.add(evaluate(expressionValue, document)); } else { for (Object value : ((Collection<?>) expressionValue)) { evaluatedValues.add(evaluate(value, document)); } } return apply(evaluatedValues, document); } abstract Object apply(List<?> expressionValue, Document document); public static Object evaluateDocument(Object documentWithExpression, Document document) { Object evaluatedValue = evaluate(documentWithExpression, document); if (evaluatedValue instanceof Document) { Document projectedDocument = (Document) evaluatedValue; Document result = new Document(); for (Entry<String, Object> entry : projectedDocument.entrySet()) { String field = entry.getKey(); Object expression = entry.getValue(); Object value = evaluate(expression, document); if (!(value instanceof Missing)) { result.put(field, value); } } return result; } else { return evaluatedValue; } } static Object evaluate(Object expression, Document document) { if (expression instanceof String && ((String) expression).startsWith("$")) { if (KEYWORD_EXPRESSIONS.contains(expression)) { return expression; } String value = ((String) expression).substring(1); if (value.startsWith("$")) { final String variableName; if (value.contains(".")) { variableName = value.substring(0, value.indexOf('.')); } else { variableName = value; } Object variableValue = Utils.getSubdocumentValue(document, variableName); if (variableValue instanceof Missing) { if (variableName.equals("$ROOT")) { variableValue = document; } else if (variableName.equals("$NOW")) { variableValue = Instant.now(); } else { throw new MongoServerError(17276, "Use of undefined variable: " + variableName.substring(1)); } } if (variableValue instanceof String) { String variableValueString = (String) variableValue; if (variableValueString.startsWith("$")) { variableValue = evaluate(variableValue, document); } } if (!value.equals(variableName)) { String path = value.substring(variableName.length() + 1); return Utils.getSubdocumentValue((Document) variableValue, path); } else { return variableValue; } } return Utils.getSubdocumentValueCollectionAware(document, value); } else if (expression instanceof Document) { return evaluateDocumentExpression((Document) expression, document); } else { return expression; } } private static Object evaluateDocumentExpression(Document expression, Document document) { Document result = new Document(); for (Entry<String, Object> entry : expression.entrySet()) { String expressionKey = entry.getKey(); Object expressionValue = entry.getValue(); if (expressionKey.startsWith("$")) { if (expression.keySet().size() > 1) { throw new MongoServerError(15983, "An object representing an expression must have exactly one field: " + expression); } final Expression exp; try { exp = valueOf(expressionKey); } catch (IllegalArgumentException ex) { throw new MongoServerError(168, "InvalidPipelineOperator", "Unrecognized expression '" + expressionKey + "'"); } return exp.apply(expressionValue, document); } else { result.put(expressionKey, evaluate(expressionValue, document)); } } return result; } private static Number toIntOrLong(double value) { long number = (long) value; if (number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) { return number; } else { return Math.toIntExact(number); } } } <file_sep>/examples/src/main/java/SimpleJUnit5WithLegacyClientTest.java import static org.assertj.core.api.Assertions.assertThat; import java.net.InetSocketAddress; import org.bson.Document; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.mongodb.MongoClient; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; class SimpleJUnit5WithLegacyClientTest { private MongoCollection<Document> collection; private MongoClient client; private MongoServer server; @BeforeEach void setUp() { server = new MongoServer(new MemoryBackend()); // bind on a random local port InetSocketAddress serverAddress = server.bind(); client = new MongoClient(new ServerAddress(serverAddress)); collection = client.getDatabase("testdb").getCollection("testcollection"); } @AfterEach void tearDown() { client.close(); server.shutdown(); } @Test void testSimpleInsertQuery() throws Exception { assertThat(collection.countDocuments()).isZero(); // creates the database and collection in memory and insert the object Document obj = new Document("_id", 1).append("key", "value"); collection.insertOne(obj); assertThat(collection.countDocuments()).isEqualTo(1L); assertThat(collection.find().first()).isEqualTo(obj); } } <file_sep>/build.gradle buildscript { repositories { mavenCentral() } dependencyLocking { lockAllConfigurations() } } plugins { id 'com.github.johnrengelman.shadow' version 'latest.release' id 'org.sonarqube' version 'latest.release' id 'jacoco-report-aggregation' } allprojects { apply plugin: 'java-library' apply plugin: 'jacoco' version = '1.45.0-SNAPSHOT' group = 'de.bwaldvogel' sourceCompatibility = '11' compileJava.options.encoding = 'UTF-8' repositories { mavenCentral() } dependencies { components.all { ComponentMetadataDetails details -> if (details.id.version =~ /(?i).+(-|\.)(CANDIDATE|RC|BETA|ALPHA|PR|M\d+).*/) { details.status = 'milestone' } } } dependencyLocking { lockAllConfigurations() } } subprojects { dependencies { implementation group: 'org.slf4j', name: 'slf4j-api', version: 'latest.release' testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: 'latest.release' testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: 'latest.release' testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: 'latest.release' testImplementation group: 'org.assertj', name: 'assertj-core', version: 'latest.release' testRuntimeOnly group: 'ch.qos.logback', name: 'logback-classic', version: '[1.3.0, 1.4.0)' testRuntimeOnly group: 'org.slf4j', name: 'jcl-over-slf4j', version: 'latest.release' } test { useJUnitPlatform() maxHeapSize = "256m" systemProperties['io.netty.leakDetectionLevel'] = 'advanced' } } ext { title = 'mongo-java-server' isReleaseVersion = !version.endsWith('SNAPSHOT') } jar { manifest { attributes 'Implementation-Title': title, 'Implementation-Version': archiveVersion } } allprojects { task sourceJar(type: Jar) { archiveClassifier = "sources" from sourceSets.main.allJava } task javadocJar(type: Jar, dependsOn: javadoc) { archiveClassifier = "javadoc" from javadoc.destinationDir } } configure(allprojects.findAll {it.name != 'mongo-java-server-examples'}) { apply plugin: 'maven-publish' apply plugin: 'signing' publishing { publications { mavenJava(MavenPublication) { groupId = 'de.bwaldvogel' artifactId = project.name version = project.version pom { name = title description = 'Fake implementation of MongoDB in Java that speaks the wire protocol' url = 'https://github.com/bwaldvogel/mongo-java-server' inceptionYear = '2012' licenses { license { name = 'The BSD License' url = 'http://www.opensource.org/licenses/bsd-license.php' distribution = 'repo' } } developers { developer { id = 'bwaldvogel' name = '<NAME>' email = '<EMAIL>' } } scm { url = '<EMAIL>:bwaldvogel/mongo-java-server.git' connection = 'scm:git:[email protected]:bwaldvogel/mongo-java-server.git' developerConnection = 'scm:git:[email protected]:bwaldvogel/mongo-java-server.git' } } from components.java artifact sourceJar artifact javadocJar versionMapping { usage('java-api') { fromResolutionOf('runtimeClasspath') } usage('java-runtime') { fromResolutionResult() } } } } repositories { maven { url isReleaseVersion ? 'https://oss.sonatype.org/service/local/staging/deploy/maven2' : 'https://oss.sonatype.org/content/repositories/snapshots/' credentials { username = project.hasProperty('nexusUsername') ? project.property('nexusUsername') : System.getenv('NEXUS_USERNAME') password = project.hasProperty('nexusPassword') ? project.property('nexusPassword') : System.getenv('NEXUS_PASSWORD') } } } } signing { useGpgCmd() sign publishing.publications.mavenJava } tasks.withType(Sign) { onlyIf { isReleaseVersion } } } wrapper { gradleVersion = "8.1.1" distributionType = Wrapper.DistributionType.ALL } javadoc { options.addBooleanOption('html5', true) } dependencies { api project(':mongo-java-server-core') api project(':mongo-java-server-memory-backend') jacocoAggregation subprojects } tasks.named('check') { dependsOn tasks.named('testCodeCoverageReport', JacocoReport) } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/oplog/OplogDocumentFields.java package de.bwaldvogel.mongo.oplog; import de.bwaldvogel.mongo.backend.Constants; public interface OplogDocumentFields { String ID = Constants.ID_FIELD; String TIMESTAMP = "ts"; String O = "o"; String O2 = "o2"; String ID_DATA_KEY = "_data"; String NAMESPACE = "ns"; String OPERATION_TYPE = "op"; } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/NoSuchCommandException.java package de.bwaldvogel.mongo.exception; public class NoSuchCommandException extends MongoServerError { private static final long serialVersionUID = 1L; public NoSuchCommandException(String command) { super(ErrorCode.CommandNotFound, "no such command: '" + command + "'"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoReply.java package de.bwaldvogel.mongo.wire.message; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.wire.ReplyFlag; public class MongoReply { private final MessageHeader header; private final List<? extends Document> documents; private final long cursorId; private int startingFrom; private int flags; public MongoReply(MessageHeader header, Document document, ReplyFlag... replyFlags) { this(header, List.of(document), 0, replyFlags); } public MongoReply(MessageHeader header, Iterable<? extends Document> documents, long cursorId, ReplyFlag... replyFlags) { this.cursorId = cursorId; this.header = header; this.documents = StreamSupport.stream(documents.spliterator(), false).collect(Collectors.toList()); for (ReplyFlag replyFlag : replyFlags) { flags = replyFlag.addTo(flags); } } public MessageHeader getHeader() { return header; } public List<Document> getDocuments() { return Collections.unmodifiableList(documents); } public long getCursorId() { return cursorId; } public int getStartingFrom() { return startingFrom; } public int getFlags() { return flags; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("("); sb.append("documents: ").append(getDocuments()); sb.append(")"); return sb.toString(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/MongoSilentServerException.java package de.bwaldvogel.mongo.exception; /** * similar to {@link MongoServerException} but will not be logged as error with stacktrace */ public class MongoSilentServerException extends MongoServerException { private static final long serialVersionUID = 1L; public MongoSilentServerException(String message) { super(message); setLogError(false); } } <file_sep>/h2-backend/src/test/java/de/bwaldvogel/mongo/backend/memory/H2OnDiskBackendTest.java package de.bwaldvogel.mongo.backend.memory; import static de.bwaldvogel.mongo.backend.TestUtils.json; import static de.bwaldvogel.mongo.backend.TestUtils.toArray; import java.nio.file.Path; import java.util.List; import org.bson.Document; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.client.model.IndexOptions; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.backend.AbstractBackendTest; import de.bwaldvogel.mongo.backend.h2.H2Backend; class H2OnDiskBackendTest extends AbstractBackendTest { private static final Logger log = LoggerFactory.getLogger(H2OnDiskBackendTest.class); private static H2Backend backend; @TempDir static Path tempFolder; private static Path tempFile; @Override protected void setUpBackend() throws Exception { if (tempFile == null) { tempFile = tempFolder.resolve(getClass().getSimpleName() + ".mv"); log.debug("created {} for testing", tempFile); } super.setUpBackend(); } @Override protected MongoBackend createBackend() throws Exception { backend = new H2Backend(tempFile.toString(), clock); backend.getMvStore().setAutoCommitDelay(0); return backend; } @Test void testShutdownAndRestart() throws Exception { collection.insertOne(json("_id: 1")); collection.insertOne(json("_id: 2")); long versionBeforeUpdate = backend.getMvStore().commit(); collection.findOneAndUpdate(json("_id: 2"), json("$set: {x: 10}")); long versionAfterUpdate = backend.getMvStore().commit(); assertThat(versionAfterUpdate).isEqualTo(versionBeforeUpdate + 1); restart(); assertThat(collection.find()) .containsExactly(json("_id: 1"), json("_id: 2, x: 10")); } @Test void testShutdownAndRestartOpensDatabasesAndCollections() throws Exception { List<String> dbs = List.of("local", "testdb1", "testdb2"); for (String db : dbs) { for (String coll : new String[] { "collection1", "collection2" }) { syncClient.getDatabase(db).getCollection(coll).insertOne(json("")); } } assertThat(syncClient.listDatabaseNames()) .isEqualTo(dbs); restart(); assertThat(syncClient.listDatabaseNames()) .isEqualTo(dbs); } @Test void testShutdownAndRestartOpensIndexes() throws Exception { collection.createIndex(json("a: 1")); collection.createIndex(json("b: 1")); assertThat(collection.listIndexes()).hasSize(3); collection.insertOne(json("_id: 1")); collection.insertOne(json("_id: 2")); List<String> databaseNames = toArray(syncClient.listDatabaseNames()); restart(); assertThat(syncClient.listDatabaseNames()).containsExactlyElementsOf(databaseNames); assertThat(collection.countDocuments()).isEqualTo(2); assertThat(collection.listIndexes()).containsExactlyElementsOf(toArray(collection.listIndexes())); } @Test void testShutdownAndRestartKeepsStatistics() throws Exception { collection.createIndex(json("a: 1"), new IndexOptions().unique(true)); collection.createIndex(json("b: 1"), new IndexOptions().unique(true)); collection.insertOne(json("_id: 1, a: 10, b: 100")); collection.insertOne(json("_id: 2, a: 20, b: 200")); backend.commit(); Document statsBefore = db.runCommand(json("dbStats: 1, scale: 1")); restart(); Document statsAfter = db.runCommand(json("dbStats: 1, scale: 1")); assertThat(statsAfter).isEqualTo(statsBefore); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/Json.java package de.bwaldvogel.mongo.bson; import java.nio.ByteBuffer; import java.time.Instant; import java.util.Collection; import java.util.UUID; import java.util.stream.Collectors; import de.bwaldvogel.mongo.backend.Missing; public final class Json { private Json() { } public static String toJsonValue(Object value) { return toJsonValue(value, false, "{", "}"); } public static String toCompactJsonValue(Object value) { return toJsonValue(value, true, "{ ", " }"); } public static String toJsonValue(Object value, boolean compactKey, String jsonPrefix, String jsonSuffix) { if (Missing.isNullOrMissing(value)) { return "null"; } if (value instanceof Number) { return value.toString(); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof String) { return "\"" + escapeJson((String) value) + "\""; } if (value instanceof Document) { Document document = (Document) value; return document.toString(compactKey, jsonPrefix, jsonSuffix); } if (value instanceof Instant) { Instant instant = (Instant) value; return toJsonValue(instant.toString()); } if (value instanceof Collection) { Collection<?> collection = (Collection<?>) value; if (collection.isEmpty()) { return "[]"; } return collection.stream() .map(v -> toJsonValue(v, compactKey, "{ ", " }")) .collect(Collectors.joining(", ", "[ ", " ]")); } if (value instanceof ObjectId) { ObjectId objectId = (ObjectId) value; return objectId.getHexData(); } if (value instanceof BinData) { BinData binData = (BinData) value; return "BinData(0, " + toHex(binData.getData()) + ")"; } if (value instanceof LegacyUUID) { UUID uuid = ((LegacyUUID) value).getUuid(); return "BinData(3, " + toHex(uuid) + ")"; } if (value instanceof UUID) { UUID uuid = (UUID) value; return "UUID(\"" + uuid + "\")"; } return toJsonValue(value.toString()); } static String escapeJson(String input) { String escaped = input; escaped = escaped.replace("\\", "\\\\"); escaped = escaped.replace("\"", "\\\""); escaped = escaped.replace("\b", "\\b"); escaped = escaped.replace("\f", "\\f"); escaped = escaped.replace("\n", "\\n"); escaped = escaped.replace("\r", "\\r"); escaped = escaped.replace("\t", "\\t"); return escaped; } private static StringBuilder toHex(UUID uuid) { byte[] bytes = toBytes(uuid); StringBuilder hex = new StringBuilder(); for (int i = bytes.length; i > 0; i--) { hex.append(String.format("%02X", bytes[i - 1])); } return hex; } private static StringBuilder toHex(byte[] bytes) { StringBuilder hex = new StringBuilder(); for (byte aByte : bytes) { hex.append(String.format("%02X", aByte)); } return hex; } private static byte[] toBytes(UUID uuid) { ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); byteBuffer.putLong(uuid.getLeastSignificantBits()); byteBuffer.putLong(uuid.getMostSignificantBits()); return byteBuffer.array(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/FacetStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import java.util.stream.Stream; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.DatabaseResolver; import de.bwaldvogel.mongo.backend.aggregation.Aggregation; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.oplog.Oplog; public class FacetStage implements AggregationStage { private final Map<String, Aggregation> facets = new LinkedHashMap<>(); public FacetStage(Document facetsConfiguration, DatabaseResolver databaseResolver, MongoDatabase database, MongoCollection<?> collection, Oplog oplog) { for (Entry<String, Object> entry : facetsConfiguration.entrySet()) { Aggregation aggregation = Aggregation.fromPipeline(entry.getValue(), databaseResolver, database, collection, oplog); facets.put(entry.getKey(), aggregation); } } @Override public String name() { return "$facet"; } @Override public Stream<Document> apply(Stream<Document> stream) { List<Document> allDocuments = stream.collect(Collectors.toList()); Document result = new Document(); for (Entry<String, Aggregation> entry : facets.entrySet()) { Aggregation aggregation = entry.getValue(); List<Document> documents = aggregation.runStages(allDocuments.stream()); result.put(entry.getKey(), documents); } return Stream.of(result); } @Override public boolean isModifying() { return facets.values().stream().anyMatch(Aggregation::isModifying); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/StreamUtilsTest.java package de.bwaldvogel.mongo.backend; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; import java.util.AbstractMap.SimpleEntry; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import org.junit.jupiter.api.Test; public class StreamUtilsTest { @Test void testToLinkedHashMap() throws Exception { Map<String, String> result = Stream.of("a", "b", "c") .map(value -> new SimpleEntry<>(value, value)) .collect(StreamUtils.toLinkedHashMap()); assertThat(result) .containsExactly( entry("a", "a"), entry("b", "b"), entry("c", "c") ); } @Test void testToLinkedHashMap_duplicates() throws Exception { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Stream.of("a", "b", "c", "b") .map(value -> new SimpleEntry<>(value, value)) .collect(StreamUtils.toLinkedHashMap())) .withMessage("Duplicate key 'b'"); } @Test void testToLinkedHashSet() throws Exception { Set<String> result = Stream.of("a", "b", "c", "b") .collect(StreamUtils.toLinkedHashSet()); assertThat(result).containsExactly("a", "b", "c"); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/UnwindStageTest.java package de.bwaldvogel.mongo.backend.aggregation.stage; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; public class UnwindStageTest { @Test void testUnwind() throws Exception { assertThat(unwind("$field", json("_id: 1, field: [1, 2, 3]"), json("_id: 2, field: [2, 3]"), json("_id: 3"))) .containsExactly( json("_id: 1, field: 1"), json("_id: 1, field: 2"), json("_id: 1, field: 3"), json("_id: 2, field: 2"), json("_id: 2, field: 3") ); assertThat(unwind(json("path: '$field'"), json("_id: 1, field: ['A', 'B']"))) .containsExactly( json("_id: 1, field: 'A'"), json("_id: 1, field: 'B'") ); } @Test void testUnwindWithSubdocument() throws Exception { assertThat(unwind("$field.values", json("_id: 1, field: {values: [1, 2, 3]}"), json("_id: 2, field: {values: [2, 3]}"))) .containsExactly( json("_id: 1, field: {values: 1}"), json("_id: 1, field: {values: 2}"), json("_id: 1, field: {values: 3}"), json("_id: 2, field: {values: 2}"), json("_id: 2, field: {values: 3}") ); assertThat(unwind("$field.values", json("_id: 1, field: {x: 1, values: [1, 2, 3]}"), json("_id: 2, field: {x: 2, values: [2, 3]}"))) .containsExactly( json("_id: 1, field: {x: 1, values: 1}"), json("_id: 1, field: {x: 1, values: 2}"), json("_id: 1, field: {x: 1, values: 3}"), json("_id: 2, field: {x: 2, values: 2}"), json("_id: 2, field: {x: 2, values: 3}") ); } private List<Document> unwind(Object input, Document... documents) { return new UnwindStage(input).apply(Stream.of(documents)).collect(Collectors.toList()); } @Test void testIllegalParameter() throws Exception { assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnwindStage("illegalField")) .withMessage("[Error 28818] path option to $unwind stage should be prefixed with a '$': illegalField"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnwindStage(null)) .withMessage("[Error 15981] expected either a string or an object as specification for $unwind stage, got null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnwindStage(json(""))) .withMessage("[Error 28812] no path specified to $unwind stage"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new UnwindStage(json("path: {}"))) .withMessage("[Error 28808] expected a string as the path for $unwind stage, got object"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/QueryFilter.java package de.bwaldvogel.mongo.backend; import java.util.HashMap; import java.util.Map; enum QueryFilter { AND("$and"), OR("$or"), NOR("$nor"), EXPR("$expr"), ; private final String value; QueryFilter(String value) { this.value = value; } private static final Map<String, QueryFilter> MAP = new HashMap<>(); static { for (QueryFilter filter : QueryFilter.values()) { QueryFilter old = MAP.put(filter.getValue(), filter); Assert.isNull(old, () -> "Duplicate value: " + filter.getValue()); } } public String getValue() { return value; } static boolean isQueryFilter(String value) { return MAP.containsKey(value); } static QueryFilter fromValue(String value) throws IllegalArgumentException { QueryFilter filter = MAP.get(value); Assert.notNull(filter, () -> "Illegal filter: " + value); return filter; } @Override public String toString() { return value; } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/ReplaceRootStageTest.java package de.bwaldvogel.mongo.backend.aggregation.stage; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; public class ReplaceRootStageTest { @Test void testReplaceRoot() throws Exception { assertThat(replaceRoot(json("newRoot: '$a'"), json("a: { b: { c: 1 } }"))).isEqualTo(json("b: { c: 1 }")); assertThat(replaceRoot(json("newRoot: '$a.b'"), json("a: { b: { c: 1 } }"))).isEqualTo(json("c: 1")); assertThat(replaceRoot(json("newRoot: { x: '$a.b' }"), json("a: { b: { c: 1 } }"))).isEqualTo(json("x: { c: 1 }")); } private static Document replaceRoot(Document replaceRoot, Document document) { return new ReplaceRootStage(replaceRoot).replaceRoot(document); } @Test void testIllegalReplaceRoot() throws Exception { assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json(""))) .withMessage("[Error 40231] no newRoot specified for the $replaceRoot stage"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: 1")).replaceRoot(json("a: { b: {} }"))) .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: 1. Type of resulting value: 'int'. Input document: {a: {b: {}}}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: 'x'")).replaceRoot(json("a: { b: {} }"))) .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: \"x\". Type of resulting value: 'string'. Input document: {a: {b: {}}}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: '$c'")).replaceRoot(json("a: { b: {} }"))) .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'missing'. Input document: {a: {b: {}}}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> new ReplaceRootStage(json("newRoot: '$a.c'")).replaceRoot(json("a: { b: {} }"))) .withMessage("[Error 40228] 'newRoot' expression must evaluate to an object, but resulting value was: null. Type of resulting value: 'missing'. Input document: {a: {b: {}}}"); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/accumulator/MaxAccumulatorTest.java package de.bwaldvogel.mongo.backend.aggregation.accumulator; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Test; public class MaxAccumulatorTest { private final ComparingAccumulator accumulator = new MaxAccumulator(null, null); @Test void testAccumulateNumbers() throws Exception { accumulator.aggregate(1); accumulator.aggregate(5); accumulator.aggregate(3); Object result = accumulator.getResult(); assertThat(result).isEqualTo(5); } @Test void testAccumulateArrays() throws Exception { accumulator.aggregate(List.of(10, 20, 30)); accumulator.aggregate(List.of(3, 40)); accumulator.aggregate(List.of(11, 25)); Object result = accumulator.getResult(); assertThat(result).isEqualTo(List.of(11, 25)); } @Test void testAccumulateArraysAndNonArray() throws Exception { accumulator.aggregate(List.of(3, 40)); accumulator.aggregate(List.of(10, 20, 30)); accumulator.aggregate(50); Object result = accumulator.getResult(); assertThat(result).isEqualTo(List.of(10, 20, 30)); } @Test void testAccumulateNothing() throws Exception { Object result = accumulator.getResult(); assertThat(result).isNull(); } } <file_sep>/core/build.gradle dependencies { implementation group: 'io.netty', name: 'netty-transport', version: 'latest.release' implementation group: 'io.netty', name: 'netty-codec', version: 'latest.release' implementation group: 'io.netty', name: 'netty-handler', version: 'latest.release' testImplementation group: 'org.mongodb', name: 'mongo-java-driver', version: 'latest.release' testImplementation "org.mockito:mockito-core:latest.release" testImplementation "org.mockito:mockito-junit-jupiter:latest.release" testImplementation "nl.jqno.equalsverifier:equalsverifier:latest.release" } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidNamespaceError.java package de.bwaldvogel.mongo.exception; public class InvalidNamespaceError extends MongoServerError { private static final long serialVersionUID = 1L; public InvalidNamespaceError(String namespace) { super(ErrorCode.InvalidNamespace, "Invalid system namespace: " + namespace); } } <file_sep>/README.md [![CI](https://github.com/bwaldvogel/mongo-java-server/workflows/CI/badge.svg)](https://github.com/bwaldvogel/mongo-java-server/actions) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/de.bwaldvogel/mongo-java-server/badge.svg)](http://maven-badges.herokuapp.com/maven-central/de.bwaldvogel/mongo-java-server) [![codecov](https://codecov.io/gh/bwaldvogel/mongo-java-server/branch/main/graph/badge.svg?token=jZ7zBT4niu)](https://codecov.io/gh/bwaldvogel/mongo-java-server) [![BSD 3-Clause License](https://img.shields.io/github/license/bwaldvogel/mongo-java-server.svg)](https://opensource.org/licenses/BSD-3-Clause) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/BenediktWaldvogel) # MongoDB Java Server # Fake implementation of the core [MongoDB][mongodb] server in Java that can be used for integration tests. Think of H2/HSQLDB/SQLite but for MongoDB. The [MongoDB Wire Protocol][wire-protocol] is implemented with [Netty][netty]. Different backends are possible and can be extended. ## In-Memory backend ## The in-memory backend is the default backend that is typically used to fake MongoDB for integration tests. It supports most CRUD operations, commands and the aggregation framework. Some features are not yet implemented, such as transactions, full-text search or map/reduce. Add the following Maven dependency to your project: ```xml <dependency> <groupId>de.bwaldvogel</groupId> <artifactId>mongo-java-server</artifactId> <version>1.44.0</version> </dependency> ``` ### Example ### ```java class SimpleTest { private MongoCollection<Document> collection; private MongoClient client; private MongoServer server; @BeforeEach void setUp() { server = new MongoServer(new MemoryBackend()); // optionally: // server.enableSsl(key, keyPassword, certificate); // server.enableOplog(); // bind on a random local port String connectionString = server.bindAndGetConnectionString(); client = MongoClients.create(connectionString); collection = client.getDatabase("testdb").getCollection("testcollection"); } @AfterEach void tearDown() { client.close(); server.shutdown(); } @Test void testSimpleInsertQuery() throws Exception { assertThat(collection.countDocuments()).isZero(); // creates the database and collection in memory and insert the object Document obj = new Document("_id", 1).append("key", "value"); collection.insertOne(obj); assertThat(collection.countDocuments()).isEqualTo(1L); assertThat(collection.find().first()).isEqualTo(obj); } } ``` ### Example with SpringBoot ### ```java @RunWith(SpringRunner.class) @SpringBootTest(classes={SimpleSpringBootTest.TestConfiguration.class}) public class SimpleSpringBootTest { @Autowired private MyRepository repository; @Before public void setUp() { // initialize your repository with some test data repository.deleteAll(); repository.save(...); } @Test public void testMyRepository() { // test your repository ... ... } @Configuration @EnableMongoTestServer @EnableMongoRepositories(basePackageClasses={MyRepository.class}) protected static class TestConfiguration { // test bean definitions ... ... } } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(MongoTestServerConfiguration.class) public @interface EnableMongoTestServer { } public class MongoTestServerConfiguration { @Bean public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory) { return new MongoTemplate(mongoDbFactory); } @Bean public MongoDatabaseFactory mongoDbFactory(MongoServer mongoServer) { String connectionString = mongoServer.getConnectionString(); return new SimpleMongoClientDatabaseFactory(connectionString + "/test"); } @Bean(destroyMethod = "shutdown") public MongoServer mongoServer() { MongoServer mongoServer = new MongoServer(new MemoryBackend()); mongoServer.bind(); return mongoServer; } } ``` ## H2 MVStore backend ## The [H2 MVStore][h2-mvstore] backend connects the server to a `MVStore` that can either be in-memory or on-disk. ```xml <dependency> <groupId>de.bwaldvogel</groupId> <artifactId>mongo-java-server-h2-backend</artifactId> <version>1.44.0</version> </dependency> ``` ### Example ### ```java public class Application { public static void main(String[] args) throws Exception { MongoServer server = new MongoServer(new H2Backend("database.mv")); server.bind("localhost", 27017); } } ``` ## PostgreSQL backend ## The PostgreSQL backend is a proof-of-concept implementation that connects the server to a database in a running PostgreSQL 9.5+ instance. Each MongoDB database is mapped to a schema in Postgres and each MongoDB collection is stored as a table. ```xml <dependency> <groupId>de.bwaldvogel</groupId> <artifactId>mongo-java-server-postgresql-backend</artifactId> <version>1.44.0</version> </dependency> ``` ### Example ### ```java public class Application { public static void main(String[] args) throws Exception { DataSource dataSource = new org.postgresql.jdbc3.Jdbc3PoolingDataSource(); dataSource.setDatabaseName(…); dataSource.setUser(…); dataSource.setPassword(…); MongoServer server = new MongoServer(new PostgresqlBackend(dataSource)); server.bind("localhost", 27017); } } ``` ## Building a "fat" JAR that contains all dependencies ## If you want to build a version that is not on Maven Central you can do the following: 1. Build a "fat" JAR that includes all dependencies using "`./gradlew shadowJar`" 2. Copy `build/libs/mongo-java-server-[version]-all.jar` to your project, e.g. to the `libs` directory. 3. Import that folder (e.g. via Gradle using `testCompile fileTree(dir: 'libs', include: '*.jar')`) ## Contributing ## Please read the [contributing guidelines](CONTRIBUTING.md) if you want to contribute code to the project. If you want to thank the author for this library or want to support the maintenance work, we are happy to receive a donation. [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/BenediktWaldvogel) ## Ideas for other backends ## ### Faulty backend ### A faulty backend could randomly fail queries or cause timeouts. This could be used to test the client for error resilience. ### Fuzzy backend ### Fuzzing the wire protocol could be used to check the robustness of client drivers. ## Transactions ## Please note that transactions are currently not supported. Please see [the discussion in issue #143](https://github.com/bwaldvogel/mongo-java-server/issues/143). When using `mongo-java-server` for integration tests, you can use [Testcontainers][testcontainers] or [Embedded MongoDB][embedded-mongodb] instead to spin-up a real MongoDB that will have full transaction support. ## Related Work ## * [Testcontainers][testcontainers] * Can be used to spin-up a real MongoDB instance in a Docker container * [Embedded MongoDB][embedded-mongodb] * Spins up a real MongoDB instance * [fongo][fongo] * focus on unit testing * no wire protocol implementation * intercepts the java mongo driver * currently used in [nosql-unit][nosql-unit] [mongodb]: http://www.mongodb.org/ [wire-protocol]: https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/ [netty]: http://netty.io/ [testcontainers]: https://www.testcontainers.org/ [embedded-mongodb]: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo [fongo]: https://github.com/fakemongo/fongo [nosql-unit]: https://github.com/lordofthejars/nosql-unit [h2-mvstore]: http://www.h2database.com/html/mvstore.html <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Range.java package de.bwaldvogel.mongo.backend.aggregation; public class Range { private final int start; private final int end; Range(int start, int end) { this.start = start; this.end = end; } public int getStart() { return start; } public int getEnd() { return end; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/BsonRegularExpression.java package de.bwaldvogel.mongo.bson; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.bwaldvogel.mongo.backend.Assert; public class BsonRegularExpression implements Bson { private static final long serialVersionUID = 1L; private static final String REGEX = "$regex"; private static final String OPTIONS = "$options"; private final String pattern; private final String options; private transient final AtomicReference<Pattern> compiledPattern = new AtomicReference<>(null); public BsonRegularExpression(String pattern, String options) { this.pattern = pattern; this.options = options; } public BsonRegularExpression(String pattern) { this(pattern, null); } public Document toDocument() { Document document = new Document(REGEX, pattern); if (options != null) { document.append(OPTIONS, options); } return document; } private static BsonRegularExpression fromDocument(Document queryObject) { String options = ""; if (queryObject.containsKey(OPTIONS)) { options = queryObject.get(OPTIONS).toString(); } String pattern = queryObject.get(REGEX).toString(); return new BsonRegularExpression(pattern, options); } public static boolean isRegularExpression(Object object) { if (object instanceof Document) { return ((Document) object).containsKey(REGEX); } else { return object instanceof BsonRegularExpression; } } public static BsonRegularExpression convertToRegularExpression(Object pattern) { Assert.isTrue(isRegularExpression(pattern), () -> "'" + pattern + "' is not a regular expression"); if (pattern instanceof BsonRegularExpression) { return (BsonRegularExpression) pattern; } else { return fromDocument((Document) pattern); } } public String getPattern() { return pattern; } public String getOptions() { return options; } private Pattern toPattern() { Pattern pattern = compiledPattern.get(); if (pattern == null) { pattern = createPattern(); compiledPattern.lazySet(pattern); } return pattern; } Pattern createPattern() { int flags = 0; for (char flag : options.toCharArray()) { switch (flag) { case 'i': flags |= Pattern.CASE_INSENSITIVE; break; case 'm': flags |= Pattern.MULTILINE; break; case 'x': flags |= Pattern.COMMENTS; break; case 's': flags |= Pattern.DOTALL; break; case 'u': flags |= Pattern.UNICODE_CASE; break; default: throw new IllegalArgumentException("unknown pattern flag: '" + flag + "'"); } } // always enable unicode aware case matching flags |= Pattern.UNICODE_CASE; return Pattern.compile(pattern, flags); } @Override public String toString() { Document representative = new Document("$regex", pattern); if (options != null) { representative.put("$options", options); } return Json.toJsonValue(representative); } public Matcher matcher(String string) { return toPattern().matcher(string); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoDatabase.java package de.bwaldvogel.mongo.backend; import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD; import static de.bwaldvogel.mongo.backend.Constants.PRIMARY_KEY_INDEX_NAME; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.aggregation.Aggregation; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.IndexNotFoundException; import de.bwaldvogel.mongo.exception.InvalidNamespaceError; import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.MongoServerException; import de.bwaldvogel.mongo.exception.MongoSilentServerException; import de.bwaldvogel.mongo.exception.NamespaceExistsException; import de.bwaldvogel.mongo.exception.NoSuchCommandException; import de.bwaldvogel.mongo.oplog.NoopOplog; import de.bwaldvogel.mongo.oplog.Oplog; import de.bwaldvogel.mongo.wire.message.MongoQuery; import io.netty.channel.Channel; public abstract class AbstractMongoDatabase<P> implements MongoDatabase { private static final String NAMESPACES_COLLECTION_NAME = "system.namespaces"; private static final String INDEXES_COLLECTION_NAME = "system.indexes"; private static final Logger log = LoggerFactory.getLogger(AbstractMongoDatabase.class); protected final String databaseName; private final Map<String, MongoCollection<P>> collections = new ConcurrentHashMap<>(); protected final AtomicReference<MongoCollection<P>> indexes = new AtomicReference<>(); private final Map<Channel, List<Document>> lastResults = new ConcurrentHashMap<>(); private MongoCollection<P> namespaces; protected final CursorRegistry cursorRegistry; protected AbstractMongoDatabase(String databaseName, CursorRegistry cursorRegistry) { this.databaseName = databaseName; this.cursorRegistry = cursorRegistry; } protected void initializeNamespacesAndIndexes() { this.namespaces = openOrCreateCollection(NAMESPACES_COLLECTION_NAME, CollectionOptions.withIdField("name")); this.collections.put(namespaces.getCollectionName(), namespaces); if (!namespaces.isEmpty()) { for (String name : listCollectionNamespaces()) { log.debug("opening {}", name); String collectionName = extractCollectionNameFromNamespace(name); MongoCollection<P> collection = openOrCreateCollection(collectionName, CollectionOptions.withDefaults()); collections.put(collectionName, collection); log.debug("opened collection '{}'", collectionName); } MongoCollection<P> indexCollection = openOrCreateCollection(INDEXES_COLLECTION_NAME, CollectionOptions.withoutIdField()); collections.put(indexCollection.getCollectionName(), indexCollection); this.indexes.set(indexCollection); for (Document indexDescription : indexCollection.queryAll()) { openOrCreateIndex(indexDescription); } } } @Override public final String getDatabaseName() { return databaseName; } @Override public String toString() { return getClass().getSimpleName() + "(" + getDatabaseName() + ")"; } private Document commandError(Channel channel, String command, Document query) { // getlasterror must not clear the last error if (command.equalsIgnoreCase("getlasterror")) { return commandGetLastError(channel, command, query); } else if (command.equalsIgnoreCase("reseterror")) { return commandResetError(channel); } return null; } @Override public Document handleCommand(Channel channel, String command, Document query, DatabaseResolver databaseResolver, Oplog oplog) { Document commandErrorDocument = commandError(channel, command, query); if (commandErrorDocument != null) { return commandErrorDocument; } clearLastStatus(channel); if (command.equalsIgnoreCase("find")) { return commandFind(command, query); } else if (command.equalsIgnoreCase("insert")) { return commandInsert(channel, command, query, oplog); } else if (command.equalsIgnoreCase("update")) { return commandUpdate(channel, command, query, oplog); } else if (command.equalsIgnoreCase("delete")) { return commandDelete(channel, command, query, oplog); } else if (command.equalsIgnoreCase("create")) { return commandCreate(command, query); } else if (command.equalsIgnoreCase("createIndexes")) { String collectionName = (String) query.get(command); return commandCreateIndexes(query, collectionName); } else if (command.equalsIgnoreCase("count")) { return commandCount(command, query); } else if (command.equalsIgnoreCase("aggregate")) { return commandAggregate(command, query, databaseResolver, oplog); } else if (command.equalsIgnoreCase("distinct")) { MongoCollection<P> collection = resolveCollection(command, query); if (collection == null) { Document response = new Document("values", Collections.emptyList()); Utils.markOkay(response); return response; } else { return collection.handleDistinct(query); } } else if (command.equalsIgnoreCase("drop")) { return commandDrop(query, oplog); } else if (command.equalsIgnoreCase("dropIndexes")) { return commandDropIndexes(query); } else if (command.equalsIgnoreCase("dbstats")) { return commandDatabaseStats(); } else if (command.equalsIgnoreCase("collstats")) { MongoCollection<P> collection = resolveCollection(command, query); if (collection == null) { Document emptyStats = new Document() .append("count", 0) .append("size", 0); Utils.markOkay(emptyStats); return emptyStats; } else { return collection.getStats(); } } else if (command.equalsIgnoreCase("validate")) { MongoCollection<P> collection = resolveCollection(command, query); if (collection == null) { String collectionName = query.get(command).toString(); String fullCollectionName = getDatabaseName() + "." + collectionName; throw new MongoServerError(26, "NamespaceNotFound", "Collection '" + fullCollectionName + "' does not exist to validate."); } return collection.validate(); } else if (command.equalsIgnoreCase("findAndModify")) { String collectionName = query.get(command).toString(); MongoCollection<P> collection = resolveOrCreateCollection(collectionName); return collection.findAndModify(query); } else if (command.equalsIgnoreCase("listCollections")) { return listCollections(); } else if (command.equalsIgnoreCase("listIndexes")) { String collectionName = query.get(command).toString(); return listIndexes(collectionName); } else if (command.equals("triggerInternalException")) { throw new NullPointerException("For testing purposes"); } else { log.error("unknown query: {}", query); } throw new NoSuchCommandException(command); } private Document listCollections() { List<Document> firstBatch = new ArrayList<>(); for (String namespace : listCollectionNamespaces()) { if (namespace.endsWith(INDEXES_COLLECTION_NAME)) { continue; } Document collectionDescription = new Document(); Document collectionOptions = new Document(); String collectionName = extractCollectionNameFromNamespace(namespace); collectionDescription.put("name", collectionName); collectionDescription.put("options", collectionOptions); collectionDescription.put("info", new Document("readOnly", false)); collectionDescription.put("type", "collection"); collectionDescription.put("idIndex", getPrimaryKeyIndexDescription()); firstBatch.add(collectionDescription); } return Utils.firstBatchCursorResponse(getDatabaseName() + ".$cmd.listCollections", firstBatch); } private static Document getPrimaryKeyIndexDescription() { return getPrimaryKeyIndexDescription(null); } private static Document getPrimaryKeyIndexDescription(String namespace) { Document indexDescription = new Document("key", new Document(ID_FIELD, 1)) .append("name", PRIMARY_KEY_INDEX_NAME); if (namespace != null) { indexDescription.put("ns", namespace); } return indexDescription.append("v", 2); } private Iterable<String> listCollectionNamespaces() { return namespaces.queryAllAsStream() .map(document -> document.get("name").toString()) ::iterator; } private Document listIndexes(String collectionName) { Stream<Document> indexes = Optional.ofNullable(resolveCollection(INDEXES_COLLECTION_NAME, false)) .map(collection -> collection.handleQueryAsStream(new Document("ns", getFullCollectionNamespace(collectionName)))) .orElse(Stream.empty()) .map(indexDescription -> { Document clone = indexDescription.clone(); clone.remove("ns"); return clone; }); return Utils.firstBatchCursorResponse(getDatabaseName() + ".$cmd.listIndexes", indexes); } protected MongoCollection<P> resolveOrCreateCollection(String collectionName) { final MongoCollection<P> collection = resolveCollection(collectionName, false); if (collection != null) { return collection; } else { return createCollection(collectionName, CollectionOptions.withDefaults()); } } private Document commandFind(String command, Document query) { String collectionName = (String) query.get(command); MongoCollection<P> collection = resolveCollection(collectionName, false); if (collection == null) { return Utils.firstBatchCursorResponse(getFullCollectionNamespace(collectionName), Collections.emptyList()); } QueryParameters queryParameters = toQueryParameters(query); QueryResult queryResult = collection.handleQuery(queryParameters); return toCursorResponse(collection, queryResult); } private static QueryParameters toQueryParameters(Document query) { int numberToSkip = ((Number) query.getOrDefault("skip", 0)).intValue(); int numberToReturn = ((Number) query.getOrDefault("limit", 0)).intValue(); int batchSize = ((Number) query.getOrDefault("batchSize", 0)).intValue(); Document querySelector = new Document(); querySelector.put("$query", query.getOrDefault("filter", new Document())); querySelector.put("$orderby", query.get("sort")); Document projection = (Document) query.get("projection"); return new QueryParameters(querySelector, numberToSkip, numberToReturn, batchSize, projection); } private QueryParameters toQueryParameters(MongoQuery query, int numberToSkip, int batchSize) { return new QueryParameters(query.getQuery(), numberToSkip, 0, batchSize, query.getReturnFieldSelector()); } private Document toCursorResponse(MongoCollection<P> collection, QueryResult queryResult) { List<Document> documents = new ArrayList<>(); for (Document document : queryResult) { documents.add(document); } return Utils.firstBatchCursorResponse(collection.getFullName(), documents, queryResult.getCursorId()); } private Document commandInsert(Channel channel, String command, Document query, Oplog oplog) { String collectionName = query.get(command).toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); log.trace("ordered: {}", isOrdered); @SuppressWarnings("unchecked") List<Document> documents = (List<Document>) query.get("documents"); List<Document> writeErrors = insertDocuments(channel, collectionName, documents, oplog, isOrdered); Document result = new Document(); result.put("n", Integer.valueOf(documents.size())); if (!writeErrors.isEmpty()) { result.put("writeErrors", writeErrors); } // odd by true: also mark error as okay Utils.markOkay(result); return result; } private Document commandUpdate(Channel channel, String command, Document query, Oplog oplog) { clearLastStatus(channel); String collectionName = query.get(command).toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); log.trace("ordered: {}", isOrdered); @SuppressWarnings("unchecked") List<Document> updates = (List<Document>) query.get("updates"); int nMatched = 0; int nModified = 0; Collection<Document> upserts = new ArrayList<>(); List<Document> writeErrors = new ArrayList<>(); Document response = new Document(); for (int i = 0; i < updates.size(); i++) { Document updateObj = updates.get(i); Document selector = (Document) updateObj.get("q"); Document update = (Document) updateObj.get("u"); ArrayFilters arrayFilters = ArrayFilters.parse(updateObj, update); boolean multi = Utils.isTrue(updateObj.get("multi")); boolean upsert = Utils.isTrue(updateObj.get("upsert")); final Document result; try { result = updateDocuments(collectionName, selector, update, arrayFilters, multi, upsert, oplog); } catch (MongoServerException e) { writeErrors.add(toWriteError(i, e)); continue; } if (result.containsKey("upserted")) { final Object id = result.get("upserted"); final Document upserted = new Document("index", i); upserted.put(ID_FIELD, id); upserts.add(upserted); } nMatched += ((Integer) result.get("n")).intValue(); nModified += ((Integer) result.get("nModified")).intValue(); } response.put("n", nMatched + upserts.size()); response.put("nModified", nModified); if (!upserts.isEmpty()) { response.put("upserted", upserts); } if (!writeErrors.isEmpty()) { response.put("writeErrors", writeErrors); } Utils.markOkay(response); putLastResult(channel, response); return response; } private Document commandDelete(Channel channel, String command, Document query, Oplog oplog) { String collectionName = query.get(command).toString(); boolean isOrdered = Utils.isTrue(query.get("ordered")); log.trace("ordered: {}", isOrdered); @SuppressWarnings("unchecked") List<Document> deletes = (List<Document>) query.get("deletes"); int n = 0; for (Document delete : deletes) { final Document selector = (Document) delete.get("q"); final int limit = ((Number) delete.get("limit")).intValue(); Document result = deleteDocuments(channel, collectionName, selector, limit, oplog); Integer resultNumber = (Integer) result.get("n"); n += resultNumber.intValue(); } Document response = new Document("n", Integer.valueOf(n)); Utils.markOkay(response); return response; } private Document commandCreate(String command, Document query) { String collectionName = query.get(command).toString(); CollectionOptions collectionOptions = CollectionOptions.fromQuery(query); collectionOptions.validate(); createCollectionOrThrowIfExists(collectionName, collectionOptions); Document response = new Document(); Utils.markOkay(response); return response; } @Override public MongoCollection<P> createCollectionOrThrowIfExists(String collectionName, CollectionOptions options) { MongoCollection<P> collection = resolveCollection(collectionName, false); if (collection != null) { throw new NamespaceExistsException("Collection already exists. NS: " + collection.getFullName()); } return createCollection(collectionName, options); } private Document commandCreateIndexes(Document query, String collectionName) { int indexesBefore = countIndexes(); @SuppressWarnings("unchecked") Collection<Document> indexDescriptions = (Collection<Document>) query.get("indexes"); for (Document indexDescription : indexDescriptions) { indexDescription.putIfAbsent("ns", getFullCollectionNamespace(collectionName)); addIndex(indexDescription); } int indexesAfter = countIndexes(); Document response = new Document(); response.put("numIndexesBefore", Integer.valueOf(indexesBefore)); response.put("numIndexesAfter", Integer.valueOf(indexesAfter)); Utils.markOkay(response); return response; } private Document commandDropIndexes(Document query) { String collectionName = (String) query.get("dropIndexes"); MongoCollection<P> collection = resolveCollection(collectionName, false); if (collection != null) { dropIndexes(collection, query); } Document response = new Document(); Utils.markOkay(response); return response; } private void dropIndexes(MongoCollection<P> collection, Document query) { Object index = query.get("index"); Assert.notNull(index, () -> "Index name must not be null"); MongoCollection<P> indexCollection = indexes.get(); if (Objects.equals(index, "*")) { for (Document indexDocument : indexCollection.queryAll()) { Document indexKeys = (Document) indexDocument.get("key"); if (!isPrimaryKeyIndex(indexKeys)) { dropIndex(collection, indexDocument); } } } else if (index instanceof String) { dropIndex(collection, new Document("name", index)); } else { Document indexKeys = (Document) index; Document indexQuery = new Document("key", indexKeys).append("ns", collection.getFullName()); Document indexToDrop = CollectionUtils.getSingleElement(indexCollection.handleQuery(indexQuery), () -> new IndexNotFoundException(indexKeys)); int numDeleted = dropIndex(collection, indexToDrop); Assert.equals(numDeleted, 1, () -> "Expected one deleted document"); } } private int dropIndex(MongoCollection<P> collection, Document indexDescription) { String indexName = (String) indexDescription.get("name"); dropIndex(collection, indexName); return indexes.get().deleteDocuments(indexDescription, -1); } protected void dropIndex(MongoCollection<P> collection, String indexName) { collection.dropIndex(indexName); } protected int countIndexes() { MongoCollection<P> indexesCollection = indexes.get(); if (indexesCollection == null) { return 0; } else { return indexesCollection.count(); } } private Collection<MongoCollection<P>> collections() { return collections.values().stream() .filter(collection -> !isSystemCollection(collection.getCollectionName())) .collect(Collectors.toCollection(LinkedHashSet::new)); } private Document commandDatabaseStats() { Document response = new Document("db", getDatabaseName()); response.put("collections", Integer.valueOf(collections().size())); long storageSize = getStorageSize(); long fileSize = getFileSize(); long indexSize = 0; int objects = 0; double dataSize = 0; double averageObjectSize = 0; for (MongoCollection<P> collection : collections()) { Document stats = collection.getStats(); objects += ((Number) stats.get("count")).intValue(); dataSize += ((Number) stats.get("size")).doubleValue(); Document indexSizes = (Document) stats.get("indexSize"); for (String indexName : indexSizes.keySet()) { indexSize += ((Number) indexSizes.get(indexName)).longValue(); } } if (objects > 0) { averageObjectSize = dataSize / ((double) objects); } response.put("objects", Integer.valueOf(objects)); response.put("avgObjSize", Double.valueOf(averageObjectSize)); if (dataSize == 0.0) { response.put("dataSize", Integer.valueOf(0)); } else { response.put("dataSize", Double.valueOf(dataSize)); } response.put("storageSize", Long.valueOf(storageSize)); response.put("numExtents", Integer.valueOf(0)); response.put("indexes", Integer.valueOf(countIndexes())); response.put("indexSize", Long.valueOf(indexSize)); response.put("fileSize", Long.valueOf(fileSize)); response.put("nsSizeMB", Integer.valueOf(0)); Utils.markOkay(response); return response; } protected abstract long getFileSize(); protected abstract long getStorageSize(); private Document commandDrop(Document query, Oplog oplog) { String collectionName = query.get("drop").toString(); MongoCollection<P> collection = resolveCollection(collectionName, false); if (collection == null) { throw new MongoSilentServerException("ns not found"); } int numIndexes = collection.getNumIndexes(); dropCollection(collectionName, oplog); Document response = new Document(); response.put("nIndexesWas", Integer.valueOf(numIndexes)); response.put("ns", collection.getFullName()); Utils.markOkay(response); return response; } private Document commandGetLastError(Channel channel, String command, Document query) { query.forEach((subCommand, value) -> { if (subCommand.equals(command)) { return; } switch (subCommand) { case "w": // ignore break; case "fsync": // ignore break; case "$db": Assert.equals(value, getDatabaseName()); break; default: throw new MongoServerException("unknown subcommand: " + subCommand); } }); List<Document> results = lastResults.get(channel); Document result; if (results != null && !results.isEmpty()) { result = results.get(results.size() - 1); if (result == null) { result = new Document(); } } else { result = new Document(); result.put("err", null); result.put("n", 0); } if (result.containsKey("writeErrors")) { @SuppressWarnings("unchecked") List<Document> writeErrors = (List<Document>) result.get("writeErrors"); if (writeErrors.size() == 1) { result.putAll(CollectionUtils.getSingleElement(writeErrors)); result.remove("writeErrors"); } } Utils.markOkay(result); return result; } private Document commandResetError(Channel channel) { List<Document> results = lastResults.get(channel); if (results != null) { results.clear(); } Document result = new Document(); Utils.markOkay(result); return result; } private Document commandCount(String command, Document query) { MongoCollection<P> collection = resolveCollection(command, query); Document response = new Document(); if (collection == null) { response.put("n", Integer.valueOf(0)); } else { Document queryObject = (Document) query.get("query"); int limit = getOptionalNumber(query, "limit", -1); int skip = getOptionalNumber(query, "skip", 0); response.put("n", Integer.valueOf(collection.count(queryObject, skip, limit))); } Utils.markOkay(response); return response; } private Document commandAggregate(String command, Document query, DatabaseResolver databaseResolver, Oplog oplog) { String collectionName = query.get(command).toString(); MongoCollection<P> collection = resolveCollection(collectionName, false); Object pipelineObject = Aggregation.parse(query.get("pipeline")); List<Document> pipeline = Aggregation.parse(pipelineObject); if (!pipeline.isEmpty()) { Document changeStream = (Document) pipeline.get(0).get("$changeStream"); if (changeStream != null) { Aggregation aggregation = getAggregation(pipeline.subList(1, pipeline.size()), query, databaseResolver, collection, oplog); aggregation.validate(query); return commandChangeStreamPipeline(query, oplog, collectionName, changeStream, aggregation); } } Aggregation aggregation = getAggregation(pipeline, query, databaseResolver, collection, oplog); return Utils.firstBatchCursorResponse(getFullCollectionNamespace(collectionName), aggregation.computeResult()); } private Aggregation getAggregation(List<Document> pipeline, Document query, DatabaseResolver databaseResolver, MongoCollection<?> collection, Oplog oplog) { Aggregation aggregation = Aggregation.fromPipeline(pipeline, databaseResolver, this, collection, oplog); aggregation.validate(query); return aggregation; } private Document commandChangeStreamPipeline(Document query, Oplog oplog, String collectionName, Document changeStreamDocument, Aggregation aggregation) { Document cursorDocument = (Document) query.get("cursor"); int batchSize = (int) cursorDocument.getOrDefault("batchSize", 0); String namespace = getFullCollectionNamespace(collectionName); Cursor cursor = oplog.createCursor(changeStreamDocument, namespace, aggregation); return Utils.firstBatchCursorResponse(namespace, cursor.takeDocuments(batchSize), cursor); } private int getOptionalNumber(Document query, String fieldName, int defaultValue) { Number limitNumber = (Number) query.get(fieldName); return limitNumber != null ? limitNumber.intValue() : defaultValue; } @Override public QueryResult handleQuery(MongoQuery query) { clearLastStatus(query.getChannel()); String collectionName = query.getCollectionName(); MongoCollection<P> collection = resolveCollection(collectionName, false); if (collection == null) { return new QueryResult(); } int numberToSkip = query.getNumberToSkip(); int batchSize = query.getNumberToReturn(); if (batchSize < -1) { // actually: request to close cursor automatically batchSize = -batchSize; } QueryParameters queryParameters = toQueryParameters(query, numberToSkip, batchSize); return collection.handleQuery(queryParameters); } @Override public void handleClose(Channel channel) { lastResults.remove(channel); } protected void clearLastStatus(Channel channel) { List<Document> results = lastResults.computeIfAbsent(channel, k -> new LimitedList<>(10)); results.add(null); } private MongoCollection<P> resolveCollection(String command, Document query) { String collectionName = query.get(command).toString(); return resolveCollection(collectionName, false); } @Override public MongoCollection<P> resolveCollection(String collectionName, boolean throwIfNotFound) { checkCollectionName(collectionName); MongoCollection<P> collection = collections.get(collectionName); if (collection == null && throwIfNotFound) { throw new MongoServerException("Collection [" + getFullCollectionNamespace(collectionName) + "] not found."); } return collection; } private void checkCollectionName(String collectionName) { if (collectionName.length() > Constants.MAX_NS_LENGTH) { throw new MongoServerError(10080, "ns name too long, max size is " + Constants.MAX_NS_LENGTH); } if (collectionName.isEmpty()) { throw new MongoServerError(16256, "Invalid ns [" + collectionName + "]"); } } @Override public boolean isEmpty() { return collections.isEmpty(); } private void addNamespace(MongoCollection<P> collection) { collections.put(collection.getCollectionName(), collection); if (!isSystemCollection(collection.getCollectionName())) { namespaces.addDocument(new Document("name", collection.getFullName())); } } protected void addIndex(Document indexDescription) { if (!indexDescription.containsKey("v")) { indexDescription.put("v", 2); } openOrCreateIndex(indexDescription); } protected MongoCollection<P> getOrCreateIndexesCollection() { if (indexes.get() == null) { MongoCollection<P> indexCollection = openOrCreateCollection(INDEXES_COLLECTION_NAME, CollectionOptions.withoutIdField()); addNamespace(indexCollection); indexes.set(indexCollection); } return indexes.get(); } private String extractCollectionNameFromNamespace(String namespace) { Assert.startsWith(namespace, databaseName); return namespace.substring(databaseName.length() + 1); } private void openOrCreateIndex(Document indexDescription) { String ns = indexDescription.get("ns").toString(); String collectionName = extractCollectionNameFromNamespace(ns); MongoCollection<P> collection = resolveOrCreateCollection(collectionName); Index<P> index = openOrCreateIndex(collectionName, indexDescription); MongoCollection<P> indexesCollection = getOrCreateIndexesCollection(); if (index != null) { collection.addIndex(index); indexesCollection.addDocumentIfMissing(indexDescription); } } private Index<P> openOrCreateIndex(String collectionName, Document indexDescription) { String indexName = (String) indexDescription.get("name"); Document key = (Document) indexDescription.get("key"); if (isPrimaryKeyIndex(key)) { if (!indexName.equals(PRIMARY_KEY_INDEX_NAME)) { log.warn("Ignoring primary key index with name '{}'", indexName); return null; } boolean ascending = isAscending(key.get(ID_FIELD)); Index<P> index = openOrCreateIdIndex(collectionName, indexName, ascending); log.info("adding unique _id index for collection {}", collectionName); return index; } else { List<IndexKey> keys = new ArrayList<>(); for (Entry<String, Object> entry : key.entrySet()) { String field = entry.getKey(); boolean ascending = isAscending(entry.getValue()); keys.add(new IndexKey(field, ascending)); } boolean sparse = Utils.isTrue(indexDescription.get("sparse")); if (Utils.isTrue(indexDescription.get("unique"))) { log.info("adding {} unique index {} for collection {}", sparse ? "sparse" : "non-sparse", keys, collectionName); return openOrCreateUniqueIndex(collectionName, indexName, keys, sparse); } else { return openOrCreateSecondaryIndex(collectionName, indexName, keys, sparse); } } } @VisibleForExternalBackends protected boolean isPrimaryKeyIndex(Document key) { return key.keySet().equals(Set.of(ID_FIELD)); } @VisibleForExternalBackends protected Index<P> openOrCreateSecondaryIndex(String collectionName, String indexName, List<IndexKey> keys, boolean sparse) { log.warn("adding secondary index with keys {} is not yet implemented. ignoring", keys); return new EmptyIndex<>(indexName, keys); } private static boolean isAscending(Object keyValue) { return Objects.equals(Utils.normalizeValue(keyValue), Double.valueOf(1.0)); } private Index<P> openOrCreateIdIndex(String collectionName, String indexName, boolean ascending) { return openOrCreateUniqueIndex(collectionName, indexName, List.of(new IndexKey(ID_FIELD, ascending)), false); } protected abstract Index<P> openOrCreateUniqueIndex(String collectionName, String indexName, List<IndexKey> keys, boolean sparse); private List<Document> insertDocuments(Channel channel, String collectionName, List<Document> documents, Oplog oplog, boolean isOrdered) { clearLastStatus(channel); try { if (isSystemCollection(collectionName)) { throw new MongoServerError(16459, "attempt to insert in system namespace"); } MongoCollection<P> collection = resolveOrCreateCollection(collectionName); List<Document> writeErrors = collection.insertDocuments(documents, isOrdered); oplog.handleInsert(collection.getFullName(), documents); if (!writeErrors.isEmpty()) { Document writeError = new Document(writeErrors.get(0)); writeError.put("err", writeError.remove("errmsg")); putLastResult(channel, writeError); } else { Document result = new Document("n", 0); result.put("err", null); putLastResult(channel, result); } return writeErrors; } catch (MongoServerError e) { putLastError(channel, e); return List.of(toWriteError(0, e)); } } private Document deleteDocuments(Channel channel, String collectionName, Document selector, int limit, Oplog oplog) { clearLastStatus(channel); try { if (isSystemCollection(collectionName)) { throw new InvalidNamespaceError(getFullCollectionNamespace(collectionName)); } MongoCollection<P> collection = resolveCollection(collectionName, false); final int n; if (collection == null) { n = 0; } else { n = collection.deleteDocuments(selector, limit, oplog); } Document result = new Document("n", Integer.valueOf(n)); putLastResult(channel, result); return result; } catch (MongoServerError e) { putLastError(channel, e); throw e; } } private Document updateDocuments(String collectionName, Document selector, Document update, ArrayFilters arrayFilters, boolean multi, boolean upsert, Oplog oplog) { if (isSystemCollection(collectionName)) { throw new MongoServerError(10156, "cannot update system collection"); } MongoCollection<P> collection = resolveOrCreateCollection(collectionName); return collection.updateDocuments(selector, update, arrayFilters, multi, upsert, oplog); } private void putLastError(Channel channel, MongoServerException ex) { Document error = toError(channel, ex); putLastResult(channel, error); } private Document toWriteError(int index, MongoServerException e) { Document error = new Document(); error.put("index", index); error.put("errmsg", e.getMessageWithoutErrorCode()); if (e instanceof MongoServerError) { MongoServerError err = (MongoServerError) e; error.put("code", Integer.valueOf(err.getCode())); error.putIfNotNull("codeName", err.getCodeName()); } return error; } private Document toError(Channel channel, MongoServerException ex) { Document error = new Document(); error.put("err", ex.getMessageWithoutErrorCode()); if (ex instanceof MongoServerError) { MongoServerError err = (MongoServerError) ex; error.put("code", Integer.valueOf(err.getCode())); error.putIfNotNull("codeName", err.getCodeName()); } error.put("connectionId", channel.id().asShortText()); return error; } protected void putLastResult(Channel channel, Document result) { List<Document> results = lastResults.get(channel); // list must not be empty Document last = results.get(results.size() - 1); Assert.isNull(last, () -> "last result already set: " + last); results.set(results.size() - 1, result); } private MongoCollection<P> createCollection(String collectionName, CollectionOptions options) { checkCollectionName(collectionName); if (collectionName.contains("$")) { throw new MongoServerError(10093, "cannot insert into reserved $ collection"); } MongoCollection<P> collection = openOrCreateCollection(collectionName, options); addNamespace(collection); addIndex(getPrimaryKeyIndexDescription(collection.getFullName())); log.info("created collection {}", collection.getFullName()); return collection; } protected abstract MongoCollection<P> openOrCreateCollection(String collectionName, CollectionOptions options); @Override public void drop(Oplog oplog) { log.debug("dropping {}", this); for (String collectionName : collections.keySet()) { if (!isSystemCollection(collectionName)) { dropCollection(collectionName, oplog); } } dropCollectionIfExists(INDEXES_COLLECTION_NAME, oplog); dropCollectionIfExists(NAMESPACES_COLLECTION_NAME, oplog); } private void dropCollectionIfExists(String collectionName, Oplog oplog) { if (collections.containsKey(collectionName)) { dropCollection(collectionName, oplog); } } @Override public void dropCollection(String collectionName, Oplog oplog) { MongoCollection<P> collection = resolveCollection(collectionName, true); dropAllIndexes(collection); collection.drop(); unregisterCollection(collectionName); oplog.handleDropCollection(String.format("%s.%s", databaseName, collectionName)); } private void dropAllIndexes(MongoCollection<P> collection) { MongoCollection<P> indexCollection = indexes.get(); if (indexCollection == null) { return; } List<Document> indexesToDrop = new ArrayList<>(); for (Document index : indexCollection.handleQuery(new Document("ns", collection.getFullName()))) { indexesToDrop.add(index); } for (Document indexToDrop : indexesToDrop) { dropIndex(collection, indexToDrop); } } @Override public void unregisterCollection(String collectionName) { MongoCollection<P> removedCollection = collections.remove(collectionName); namespaces.deleteDocuments(new Document("name", removedCollection.getFullName()), 1); } @Override public void moveCollection(MongoDatabase oldDatabase, MongoCollection<?> collection, String newCollectionName) { String oldFullName = collection.getFullName(); oldDatabase.unregisterCollection(collection.getCollectionName()); collection.renameTo(this, newCollectionName); // TODO resolve cast @SuppressWarnings("unchecked") MongoCollection<P> newCollection = (MongoCollection<P>) collection; MongoCollection<P> oldCollection = collections.put(newCollectionName, newCollection); Assert.isNull(oldCollection, () -> "Failed to register renamed collection. Another collection still existed: " + oldCollection); List<Document> newDocuments = new ArrayList<>(); newDocuments.add(new Document("name", collection.getFullName())); indexes.get().updateDocuments(new Document("ns", oldFullName), new Document("$set", new Document("ns", newCollection.getFullName())), ArrayFilters.empty(), true, false, NoopOplog.get()); namespaces.insertDocuments(newDocuments, true); } protected String getFullCollectionNamespace(String collectionName) { return getDatabaseName() + "." + collectionName; } static boolean isSystemCollection(String collectionName) { return collectionName.startsWith("system."); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/ErrorCode.java package de.bwaldvogel.mongo.exception; public enum ErrorCode { BadValue(2), FailedToParse(9), TypeMismatch(14), IllegalOperation(20), IndexNotFound(27), PathNotViable(28), ConflictingUpdateOperators(40), CursorNotFound(43), NamespaceExists(48), DollarPrefixedFieldName(52), InvalidIdField(53), NotSingleValueField(54), CommandNotFound(59), ImmutableField(66), InvalidOptions(72), InvalidNamespace(73), IndexKeySpecsConflict(86), CannotIndexParallelArrays(171), ConversionFailure(241), DuplicateKey(11000), MergeStageNoMatchingDocument(13113), _15998(15998) { @Override public String getName() { return "Location" + getValue(); } }, _34471(34471) { @Override public String getName() { return "Location" + getValue(); } }, _40353(40353) { @Override public String getName() { return "Location" + getValue(); } }, _40390(40390) { @Override public String getName() { return "Location" + getValue(); } }, ; private final int id; ErrorCode(int id) { this.id = id; } public int getValue() { return id; } public String getName() { return name(); } } <file_sep>/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractPerformanceTest.java package de.bwaldvogel.mongo.backend; import static de.bwaldvogel.mongo.backend.TestUtils.json; import org.bson.Document; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.client.model.UpdateOptions; public abstract class AbstractPerformanceTest extends AbstractTest { private static final Logger log = LoggerFactory.getLogger(AbstractPerformanceTest.class); // https://github.com/bwaldvogel/mongo-java-server/issues/84 @Test @EnabledIfSystemProperty(named = "run-mongo-java-server-performance-tests", matches = "true") public void testComplexUpsert() throws Exception { Document incUpdate = new Document(); Document updateQuery = new Document("$inc", incUpdate); incUpdate.put("version", 1); for (int hour = 0; hour < 24; hour++) { for (int minute = 0; minute < 60; minute++) { incUpdate.put("data." + hour + "." + minute + ".requests", 0); incUpdate.put("data." + hour + "." + minute + ".responses", 0); incUpdate.put("data." + hour + "." + minute + ".duration", 0); } } for (int i = 0; i < 10; i++) { long start = System.currentTimeMillis(); collection.updateOne(json("_id: 1"), updateQuery, new UpdateOptions().upsert(true)); long stop = System.currentTimeMillis(); log.info("Update took {} ms", stop - start); } } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/OpCode.java package de.bwaldvogel.mongo.wire; import java.util.HashMap; import java.util.Map; public enum OpCode { OP_REPLY(1), // Reply to a client request. responseTo is set @Deprecated(/* no longer supported */) OP_UPDATE(2001), // update document @Deprecated(/* no longer supported */) OP_INSERT(2002), // insert new document RESERVED(2003), // formerly used for OP_GET_BY_OID OP_QUERY(2004), // query a collection @Deprecated(/* no longer supported */) OP_GET_MORE(2005), // Get more data from a query. See Cursors @Deprecated(/* no longer supported */) OP_DELETE(2006), // Delete documents @Deprecated(/* no longer supported */) OP_KILL_CURSORS(2007), // Tell database client is done with a cursor OP_MSG(2013); // Send a message using the format introduced in MongoDB 3.6 private final int id; private static final Map<Integer, OpCode> byIdMap = new HashMap<>(); static { for (final OpCode opCode : values()) { byIdMap.put(Integer.valueOf(opCode.id), opCode); } } OpCode(final int id) { this.id = id; } public int getId() { return id; } public static OpCode getById(int id) { return byIdMap.get(Integer.valueOf(id)); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/SortStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.stream.Stream; import de.bwaldvogel.mongo.backend.DocumentComparator; import de.bwaldvogel.mongo.bson.Document; public class SortStage implements AggregationStage { private final DocumentComparator documentComparator; public SortStage(Document orderBy) { this.documentComparator = new DocumentComparator(orderBy); } @Override public String name() { return "$sort"; } @Override public Stream<Document> apply(Stream<Document> stream) { return stream.sorted(documentComparator); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/ProjectionTest.java package de.bwaldvogel.mongo.backend; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; class ProjectionTest { @Test void testProjectDocument() throws Exception { assertThat(projectDocument(null, new Document(), null)).isNull(); assertThat(projectDocument(json("_id: 100"), json("_id: 1"), "_id")) .isEqualTo(json("_id: 100")); assertThat(projectDocument(json("_id: 100, foo: 123"), json("foo: 1"), "_id")) .isEqualTo(json("_id: 100, foo: 123")); assertThat(projectDocument(json("_id: 100, foo: 123"), json("_id: 1"), "_id")) .isEqualTo(json("_id: 100")); assertThat(projectDocument(json("_id: 100, foo: 123"), json("_id: 0"), "_id")) .isEqualTo(json("foo: 123")); assertThat(projectDocument(json("_id: 100, foo: 123"), json("_id: 0, foo: 1"), "_id")) .isEqualTo(json("foo: 123")); assertThat(projectDocument(json("_id: 100, foo: 123, bar: 456"), json("_id: 0, foo: 1"), "_id")) .isEqualTo(json("foo: 123")); assertThat(projectDocument(json("_id: 100, foo: 123, bar: 456"), json("foo: 0"), "_id")) .isEqualTo(json("_id: 100, bar: 456")); assertThat(projectDocument(json("_id: 1, foo: {bar: 123, bla: 'x'}"), json("'foo.bar': 1"), "_id")) .isEqualTo(json("_id: 1, foo: {bar: 123}")); assertThat(projectDocument(json("_id: 1"), json("'foo.bar': 1"), "_id")) .isEqualTo(json("_id: 1")); assertThat(projectDocument(json("_id: 1, foo: {a: 'x', b: 'y', c: 'z'}"), json("'foo.a': 1, 'foo.c': 1"), "_id")) .isEqualTo(json("_id: 1, foo: {a: 'x', c: 'z'}")); assertThat(projectDocument(json("_id: 1, foo: {a: 'x', b: 'y', c: 'z'}"), json("'foo.b': 0"), "_id")) .isEqualTo(json("_id: 1, foo: {a: 'x', c: 'z'}")); } @Test void testInvalidMixedProjections() throws Exception { assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> projectDocument(json("{}"), json("_id: 1, foo: 0"), "_id")) .withMessage("[Error 31253] Cannot do inclusion on field _id in exclusion projection"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> projectDocument(json("{}"), json("_id: 1, foo: 1, bar: 0"), "_id")) .withMessage("[Error 31253] Cannot do inclusion on field _id in exclusion projection"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> projectDocument(json("{}"), json("_id: 1, 'foo.a': 1, 'foo.b': 0"), "_id")) .withMessage("[Error 31253] Cannot do inclusion on field _id in exclusion projection"); } @Test void testProjectIn() { Document document = json("_id: 1, students: [" + "{name: 'john', school: 'A', age: 10}, " + "{name: 'jess', school: 'B', age: 12}, " + "{name: 'jeff', school: 'A', age: 12}" + "]"); assertThat(projectDocument(document, json("_id: 1, \"students.name\": 1"))) .isEqualTo(json("_id:1, students: [{name: 'john'}, {name: 'jess'}, {name: 'jeff'}]")); Document document2 = json("_id: 1, students: {name: 'john', school: 'A', age: 10}"); assertThat(projectDocument(document2, json("_id: 1, \"students.name\": 1"))) .isEqualTo(json("_id:1, students: {name: 'john'}")); } @Test void testProjectOut() { Document document = json("_id: 1, students: [" + "{name: 'john', school: 'A', age: 10}, " + "{name: 'jess', school: 'B', age: 12}, " + "{name: 'jeff', school: 'A', age: 12}" + "]"); assertThat(projectDocument(document, json("\"students.school\": 0, \"students.age\": 0"))) .isEqualTo(json("_id:1, students: [{name: 'john'}, {name: 'jess'}, {name: 'jeff'}]")); Document document2 = json("_id: 1, students: {name: 'john', school: 'A', age: 10}"); assertThat(projectDocument(document2, json("\"students.school\": 0, \"students.age\": 0"))) .isEqualTo(json("_id:1, students: {name: 'john'}")); } @Test void testProjectMissingValue() throws Exception { assertThat(projectDocument(json("_id: 1"), json("'a.b': 1"), "_id")) .isEqualTo(json("_id: 1")); assertThat(projectDocument(json("_id: 1, a: null"), json("'a.b': 1"), "_id")) .isEqualTo(json("_id: 1")); assertThat(projectDocument(json("_id: 1, a: {b: null}"), json("'a.b': 1"), "_id")) .isEqualTo(json("_id: 1, a: {b: null}")); assertThat(projectDocument(json("_id: 1, a: {b: null}"), json("'a.c': 1"), "_id")) .isEqualTo(json("_id: 1, a: {}")); } @Test void testProjectListValues() throws Exception { assertThat(projectDocument(json("_id: 1, a: [1, 2, 3]"), json("'a.c': 1"), "_id")) .isEqualTo(json("_id: 1, a: []")); assertThat(projectDocument(json("_id: 1, a: [{x: 1}, 500, {y: 2}, {x: 3}]"), json("'a.x': 1"), "_id")) .isEqualTo(json("_id: 1, a: [{x: 1}, {}, {x: 3}]")); assertThat(projectDocument(json("_id: 1, a: [{x: 10, y: 100}, 100, {x: 20, y: 200}, {x: 3}, {z: 4}]"), json("'a.x': 1, 'a.y': 1"), "_id")) .isEqualTo(json("_id: 1, a: [{x: 10, y: 100}, {x: 20, y: 200}, {x: 3}, {}]")); assertThat(projectDocument(json("_id: 1, a: [{x: 10, y: 100}, 100, {x: 20, y: 200}, {x: 3}, {z: 4}]"), json("'a.z': 0"), "_id")) .isEqualTo(json("_id: 1, a: [{x: 10, y: 100}, 100, {x: 20, y: 200}, {x: 3}, {}]")); assertThat(projectDocument(json("_id: 1, a: [100, {z: 4}, {y: 3}, {x: 1, y: 4}]"), json("'a.x': 1, 'a.y': 1"), "_id")) .isEqualTo(json("_id: 1, a: [{}, {y: 3}, {x: 1, y: 4}]")); assertThat(projectDocument(json("_id: 1, a: [100, {z: 4}, {y: 3}, {x: 1, y: 4}]"), json("'a.z': 0"), "_id")) .isEqualTo(json("_id: 1, a: [100, {}, {y: 3}, {x: 1, y: 4}]")); assertThat(projectDocument(json("_id: 1, a: [100, {z: 4}, {y: 3}, {x: 1, y: 4}]"), json("'a.x': 0, 'a.z': 0"), "_id")) .isEqualTo(json("_id: 1, a: [100, {}, {y: 3}, {y: 4}]")); } @Test void testProjectListValuesWithPositionalOperator() throws Exception { Document document = json("_id: 1, students: [" + "{name: 'john', school: 'A', age: 10}, " + "{name: 'jess', school: 'B', age: 12}, " + "{name: 'jeff', school: 'A', age: 12}" + "]"); assertThat(projectDocument(document, json("'students.$': 1"), "_id")) .isEqualTo(json("_id: 1, students: [{name: 'john', school: 'A', age: 10}]")); assertThat(projectDocument(document, json("'unknown.$': 1"), "_id")) .isEqualTo(json("_id: 1")); } @Test void testProjectWithElemMatch() throws Exception { Document document = json("_id: 1, students: [" + "{name: 'john', school: 'A', age: 10}, " + "{name: 'jess', school: 'B', age: 12}, " + "{name: 'jeff', school: 'A', age: 12}" + "]"); assertThat(projectDocument(document, json("students: {$elemMatch: {school: 'B'}}"), "_id")) .isEqualTo(json("_id: 1, students: [{name: 'jess', school: 'B', age: 12}]")); assertThat(projectDocument(document, json("students: {$elemMatch: {school: 'A', age: {$gt: 10}}}"), "_id")) .isEqualTo(json("_id: 1, students: [{name: 'jeff', school: 'A', age: 12}]")); assertThat(projectDocument(document, json("students: {$elemMatch: {school: 'C'}}"), "_id")) .isEqualTo(json("_id: 1")); assertThat(projectDocument(json("_id: 1, students: [1, 2, 3]"), json("students: {$elemMatch: {school: 'C'}}"), "_id")) .isEqualTo(json("_id: 1")); assertThat(projectDocument(json("_id: 1, students: {school: 'C'}"), json("students: {$elemMatch: {school: 'C'}}"), "_id")) .isEqualTo(json("_id: 1")); assertThat(projectDocument(document, json("students: {$elemMatch: {school: 'A'}}"), "_id")) .isEqualTo(json("_id: 1, students: [{name: 'john', school: 'A', age: 10}]")); } @Test void testProjectWithSlice() throws Exception { Document document = json("_id: 1, values: [1, 2, 3, 4], value: 'other'"); assertThat(projectDocument(document, json("values: {$slice: 2}"), "_id")) .isEqualTo(json("_id: 1, values: [1, 2]")); assertThat(projectDocument(document, json("values: {$slice: 20}"), "_id")) .isEqualTo(json("_id: 1, values: [1, 2, 3, 4]")); assertThat(projectDocument(document, json("values: {$slice: -2}"), "_id")) .isEqualTo(json("_id: 1, values: [3, 4]")); assertThat(projectDocument(document, json("values: {$slice: -10}"), "_id")) .isEqualTo(json("_id: 1, values: [1, 2, 3, 4]")); assertThat(projectDocument(document, json("values: {$slice: [-2, 1]}"), "_id")) .isEqualTo(json("_id: 1, values: [3]")); assertThat(projectDocument(document, json("value: {$slice: 2}"), "_id")) .isEqualTo(json("_id: 1, value: 'other'")); } private Document projectDocument(Document document, Document fields) { return projectDocument(document, fields, "_id"); } private Document projectDocument(Document document, Document fields, String idField) { return new Projection(fields, idField).projectDocument(document); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/AbstractLookupStageTest.java package de.bwaldvogel.mongo.backend.aggregation.stage; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import de.bwaldvogel.mongo.MongoDatabase; @ExtendWith(MockitoExtension.class) public abstract class AbstractLookupStageTest { @Mock MongoDatabase database; } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/CannotIndexParallelArraysError.java package de.bwaldvogel.mongo.exception; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class CannotIndexParallelArraysError extends KeyConstraintError { private static final long serialVersionUID = 1L; public CannotIndexParallelArraysError(Collection<String> paths) { super(ErrorCode.CannotIndexParallelArrays, "cannot index parallel arrays " + formatPaths(paths)); } private static String formatPaths(Collection<String> paths) { List<String> firstTwoPaths = paths.stream() .map(v -> "[" + v + "]") .limit(2) .collect(Collectors.toList()); Collections.reverse(firstTwoPaths); return String.join(" ", firstTwoPaths); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/InMemoryCursorTest.java package de.bwaldvogel.mongo.backend; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; class InMemoryCursorTest { @Test void testIsEmpty() { InMemoryCursor cursor = new InMemoryCursor(1L, List.of(new Document())); assertThat(cursor.isEmpty()).isFalse(); } @Test void testGetCursorId() { Cursor cursor = new InMemoryCursor(1L, List.of(new Document())); assertThat(cursor.getId()).isEqualTo(1); } @Test void testTakeDocuments() { List<Document> documents = IntStream.range(0, 22) .mapToObj(idx -> new Document("number", idx + 1)) .collect(Collectors.toList()); InMemoryCursor cursor = new InMemoryCursor(1L, documents); assertThat(cursor.takeDocuments(1)).containsExactly(documents.get(0)); assertThat(cursor.takeDocuments(2)).containsExactly(documents.get(1), documents.get(2)); assertThat(cursor.takeDocuments(1)).containsExactly(documents.get(3)); assertThat(cursor.takeDocuments(6)).containsExactlyElementsOf(documents.subList(4, 10)); assertThat(cursor.takeDocuments(10)).containsExactlyElementsOf(documents.subList(10, 20)); assertThat(cursor.takeDocuments(10)).containsExactly(documents.get(20), documents.get(21)); assertThat(cursor.takeDocuments(10)).isEmpty(); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> cursor.takeDocuments(0)) .withMessage("Illegal number to return: 0"); } @Test void testTakeDocuments_returnsUnmodifiableList() { InMemoryCursor cursor = new InMemoryCursor(123L, List.of(new Document(), new Document())); List<Document> documents = cursor.takeDocuments(5); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> documents.remove(0)); } @Test void testToString() throws Exception { assertThat(new InMemoryCursor(123L, List.of(new Document()))) .hasToString("InMemoryCursor(id: 123)"); } } <file_sep>/test-common/src/main/java/de/bwaldvogel/mongo/repository/AccountRepository.java package de.bwaldvogel.mongo.repository; import org.bson.types.ObjectId; import org.springframework.data.repository.PagingAndSortingRepository; import de.bwaldvogel.mongo.entity.Account; public interface AccountRepository extends PagingAndSortingRepository<Account, ObjectId> { } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/AbstractLookupStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.Set; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.Json; import de.bwaldvogel.mongo.exception.FailedToParseException; abstract class AbstractLookupStage implements AggregationStage { static final String FROM = "from"; static final String AS = "as"; @Override public String name() { return "$lookup"; } String readStringConfigurationProperty(Document configuration, String name) { Object value = configuration.get(name); if (value == null) { throw new FailedToParseException("missing '" + name + "' option to " + name() + " stage specification: " + configuration); } if (value instanceof String) { return (String) value; } throw new FailedToParseException("'" + name + "' option to " + name() + " must be a string, but was type " + Utils.describeType(value)); } Document readOptionalDocumentArgument(Document configuration, String name) { Object value = configuration.get(name); if (value == null) { return new Document(); } if (value instanceof Document) { return (Document) value; } throw new FailedToParseException(name() + " argument '" + name + ": " + Json.toJsonValue(value) + "' must be an object, is type " + Utils.describeType(value)); } void ensureAllConfigurationPropertiesAreKnown(Document configuration, Set<String> configurationKeys) { for (String name : configuration.keySet()) { if (!configurationKeys.contains(name)) { String message = "unknown argument to " + name() + ": " + name; throw new FailedToParseException(message); } } } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/bson/BsonJavaScriptTest.java package de.bwaldvogel.mongo.bson; import org.junit.jupiter.api.Test; import nl.jqno.equalsverifier.EqualsVerifier; class BsonJavaScriptTest { @Test void testEqualsAndHashCode() throws Exception { EqualsVerifier.forClass(BsonJavaScript.class).verify(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/QueryFlag.java package de.bwaldvogel.mongo.wire; public enum QueryFlag { TAILABLE(1), SLAVE_OK(2), OPLOG_REPLAY(3), NO_CURSOR_TIMEOUT(4), AWAIT_DATA(5), EXHAUST(6), PARTIAL(7); private final int value; QueryFlag(int bit) { this.value = 1 << bit; } public boolean isSet(int flags) { return (flags & value) == value; } public int removeFrom(int flags) { return flags - value; } } <file_sep>/test-common/src/main/java/de/bwaldvogel/mongo/backend/TestSubscriber.java package de.bwaldvogel.mongo.backend; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class TestSubscriber<T> implements Subscriber<T> { private static final Logger log = LoggerFactory.getLogger(TestSubscriber.class); private final CountDownLatch countDownLatch = new CountDownLatch(1); private T value; private Throwable throwable; private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(T value) { log.debug("onNext: {}", value); Assert.isNull(this.value, () -> "Got a second value: " + this.value + " and " + value); this.value = value; subscription.cancel(); countDownLatch.countDown(); } @Override public void onError(Throwable throwable) { log.error("onError", throwable); this.throwable = throwable; } @Override public void onComplete() { log.info("onComplete", throwable); } T awaitSingleValue() throws Exception { boolean success = countDownLatch.await(30, TimeUnit.SECONDS); Assert.isTrue(success, () -> "Failed waiting countdown latch"); if (throwable != null) { throw new RuntimeException(throwable); } Assert.notNull(value, () -> "Got no value yet"); return value; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractMongoCollection.java package de.bwaldvogel.mongo.backend; import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.ObjectId; import de.bwaldvogel.mongo.exception.ConflictingUpdateOperatorsException; import de.bwaldvogel.mongo.exception.ErrorCode; import de.bwaldvogel.mongo.exception.FailedToParseException; import de.bwaldvogel.mongo.exception.ImmutableFieldException; import de.bwaldvogel.mongo.exception.IndexBuildFailedException; import de.bwaldvogel.mongo.exception.IndexKeySpecsConflictException; import de.bwaldvogel.mongo.exception.IndexNotFoundException; import de.bwaldvogel.mongo.exception.InvalidIdFieldError; import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.MongoServerException; import de.bwaldvogel.mongo.exception.PathNotViableException; import de.bwaldvogel.mongo.oplog.Oplog; public abstract class AbstractMongoCollection<P> implements MongoCollection<P> { private static final Logger log = LoggerFactory.getLogger(AbstractMongoCollection.class); private final UUID uuid = UUID.randomUUID(); private MongoDatabase database; private String collectionName; private final List<Index<P>> indexes = new ArrayList<>(); private final QueryMatcher matcher = new DefaultQueryMatcher(); protected final CollectionOptions options; protected final CursorRegistry cursorRegistry; protected AbstractMongoCollection(MongoDatabase database, String collectionName, CollectionOptions options, CursorRegistry cursorRegistry) { this.database = Objects.requireNonNull(database); this.collectionName = Objects.requireNonNull(collectionName); this.options = Objects.requireNonNull(options); this.cursorRegistry = cursorRegistry; } @Override public UUID getUuid() { return uuid; } protected boolean documentMatchesQuery(Document document, Document query) { return matcher.matches(document, query); } protected QueryResult queryDocuments(Document query, Document orderBy, int numberToSkip, int limit, int batchSize, Document fieldSelector) { for (Index<P> index : indexes) { if (index.canHandle(query)) { Iterable<P> positions = index.getPositions(query); return matchDocuments(query, positions, orderBy, numberToSkip, limit, batchSize, fieldSelector); } } return matchDocuments(query, orderBy, numberToSkip, limit, batchSize, fieldSelector); } protected abstract QueryResult matchDocuments(Document query, Document orderBy, int numberToSkip, int numberToReturn, int batchSize, Document fieldSelector); protected QueryResult matchDocumentsFromStream(Stream<Document> documentStream, Document query, Document orderBy, int numberToSkip, int limit, int batchSize, Document fieldSelector) { Comparator<Document> documentComparator = deriveComparator(orderBy); return matchDocumentsFromStream(query, documentStream, numberToSkip, limit, batchSize, documentComparator, fieldSelector); } protected QueryResult matchDocumentsFromStream(Document query, Stream<Document> documentStream, int numberToSkip, int limit, int batchSize, Comparator<Document> documentComparator, Document fieldSelector) { documentStream = documentStream .filter(document -> documentMatchesQuery(document, query)); if (documentComparator != null) { documentStream = documentStream.sorted(documentComparator); } if (numberToSkip > 0) { documentStream = documentStream.skip(numberToSkip); } if (limit > 0) { documentStream = documentStream.limit(limit); } if (fieldSelector != null && !fieldSelector.keySet().isEmpty()) { Projection projection = new Projection(fieldSelector, getIdField()); documentStream = documentStream.map(projection::projectDocument); } List<Document> matchedDocuments = documentStream.collect(Collectors.toList()); return createQueryResult(matchedDocuments, batchSize); } protected QueryResult matchDocuments(Document query, Iterable<P> positions, Document orderBy, int numberToSkip, int limit, int batchSize, Document fieldSelector) { Stream<Document> documentStream = StreamSupport.stream(positions.spliterator(), false) .map(this::getDocument); return matchDocumentsFromStream(documentStream, query, orderBy, numberToSkip, limit, batchSize, fieldSelector); } protected static boolean isNaturalDescending(Document orderBy) { if (orderBy != null && !orderBy.keySet().isEmpty()) { if (orderBy.keySet().iterator().next().equals("$natural")) { Number sortValue = (Number) orderBy.get("$natural"); if (sortValue.intValue() == -1) { return true; } if (sortValue.intValue() != 1) { throw new IllegalArgumentException("Illegal sort value: " + sortValue); } } } return false; } protected static DocumentComparator deriveComparator(Document orderBy) { if (orderBy != null && !orderBy.keySet().isEmpty()) { if (orderBy.keySet().iterator().next().equals("$natural")) { // already sorted } else { return new DocumentComparator(orderBy); } } return null; } protected abstract Document getDocument(P position); protected abstract void updateDataSize(int sizeDelta); protected abstract int getDataSize(); protected abstract P addDocumentInternal(Document document); @Override public void addDocument(Document document) { if (document.get(ID_FIELD) instanceof Collection) { throw new InvalidIdFieldError("The '_id' value cannot be of type array"); } if (!document.containsKey(ID_FIELD) && !isSystemCollection()) { ObjectId generatedObjectId = new ObjectId(); log.debug("Generated {} for {} in {}", generatedObjectId, document, this); document.put(ID_FIELD, generatedObjectId); } for (Index<P> index : indexes) { index.checkAdd(document, this); } P position = addDocumentInternal(document); for (Index<P> index : indexes) { index.add(document, position, this); } if (tracksDataSize()) { updateDataSize(Utils.calculateSize(document)); } } @Override public MongoDatabase getDatabase() { return database; } @Override public String getCollectionName() { return collectionName; } @Override public String toString() { return getClass().getSimpleName() + "(" + getFullName() + ")"; } @Override public void addIndex(Index<P> index) { Index<P> existingIndex = findByName(index.getName()); if (existingIndex != null) { if (!existingIndex.hasSameOptions(index)) { throw new IndexKeySpecsConflictException(index, existingIndex); } log.debug("Index with name '{}' already exists", index.getName()); return; } if (index.isEmpty()) { try { streamAllDocumentsWithPosition().forEach(documentWithPosition -> { Document document = documentWithPosition.getDocument(); index.checkAdd(document, this); }); streamAllDocumentsWithPosition().forEach(documentWithPosition -> { Document document = documentWithPosition.getDocument(); P position = documentWithPosition.getPosition(); index.add(document, position, this); }); } catch (MongoServerError e) { throw new IndexBuildFailedException(e, this); } } else { log.debug("Index is not empty"); } indexes.add(index); } private Index<P> findByName(String indexName) { return indexes.stream() .filter(index -> index.getName().equals(indexName)) .findFirst() .orElse(null); } @Override public void drop() { log.debug("Dropping collection {}", getFullName()); Assert.isEmpty(indexes); } @Override public void dropIndex(String indexName) { log.debug("Dropping index '{}'", indexName); List<Index<P>> indexesToDrop = indexes.stream() .filter(index -> index.getName().equals(indexName)) .collect(Collectors.toList()); if (indexesToDrop.isEmpty()) { throw new IndexNotFoundException("index not found with name [" + indexName + "]"); } Index<P> indexToDrop = CollectionUtils.getSingleElement(indexesToDrop); indexToDrop.drop(); indexes.remove(indexToDrop); } private void modifyField(Document document, String modifier, Document update, ArrayFilters arrayFilters, Integer matchPos, boolean isUpsert) { Document change = (Document) update.get(modifier); UpdateOperator updateOperator = getUpdateOperator(modifier, change); FieldUpdates updates = new FieldUpdates(document, updateOperator, getIdField(), isUpsert, matchPos, arrayFilters); updates.apply(change, modifier); } protected String getIdField() { return options.getIdField(); } private UpdateOperator getUpdateOperator(String modifier, Document change) { final UpdateOperator op; try { op = UpdateOperator.fromValue(modifier); } catch (IllegalArgumentException e) { throw new FailedToParseException("Unknown modifier: " + modifier + ". Expected a valid update modifier or pipeline-style update specified as an array"); } return op; } private void applyUpdate(Document oldDocument, Document newDocument) { if (newDocument.equals(oldDocument)) { return; } Object oldId = oldDocument.get(getIdField()); Object newId = newDocument.get(getIdField()); if (newId != null && oldId != null && !Utils.nullAwareEquals(oldId, newId)) { throw new ImmutableFieldException("After applying the update, the (immutable) field '_id' was found to have been altered to _id: " + newId); } if (newId == null && oldId != null) { newDocument.put(getIdField(), oldId); } newDocument.cloneInto(oldDocument); } Object deriveDocumentId(Document selector) { Object value = selector.get(getIdField()); if (value != null) { if (!Utils.containsQueryExpression(value)) { return value; } else { return deriveIdFromExpression(value); } } return new ObjectId(); } private Object deriveIdFromExpression(Object value) { Document expression = (Document) value; for (String key : expression.keySet()) { Object expressionValue = expression.get(key); if (key.equals("$in")) { Collection<?> list = (Collection<?>) expressionValue; if (!list.isEmpty()) { return list.iterator().next(); } } } // fallback to random object id return new ObjectId(); } private Document calculateUpdateDocument(Document oldDocument, Document update, ArrayFilters arrayFilters, Integer matchPos, boolean isUpsert) { int numStartsWithDollar = 0; for (String key : update.keySet()) { if (key.startsWith("$")) { numStartsWithDollar++; } } Document newDocument = new Document(); if (getIdField() != null) { newDocument.put(getIdField(), oldDocument.get(getIdField())); } if (numStartsWithDollar == update.keySet().size()) { validateUpdateQuery(update); oldDocument.cloneInto(newDocument); for (String key : update.keySet()) { modifyField(newDocument, key, update, arrayFilters, matchPos, isUpsert); } } else if (numStartsWithDollar == 0) { applyUpdate(newDocument, update); } else { throw new MongoServerException("illegal update: " + update); } Utils.validateFieldNames(newDocument); return newDocument; } static void validateUpdateQuery(Document update) { Set<String> allModifiedPaths = new LinkedHashSet<>(); for (Object value : update.values()) { Document modification = (Document) value; for (String path : modification.keySet()) { for (String otherPath : allModifiedPaths) { String commonPathPrefix = Utils.getShorterPathIfPrefix(path, otherPath); if (commonPathPrefix != null) { throw new ConflictingUpdateOperatorsException(path, commonPathPrefix); } } allModifiedPaths.add(path); } } } @Override public Document findAndModify(Document query) { boolean returnNew = Utils.isTrue(query.get("new")); if (!query.containsKey("remove") && !query.containsKey("update")) { throw new FailedToParseException("Either an update or remove=true must be specified"); } Document queryObject = new Document(); if (query.containsKey("query")) { queryObject.put("query", query.get("query")); } else { queryObject.put("query", new Document()); } if (query.containsKey("sort")) { queryObject.put("orderby", query.get("sort")); } Document lastErrorObject = null; Document returnDocument = null; boolean matchingDocument = false; for (Document document : handleQuery(queryObject, 0, 1)) { matchingDocument = true; if (Utils.isTrue(query.get("remove"))) { removeDocument(document); returnDocument = document; } else if (query.get("update") != null) { Document updateQuery = (Document) query.get("update"); Integer matchPos = matcher.matchPosition(document, (Document) queryObject.get("query")); ArrayFilters arrayFilters = ArrayFilters.parse(query, updateQuery); final Document oldDocument; try { oldDocument = updateDocument(document, updateQuery, arrayFilters, matchPos); } catch (MongoServerError e) { if (e.shouldPrefixCommandContext()) { throw new FindAndModifyPlanExecutorError(e); } else { throw e; } } if (returnNew) { returnDocument = document; } else { returnDocument = oldDocument; } lastErrorObject = new Document("updatedExisting", Boolean.TRUE); lastErrorObject.put("n", Integer.valueOf(1)); } } if (!matchingDocument && Utils.isTrue(query.get("upsert"))) { Document selector = (Document) query.get("query"); Document updateQuery = (Document) query.get("update"); ArrayFilters arrayFilters = ArrayFilters.parse(query, updateQuery); Document newDocument = handleUpsert(updateQuery, selector, arrayFilters); if (returnNew) { returnDocument = newDocument; } else { returnDocument = null; } } Document fields = (Document) query.get("fields"); if (fields != null) { returnDocument = new Projection(fields, getIdField()).projectDocument(returnDocument); } Document result = new Document(); if (lastErrorObject != null) { result.put("lastErrorObject", lastErrorObject); } result.put("value", returnDocument); Utils.markOkay(result); return result; } public static class FindAndModifyPlanExecutorError extends MongoServerError { private static final long serialVersionUID = 1L; private static final String PREFIX = "Plan executor error during findAndModify :: caused by :: "; private FindAndModifyPlanExecutorError(MongoServerError cause) { super(cause.getCode(), cause.getCodeName(), PREFIX + cause.getMessageWithoutErrorCode(), cause); } @Override public synchronized MongoServerError getCause() { return (MongoServerError) super.getCause(); } } @Override public QueryResult handleQuery(QueryParameters queryParameters) { final Document query; final Document orderBy; Document querySelector = queryParameters.getQuerySelector(); if (querySelector.containsKey("query")) { query = (Document) querySelector.get("query"); orderBy = (Document) querySelector.get("orderby"); } else if (querySelector.containsKey("$query")) { query = (Document) querySelector.get("$query"); orderBy = (Document) querySelector.get("$orderby"); } else { query = querySelector; orderBy = null; } return queryDocuments(query, orderBy, queryParameters.getNumberToSkip(), queryParameters.getLimit(), queryParameters.getBatchSize(), queryParameters.getProjection()); } @Override public List<Document> insertDocuments(List<Document> documents, boolean isOrdered) { int index = 0; List<Document> writeErrors = new ArrayList<>(); for (Document document : documents) { try { addDocument(document); } catch (MongoServerError e) { writeErrors.add(toErrorDocument(e, index)); if (isOrdered) { break; } } index++; } return writeErrors; } private static Document toErrorDocument(MongoServerError e, int index) { Document error = new Document(); error.put("index", index); error.put("errmsg", e.getMessageWithoutErrorCode()); error.put("code", Integer.valueOf(e.getCode())); error.putIfNotNull("codeName", e.getCodeName()); return error; } @Override public Document handleDistinct(Document query) { String key = (String) query.get("key"); Document filter = (Document) query.getOrDefault("query", new Document()); Set<Object> values = new TreeSet<>(ValueComparator.ascWithoutListHandling()); for (Document document : queryDocuments(filter, null, 0, 0, 0, null)) { Object value = Utils.getSubdocumentValueCollectionAware(document, key); if (!(value instanceof Missing)) { if (value instanceof Collection) { values.addAll((Collection<?>) value); } else { values.add(value); } } } Document response = new Document("values", values); Utils.markOkay(response); return response; } @Override public int deleteDocuments(Document selector, int limit, Oplog oplog) { List<Object> deletedDocumentIds = new ArrayList<>(); for (Document document : handleQuery(selector, 0, limit)) { if (limit > 0 && deletedDocumentIds.size() >= limit) { throw new MongoServerException("internal error: too many elements (" + deletedDocumentIds.size() + " >= " + limit + ")"); } deletedDocumentIds.add(document.get(getIdField())); removeDocument(document); } oplog.handleDelete(getFullName(), selector, deletedDocumentIds); return deletedDocumentIds.size(); } @Override public Document updateDocuments(Document selector, Document updateQuery, ArrayFilters arrayFilters, boolean isMulti, boolean isUpsert, Oplog oplog) { if (isMulti) { for (String key : updateQuery.keySet()) { if (!key.startsWith("$")) { throw new MongoServerError(10158, "multi update only works with $ operators"); } } } int nMatched = 0; List<Object> updatedIds = new ArrayList<>(); for (Document document : queryDocuments(selector, null, 0, 0, 0, null)) { Integer matchPos = matcher.matchPosition(document, selector); Document oldDocument = updateDocument(document, updateQuery, arrayFilters, matchPos); if (!Utils.nullAwareEquals(oldDocument, document)) { updatedIds.add(document.get(getIdField())); } nMatched++; if (!isMulti) { break; } } Document result = new Document(); // insert? if (nMatched == 0 && isUpsert) { Document newDocument = handleUpsert(updateQuery, selector, arrayFilters); result.put("upserted", newDocument.get(getIdField())); oplog.handleInsert(getFullName(), List.of(newDocument)); } else { oplog.handleUpdate(getFullName(), selector, updateQuery, updatedIds); } result.put("n", Integer.valueOf(nMatched)); result.put("nModified", Integer.valueOf(updatedIds.size())); return result; } private Document updateDocument(Document document, Document updateQuery, ArrayFilters arrayFilters, Integer matchPos) { Document oldDocument = document.cloneDeeply(); Document newDocument = calculateUpdateDocument(document, updateQuery, arrayFilters, matchPos, false); if (!newDocument.equals(oldDocument)) { for (Index<P> index : indexes) { index.checkUpdate(oldDocument, newDocument, this); } P position = getSinglePosition(oldDocument); for (Index<P> index : indexes) { index.updateInPlace(oldDocument, newDocument, position, this); } if (tracksDataSize()) { int oldSize = Utils.calculateSize(oldDocument); int newSize = Utils.calculateSize(newDocument); updateDataSize(newSize - oldSize); } // only keep fields that are also in the updated document Set<String> fields = new LinkedHashSet<>(document.keySet()); fields.removeAll(newDocument.keySet()); for (String key : fields) { document.remove(key); } // update the fields for (String key : newDocument.keySet()) { if (key.contains(".")) { throw new MongoServerException( "illegal field name. must not happen as it must be caught by the driver"); } document.put(key, newDocument.get(key)); } handleUpdate(position, oldDocument, document); } return oldDocument; } private P getSinglePosition(Document document) { if (indexes.isEmpty()) { return findDocumentPosition(document); } Set<P> positions = indexes.stream() .map(index -> index.getPosition(document)) .filter(Objects::nonNull) .collect(Collectors.toSet()); return CollectionUtils.getSingleElement(positions); } protected abstract void handleUpdate(P position, Document oldDocument, Document newDocument); private Document handleUpsert(Document updateQuery, Document selector, ArrayFilters arrayFilters) { Document document = convertSelectorToDocument(selector); Document newDocument = calculateUpdateDocument(document, updateQuery, arrayFilters, null, true); newDocument.computeIfAbsent(getIdField(), k -> deriveDocumentId(selector)); addDocument(newDocument); return newDocument; } /** * convert selector used in an upsert statement into a document */ Document convertSelectorToDocument(Document selector) { Document document = new Document(); convertSelectorToDocument(selector, document); return document; } private void convertSelectorToDocument(Document selector, Document document) { for (Map.Entry<String, Object> entry : selector.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.equals("$and")) { List<Document> andValues = (List<Document>) value; for (Document andValue : andValues) { convertSelectorToDocument(andValue, document); } continue; } else if (key.equals("$or")) { List<Document> orValues = (List<Document>) value; if (orValues.size() == 1) { convertSelectorToDocument(orValues.get(0), document); } continue; } else if (key.startsWith("$")) { continue; } else if (value instanceof Document) { Document documentValue = (Document) value; if (documentValue.keySet().equals(Set.of("$eq"))) { changeSubdocumentValueOrThrow(document, key, documentValue.get("$eq")); } } if (!Utils.containsQueryExpression(value)) { changeSubdocumentValueOrThrow(document, key, value); } } } private static void changeSubdocumentValueOrThrow(Document document, String key, Object value) { try { Object previousValue = Utils.changeSubdocumentValue(document, key, value, (AtomicReference<Integer>) null); if (previousValue != null) { throw new MongoServerError(ErrorCode.NotSingleValueField, "cannot infer query fields to set, path '" + key + "' is matched twice"); } } catch (PathNotViableException e) { String violatingKey = e.getField(); List<String> keyPathFragments = Utils.splitPath(key); int indexOfViolatingKey = keyPathFragments.indexOf(violatingKey); List<String> violatingKeyPathFragments = keyPathFragments.subList(0, indexOfViolatingKey); String violatingKeyPath = Utils.joinPath(violatingKeyPathFragments); throw new MongoServerError(ErrorCode.NotSingleValueField, "cannot infer query fields to set, both paths '" + key + "' and '" + violatingKeyPath + "' are matched"); } } @Override public List<Index<P>> getIndexes() { return indexes; } @Override public int count(Document query, int skip, int limit) { if (query == null || query.keySet().isEmpty()) { int count = count(); if (skip > 0) { count = Math.max(0, count - skip); } if (limit > 0) { return Math.min(limit, count); } return count; } int numberToReturn = Math.max(limit, 0); int count = 0; Iterator<?> it = queryDocuments(query, null, skip, numberToReturn, 0, new Document(getIdField(), 1)).iterator(); while (it.hasNext()) { it.next(); count++; } return count; } @Override public Document getStats() { int dataSize = getDataSize(); int count = count(); Document response = new Document("ns", getFullName()); response.put("count", Integer.valueOf(count)); response.put("size", Integer.valueOf(dataSize)); int averageSize = 0; if (count > 0) { averageSize = dataSize / count; } response.put("avgObjSize", Integer.valueOf(averageSize)); response.put("storageSize", Integer.valueOf(0)); response.put("numExtents", Integer.valueOf(0)); response.put("nindexes", Integer.valueOf(indexes.size())); Document indexSizes = new Document(); for (Index<P> index : indexes) { indexSizes.put(index.getName(), Long.valueOf(index.getDataSize())); } response.put("indexSize", indexSizes); Utils.markOkay(response); return response; } @Override public void removeDocument(Document document) { P position = null; if (!indexes.isEmpty()) { for (Index<P> index : indexes) { P indexPosition = index.remove(document); if (indexPosition == null) { if (index.isSparse()) { continue; } else { throw new IllegalStateException("Found no position for " + document + " in " + index); } } if (position != null) { Assert.equals(position, indexPosition, () -> "Got different positions for " + document); } position = indexPosition; } } else { position = findDocumentPosition(document); } if (position == null) { // not found return; } if (tracksDataSize()) { updateDataSize(-Utils.calculateSize(document)); } removeDocument(position); } @VisibleForExternalBackends protected boolean tracksDataSize() { return true; } @Override public Document validate() { Document response = new Document("ns", getFullName()); response.put("extentCount", Integer.valueOf(0)); response.put("datasize", Long.valueOf(getDataSize())); response.put("nrecords", Integer.valueOf(count())); response.put("nIndexes", Integer.valueOf(indexes.size())); Document keysPerIndex = new Document(); for (Index<P> index : indexes) { keysPerIndex.put(index.getName(), Long.valueOf(index.getCount())); } response.put("keysPerIndex", keysPerIndex); response.put("valid", Boolean.TRUE); response.put("errors", Collections.emptyList()); Utils.markOkay(response); return response; } @Override public void renameTo(MongoDatabase newDatabase, String newCollectionName) { this.database = newDatabase; this.collectionName = newCollectionName; } protected abstract void removeDocument(P position); protected P findDocumentPosition(Document document) { return streamAllDocumentsWithPosition() .filter(match -> documentMatchesQuery(match.getDocument(), document)) .map(DocumentWithPosition::getPosition) .findFirst() .orElse(null); } protected abstract Stream<DocumentWithPosition<P>> streamAllDocumentsWithPosition(); private boolean isSystemCollection() { return AbstractMongoDatabase.isSystemCollection(getCollectionName()); } protected QueryResult createQueryResult(List<Document> matchedDocuments, int batchSize) { final Collection<Document> firstBatch; if (batchSize > 0) { firstBatch = matchedDocuments.stream() .limit(batchSize) .collect(Collectors.toList()); } else { firstBatch = matchedDocuments; } List<Document> remainingDocuments = matchedDocuments.subList(firstBatch.size(), matchedDocuments.size()); if (remainingDocuments.isEmpty()) { return new QueryResult(firstBatch); } else { Cursor cursor = createCursor(remainingDocuments); return new QueryResult(firstBatch, cursor); } } protected Cursor createCursor(List<Document> remainingDocuments) { InMemoryCursor cursor = new InMemoryCursor(cursorRegistry.generateCursorId(), remainingDocuments); cursorRegistry.add(cursor); return cursor; } } <file_sep>/updateDependencies.sh #!/bin/bash ./gradlew --refresh-dependencies dependencies mongo-java-server-{core,test-common,{h2,memory,postgres}-backend,examples}:dependencies --update-locks '*:*' <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LimitStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.stream.Stream; import de.bwaldvogel.mongo.bson.Document; public class LimitStage implements AggregationStage { private final long maxSize; public LimitStage(long maxSize) { this.maxSize = maxSize; } @Override public String name() { return "$limit"; } @Override public Stream<Document> apply(Stream<Document> stream) { return stream.limit(maxSize); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/DefaultQueryMatcher.java package de.bwaldvogel.mongo.backend; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.backend.aggregation.Expression; import de.bwaldvogel.mongo.bson.BsonRegularExpression; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.MaxKey; import de.bwaldvogel.mongo.bson.MinKey; import de.bwaldvogel.mongo.exception.BadValueException; import de.bwaldvogel.mongo.exception.ErrorCode; import de.bwaldvogel.mongo.exception.FailedToParseException; import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.MongoServerException; import de.bwaldvogel.mongo.exception.MongoServerNotYetImplementedException; public class DefaultQueryMatcher implements QueryMatcher { private static final Logger log = LoggerFactory.getLogger(DefaultQueryMatcher.class); private Integer lastPosition; @Override public boolean matches(Document document, Document query) { for (String key : query.keySet()) { Object queryValue = query.get(key); validateQueryValue(queryValue, key); if (!checkMatch(queryValue, key, document)) { return false; } } return true; } private void validateQueryValue(Object queryValue, String key) { if (!(queryValue instanceof Document)) { return; } if (BsonRegularExpression.isRegularExpression(queryValue)) { return; } Document queryObject = (Document) queryValue; if (!queryObject.keySet().isEmpty() && queryObject.keySet().iterator().next().startsWith("$")) { for (String operator : queryObject.keySet()) { if (Constants.REFERENCE_KEYS.contains(operator)) { continue; } QueryOperator queryOperator = QueryOperator.fromValue(operator); if (queryOperator == QueryOperator.TYPE) { Object value = queryObject.get(operator); if (value instanceof Collection) { Collection<?> values = (Collection<?>) value; if (values.isEmpty()) { throw new FailedToParseException(key + " must match at least one type"); } } } } } } @Override public synchronized Integer matchPosition(Document document, Document query) { lastPosition = null; for (String key : query.keySet()) { if (!checkMatch(query.get(key), key, document)) { return null; } } return lastPosition; } private List<String> splitKey(String key) { List<String> keys = List.of(key.split("\\.", -1)); for (int i = 0; i < keys.size(); i++) { if (keys.get(i).isEmpty() && i != keys.size() - 1) { log.warn("Illegal key: '{}'", key); return List.of(key); } } return keys; } private boolean checkMatch(Object queryValue, String key, Object document) { return checkMatch(queryValue, splitKey(key), document); } private boolean checkMatch(Object queryValue, List<String> keys, Object value) { if (keys.isEmpty()) { throw new MongoServerException("illegal keys: " + keys); } String firstKey = keys.get(0); if (firstKey.equals("$comment")) { log.debug("query comment: '{}'", queryValue); return true; } List<String> subKeys = Collections.emptyList(); if (keys.size() > 1) { subKeys = keys.subList(1, keys.size()); } if (QueryFilter.isQueryFilter(firstKey)) { QueryFilter filter = QueryFilter.fromValue(firstKey); return checkMatch(queryValue, filter, value); } else if (firstKey.startsWith("$") && !Constants.REFERENCE_KEYS.contains(firstKey)) { throw new BadValueException("unknown top level operator: " + firstKey + ". If you have a field name that starts with a '$' symbol, consider using $getField or $setField."); } if (value instanceof List<?>) { if (firstKey.matches("\\d+")) { Object listValue = Utils.getFieldValueListSafe(value, firstKey); if (subKeys.isEmpty()) { return checkMatchesValue(queryValue, listValue); } else { return checkMatch(queryValue, subKeys, listValue); } } else if (firstKey.isEmpty()) { Assert.isEmpty(subKeys); return checkMatchesValue(queryValue, value); } if (queryValue instanceof Document) { Document query = (Document) queryValue; if (query.containsKey(QueryOperator.ALL.getValue())) { Object allQuery = query.get(QueryOperator.ALL.getValue()); return checkMatchesAllDocuments(allQuery, keys, value); } if (query.containsKey(QueryOperator.NOT_EQUALS.getValue())) { Object notEqualQuery = query.get(QueryOperator.NOT_EQUALS.getValue()); return !checkMatchesAnyDocument(notEqualQuery, keys, value); } if (query.containsKey(QueryOperator.NOT_IN.getValue())) { Object notInQueryValue = query.get(QueryOperator.NOT_IN.getValue()); Document inQuery = new Document(QueryOperator.IN.getValue(), notInQueryValue); return !checkMatchesAnyDocument(inQuery, keys, value); } } return checkMatchesAnyDocument(queryValue, keys, value); } if (!subKeys.isEmpty()) { Object subObject = Utils.getFieldValueListSafe(value, firstKey); return checkMatch(queryValue, subKeys, subObject); } final Document document; final Object documentValue; if (Missing.isNullOrMissing(value)) { document = null; documentValue = Missing.getInstance(); } else if (value instanceof Document) { document = (Document) value; documentValue = document.getOrMissing(firstKey); } else { return checkMatchesValue(queryValue, Missing.getInstance()); } if (documentValue instanceof Collection<?>) { Collection<?> documentValues = (Collection<?>) documentValue; if (queryValue instanceof Document) { Document queryDocument = (Document) queryValue; boolean matches = checkMatchesAnyValue(queryDocument, keys, document, documentValues); if (matches) { return true; } if (isInQuery(queryDocument)) { return checkMatchesValue(queryValue, documentValue); } else { return false; } } else if (queryValue instanceof Collection<?>) { return checkMatchesValue(queryValue, documentValues); } else if (checkMatchesAnyValue(queryValue, documentValues)) { return true; } } return checkMatchesValue(queryValue, documentValue); } private static boolean isInQuery(Document queryDocument) { return queryDocument.keySet().equals(Set.of(QueryOperator.IN.getValue())); } private boolean checkMatchesAnyValue(Document queryValue, List<String> keys, Document document, Collection<?> value) { Set<String> keySet = queryValue.keySet(); // clone first Document queryValueClone = queryValue.clone(); for (String queryOperator : keySet) { Object subQuery = queryValueClone.remove(queryOperator); if (queryOperator.equals(QueryOperator.ALL.getValue())) { if (!checkMatchesAllValues(subQuery, value)) { return false; } } else if (queryOperator.equals(QueryOperator.IN.getValue())) { Document inQuery = new Document(queryOperator, subQuery); if (!checkMatchesAnyValue(inQuery, value)) { return false; } } else if (queryOperator.equals(QueryOperator.NOT_IN.getValue())) { Document inQuery = new Document(QueryOperator.IN.getValue(), subQuery); if (checkMatchesAnyValue(inQuery, value)) { return false; } } else if (queryOperator.equals(QueryOperator.NOT.getValue())) { if (checkMatch(subQuery, keys, document)) { return false; } } else if (queryOperator.equals(QueryOperator.NOT_EQUALS.getValue())) { Document equalQuery = new Document(QueryOperator.EQUAL.getValue(), subQuery); if (subQuery instanceof Collection) { if (checkMatchesValue(subQuery, value)) { return false; } } else if (checkMatchesAnyValue(equalQuery, value)) { return false; } } else if (queryOperator.equals(QueryOperator.SIZE.getValue())) { Document sizeQuery = new Document(QueryOperator.SIZE.getValue(), subQuery); if (!checkMatchesValue(sizeQuery, value)) { return false; } } else { if (!checkMatchesAnyValue(queryValue, value) && !checkMatchesValue(queryValue, value)) { return false; } } } return true; } private boolean checkMatch(Object queryValue, QueryFilter filter, Object document) { if (filter == QueryFilter.EXPR) { Object result = Expression.evaluateDocument(queryValue, (Document) document); return Utils.isTrue(result); } if (!(queryValue instanceof List<?>)) { throw new BadValueException("$and/$or/$nor must be a nonempty array"); } @SuppressWarnings("unchecked") List<Object> list = (List<Object>) queryValue; if (list.isEmpty()) { throw new BadValueException("$and/$or/$nor must be a nonempty array"); } for (Object subqueryValue : list) { if (!(subqueryValue instanceof Document)) { throw new MongoServerError(14817, filter + " elements must be objects"); } } switch (filter) { case AND: for (Object subqueryValue : list) { if (!matches((Document) document, (Document) subqueryValue)) { return false; } } return true; case OR: for (Object subqueryValue : list) { if (matches((Document) document, (Document) subqueryValue)) { return true; } } return false; case NOR: return !checkMatch(queryValue, QueryFilter.OR, document); default: throw new MongoServerException("illegal query filter: " + filter + ". must not happen"); } } @SuppressWarnings("unchecked") private boolean checkMatchesAllDocuments(Object queryValue, List<String> keys, Object document) { for (Object query : (Collection<Object>) queryValue) { if (!checkMatchesAnyDocument(query, keys, document)) { return false; } } return true; } @SuppressWarnings("unchecked") private boolean checkMatchesAnyDocument(Object queryValue, List<String> keys, Object document) { int i = 0; for (Object object : (Collection<Object>) document) { if (checkMatch(queryValue, keys, object)) { if (lastPosition == null) { lastPosition = Integer.valueOf(i); } return true; } i++; } return false; } @Override public boolean matchesValue(Object queryValue, Object value) { return checkMatchesValue(queryValue, value, false); } private boolean checkMatchesValue(Object queryValue, Object value) { return checkMatchesValue(queryValue, value, true); } private boolean checkMatchesValue(Object queryValue, Object value, boolean requireExactMatch) { if (BsonRegularExpression.isRegularExpression(queryValue)) { if (Missing.isNullOrMissing(value)) { return false; } else { BsonRegularExpression pattern = BsonRegularExpression.convertToRegularExpression(queryValue); Matcher matcher = pattern.matcher(value.toString()); return matcher.find(); } } if (queryValue instanceof Document) { Document queryObject = (Document) queryValue; if (queryObject.keySet().equals(Constants.REFERENCE_KEYS)) { if (value instanceof Document) { return matches((Document) value, queryObject); } else { return false; } } if (requireExactMatch && value instanceof Document) { if (queryObject.keySet().stream().noneMatch(key -> key.startsWith("$"))) { return Utils.nullAwareEquals(value, queryValue); } } for (String key : queryObject.keySet()) { Object querySubvalue = queryObject.get(key); if (key.startsWith("$")) { if (!checkExpressionMatch(value, querySubvalue, key)) { return false; } } else if (Missing.isNullOrMissing(value) && querySubvalue == null) { return false; } else if (!checkMatch(querySubvalue, key, value)) { // the value of the query itself can be a complex query return false; } } return true; } return Utils.nullAwareEquals(value, queryValue); } private boolean checkMatchesAllValues(Object queryValue, Object values) { if (!(queryValue instanceof Collection)) { return false; } Collection<?> list = (Collection<?>) values; Collection<?> queryValues = (Collection<?>) queryValue; if (queryValues.isEmpty()) { return false; } for (Object query : queryValues) { if (!checkMatchesAnyValue(query, list)) { return false; } } return true; } @SuppressWarnings("unchecked") private boolean checkMatchesElemValues(Object queryValue, Object values) { if (!(queryValue instanceof Document)) { throw new BadValueException(QueryOperator.ELEM_MATCH.getValue() + " needs an Object"); } if (!(values instanceof Collection)) { return false; } Collection<Object> list = (Collection<Object>) values; for (Object value : list) { if (checkMatchesValue(queryValue, value, false)) { return true; } } return false; } private boolean checkMatchesAnyValue(Object queryValue, Collection<?> values) { if (queryValue instanceof Document) { Document queryDocument = (Document) queryValue; if (queryDocument.keySet().equals(Set.of(QueryOperator.ELEM_MATCH.getValue()))) { queryValue = queryDocument.get(QueryOperator.ELEM_MATCH.getValue()); } } int i = 0; for (Object value : values) { if (checkMatchesValue(queryValue, value)) { if (lastPosition == null) { lastPosition = Integer.valueOf(i); } return true; } i++; } return false; } private boolean checkExpressionMatch(Object value, Object expressionValue, String operator) { if (QueryFilter.isQueryFilter(operator)) { QueryFilter filter = QueryFilter.fromValue(operator); return checkMatch(expressionValue, filter, value); } QueryOperator queryOperator = QueryOperator.fromValue(operator); switch (queryOperator) { case IN: Collection<?> queriedObjects = (Collection<?>) expressionValue; for (Object o : queriedObjects) { if (o instanceof BsonRegularExpression && value instanceof String) { BsonRegularExpression pattern = (BsonRegularExpression) o; if (pattern.matcher((String) value).find()) { return true; } } else if (value instanceof Collection && !(o instanceof Collection)) { Collection<?> values = (Collection<?>) value; return values.stream().anyMatch(v -> Utils.nullAwareEquals(o, v)); } else if (Utils.nullAwareEquals(o, value)) { return true; } } return false; case NOT: return !checkMatchesValue(expressionValue, value); case EQUAL: return Utils.nullAwareEquals(value, expressionValue); case NOT_EQUALS: return !Utils.nullAwareEquals(value, expressionValue); case NOT_IN: return !checkExpressionMatch(value, expressionValue, "$in"); case EXISTS: return ((value instanceof Missing) != Utils.isTrue(expressionValue)); case GREATER_THAN: if (!comparableTypes(value, expressionValue)) { return false; } return ValueComparator.desc().compare(value, expressionValue) < 0; case GREATER_THAN_OR_EQUAL: if (!comparableTypes(value, expressionValue)) { return false; } return ValueComparator.desc().compare(value, expressionValue) <= 0; case LESS_THAN: if (!comparableTypes(value, expressionValue)) { return false; } return ValueComparator.asc().compare(value, expressionValue) < 0; case LESS_THAN_OR_EQUAL: if (!comparableTypes(value, expressionValue)) { return false; } return ValueComparator.asc().compare(value, expressionValue) <= 0; case MOD: { if (!(value instanceof Number)) { return false; } @SuppressWarnings("unchecked") List<Number> modValue = (List<Number>) expressionValue; return (((Number) value).intValue() % modValue.get(0).intValue() == modValue.get(1).intValue()); } case SIZE: { if (!(expressionValue instanceof Number)) { throw new BadValueException("$size needs a number"); } if (!(value instanceof Collection<?>)) { return false; } int listSize = ((Collection<?>) value).size(); double matchingSize = ((Number) expressionValue).doubleValue(); return listSize == matchingSize; } case ALL: return false; case TYPE: return matchTypes(value, expressionValue); case ELEM_MATCH: return checkMatchesElemValues(expressionValue, value); case NEAR_SPHERE: return checkNearSphere(expressionValue, value); case GEO_WITHIN: return checkGeoWithin(expressionValue, value); default: throw new IllegalArgumentException("unhandled query operator: " + queryOperator); } } static boolean matchTypes(Object value, Object expressionValue) { if (Objects.equals(expressionValue, "number")) { List<String> types = Stream.of(BsonType.INT, BsonType.LONG, BsonType.DOUBLE, BsonType.DECIMAL128) .map(BsonType::getAlias) .collect(Collectors.toList()); return matchTypes(value, types); } else if (expressionValue instanceof String) { return matchTypes(value, BsonType.forString((String) expressionValue)); } else if (expressionValue instanceof Number) { return matchTypes(value, BsonType.forNumber((Number) expressionValue)); } else if (expressionValue instanceof Collection) { Collection<?> values = (Collection<?>) expressionValue; for (Object type : values) { if (matchTypes(value, type)) { return true; } } return false; } else { throw new MongoServerError(ErrorCode.TypeMismatch, "type must be represented as a number or a string"); } } private static boolean matchTypes(Object value, BsonType type) { return type.matches(value); } private boolean comparableTypes(Object value, Object expressionValue) { if (expressionValue instanceof MinKey || expressionValue instanceof MaxKey) { return true; } value = Utils.normalizeValue(value); expressionValue = Utils.normalizeValue(expressionValue); if (value == null || expressionValue == null) { return false; } if (value instanceof Number && expressionValue instanceof Number) { return true; } return value.getClass().equals(expressionValue.getClass()); } private boolean checkNearSphere(Object expressionValue, Object value) { log.debug("Expression value: {}, value: {}", expressionValue, value); throw new MongoServerNotYetImplementedException(132, QueryOperator.NEAR_SPHERE.getValue()); } private boolean checkGeoWithin(Object expressionValue, Object value) { log.debug("Expression value: {}, value: {}", expressionValue, value); throw new MongoServerNotYetImplementedException(132, QueryOperator.GEO_WITHIN.getValue()); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/UnsupportedConversionError.java package de.bwaldvogel.mongo.exception; import static de.bwaldvogel.mongo.backend.Utils.describeType; public class UnsupportedConversionError extends ConversionFailureException { private static final long serialVersionUID = 1L; public UnsupportedConversionError(Object value, Class<?> targetType) { super("Unsupported conversion from " + describeType(value) + " to " + describeType(targetType) + " in $convert with no onError value"); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTest.java package de.bwaldvogel.mongo.backend.aggregation; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Collection; import java.util.Collections; import java.util.List; import org.assertj.core.data.Offset; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.backend.Missing; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.FailedToOptimizePipelineError; import de.bwaldvogel.mongo.exception.MongoServerError; class ExpressionTest { @Test void testEvaluateSimpleValue() throws Exception { assertThat(Expression.evaluate(1, json(""))).isEqualTo(1); assertThat(Expression.evaluate(null, json(""))).isNull(); assertThat(Expression.evaluate("abc", json(""))).isEqualTo("abc"); assertThat(Expression.evaluate("$a", json("a: 123"))).isEqualTo(123); assertThat(Expression.evaluate("$a", json(""))).isInstanceOf(Missing.class); assertThat(Expression.evaluate("$a", json("a: null"))).isNull(); assertThat(Expression.evaluate(json("a: 1, b: 2"), json("a: -2"))).isEqualTo(json("a: 1, b: 2")); } @Test void testEvaluateAbs() throws Exception { assertThat(Expression.evaluate(json("$abs: '$a'"), json("a: -2"))).isEqualTo(2); assertThat(Expression.evaluate(json("$abs: '$a'"), json("a: -2.5"))).isEqualTo(2.5); assertThat(Expression.evaluate(json("$abs: ['$a']"), json("a: -2.5"))).isEqualTo(2.5); assertThat(Expression.evaluate(new Document("$abs", 123L), json(""))).isEqualTo(123); assertThat(Expression.evaluate(json("$abs: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$abs: '$a'"), json("a: -25"))).isEqualTo(25); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$abs: '$a', $ceil: '$b'"), json(""))) .withMessage("[Error 15983] An object representing an expression must have exactly one field: {\"$abs\" : \"$a\", \"$ceil\" : \"$b\"}"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$abs: 'abc'"), json(""))) .withMessage("[Error 28765] $abs only supports numeric types, not string"); } @Test void testEvaluateAdd() throws Exception { assertThat(Expression.evaluate(json("$add: ['$a', '$b']"), json("a: 7, b: 5"))).isEqualTo(12); assertThat(Expression.evaluate(json("$add: ['$doesNotExist', 5]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$add: [7.5, 3]"), json(""))).isEqualTo(10.5); assertThat(Expression.evaluate(json("$add: [1, 2, 3]"), json(""))).isEqualTo(6); assertThat(Expression.evaluate(json("$add: []"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$add: 17"), json(""))).isEqualTo(17); assertThat(Expression.evaluate(json("$add: [1, null, 2]"), json(""))).isNull(); assertThat(Expression.evaluate(new Document("$add", List.of(Instant.ofEpochSecond(1000), Instant.ofEpochSecond(2000))), json(""))) .isEqualTo(Instant.ofEpochSecond(3000)); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$add: 'abc'"), json(""))) .withMessage("[Error 16554] $add only supports numeric or date types, not string"); } @Test void testEvaluateAnd() throws Exception { assertThat(Expression.evaluate(json("$and: [1, 'green']"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: []"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: [[null], [false], [0]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: 'abc'"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: '$value'"), json("value: true"))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: '$value'"), json("value: false"))).isEqualTo(false); assertThat(Expression.evaluate(json("$and: true"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: [{$gt: ['$qty', 100]}, {$lt: ['$qty', 250]}]"), json("qty: 150"))).isEqualTo(true); assertThat(Expression.evaluate(json("$and: [{$gt: ['$qty', 100]}, {$lt: ['$qty', 250]}]"), json("qty: 300"))).isEqualTo(false); assertThat(Expression.evaluate(json("$and: false"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$and: null"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$and: [null, true]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$and: [0, true]"), json(""))).isEqualTo(false); } @Test void testEvaluateAnyElementTrue() throws Exception { assertThat(Expression.evaluate(json("$anyElementTrue: [[true, false]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$anyElementTrue: ['$items']"), json("items: [false, true]"))).isEqualTo(true); assertThat(Expression.evaluate(json("$anyElementTrue: [[[false]]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$anyElementTrue: ['$items']"), json("items: [false, false]"))).isEqualTo(false); assertThat(Expression.evaluate(json("$anyElementTrue: [[null, false, 0]]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$anyElementTrue: [[]]"), json(""))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$anyElementTrue: null"), json(""))) .withMessage("[Error 17041] $anyElementTrue's argument must be an array, but is null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$anyElementTrue: [null]"), json(""))) .withMessage("[Error 17041] $anyElementTrue's argument must be an array, but is null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$anyElementTrue: 'abc'"), json(""))) .withMessage("[Error 17041] $anyElementTrue's argument must be an array, but is string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$anyElementTrue: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $anyElementTrue takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateAllElementsTrue() throws Exception { assertThat(Expression.evaluate(json("$allElementsTrue: [[true, 1, 'someString']]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$allElementsTrue: [[[false]]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$allElementsTrue: [[]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$allElementsTrue: ['$items']"), json("items: [true]"))).isEqualTo(true); assertThat(Expression.evaluate(json("$allElementsTrue: [[null, false, 0]]"), json(""))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$allElementsTrue: null"), json(""))) .withMessage("[Error 17040] $allElementsTrue's argument must be an array, but is null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$allElementsTrue: [null]"), json(""))) .withMessage("[Error 17040] $allElementsTrue's argument must be an array, but is null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$allElementsTrue: 'abc'"), json(""))) .withMessage("[Error 17040] $allElementsTrue's argument must be an array, but is string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$allElementsTrue: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $allElementsTrue takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateArrayElemAt() throws Exception { assertThat(Expression.evaluate(json("$arrayElemAt: [[1, 2, 3], 0]"), json(""))).isEqualTo(1); assertThat(Expression.evaluate(json("$arrayElemAt: [[1, 2, 3], 1.0]"), json(""))).isEqualTo(2); assertThat(Expression.evaluate(json("$arrayElemAt: [[1, 2, 3], -2]"), json(""))).isEqualTo(2); assertThat(Expression.evaluate(json("$arrayElemAt: [[1, 2, 3], 15]"), json(""))).isInstanceOf(Missing.class); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items', 1]"), json("items: ['a', 'b', 'c']"))).isEqualTo("b"); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items', '$pos']"), json("items: ['a', 'b', 'c'], pos: -1"))).isEqualTo("c"); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items', '$pos']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items.foo', -1]"), json("items: [{foo: 'bar'}, {foo: 'bas'}, {foo: 'bat'}]"))) .isEqualTo("bat"); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items.foo', 0]"), json("items: [{foo: {ping: 'pong'}}, {foo: 'bas'}, {foo: 'bat'}]"))) .isEqualTo(json("ping: 'pong'")); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items.foo', 1]"), json("items: [1, {foo: 11}, 3]"))) .isEqualTo(11); assertThat(Expression.evaluate(json("$arrayElemAt: ['$items.foo', 0]"), json("items: [1, {foo: 11}, 3]"))) .isInstanceOf(Missing.class); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayElemAt: null"), json(""))) .withMessage("[Error 16020] Expression $arrayElemAt takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayElemAt: [1, 2, 3]"), json(""))) .withMessage("[Error 16020] Expression $arrayElemAt takes exactly 2 arguments. 3 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayElemAt: ['a', 'b']"), json(""))) .withMessage("[Error 28689] $arrayElemAt's first argument must be an array, but is string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayElemAt: [['a', 'b'], 'b']"), json(""))) .withMessage("[Error 28690] $arrayElemAt's second argument must be a numeric value, but is string"); } @Test void testEvaluateArrayToObject() throws Exception { assertThat(Expression.evaluate(json("$arrayToObject: {$literal: [['item', 'abc123'], ['qty', 25]]}"), json(""))) .isEqualTo(json("item: 'abc123', qty: 25")); assertThat(Expression.evaluate(json("$arrayToObject: {$literal: [{k: 'item', v: 'abc123'}, {k: 'qty', v: 25}]}"), json(""))) .isEqualTo(json("item: 'abc123', qty: 25")); assertThat(Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [['k', 'v']]"))) .isEqualTo(json("k: 'v'")); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: 'str'"), json(""))) .withMessage("[Error 40386] Failed to optimize pipeline :: caused by :: $arrayToObject requires an array input, found: string"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [1, 2]"))) .withMessage("[Error 40398] Failed to optimize pipeline :: caused by :: Unrecognised input type format for $arrayToObject: int"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [[1, 2, 3]]"))) .withMessage("[Error 40397] Failed to optimize pipeline :: caused by :: $arrayToObject requires an array of size 2 arrays,found array of size: 3"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [[1, 2]]"))) .withMessage("[Error 40395] Failed to optimize pipeline :: caused by :: $arrayToObject requires an array of key-value pairs, where the key must be of type string. Found key type: int"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: 1"))) .withMessage("[Error 40386] Failed to optimize pipeline :: caused by :: $arrayToObject requires an array input, found: int"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [{}]"))) .withMessage("[Error 40392] Failed to optimize pipeline :: caused by :: $arrayToObject requires an object keys of 'k' and 'v'. Found incorrect number of keys:0"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [{k: 1, v: 2}]"))) .withMessage("[Error 40394] Failed to optimize pipeline :: caused by :: $arrayToObject requires an object with keys 'k' and 'v', where the value of 'k' must be of type string. Found type: int"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$arrayToObject: '$kv'"), json("kv: [{k: 'key', z: 2}]"))) .withMessage("[Error 40393] Failed to optimize pipeline :: caused by :: $arrayToObject requires an object with keys 'k' and 'v'. Missing either or both keys from: {k: \"key\", z: 2}"); } @Test void testEvaluateCeil() throws Exception { assertThat(Expression.evaluate(json("$ceil: '$a'"), json("a: 2.5"))).isEqualTo(3.0); assertThat(Expression.evaluate(json("$ceil: 42"), json(""))).isEqualTo(42.0); assertThat(Expression.evaluate(json("$ceil: [5.4]"), json(""))).isEqualTo(6.0); assertThat(Expression.evaluate(json("$ceil: ['$a']"), json("a: 9.9"))).isEqualTo(10.0); assertThat(Expression.evaluate(json("$ceil: 42.3"), json(""))).isEqualTo(43.0); assertThat(Expression.evaluate(new Document("$ceil", (double) Long.MAX_VALUE), json(""))).isEqualTo(9.223372036854776E18); assertThat(Expression.evaluate(new Document("$ceil", (double) Long.MIN_VALUE), json(""))).isEqualTo(-9.223372036854776E18); assertThat(Expression.evaluate(json("$ceil: null"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ceil: 'abc'"), json(""))) .withMessage("[Error 28765] $ceil only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ceil: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $ceil takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateCmp() throws Exception { assertThat(Expression.evaluate(json("$cmp: [20, 10]"), json(""))).isEqualTo(1); assertThat(Expression.evaluate(json("$cmp: [20, 20]"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$cmp: [10, 20]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$cmp: ['$a', '$b']"), json("a: 10, b: 5"))).isEqualTo(1); assertThat(Expression.evaluate(json("$cmp: ['b', 'a']"), json(""))).isEqualTo(1); assertThat(Expression.evaluate(json("$cmp: ['a', 'b']"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$cmp: ['$qty', 250]"), json("qty: 500"))).isEqualTo(1); assertThat(Expression.evaluate(json("$cmp: ['$qty', 250]"), json("qty: 100"))).isEqualTo(-1); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cmp: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $cmp takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cmp: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $cmp takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateConcat() throws Exception { assertThat(Expression.evaluate(json("$concat: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$concat: ['A', 'B', 'C']"), json(""))).isEqualTo("ABC"); assertThat(Expression.evaluate(json("$concat: ['$a', '-', '$b']"), json("a: 'A', b: 'B'"))).isEqualTo("A-B"); assertThat(Expression.evaluate(json("$concat: ['$a', '$b']"), json("b: 'B'"))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$concat: 1"), json(""))) .withMessage("[Error 16702] $concat only supports strings, not int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$concat: '$a'"), json("a: ['abc', 'def']"))) .withMessage("[Error 16702] $concat only supports strings, not array"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$concat: [1]"), json(""))) .withMessage("[Error 16702] $concat only supports strings, not int"); } @Test void testEvaluateConcatArrays() throws Exception { assertThat(Expression.evaluate(json("$concatArrays: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$concatArrays: [['hello', ' '], ['world']]"), json(""))) .isEqualTo(List.of("hello", " ", "world")); assertThat(Expression.evaluate(json("$concatArrays: [['hello', ' '], [['world'], 'again']]"), json(""))) .isEqualTo(List.of("hello", " ", List.of("world"), "again")); assertThat(Expression.evaluate(json("$concatArrays: ['$a', '$b']"), json("a: [1, 2], b: [3, 4]"))) .isEqualTo(List.of(1, 2, 3, 4)); assertThat(Expression.evaluate(json("$concatArrays: ['$a', '$b']"), json("a: [1, 2]"))) .isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$concatArrays: 1"), json(""))) .withMessage("[Error 28664] $concatArrays only supports arrays, not int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$concatArrays: [1]"), json(""))) .withMessage("[Error 28664] $concatArrays only supports arrays, not int"); } @Test void testEvaluateCond() throws Exception { assertThat(Expression.evaluate(json("$cond: {if: {$gte: ['$qty', 250]}, then: 30, else: 20}"), json("qty: 100"))) .isEqualTo(20); assertThat(Expression.evaluate(json("$cond: [{$gte: ['$qty', 250]}, 30, 20]"), json("qty: 300"))) .isEqualTo(30); assertThat(Expression.evaluate(json("$cond: {if: {$gte: ['$qty', 250]}, then: '$qty', else: 20}"), json("qty: 300"))) .isEqualTo(300); assertThat(Expression.evaluate(json("$cond: {if: {$gte: ['$qty', 250]}, then: 10, else: '$qty'}"), json("qty: 200"))) .isEqualTo(200); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: null"), json(""))) .withMessage("[Error 16020] Expression $cond takes exactly 3 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: [1, 2, 3, 4]"), json(""))) .withMessage("[Error 16020] Expression $cond takes exactly 3 arguments. 4 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: {}"), json(""))) .withMessage("[Error 17080] Missing 'if' parameter to $cond"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: {then: 1, else: 1}"), json(""))) .withMessage("[Error 17080] Missing 'if' parameter to $cond"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: {if: 1, else: 1}"), json(""))) .withMessage("[Error 17080] Missing 'then' parameter to $cond"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: {if: 1, then: 1}"), json(""))) .withMessage("[Error 17080] Missing 'else' parameter to $cond"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$cond: {if: 1, then: 1, else: 1, foo: 1}"), json(""))) .withMessage("[Error 17083] Unrecognized parameter to $cond: foo"); } @Test void testEvaluateEq() throws Exception { assertThat(Expression.evaluate(json("$eq: [20, 20]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$eq: [20, 10]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$eq: [null, null]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$eq: ['$a', '$b']"), json("a: 10, b: 10"))).isEqualTo(true); assertThat(Expression.evaluate(json("$eq: ['$qty', 250]"), json("qty: 250"))).isEqualTo(true); assertThat(Expression.evaluate(json("$eq: ['$qty', 250]"), json("qty: 100"))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$eq: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $eq takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$eq: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $eq takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateMap() throws Exception { assertThat((Collection<Object>) Expression.evaluate( json("$map: {input: '$quizzes', as: 'grade', in: {$add: ['$$grade', 2]}}"), json("quizzes: [5, 6, 7]"))) .containsExactly(7, 8, 9); assertThat((Collection<Object>) Expression.evaluate( json("$map: {input: '$quizzes', as: 'grade', in: {$add: ['$$grade', 2]}}"), json("quizzes: []"))) .isEmpty(); assertThat(Expression.evaluate(json("$map: {input: '$q', in: '$this'}"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: 'a'"), json(""))) .withMessage("[Error 16878] $map only supports an object as its argument"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Expression.evaluate(json("$map: {input: [1, 2, 3], in: true}"), json("$this: 1"))) .withMessage("Document already contains '$this'"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: {input: 'a', in: null}"), json(""))) .withMessage("[Error 16883] input to $map must be an array not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: {}"), json(""))) .withMessage("[Error 16882] Missing 'input' parameter to $map"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: {input: null}"), json(""))) .withMessage("[Error 16882] Missing 'in' parameter to $map"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: {input: 1, in: 1, foo: 1}"), json(""))) .withMessage("[Error 16879] Unrecognized parameter to $map: foo"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: {input: [], as: [], in: 1}"), json(""))) .withMessage("[Error 16866] empty variable names are not allowed"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$map: {input: [], as: '', in: 1}"), json(""))) .withMessage("[Error 16866] empty variable names are not allowed"); } @Test void testEvaluateReduce() throws Exception { assertThat((Integer) Expression.evaluate( json("$reduce: {input: '$quizzes', initialValue: 0, in: {$add: ['$$this', '$$value']}}"), json("quizzes: [5, 6, 7]"))) .isEqualTo(18); final Document expectedDocument = new Document(); expectedDocument.put("sum", 15); expectedDocument.put("product", 48); assertThat(Expression.evaluate( json("$reduce: {input: '$quizzes', initialValue: { sum: 5, product: 2 }, in: {sum: {$add : ['$$value.sum', '$$this']},product: {$multiply: [ '$$value.product', '$$this' ]}}}"), json("quizzes: [ 1, 2, 3, 4 ]"))) .isEqualTo(expectedDocument); assertThat((Collection<Object>) Expression.evaluate( json("$reduce: {input: '$quizzes',initialValue: [ 1, 2 ],in: {$concatArrays : ['$$value', '$$this']}}"), json("quizzes: [ [ 3, 4 ], [ 5, 6 ] ]"))) .containsExactly(1, 2, 3, 4, 5, 6); assertThat((Collection<Object>) Expression.evaluate( json("$reduce: {input: '$quizzes',initialValue: [],in: {$concatArrays : ['$$value', '$$this']}}"), json("quizzes: []"))) .isEmpty(); assertThat((Collection<Object>) Expression.evaluate( json("$reduce: {input: '$quizzes', initialValue: [ 1, 2 ], in: '$$this'}"), json(""))) .isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: 'a'"), json(""))) .withMessage("[Error 40075] $reduce only supports an object as its argument"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {input: [1, 2, 3], initialValue: null, in: '$this'}"), json("$this: 1"))) .withMessage("Document already contains '$this'"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {input: [1, 2, 3], initialValue: null, in: '$value'}"), json("$value: 1"))) .withMessage("Document already contains '$value'"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {input: 'a', initialValue: null, in: null}"), json(""))) .withMessage("[Error 40080] input to $reduce must be an array not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {initialValue: null, in: '$value'}"), json(""))) .withMessage("[Error 40079] Missing 'input' parameter to $reduce"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {input: [1, 2, 3], in: '$value'}"), json(""))) .withMessage("[Error 40079] Missing 'initialValue' parameter to $reduce"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {input: [1, 2, 3], initialValue: null}"), json(""))) .withMessage("[Error 40079] Missing 'in' parameter to $reduce"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reduce: {input: [1, 2, 3], initialValue: null, in: '$value', foo: 1}"), json(""))) .withMessage("[Error 40076] Unrecognized parameter to $reduce: foo"); } @Test void testEvaluateMergeObjects() throws Exception { assertThat(Expression.evaluate(json("$mergeObjects: [{a: 1}, null]"), json(""))).isEqualTo(json("a: 1")); assertThat(Expression.evaluate(json("$mergeObjects: [null, null]"), json(""))).isEqualTo(json("")); assertThat(Expression.evaluate(json("$mergeObjects: ['$a', '$b']"), json(""))).isEqualTo(json("")); assertThat(Expression.evaluate(json("$mergeObjects: ['$a', '$b']"), json("a: {x: 1}, b: {y: 2}"))).isEqualTo(json("x: 1, y: 2")); assertThat(Expression.evaluate(json("$mergeObjects: ['$a']"), json("a: {x: 1, y: 2}"))).isEqualTo(json("x: 1, y: 2")); assertThat(Expression.evaluate(json("$mergeObjects: ['$a', '$a.x']"), json("a: {x: {y: 2}}"))).isEqualTo(json("x: {y: 2}, y: 2")); assertThat(Expression.evaluate(json("$mergeObjects: [{a: 1}, {a: 2, b: 2}, {a: 3, c: 3}]"), json(""))) .isEqualTo(json("a: 3, b: 2, c: 3")); assertThat(Expression.evaluate(json("$mergeObjects: [{a: 1}, {a: 2, b: 2}, {a: 3, b: null, c: 3}]"), json(""))) .isEqualTo(json("a: 3, b: null, c: 3")); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$mergeObjects: [[], []]"), json(""))) .withMessage("[Error 40400] $mergeObjects requires object inputs, but input [] is of type array"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$mergeObjects: 'x'"), json(""))) .withMessage("[Error 40400] $mergeObjects requires object inputs, but input \"x\" is of type string"); } @Test void testEvaluateMinute() throws Exception { assertThat(Expression.evaluate(json("$minute: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$minute: '$a'"), new Document("a", toDate("2018-07-03T14:10:00Z")))).isEqualTo(10); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$minute: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateMod() throws Exception { assertThat(Expression.evaluate(json("$mod: [10, 2]"), json(""))).isEqualTo(0.0); assertThat(Expression.evaluate(json("$mod: [3, 2]"), json(""))).isEqualTo(1.0); assertThat(Expression.evaluate(json("$mod: [3.5, 3]"), json(""))).isEqualTo(0.5); assertThat(Expression.evaluate(json("$mod: ['$a', '$b']"), json("a: -10, b: 4"))).isEqualTo(-2.0); assertThat(Expression.evaluate(json("$mod: ['$a', '$b']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$mod: [null, 2]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$mod: [2, null]"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$mod: ''"), json(""))) .withMessage("[Error 16020] Expression $mod takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$mod: [1, 2, 3]"), json(""))) .withMessage("[Error 16020] Expression $mod takes exactly 2 arguments. 3 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$mod: ['a', 'b']"), json(""))) .withMessage("[Error 16611] $mod only supports numeric types, not string and string"); } @Test void testEvaluateMonth() throws Exception { assertThat(Expression.evaluate(json("$month: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$month: '$a'"), new Document("a", toDate("2018-07-03T14:00:00Z")))).isEqualTo(7); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$month: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateMultiply() throws Exception { assertThat(Expression.evaluate(json("$multiply: ['$a', '$b']"), json("a: 8, b: 4"))).isEqualTo(32); assertThat(Expression.evaluate(json("$multiply: [4.5, 3]"), json(""))).isEqualTo(13.5); assertThat(Expression.evaluate(json("$multiply: [5, 3.0]"), json(""))).isEqualTo(15.0); assertThat(Expression.evaluate(json("$multiply: [null, 3]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$multiply: [null, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$multiply: [3, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$multiply: [3, 0]"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$multiply: [5000, 9000]"), json(""))).isEqualTo(45000000); assertThat(Expression.evaluate(json("$multiply: [50000, 90000]"), json(""))).isEqualTo(4500000000L); assertThat(Expression.evaluate(json("$multiply: [45000000000, 2]"), json(""))).isEqualTo(90000000000L); assertThat(Expression.evaluate(json("$multiply: [-45000000000, 2]"), json(""))).isEqualTo(-90000000000L); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$multiply: []"), json(""))) .withMessage("[Error 16020] Expression $multiply takes exactly 2 arguments. 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$multiply: [1]"), json(""))) .withMessage("[Error 16020] Expression $multiply takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$multiply: 123"), json(""))) .withMessage("[Error 16020] Expression $multiply takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$multiply: ['a', 'b']"), json(""))) .withMessage("[Error 16555] $multiply only supports numeric types, not string and string"); } @Test void testEvaluateNe() throws Exception { assertThat(Expression.evaluate(json("$ne: [20, 20]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$ne: [20, 10]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$ne: [20, 'a']"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$ne: ['$a', '$b']"), json("a: 10, b: 10"))).isEqualTo(false); assertThat(Expression.evaluate(json("$ne: ['$qty', 250]"), json("qty: 250"))).isEqualTo(false); assertThat(Expression.evaluate(json("$ne: ['$qty', 250]"), json("qty: 100"))).isEqualTo(true); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ne: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $ne takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ne: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $ne takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateNot() throws Exception { assertThat(Expression.evaluate(json("$not: false"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$not: true"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$not: 1"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$not: 0"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$not: [true]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$not: [[false]]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$not: [false]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$not: [null]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$not: [0]"), json(""))).isEqualTo(true); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$not: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $not takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateOr() throws Exception { assertThat(Expression.evaluate(json("$or: [1, 'green']"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: []"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$or: [[null], [false], [0]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: 'abc'"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: '$value'"), json("value: true"))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: '$value'"), json("value: false"))).isEqualTo(false); assertThat(Expression.evaluate(json("$or: true"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: [{$gt: ['$qty', 100]}, {$lt: ['$qty', 250]}]"), json("qty: 150"))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: [{$gt: ['$qty', 100]}, {$lt: ['$qty', 250]}]"), json("qty: 300"))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: [{$gt: ['$qty', 400]}, {$lt: ['$qty', 100]}]"), json("qty: 300"))).isEqualTo(false); assertThat(Expression.evaluate(json("$or: false"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$or: null"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$or: [null, true]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: [0, true]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$or: [0, false]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$or: [0, 0]"), json(""))).isEqualTo(false); } @Test void testEvaluateObjectToArray() throws Exception { assertThat((List<Document>) Expression.evaluate(json("$objectToArray: '$v'"), json("v: {a: 1, b: 2}"))) .containsExactly( json("{k: 'a', v: 1}"), json("{k: 'b', v: 2}") ); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$objectToArray: 1"), json(""))) .withMessage("[Error 40390] $objectToArray requires a document input, found: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$objectToArray: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $objectToArray takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluatePow() throws Exception { assertThat(Expression.evaluate(json("$pow: ['$a', '$b']"), json("a: 8, b: 4"))).isEqualTo(4096.0); assertThat(Expression.evaluate(json("$pow: [4.5, 3]"), json(""))).isEqualTo(91.125); assertThat(Expression.evaluate(json("$pow: [null, 3]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$pow: [null, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$pow: [3, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$pow: [3, 0]"), json(""))).isEqualTo(1.0); assertThat(Expression.evaluate(json("$pow: [-5, 0.5]"), json(""))).isEqualTo(Double.NaN); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$pow: []"), json(""))) .withMessage("[Error 16020] Expression $pow takes exactly 2 arguments. 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$pow: [1]"), json(""))) .withMessage("[Error 16020] Expression $pow takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$pow: 123"), json(""))) .withMessage("[Error 16020] Expression $pow takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$pow: ['a', 3]"), json(""))) .withMessage("[Error 28762] $pow's base must be numeric, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$pow: [3, 'a']"), json(""))) .withMessage("[Error 28763] $pow's exponent must be numeric, not string"); } @Test void testEvaluateRange() throws Exception { assertThat(Expression.evaluate(json("$range: [0, 5]"), json(""))).isEqualTo(List.of(0, 1, 2, 3, 4)); assertThat(Expression.evaluate(json("$range: [0, 10, 2]"), json(""))).isEqualTo(List.of(0, 2, 4, 6, 8)); assertThat(Expression.evaluate(json("$range: [0, 1.0, 2]"), json(""))).isEqualTo(List.of(0)); assertThat(Expression.evaluate(json("$range: [0, 0, 1]"), json(""))).isEqualTo(Collections.emptyList()); assertThat(Expression.evaluate(json("$range: [10, 0, -2]"), json(""))).isEqualTo(List.of(10, 8, 6, 4, 2)); assertThat(Expression.evaluate(json("$range: [0, 10, -2]"), json(""))).isEqualTo(Collections.emptyList()); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: 'abc'"), json(""))) .withMessage("[Error 28667] Expression $range takes at least 2 arguments, and at most 3, but 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: ['a', 'b']"), json(""))) .withMessage("[Error 34443] $range requires a numeric starting value, found value of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 34443] $range requires a numeric starting value, found value of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: [0, 'b', 'c']"), json(""))) .withMessage("[Error 34445] $range requires a numeric ending value, found value of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: [0, 0, 'c']"), json(""))) .withMessage("[Error 34447] $range requires a numeric step value, found value of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: [0, 0, 0]"), json(""))) .withMessage("[Error 34449] $range requires a non-zero step value"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: [0.5, 0, 1]"), json(""))) .withMessage("[Error 34444] $range requires a starting value that can be represented as a 32-bit integer, found value: 0.5"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: [0, 1.5, 1]"), json(""))) .withMessage("[Error 34446] $range requires a ending value that can be represented as a 32-bit integer, found value: 1.5"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$range: [0, 10, 0.5]"), json(""))) .withMessage("[Error 34448] $range requires a step value that can be represented as a 32-bit integer, found value: 0.5"); } @Test void testEvaluateReverseArray() throws Exception { assertThat(Expression.evaluate(json("$reverseArray: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$reverseArray: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$reverseArray: [[1, 2, 3]]"), json(""))) .isEqualTo(List.of(3, 2, 1)); assertThat(Expression.evaluate(json("$reverseArray: '$a'"), json("a: ['foo', 'bar']"))) .isEqualTo(List.of("bar", "foo")); assertThat(Expression.evaluate(json("$reverseArray: ['$a']"), json("a: ['foo', 'bar']"))) .isEqualTo(List.of("bar", "foo")); assertThat(Expression.evaluate(json("$reverseArray: [[]]"), json(""))) .isEqualTo(Collections.emptyList()); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reverseArray: 1"), json(""))) .withMessage("[Error 34435] The argument to $reverseArray must be an array, but was of type: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reverseArray: [1]"), json(""))) .withMessage("[Error 34435] The argument to $reverseArray must be an array, but was of type: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$reverseArray: [[1, 2], [3, 4]]"), json(""))) .withMessage("[Error 16020] Expression $reverseArray takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateGt() throws Exception { assertThat(Expression.evaluate(json("$gt: [20, 10]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$gt: [20, 20]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$gt: ['$a', '$b']"), json("a: 10, b: 5"))).isEqualTo(true); assertThat(Expression.evaluate(json("$gt: ['b', 'a']"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$gt: ['a', 'b']"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$gt: ['$qty', 250]"), json("qty: 500"))).isEqualTo(true); assertThat(Expression.evaluate(json("$gt: ['$qty', 250]"), json("qty: 100"))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$gt: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $gt takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$gt: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $gt takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateGte() throws Exception { assertThat(Expression.evaluate(json("$gte: [20, 10]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$gte: [20, 20]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$gte: [20, 21]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$gte: ['$qty', 250]"), json("qty: 500"))).isEqualTo(true); assertThat(Expression.evaluate(json("$gte: ['$qty', 250]"), json("qty: 100"))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$gte: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $gte takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$gte: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $gte takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateHour() throws Exception { assertThat(Expression.evaluate(json("$hour: '$a'"), json(""))).isNull(); int expectedHour = ZonedDateTime.ofInstant(Instant.parse("2018-07-03T14:10:00Z"), ZoneId.systemDefault()).toLocalTime().getHour(); assertThat(Expression.evaluate(json("$hour: '$a'"), new Document("a", toDate("2018-07-03T14:10:00Z")))).isEqualTo(expectedHour); assertThat(Expression.evaluate(json("$hour: {date: '$a'}"), new Document("a", toDate("2018-07-03T14:10:00Z")))).isEqualTo(expectedHour); assertThat(Expression.evaluate(json("$hour: {date: '$a', timezone: 'UTC'}"), new Document("a", toDate("2018-07-03T14:10:00Z")))).isEqualTo(14); assertThat(Expression.evaluate(json("$hour: {date: '$a', timezone: '$TZ'}"), new Document("a", toDate("2018-07-03T14:10:00Z")).append("TZ", "Europe/Berlin"))).isEqualTo(16); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$hour: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$hour: {}"), json(""))) .withMessage("[Error 40539] missing 'date' argument to $hour, provided: {}"); } @Test void testEvaluateLt() throws Exception { assertThat(Expression.evaluate(json("$lt: [10, 20]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$lt: [20, 20]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$lt: ['$qty', 250]"), json("qty: 100"))).isEqualTo(true); assertThat(Expression.evaluate(json("$lt: ['$qty', 250]"), json("qty: 500"))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$lt: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $lt takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$lt: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $lt takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateLte() throws Exception { assertThat(Expression.evaluate(json("$lte: [10, 20]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$lte: [20, 20]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$lte: [21, 20]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$lte: ['$qty', 250]"), json("qty: 100"))).isEqualTo(true); assertThat(Expression.evaluate(json("$lte: ['$qty', 250]"), json("qty: 500"))).isEqualTo(false); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$lte: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $lte takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$lte: ['a', 'b', 'c']"), json(""))) .withMessage("[Error 16020] Expression $lte takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateSecond() throws Exception { assertThat(Expression.evaluate(json("$second: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$second: '$a'"), new Document("a", toDate("2018-07-03T14:10:23Z")))).isEqualTo(23); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$second: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateSetDifference() throws Exception { assertThat(Expression.evaluate(json("$setDifference: [null, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setDifference: [[], null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setDifference: [null, []]"), json(""))).isNull(); assertThat((Collection<Object>) Expression.evaluate(json("$setDifference: [['a', 'b', 'a'], ['b']]"), json(""))) .containsExactly("a"); assertThat((Collection<Object>) Expression.evaluate(json("$setDifference: [['a', 'b', 'a'], ['c', 'b', 'a']]"), json(""))) .isEmpty(); assertThat((Collection<Object>) Expression.evaluate(json("$setDifference: [['a', 'b'], [['a', 'b']]]"), json(""))) .containsExactly("a", "b"); assertThat((Collection<Object>) Expression.evaluate(json("$setDifference: [[1.0, 0, 2], [-0.0]]"), json(""))) .containsExactly(1.0, 2); assertThat((Collection<Object>) Expression.evaluate(json("$setDifference: [[1.0, -0.0, 2], [1, 0]]"), json(""))) .containsExactly(2); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setDifference: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16020] Expression $setDifference takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setDifference: [1, 2, 3]"), json(""))) .withMessage("[Error 16020] Expression $setDifference takes exactly 2 arguments. 3 were passed in."); } @Test void testEvaluateSetEquals() throws Exception { assertThat(Expression.evaluate(json("$setEquals: [['a', 'b', 'a'], ['b']]"), json(""))) .isEqualTo(false); assertThat(Expression.evaluate(json("$setEquals: [['a', 'b', 'a'], ['b', 'a']]"), json(""))) .isEqualTo(true); assertThat(Expression.evaluate(json("$setEquals: ['$one', '$other']"), json("one: [1, 2], other: [2, 1]"))) .isEqualTo(true); assertThat(Expression.evaluate(json("$setEquals: ['$one', '$other', [2]]"), json("one: [1, 2], other: [2, 1]"))) .isEqualTo(false); assertThat(Expression.evaluate(json("$setEquals: ['$one', '$other', [2, 2, 1]]"), json("one: [1, 2], other: [2, 1]"))) .isEqualTo(true); assertThat(Expression.evaluate(json("$setEquals: ['$one', '$other']"), json("one: [0, 2.0], other: [2, -0.0]"))) .isEqualTo(true); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setEquals: []"), json(""))) .withMessage("[Error 17045] $setEquals needs at least two arguments had: 0"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setEquals: [null]"), json(""))) .withMessage("[Error 17045] $setEquals needs at least two arguments had: 1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setEquals: null"), json(""))) .withMessage("[Error 17045] $setEquals needs at least two arguments had: 1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setEquals: [[]]"), json(""))) .withMessage("[Error 17045] $setEquals needs at least two arguments had: 1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setEquals: [1, 2]"), json(""))) .withMessage("[Error 17044] All operands of $setEquals must be arrays. One argument is of type: int"); } @Test void testEvaluateSetIntersection() throws Exception { assertThat(Expression.evaluate(json("$setIntersection: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setIntersection: '$field'"), json(""))).isNull(); assertThat((Collection<?>) Expression.evaluate(json("$setIntersection: []"), json(""))).isEmpty(); assertThat((Collection<?>) Expression.evaluate(json("$setIntersection: [[]]"), json(""))).isEmpty(); assertThat(Expression.evaluate(json("$setIntersection: [null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setIntersection: [['a'], null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setIntersection: ['$a', null]"), json(""))).isNull(); assertThat((Collection<Object>) Expression.evaluate(json("$setIntersection: [['a', 'b', 'a'], ['b']]"), json(""))) .containsExactly("b"); assertThat((Collection<Object>) Expression.evaluate(json("$setIntersection: [['a', 'b', 'a'], ['b', 'a']]"), json(""))) .containsExactly("a", "b"); assertThat((Collection<Object>) Expression.evaluate(json("$setIntersection: ['$one', '$other']"), json("one: [1, 2, 3], other: [2, 3, 5]"))) .containsExactly(2, 3); assertThat((Collection<Object>) Expression.evaluate(json("$setIntersection: ['$one', '$other', [2]]"), json("one: [1, 2], other: [2, 1]"))) .containsExactly(2); assertThat((Collection<Object>) Expression.evaluate(json("$setIntersection: ['$one', '$other']"), json("one: [1, 2.0], other: [2, 1]"))) .containsExactly(1, 2.0); assertThat((Collection<Object>) Expression.evaluate(json("$setIntersection: ['$one', '$other', [2, 2, 1]]"), json("one: [], other: [2, 1]"))) .isEmpty(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIntersection: [1, 2]"), json(""))) .withMessage("[Error 17047] All operands of $setIntersection must be arrays. One argument is of type: int"); } @Test void testEvaluateSetIsSubset() throws Exception { assertThat(Expression.evaluate(json("$setIsSubset: [['a', 'b', 'a'], ['b', 'a']]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$setIsSubset: [['a', 'b'], [['a', 'b']]]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$setIsSubset: ['$a', '$b']"), json("a: [1, 2], b: [1, 2, 3, 4]"))).isEqualTo(true); assertThat(Expression.evaluate(json("$setIsSubset: ['$a', '$b']"), json("a: [1.0, 2.0], b: [1, 2, 3, 4]"))).isEqualTo(true); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: null"), json(""))) .withMessage("[Error 16020] Expression $setIsSubset takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: [null]"), json(""))) .withMessage("[Error 16020] Expression $setIsSubset takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: [null, []]"), json(""))) .withMessage("[Error 17046] both operands of $setIsSubset must be arrays. First argument is of type: null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: ['$doestNotExist', []]"), json(""))) .withMessage("[Error 17046] both operands of $setIsSubset must be arrays. First argument is of type: missing"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: [[], '$doestNotExist']"), json(""))) .withMessage("[Error 17042] both operands of $setIsSubset must be arrays. Second argument is of type: missing"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: [[], null]"), json(""))) .withMessage("[Error 17042] both operands of $setIsSubset must be arrays. Second argument is of type: null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setIsSubset: [1, 2]"), json(""))) .withMessage("[Error 17046] both operands of $setIsSubset must be arrays. First argument is of type: int"); } @Test void testEvaluateSetUnion() throws Exception { assertThat(Expression.evaluate(json("$setUnion: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$setUnion: '$a'"), json(""))).isNull(); assertThat((Collection<Object>) Expression.evaluate(json("$setUnion: [['a', 1], ['c', 'a']]"), json(""))) .containsExactly(1, "a", "c"); assertThat((Collection<Object>) Expression.evaluate(json("$setUnion: ['$a', '$b']"), json("a: [1, 2, 3], b: [3.0, 4]"))) .containsExactly(1, 2, 3, 4); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setUnion: 1"), json(""))) .withMessage("[Error 17043] All operands of $setUnion must be arrays. One argument is of type: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$setUnion: [1]"), json(""))) .withMessage("[Error 17043] All operands of $setUnion must be arrays. One argument is of type: int"); } @Test void testEvaluateSize() throws Exception { assertThat(Expression.evaluate(json("$size: [['$a', '$b']]"), json("a: 7, b: 5"))).isEqualTo(2); assertThat(Expression.evaluate(json("$size: [[7.5, 3]]"), json(""))).isEqualTo(2); assertThat(Expression.evaluate(json("$size: {$literal: [7.5, 3]}"), json(""))).isEqualTo(2); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$size: null"), json(""))) .withMessage("[Error 17124] The argument to $size must be an array, but was of type: null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$size: 'abc'"), json(""))) .withMessage("[Error 17124] The argument to $size must be an array, but was of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$size: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $size takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateSlice() throws Exception { assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], 1, 1]"), json(""))) .isEqualTo(List.of(2)); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], 0]"), json(""))) .isEqualTo(Collections.emptyList()); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], 2]"), json(""))) .isEqualTo(List.of(1, 2)); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], 20]"), json(""))) .isEqualTo(List.of(1, 2, 3)); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], -2]"), json(""))) .isEqualTo(List.of(2, 3)); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], -20]"), json(""))) .isEqualTo(List.of(1, 2, 3)); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], 0, 10]"), json(""))) .isEqualTo(List.of(1, 2, 3)); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], 15, 2]"), json(""))) .isEqualTo(Collections.emptyList()); assertThat(Expression.evaluate(json("$slice: [[1, 2, 3], -15, 2]"), json(""))) .isEqualTo(List.of(1, 2)); assertThat(Expression.evaluate(json("$slice: [null, 0]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$slice: ['$a', 0]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$slice: ['$a', '$b', '$c']"), json("a: [1, 2, 3], b: 1, c: 1"))) .isEqualTo(List.of(2)); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$slice: 'abc'"), json(""))) .withMessage("[Error 28667] Expression $slice takes at least 2 arguments, and at most 3, but 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$slice: [1, 2, 3, 4]"), json(""))) .withMessage("[Error 28667] Expression $slice takes at least 2 arguments, and at most 3, but 4 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$slice: [1, 0, 0]"), json(""))) .withMessage("[Error 28724] First argument to $slice must be an array, but is of type: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$slice: [[], 'a', 0]"), json(""))) .withMessage("[Error 28725] Second argument to $slice must be a numeric value, but is of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$slice: [[], 0, 'a']"), json(""))) .withMessage("[Error 28725] Third argument to $slice must be numeric, but is of type: string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$slice: [[], 0, -1]"), json(""))) .withMessage("[Error 28729] Third argument to $slice must be positive: -1"); } @Test void testEvaluateSplit() throws Exception { assertThat((List<String>) Expression.evaluate(json("$split: ['June-15-2013', '-']"), json(""))).containsExactly("June", "15", "2013"); assertThat((List<String>) Expression.evaluate(json("$split: ['$a', '$b']"), json("a: 'foo bar', b: ' '"))).containsExactly("foo", "bar"); assertThat(Expression.evaluate(json("$split: [null, ' ']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$split: ['$doesNotExist', ' ']"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$split: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $split takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$split: []"), json(""))) .withMessage("[Error 16020] Expression $split takes exactly 2 arguments. 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$split: [1, 2, 3]"), json(""))) .withMessage("[Error 16020] Expression $split takes exactly 2 arguments. 3 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$split: [25, ' ']"), json(""))) .withMessage("[Error 40085] $split requires an expression that evaluates to a string as a first argument, found: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$split: ['foo', 10]"), json(""))) .withMessage("[Error 40086] $split requires an expression that evaluates to a string as a second argument, found: int"); } @Test void testEvaluateSubtract() throws Exception { assertThat(Expression.evaluate(json("$subtract: ['$a', '$b']"), json("a: 7, b: 5"))).isEqualTo(2); assertThat(Expression.evaluate(json("$subtract: [7.5, 3]"), json(""))).isEqualTo(4.5); assertThat(Expression.evaluate(json("$subtract: [null, 3]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$subtract: [3, null]"), json(""))).isNull(); // subtract two instants assertThat(Expression.evaluate(new Document("$subtract", List.of(Instant.ofEpochMilli(3000), Instant.ofEpochMilli(1000))), json(""))) .isEqualTo(2000L); // subtract milliseconds from instant assertThat(Expression.evaluate(new Document("$subtract", List.of(Instant.ofEpochMilli(3000), 1000)), json(""))) .isEqualTo(Instant.ofEpochMilli(2000)); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$subtract: []"), json(""))) .withMessage("[Error 16020] Expression $subtract takes exactly 2 arguments. 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$subtract: [1]"), json(""))) .withMessage("[Error 16020] Expression $subtract takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$subtract: 123"), json(""))) .withMessage("[Error 16020] Expression $subtract takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$subtract: ['a', 'b']"), json(""))) .withMessage("[Error 16556] cant $subtract a string from a string"); } @Test void testEvaluateSum() throws Exception { assertThat(Expression.evaluate(json("$sum: null"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$sum: ''"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$sum: 5"), json(""))).isEqualTo(5); assertThat(Expression.evaluate(json("$sum: [[1, 2, 3]]"), json(""))).isEqualTo(6); assertThat(Expression.evaluate(json("$sum: [[1], [2]]"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$sum: [1, 'foo', 2]"), json(""))).isEqualTo(3); assertThat(Expression.evaluate(json("$sum: ['$a', '$b']"), json("a: 7, b: 5"))).isEqualTo(12); assertThat(Expression.evaluate(json("$sum: []"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$sum: '$values'"), json("values: [1, 2, 3]"))).isEqualTo(6); } @Test void testEvaluateToLower() throws Exception { assertThat(Expression.evaluate(json("$toLower: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$toLower: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$toLower: '$a'"), json("a: 'FOO'"))).isEqualTo("foo"); assertThat(Expression.evaluate(json("$toLower: 1"), json(""))).isEqualTo("1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$toLower: [[1, 2]]"), json(""))) .withMessage("[Error 16007] can't convert from BSON type array to String"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$toLower: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $toLower takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateToUpper() throws Exception { assertThat(Expression.evaluate(json("$toUpper: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$toUpper: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$toUpper: '$a'"), json("a: 'foo'"))).isEqualTo("FOO"); assertThat(Expression.evaluate(json("$toUpper: 1"), json(""))).isEqualTo("1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$toUpper: [[1, 2]]"), json(""))) .withMessage("[Error 16007] can't convert from BSON type array to String"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$toUpper: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $toUpper takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateTrunc() throws Exception { assertThat(Expression.evaluate(json("$trunc: '$a'"), json("a: 2.5"))).isEqualTo(2); assertThat(Expression.evaluate(json("$trunc: 42"), json(""))).isEqualTo(42); assertThat(Expression.evaluate(json("$trunc: NaN"), json(""))).isEqualTo(Double.NaN); assertThat(Expression.evaluate(json("$trunc: [5.6]"), json(""))).isEqualTo(5); assertThat(Expression.evaluate(json("$trunc: ['$a']"), json("a: 9.9"))).isEqualTo(9); assertThat(Expression.evaluate(json("$trunc: 42.3"), json(""))).isEqualTo(42); assertThat(Expression.evaluate(new Document("$trunc", (double) Long.MAX_VALUE), json(""))).isEqualTo(Long.MAX_VALUE); assertThat(Expression.evaluate(new Document("$trunc", (double) Long.MIN_VALUE), json(""))).isEqualTo(Long.MIN_VALUE); assertThat(Expression.evaluate(json("$trunc: null"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$trunc: 'abc'"), json(""))) .withMessage("[Error 28765] $trunc only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$trunc: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $trunc takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateToString() throws Exception { assertThat(Expression.evaluate(json("$toString: null"), json(""))).isNull(); assertThat(Expression.evaluate(json("$toString: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$toString: '$a'"), json("a: 'foo'"))).isEqualTo("foo"); assertThat(Expression.evaluate(json("$toString: 1"), json(""))).isEqualTo("1"); assertThat(Expression.evaluate(json("$toString: 1.3"), json(""))).isEqualTo("1.3"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$toString: [[1, 2]]"), json(""))) .withMessage("[Error 16007] can't convert from BSON type array to String"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$toString: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $toString takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateSqrt() throws Exception { assertThat((double) Expression.evaluate(json("$sqrt: '$a'"), json("a: 2.5"))).isEqualTo(1.581, Offset.offset(0.001)); assertThat(Expression.evaluate(json("$sqrt: 16"), json(""))).isEqualTo(4.0); assertThat(Expression.evaluate(json("$sqrt: [25]"), json(""))).isEqualTo(5.0); assertThat(Expression.evaluate(json("$sqrt: null"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$sqrt: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $sqrt takes exactly 1 arguments. 2 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$sqrt: 'abc'"), json(""))) .withMessage("[Error 28765] $sqrt only supports numeric types, not string"); } @Test void testEvaluateStrLenBytes() throws Exception { assertThat(Expression.evaluate(json("$strLenBytes: ''"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$strLenBytes: '$a'"), json("a: 'value'"))).isEqualTo(5); assertThat(Expression.evaluate(json("$strLenBytes: 'cafétéria'"), json(""))).isEqualTo(11); assertThat(Expression.evaluate(json("$strLenBytes: '$a'"), json("a: '$€λA'"))).isEqualTo(7); assertThat(Expression.evaluate(json("$strLenBytes: '\u5BFF\u53F8'"), json(""))).isEqualTo(6); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$strLenBytes: null"), json(""))) .withMessage("[Error 34471] $strLenBytes requires a string argument, found: null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$strLenBytes: 123"), json(""))) .withMessage("[Error 34471] $strLenBytes requires a string argument, found: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$strLenBytes: '$a'"), json(""))) .withMessage("[Error 34471] $strLenBytes requires a string argument, found: missing"); } @Test void testEvaluateStrLenCP() throws Exception { assertThat(Expression.evaluate(json("$strLenCP: ''"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$strLenCP: '$a'"), json("a: 'value'"))).isEqualTo(5); assertThat(Expression.evaluate(json("$strLenCP: 'cafétéria'"), json(""))).isEqualTo(9); assertThat(Expression.evaluate(json("$strLenCP: '$a'"), json("a: '$€λA'"))).isEqualTo(4); assertThat(Expression.evaluate(json("$strLenCP: '\u5BFF\u53F8'"), json(""))).isEqualTo(2); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$strLenCP: null"), json(""))) .withMessage("[Error 34471] $strLenCP requires a string argument, found: null"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$strLenCP: 123"), json(""))) .withMessage("[Error 34471] $strLenCP requires a string argument, found: int"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$strLenCP: '$a'"), json(""))) .withMessage("[Error 34471] $strLenCP requires a string argument, found: missing"); } @Test void testEvaluateSubstrBytes() throws Exception { assertThat(Expression.evaluate(json("$substrBytes: ['', -1, -1]"), json(""))).isEqualTo(""); assertThat(Expression.evaluate(json("$substrBytes: ['$a', 0, -1]"), json("a: 'value'"))).isEqualTo("value"); assertThat(Expression.evaluate(json("$substrBytes: ['$a', 0, 5]"), json("a: 'cafétéria'"))).isEqualTo("café"); assertThat(Expression.evaluate(json("$substrBytes: ['$a', 0, 5]"), json("a: 123"))).isEqualTo("123"); assertThat(Expression.evaluate(json("$substrBytes: ['$a', 0, '$len']"), json("a: 'hello', len: 2"))).isEqualTo("he"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$substrBytes: null"), json(""))) .withMessage("[Error 16020] Expression $substrBytes takes exactly 3 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$substrBytes: [123]"), json(""))) .withMessage("[Error 16020] Expression $substrBytes takes exactly 3 arguments. 1 were passed in."); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$substrBytes: [123, 'abc', 'def']"), json(""))) .withMessage("[Error 16034] Failed to optimize pipeline :: caused by :: $substrBytes: starting index must be a numeric type (is BSON type string)"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$substrBytes: [123, 0, 'def']"), json(""))) .withMessage("[Error 16035] Failed to optimize pipeline :: caused by :: $substrBytes: length must be a numeric type (is BSON type string)"); } @Test void testEvaluateSubstrCP() throws Exception { assertThat(Expression.evaluate(json("$substrCP: ['', -1, -1]"), json(""))).isEqualTo(""); assertThat(Expression.evaluate(json("$substrCP: ['$a', 0, -1]"), json("a: 'value'"))).isEqualTo("value"); assertThat(Expression.evaluate(json("$substrCP: ['$a', 0, 5]"), json("a: 'cafétéria'"))).isEqualTo("cafét"); assertThat(Expression.evaluate(json("$substrCP: ['$a', 0, 5]"), json("a: 123"))).isEqualTo("123"); assertThat(Expression.evaluate(json("$substrCP: ['$a', 0, '$len']"), json("a: 'hello', len: 2"))).isEqualTo("he"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$substrCP: null"), json(""))) .withMessage("[Error 16020] Expression $substrCP takes exactly 3 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$substrCP: [123]"), json(""))) .withMessage("[Error 16020] Expression $substrCP takes exactly 3 arguments. 1 were passed in."); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$substrCP: [123, 'abc', 'def']"), json(""))) .withMessage("[Error 34450] Failed to optimize pipeline :: caused by :: $substrCP: starting index must be a numeric type (is BSON type string)"); assertThatExceptionOfType(FailedToOptimizePipelineError.class) .isThrownBy(() -> Expression.evaluate(json("$substrCP: [123, 0, 'def']"), json(""))) .withMessage("[Error 34452] Failed to optimize pipeline :: caused by :: $substrCP: length must be a numeric type (is BSON type string)"); } @Test void testEvaluateYear() throws Exception { assertThat(Expression.evaluate(json("$year: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$year: '$a'"), new Document("a", toDate("2018-07-03T14:00:00Z")))).isEqualTo(2018); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$year: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateDayOfWeek() throws Exception { assertThat(Expression.evaluate(json("$dayOfWeek: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$dayOfWeek: '$a'"), new Document("a", toDate("2018-01-01T14:00:00Z")))).isEqualTo(1); assertThat(Expression.evaluate(json("$dayOfWeek: '$a'"), new Document("a", toDate("2014-02-03T14:00:00Z")))).isEqualTo(1); assertThat(Expression.evaluate(json("$dayOfWeek: '$a'"), new Document("a", toDate("2018-11-08T22:00:00Z")))).isEqualTo(4); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dayOfWeek: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateDayOfMonth() throws Exception { assertThat(Expression.evaluate(json("$dayOfMonth: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$dayOfMonth: '$a'"), new Document("a", toDate("2018-01-01T14:00:00Z")))).isEqualTo(1); assertThat(Expression.evaluate(json("$dayOfMonth: '$a'"), new Document("a", toDate("2014-02-03T14:00:00Z")))).isEqualTo(3); assertThat(Expression.evaluate(json("$dayOfMonth: '$a'"), new Document("a", toDate("2018-11-08T22:00:00Z")))).isEqualTo(8); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dayOfMonth: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateDayOfYear() throws Exception { assertThat(Expression.evaluate(json("$dayOfYear: '$a'"), json(""))).isNull(); assertThat(Expression.evaluate(json("$dayOfYear: '$a'"), new Document("a", toDate("2018-01-01T14:00:00Z")))).isEqualTo(1); assertThat(Expression.evaluate(json("$dayOfYear: '$a'"), new Document("a", toDate("2014-02-03T14:00:00Z")))).isEqualTo(34); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dayOfYear: '$a'"), json("a: 'abc'"))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testDateToString() throws Exception { Instant instant = Instant.parse("2011-12-19T10:15:20.250Z"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a'}"), json(""))).isNull(); // default format assertThat(Expression.evaluate(json("$dateToString: {date: '$a'}"), new Document("a", instant))).isEqualTo("2011-12-19T10:15:20.250Z"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', timezone: '+01:00'}"), new Document("a", instant))).isEqualTo("2011-12-19T11:15:20.250Z"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', onNull: '1970-01-01T00:00:00Z'}"), new Document("a", null))).isEqualTo("1970-01-01T00:00:00Z"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: 'foo'}"), new Document("a", instant))).isEqualTo("foo"); // test different formats (https://docs.mongodb.com/manual/reference/operator/aggregation/dateToString/#format-specifiers) assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%d'}"), new Document("a", instant))).isEqualTo("19"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%G'}"), new Document("a", instant))).isEqualTo("2011"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%H'}"), new Document("a", instant))).isEqualTo("10"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%j'}"), new Document("a", instant))).isEqualTo("353"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%L'}"), new Document("a", instant))).isEqualTo("250"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%m'}"), new Document("a", instant))).isEqualTo("12"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%M'}"), new Document("a", instant))).isEqualTo("15"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%S'}"), new Document("a", instant))).isEqualTo("20"); // assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%w'}"), new Document("a", instant))).isEqualTo("2"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: '$a', format: '%w'}"), new Document("a", instant))) .withMessage("[Error 18536] Not yet supported format character '%w' in $dateToString format string"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%u'}"), new Document("a", instant))).isEqualTo("1"); // assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%U'}"), new Document("a", instant))).isEqualTo("51"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: '$a', format: '%U'}"), new Document("a", instant))) .withMessage("[Error 18536] Not yet supported format character '%U' in $dateToString format string"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%V'}"), new Document("a", instant))).isEqualTo("51"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%Y'}"), new Document("a", instant))).isEqualTo("2011"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%z'}"), new Document("a", instant))).isEqualTo("+0000"); // assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%Z'}"), new Document("a", instant))).isEqualTo("+000"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: '$a', format: '%Z'}"), new Document("a", instant))) .withMessage("[Error 18536] Not yet supported format character '%Z' in $dateToString format string"); assertThat(Expression.evaluate(json("$dateToString: {date: '$a', format: '%%'}"), new Document("a", instant))).isEqualTo("%"); // empty format specifier assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: '$a', format: '%'}"), new Document("a", instant))) .withMessage("[Error 18535] Unmatched '%' at end of $dateToString format string"); // invalid format specifier assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: '$a', format: '% '}"), new Document("a", instant))) .withMessage("[Error 18536] Invalid format character '% ' in $dateToString format string"); // validation errors assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: ''"), json(""))) .withMessage("[Error 18629] $dateToString only supports an object as its argument"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {}"), json(""))) .withMessage("[Error 18628] Missing 'date' parameter to $dateToString"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: null, foo: 1}"), json(""))) .withMessage("[Error 18534] Unrecognized parameter to $dateToString: foo"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: null, format: 1}"), json(""))) .withMessage("[Error 18533] $dateToString requires that 'format' be a string, found: int with value 1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: null, format: '', timezone: 'foo'}"), json(""))) .withMessage("[Error 40485] $dateToString unrecognized time zone identifier: foo"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$dateToString: {date: 'foo'}"), json(""))) .withMessage("[Error 16006] can't convert from string to Date"); } @Test void testEvaluateDivide() throws Exception { assertThat(Expression.evaluate(json("$divide: ['$a', '$b']"), json("a: 8, b: 4"))).isEqualTo(2.0); assertThat(Expression.evaluate(json("$divide: [4.5, 3]"), json(""))).isEqualTo(1.5); assertThat(Expression.evaluate(json("$divide: [null, 3]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$divide: [null, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$divide: [3, null]"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$divide: []"), json(""))) .withMessage("[Error 16020] Expression $divide takes exactly 2 arguments. 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$divide: [1, 0]"), json(""))) .withMessage("[Error 16608] can't $divide by zero"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$divide: [1]"), json(""))) .withMessage("[Error 16020] Expression $divide takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$divide: 123"), json(""))) .withMessage("[Error 16020] Expression $divide takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$divide: ['a', 'b']"), json(""))) .withMessage("[Error 16609] $divide only supports numeric types, not string and string"); } @Test void testEvaluateExp() throws Exception { assertThat(Expression.evaluate(json("$exp: 0"), json(""))).isEqualTo(1.0); assertThat(Expression.evaluate(json("$exp: [0]"), json(""))).isEqualTo(1.0); assertThat((double) Expression.evaluate(json("$exp: '$a'"), json("a: 2"))).isEqualTo(7.389, Offset.offset(0.001)); assertThat((double) Expression.evaluate(json("$exp: '$a.b'"), json("a: {b: -2}"))).isEqualTo(0.135, Offset.offset(0.001)); assertThat(Expression.evaluate(json("$exp: '$doesNotExist'"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$exp: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $exp takes exactly 1 arguments. 2 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$exp: ['a']"), json(""))) .withMessage("[Error 28765] $exp only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$exp: 'a'"), json(""))) .withMessage("[Error 28765] $exp only supports numeric types, not string"); } @Test void testEvaluateFilter() throws Exception { assertThat(Expression.evaluate(json("$filter: {input: null, cond: null}"), json(""))).isNull(); assertThat(Expression.evaluate(json("$filter: {input: [1, 2, 3, 4], as: 'value', cond: {$lte: ['$$value', 3]}}"), json(""))) .isEqualTo(List.of(1, 2, 3)); assertThat(Expression.evaluate(json("$filter: {input: [1, 2, 3, 4], cond: {$lte: ['$$this', 3]}}"), json(""))) .isEqualTo(List.of(1, 2, 3)); assertThat(Expression.evaluate(json("$filter: {input: [1, 2, 3, 4], cond: {$lt: ['$$this', '$$ROOT.thresh']}}"), json("thresh: 3"))) .isEqualTo(List.of(1, 2)); assertThat(Expression.evaluate(json("$filter: {input: [1, 2, 3], cond: 1}"), json(""))) .isEqualTo(List.of(1, 2, 3)); assertThat(Expression.evaluate(json("$filter: {input: '$doesNotExist', cond: 1}"), json(""))) .isNull(); assertThat(Expression.evaluate(json("$filter: {input: '$items', as: 'item', cond: {$gte: ['$$item.price', 10]}}"), json("items: [{item_id: 1, price: 110}, {item_id: 2, price: 5}, {item_id: 3, price: 50}]"))) .isEqualTo(List.of( json("item_id: 1, price: 110"), json("item_id: 3, price: 50") )); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: 'a'"), json(""))) .withMessage("[Error 28646] $filter only supports an object as its argument"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {input: [1, 2, 3], cond: true}"), json("$this: 1"))) .withMessage("Document already contains '$this'"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {input: 'a', cond: null}"), json(""))) .withMessage("[Error 28651] input to $filter must be an array not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {}"), json(""))) .withMessage("[Error 28648] Missing 'input' parameter to $filter"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {input: null}"), json(""))) .withMessage("[Error 28648] Missing 'cond' parameter to $filter"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {input: 1, cond: 1, foo: 1}"), json(""))) .withMessage("[Error 28647] Unrecognized parameter to $filter: foo"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {input: [], as: [], cond: 1}"), json(""))) .withMessage("[Error 16866] empty variable names are not allowed"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$filter: {input: [], as: '', cond: 1}"), json(""))) .withMessage("[Error 16866] empty variable names are not allowed"); } @Test void testEvaluateFloor() throws Exception { assertThat(Expression.evaluate(json("$floor: '$a'"), json("a: 2.5"))).isEqualTo(2); assertThat(Expression.evaluate(json("$floor: 42"), json(""))).isEqualTo(42); assertThat(Expression.evaluate(json("$floor: NaN"), json(""))).isEqualTo(Double.NaN); assertThat(Expression.evaluate(json("$floor: [5.6]"), json(""))).isEqualTo(5); assertThat(Expression.evaluate(json("$floor: ['$a']"), json("a: 9.9"))).isEqualTo(9); assertThat(Expression.evaluate(json("$floor: 42.3"), json(""))).isEqualTo(42); assertThat(Expression.evaluate(new Document("$floor", (double) Long.MAX_VALUE), json(""))).isEqualTo(Long.MAX_VALUE); assertThat(Expression.evaluate(new Document("$floor", (double) Long.MIN_VALUE), json(""))).isEqualTo(Long.MIN_VALUE); assertThat(Expression.evaluate(json("$floor: null"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$floor: 'abc'"), json(""))) .withMessage("[Error 28765] $floor only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$floor: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $floor takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateIfNull() throws Exception { assertThat(Expression.evaluate(json("$ifNull: [17, 'Unspecified']"), json(""))).isEqualTo(17); assertThat(Expression.evaluate(json("$ifNull: [null, null]"), json(""))).isNull(); assertThat(Expression.evaluate(json("$ifNull: ['$desc', 'Unspecified']"), json(""))).isEqualTo("Unspecified"); assertThat(Expression.evaluate(json("$ifNull: ['$desc', 'Unspecified']"), json("desc: null"))).isEqualTo("Unspecified"); assertThat(Expression.evaluate(json("$ifNull: ['$desc', 'Unspecified']"), json("desc: 'prod1'"))).isEqualTo("prod1"); assertThat(Expression.evaluate(json("$ifNull: ['$desc', '$alt']"), json("alt: 'prod'"))).isEqualTo("prod"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ifNull: []"), json(""))) .withMessage("[Error 16020] Expression $ifNull takes exactly 2 arguments. 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ifNull: ['abc']"), json(""))) .withMessage("[Error 16020] Expression $ifNull takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ifNull: 'abc'"), json(""))) .withMessage("[Error 16020] Expression $ifNull takes exactly 2 arguments. 1 were passed in."); } @Test void testEvaluateIn() throws Exception { assertThat(Expression.evaluate(json("$in: [2, [1, 2, 3]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$in: ['abc', ['xyz', 'abc']]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$in: [['a'], ['a']]"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$in: [['a'], [['a']]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$in: ['bananas', '$fruits']"), json("fruits: ['apples', 'oranges']"))).isEqualTo(false); assertThat(Expression.evaluate(json("$in: ['bananas', '$fruits']"), json("fruits: ['apples', 'bananas', 'oranges']"))).isEqualTo(true); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$in: ['abc']"), json(""))) .withMessage("[Error 16020] Expression $in takes exactly 2 arguments. 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$in: ['a', 'b']"), json(""))) .withMessage("[Error 40081] $in requires an array as a second argument, found: string"); } @Test void testEvaluateIndexOfArray() throws Exception { assertThat(Expression.evaluate(json("$indexOfArray: [['a', 'abc'], 'a']"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$indexOfArray: [['a', 'abc', 'de', ['de']], ['de']]"), json(""))).isEqualTo(3); assertThat(Expression.evaluate(json("$indexOfArray: [[1, 2], 5]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfArray: [[1, 2, 3], [1, 2]]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfArray: [[10, 9, 9, 8, 9], 9, 3]"), json(""))).isEqualTo(4); assertThat(Expression.evaluate(json("$indexOfArray: [['a', 'abc', 'b'], 'b', 0, 1]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfArray: [['a', 'abc', 'b'], 'b', 1, 0]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfArray: [['a', 'abc', 'b'], 'b', 20]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfArray: [[null, null, null], null]"), json(""))).isEqualTo(0); assertThat(Expression.evaluate(json("$indexOfArray: [null, 'foo']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$indexOfArray: ['$items', 2]"), json("items: [3, 4, 5, 2]"))).isEqualTo(3); assertThat(Expression.evaluate(json("$indexOfArray: ['$items', 2]"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: ['a']"), json(""))) .withMessage("[Error 28667] Expression $indexOfArray takes at least 2 arguments, and at most 4, but 1 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: [['a'], 'a', 'illegalIndex']"), json(""))) .withMessage("[Error 40096] $indexOfArray requires an integral starting index, found a value of type: string, with value: \"illegalIndex\""); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: [['a'], 'a', 0, 'illegalIndex']"), json(""))) .withMessage("[Error 40096] $indexOfArray requires an integral ending index, found a value of type: string, with value: \"illegalIndex\""); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: [['a'], 'a', -1]"), json(""))) .withMessage("[Error 40097] $indexOfArray requires a nonnegative starting index, found: -1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: [['a'], 'a', 0, -1]"), json(""))) .withMessage("[Error 40097] $indexOfArray requires a nonnegative ending index, found: -1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: [1, 2, 3, 4, 5]"), json(""))) .withMessage("[Error 28667] Expression $indexOfArray takes at least 2 arguments, and at most 4, but 5 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfArray: ['a', 'b']"), json(""))) .withMessage("[Error 40090] $indexOfArray requires an array as a first argument, found: string"); } @Test void testEvaluateIndexOfBytes() throws Exception { assertThat(Expression.evaluate(json("$indexOfBytes: ['cafeteria', 'e']"), json(""))).isEqualTo(3); assertThat(Expression.evaluate(json("$indexOfBytes: ['cafétéria', 'é']"), json(""))).isEqualTo(3); assertThat(Expression.evaluate(json("$indexOfBytes: ['cafétéria', 'e']"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfBytes: ['cafétéria', 't']"), json(""))).isEqualTo(5); assertThat(Expression.evaluate(json("$indexOfBytes: ['foo.bar.fi', '.', 5]"), json(""))).isEqualTo(7); assertThat(Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', 0, 2]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', 12]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', 5, 2]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfBytes: ['vanilla', 'nilla', 3]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfBytes: [null, 'foo']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$indexOfBytes: ['$text', 'world']"), json("text: 'hello world'"))).isEqualTo(6); assertThat(Expression.evaluate(json("$indexOfBytes: ['$text', '$search']"), json("text: 'hello world', search: 'l'"))).isEqualTo(2); assertThat(Expression.evaluate(json("$indexOfBytes: ['$text', '$search']"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: []"), json(""))) .withMessage("[Error 28667] Expression $indexOfBytes takes at least 2 arguments, and at most 4, but 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: [1, 2, 3, 4, 5]"), json(""))) .withMessage("[Error 28667] Expression $indexOfBytes takes at least 2 arguments, and at most 4, but 5 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: [[], 'll']"), json(""))) .withMessage("[Error 40091] $indexOfBytes requires a string as the first argument, found: array"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: ['foo', ['x']]"), json(""))) .withMessage("[Error 40092] $indexOfBytes requires a string as the second argument, found: array"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', -1]"), json(""))) .withMessage("[Error 40097] $indexOfBytes requires a nonnegative starting index, found: -1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', 0, -1]"), json(""))) .withMessage("[Error 40097] $indexOfBytes requires a nonnegative ending index, found: -1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', 'a']"), json(""))) .withMessage("[Error 40096] $indexOfBytes requires an integral starting index, found a value of type: string, with value: \"a\""); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfBytes: ['vanilla', 'll', 0, 'b']"), json(""))) .withMessage("[Error 40096] $indexOfBytes requires an integral ending index, found a value of type: string, with value: \"b\""); } @Test void testEvaluateIndexOfCP() throws Exception { assertThat(Expression.evaluate(json("$indexOfCP: ['cafeteria', 'e']"), json(""))).isEqualTo(3); assertThat(Expression.evaluate(json("$indexOfCP: ['cafétéria', 'é']"), json(""))).isEqualTo(3); assertThat(Expression.evaluate(json("$indexOfCP: ['cafétéria', 'e']"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfCP: ['cafétéria', 't']"), json(""))).isEqualTo(4); assertThat(Expression.evaluate(json("$indexOfCP: ['foo.bar.fi', '.', 5]"), json(""))).isEqualTo(7); assertThat(Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', 0, 2]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', 12]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', 5, 2]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfCP: ['vanilla', 'nilla', 3]"), json(""))).isEqualTo(-1); assertThat(Expression.evaluate(json("$indexOfCP: [null, 'foo']"), json(""))).isNull(); assertThat(Expression.evaluate(json("$indexOfCP: ['$text', 'world']"), json("text: 'hello world'"))).isEqualTo(6); assertThat(Expression.evaluate(json("$indexOfCP: ['$text', '$search']"), json("text: 'hello world', search: 'l'"))).isEqualTo(2); assertThat(Expression.evaluate(json("$indexOfCP: ['$text', '$search']"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: []"), json(""))) .withMessage("[Error 28667] Expression $indexOfCP takes at least 2 arguments, and at most 4, but 0 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: [1, 2, 3, 4, 5]"), json(""))) .withMessage("[Error 28667] Expression $indexOfCP takes at least 2 arguments, and at most 4, but 5 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: [[], 'll']"), json(""))) .withMessage("[Error 40093] $indexOfCP requires a string as the first argument, found: array"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: ['foo', ['x']]"), json(""))) .withMessage("[Error 40094] $indexOfCP requires a string as the second argument, found: array"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', -1]"), json(""))) .withMessage("[Error 40097] $indexOfCP requires a nonnegative starting index, found: -1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', 0, -1]"), json(""))) .withMessage("[Error 40097] $indexOfCP requires a nonnegative ending index, found: -1"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', 'a']"), json(""))) .withMessage("[Error 40096] $indexOfCP requires an integral starting index, found a value of type: string, with value: \"a\""); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$indexOfCP: ['vanilla', 'll', 0, 'b']"), json(""))) .withMessage("[Error 40096] $indexOfCP requires an integral ending index, found a value of type: string, with value: \"b\""); } @Test void testEvaluateIsArray() throws Exception { assertThat(Expression.evaluate(json("$isArray: ['hello']"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$isArray: [[2, 3]]"), json(""))).isEqualTo(true); assertThat(Expression.evaluate(json("$isArray: 'foo'}"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$isArray: null}"), json(""))).isEqualTo(false); assertThat(Expression.evaluate(json("$isArray: '$value'}"), json("value: 'abc'"))).isEqualTo(false); assertThat(Expression.evaluate(json("$isArray: '$value'}"), json("value: ['abc']"))).isEqualTo(true); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$isArray: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $isArray takes exactly 1 arguments. 2 were passed in."); } @Test void testEvaluateLiteral() throws Exception { assertThat(Expression.evaluate(json("$literal: {$add: [2, 3]}"), json(""))).isEqualTo(json("$add: [2, 3]")); assertThat(Expression.evaluate(json("$literal: {$literal: 1}"), json(""))).isEqualTo(json("$literal: 1")); } @Test void testEvaluateLn() throws Exception { assertThat(Expression.evaluate(json("$ln: 1"), json(""))).isEqualTo(0.0); assertThat(Expression.evaluate(json("$ln: [1]"), json(""))).isEqualTo(0.0); assertThat((double) Expression.evaluate(json("$ln: '$a'"), json("a: 10"))).isEqualTo(2.302, Offset.offset(0.001)); assertThat(Expression.evaluate(json("$ln: '$a.b'"), json("a: {b: -2}"))).isEqualTo(Double.NaN); assertThat(Expression.evaluate(json("$ln: '$doesNotExist'"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ln: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $ln takes exactly 1 arguments. 2 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ln: ['a']"), json(""))) .withMessage("[Error 28765] $ln only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$ln: 'a'"), json(""))) .withMessage("[Error 28765] $ln only supports numeric types, not string"); } @Test void testEvaluateLog() throws Exception { assertThat(Expression.evaluate(json("$log: 1"), json(""))).isEqualTo(0.0); assertThat(Expression.evaluate(json("$log: [1]"), json(""))).isEqualTo(0.0); assertThat((double) Expression.evaluate(json("$log: '$a'"), json("a: 10"))).isEqualTo(2.302, Offset.offset(0.001)); assertThat(Expression.evaluate(json("$log: '$a.b'"), json("a: {b: -2}"))).isEqualTo(Double.NaN); assertThat(Expression.evaluate(json("$log: '$doesNotExist'"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$log: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $log takes exactly 1 arguments. 2 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$log: ['a']"), json(""))) .withMessage("[Error 28765] $log only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$log: 'a'"), json(""))) .withMessage("[Error 28765] $log only supports numeric types, not string"); } @Test void testEvaluateLog10() throws Exception { assertThat(Expression.evaluate(json("$log10: 1"), json(""))).isEqualTo(0.0); assertThat(Expression.evaluate(json("$log10: 10"), json(""))).isEqualTo(1.0); assertThat(Expression.evaluate(json("$log10: 100"), json(""))).isEqualTo(2.0); assertThat(Expression.evaluate(json("$log10: 1000"), json(""))).isEqualTo(3.0); assertThat(Expression.evaluate(json("$log10: [1]"), json(""))).isEqualTo(0.0); assertThat((double) Expression.evaluate(json("$log10: '$a'"), json("a: 20"))).isEqualTo(1.301, Offset.offset(0.001)); assertThat(Expression.evaluate(json("$log10: '$a.b'"), json("a: {b: -2}"))).isEqualTo(Double.NaN); assertThat(Expression.evaluate(json("$log10: '$doesNotExist'"), json(""))).isNull(); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$log10: [1, 2]"), json(""))) .withMessage("[Error 16020] Expression $log10 takes exactly 1 arguments. 2 were passed in."); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$log10: ['a']"), json(""))) .withMessage("[Error 28765] $log10 only supports numeric types, not string"); assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$log10: 'a'"), json(""))) .withMessage("[Error 28765] $log10 only supports numeric types, not string"); } @Test void testEvaluateIllegalExpression() throws Exception { assertThatExceptionOfType(MongoServerError.class) .isThrownBy(() -> Expression.evaluate(json("$foo: '$a'"), json(""))) .withMessage("[Error 168] Unrecognized expression '$foo'"); } @Test void testEvaluateDocument_SimpleExpression() throws Exception { Object evaluatedDocument = Expression.evaluateDocument(json("key: '$key2'"), json("key2: 123")); assertThat(evaluatedDocument).isEqualTo(json("key: 123")); } @Test void testEvaluateDocument_NullValue() throws Exception { Object evaluatedDocument = Expression.evaluateDocument(json("key: '$value'"), json("value: null")); assertThat(evaluatedDocument).isEqualTo(json("key: null")); } // https://github.com/bwaldvogel/mongo-java-server/issues/111 @Test void testEvaluateDocument_MissingValue() throws Exception { Object evaluatedDocument = Expression.evaluateDocument(json("key: '$missing'"), json("")); assertThat(evaluatedDocument).isEqualTo(json("")); } private static Instant toDate(String instant) { return Instant.parse(instant); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/ReadOnlyProxy.java package de.bwaldvogel.mongo.backend; import java.time.Clock; import java.util.Collection; import java.util.List; import java.util.Set; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.ServerVersion; import de.bwaldvogel.mongo.backend.aggregation.Aggregation; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerException; import de.bwaldvogel.mongo.exception.NoSuchCommandException; import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; import io.netty.channel.Channel; public class ReadOnlyProxy implements MongoBackend { private static final Set<String> allowedCommands = Set.of( "ismaster", "find", "listdatabases", "count", "dbstats", "distinct", "collstats", "serverstatus", "buildinfo", "getlasterror", "getmore" ); private final MongoBackend backend; public ReadOnlyProxy(MongoBackend backend) { this.backend = backend; } public static class ReadOnlyException extends MongoServerException { private static final long serialVersionUID = 1L; ReadOnlyException(String message) { super(message); } } @Override public void handleClose(Channel channel) { backend.handleClose(channel); } @Override public Document handleCommand(Channel channel, String database, String command, Document query) { if (isAllowed(command, query)) { return backend.handleCommand(channel, database, command, query); } throw new NoSuchCommandException(command); } private static boolean isAllowed(String command, Document query) { if (allowedCommands.contains(command.toLowerCase())) { return true; } if (command.equalsIgnoreCase("aggregate")) { List<Document> pipeline = Aggregation.parse(query.get("pipeline")); Aggregation aggregation = Aggregation.fromPipeline(pipeline, null, null, null, null); if (aggregation.isModifying()) { throw new MongoServerException("Aggregation contains a modifying stage and is therefore not allowed in read-only mode"); } return true; } return false; } @Override public Document handleMessage(MongoMessage message) { Document document = message.getDocument(); String command = document.keySet().iterator().next().toLowerCase(); if (isAllowed(command, document)) { return backend.handleMessage(message); } throw new NoSuchCommandException(command); } @Override public Collection<Document> getCurrentOperations(MongoQuery query) { return backend.getCurrentOperations(query); } @Override public QueryResult handleQuery(MongoQuery query) { return backend.handleQuery(query); } @Override public void dropDatabase(String database) { throw new ReadOnlyException("dropping of databases is not allowed"); } @Override public MongoBackend version(ServerVersion version) { throw new ReadOnlyException("not supported"); } @Override public MongoDatabase resolveDatabase(String database) { throw new ReadOnlyException("resolveDatabase not allowed"); } @Override public Document getServerStatus() { return backend.getServerStatus(); } @Override public void close() { backend.close(); } @Override public Clock getClock() { return backend.getClock(); } @Override public void enableOplog() { } @Override public void disableOplog() { } @Override public void closeCursors(List<Long> cursorIds) { backend.closeCursors(cursorIds); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/wire/MongoDatabaseHandlerTest.java package de.bwaldvogel.mongo.wire; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.wire.message.MessageHeader; import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; import io.netty.channel.Channel; class MongoDatabaseHandlerTest { @Test void testWrappedCommand() throws Exception { MongoBackend backend = mock(MongoBackend.class); Channel channel = mock(Channel.class); Document queryDoc = json("'$query': { 'count': 'collectionName' }, '$readPreference': { 'mode': 'secondaryPreferred' }"); Document subQueryDoc = json("'count': 'collectionName'"); MongoQuery query = new MongoQuery(channel, null, "dbName.$cmd", 0, 0, queryDoc, null); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); handler.handleCommand(query); verify(backend).handleCommand(channel, "dbName", "count", subQueryDoc); } @Test void testNonWrappedCommand() throws Exception { MongoBackend backend = mock(MongoBackend.class); Channel channel = mock(Channel.class); Document queryDoc = json("'count': 'collectionName'"); MongoQuery query = new MongoQuery(channel, null, "dbName.$cmd", 0, 0, queryDoc, null); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); handler.handleCommand(query); verify(backend).handleCommand(channel, "dbName", "count", queryDoc); } @Test void testHandleMessageUnknownError() throws Exception { MongoBackend backend = mock(MongoBackend.class); when(backend.handleMessage(any())).thenThrow(new RuntimeException("unexpected")); Channel channel = mock(Channel.class); MessageHeader header = new MessageHeader(0, 0); MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); MongoMessage requestMessage = new MongoMessage(channel, header, new Document("key", "1")); MongoMessage responseMessage = handler.handleMessage(requestMessage); assertThat(responseMessage).isNotNull(); Document responseMessageDoc = responseMessage.getDocument(); assertThat(responseMessageDoc).isNotNull(); assertThat(responseMessageDoc.get("$err")).isEqualTo("Unknown error: unexpected"); assertThat(responseMessageDoc.get("errmsg")).isEqualTo("Unknown error: unexpected"); assertThat(responseMessageDoc.get("ok")).isEqualTo(0); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/NumericUtilsTest.java package de.bwaldvogel.mongo.backend; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.math.BigDecimal; import org.assertj.core.data.Offset; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Decimal128; public class NumericUtilsTest { @Test void testAddNumbers() { assertThat(NumericUtils.addNumbers(-4, 3)).isEqualTo(-1); assertThat(NumericUtils.addNumbers(-0.1, 0.1)).isEqualTo(0.0); assertThat(NumericUtils.addNumbers(0.9, 0.1)).isEqualTo(1.0); assertThat(NumericUtils.addNumbers(4.3f, 7.1f)).isEqualTo(11.4f); assertThat(NumericUtils.addNumbers((short) 4, (short) 7)).isEqualTo((short) 11); assertThat(NumericUtils.addNumbers((short) 30000, (short) 20000)).isEqualTo(50000L); assertThat(NumericUtils.addNumbers(4L, 7.3)).isEqualTo(11.3); assertThat(NumericUtils.addNumbers(100000000000000L, 100000000000000L)).isEqualTo(200000000000000L); assertThat(NumericUtils.addNumbers(2000000000, 2000000000)).isEqualTo(4000000000L); assertThat(NumericUtils.addNumbers(Decimal128.fromNumber(1L), Decimal128.fromNumber(2.5))).isEqualTo(Decimal128.fromNumber(3.5)); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> NumericUtils.addNumbers(new BigDecimal(1), new BigDecimal(1))) .withMessage("cannot calculate on 1 and 1"); } @Test void testSubtractNumbers() { assertThat(NumericUtils.subtractNumbers(-4, 3)).isEqualTo(-7); assertThat(NumericUtils.subtractNumbers(0.1, 0.1)).isEqualTo(0.0); assertThat(NumericUtils.subtractNumbers(1.1, 0.1)).isEqualTo(1.0); assertThat(NumericUtils.subtractNumbers(7.6f, 4.1f)).isEqualTo(3.5f); assertThat(NumericUtils.subtractNumbers((short) 4, (short) 7)).isEqualTo((short) -3); assertThat(NumericUtils.subtractNumbers((short) 30000, (short) -20000)).isEqualTo(50000L); assertThat(NumericUtils.subtractNumbers(4L, 7.3)).isEqualTo(-3.3); assertThat(NumericUtils.subtractNumbers(100000000000000L, 1L)).isEqualTo(99999999999999L); assertThat(NumericUtils.subtractNumbers(-2000000000, 2000000000)).isEqualTo(-4000000000L); assertThat(NumericUtils.subtractNumbers(Decimal128.fromNumber(1005L), Decimal128.fromNumber(2.5))).isEqualTo(Decimal128.fromNumber(1002.5)); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> NumericUtils.subtractNumbers(new BigDecimal(1), new BigDecimal(1))) .withMessage("cannot calculate on 1 and 1"); } @Test void testMultiplyNumbers() { assertThat(NumericUtils.multiplyNumbers(-4, 3)).isEqualTo(-12); assertThat((double) NumericUtils.multiplyNumbers(0.1, 0.1)).isEqualTo(0.01, Offset.offset(0.0001)); assertThat((double) NumericUtils.multiplyNumbers(1.1, 0.1)).isEqualTo(0.11, Offset.offset(0.0001)); assertThat(NumericUtils.multiplyNumbers(2.0f, 4.0f)).isEqualTo(8.0f); assertThat(NumericUtils.multiplyNumbers((short) 4, (short) 7)).isEqualTo((short) 28); assertThat(NumericUtils.multiplyNumbers((short) 400, (short) 700)).isEqualTo(280000L); assertThat(NumericUtils.multiplyNumbers(100000000000000L, 10)).isEqualTo(1000000000000000L); assertThat(NumericUtils.multiplyNumbers(50000, 100000)).isEqualTo(5000000000L); assertThat(NumericUtils.multiplyNumbers(Decimal128.fromNumber(1000), Decimal128.fromNumber(2000.5))).isEqualTo(Decimal128.fromNumber(2000500.0)); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> NumericUtils.multiplyNumbers(new BigDecimal(1), new BigDecimal(1))) .withMessage("cannot calculate on 1 and 1"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/MongoWireMessageEncoder.java package de.bwaldvogel.mongo.wire; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.wire.bson.BsonEncoder; import de.bwaldvogel.mongo.wire.message.MongoMessage; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class MongoWireMessageEncoder extends MessageToByteEncoder<MongoMessage> { private static final Logger log = LoggerFactory.getLogger(MongoWireMessageEncoder.class); @Override protected void encode(ChannelHandlerContext ctx, MongoMessage message, ByteBuf buf) { buf.writeIntLE(0); // write length later buf.writeIntLE(message.getHeader().getRequestID()); buf.writeIntLE(message.getHeader().getResponseTo()); buf.writeIntLE(OpCode.OP_MSG.getId()); buf.writeIntLE(message.getFlags()); buf.writeByte(MongoMessage.SECTION_KIND_BODY); Document document = message.getDocument(); try { BsonEncoder.encodeDocument(document, buf); } catch (RuntimeException e) { log.error("Failed to encode {}", document, e); ctx.channel().close(); throw e; } log.debug("wrote message: {}", message); // now set the length int writerIndex = buf.writerIndex(); buf.setIntLE(0, writerIndex); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/wire/MongoWireMessageEncoderTest.java package de.bwaldvogel.mongo.wire; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import de.bwaldvogel.mongo.backend.Missing; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.wire.message.MessageHeader; import de.bwaldvogel.mongo.wire.message.MongoMessage; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; @ExtendWith(MockitoExtension.class) public class MongoWireMessageEncoderTest { @Mock private ChannelHandlerContext ctx; @Mock private Channel channel; @BeforeEach void setUpContext() throws Exception { when(ctx.channel()).thenReturn(channel); } @Test void testExceptionHandling() throws Exception { MongoWireMessageEncoder mongoWireEncoder = new MongoWireMessageEncoder(); MessageHeader header = new MessageHeader(0, 0); MongoMessage reply = new MongoMessage(channel, header, new Document("key", Missing.getInstance())); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> mongoWireEncoder.encode(ctx, reply, Unpooled.buffer())) .withMessageContaining("Unexpected missing value. This must not happen. Please report a bug."); verify(channel).close(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/MongoServer.java package de.bwaldvogel.mongo; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.List; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.backend.Assert; import de.bwaldvogel.mongo.wire.MongoDatabaseHandler; import de.bwaldvogel.mongo.wire.MongoExceptionHandler; import de.bwaldvogel.mongo.wire.MongoWireMessageEncoder; import de.bwaldvogel.mongo.wire.MongoWireProtocolHandler; import de.bwaldvogel.mongo.wire.MongoWireReplyEncoder; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; public class MongoServer { private static final Logger log = LoggerFactory.getLogger(MongoServer.class); private static final int DEFAULT_NETTY_EVENT_LOOP_THREADS = 0; private final MongoBackend backend; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private ChannelGroup channelGroup; private Channel channel; private SslContext sslContext; public MongoServer(MongoBackend backend) { this.backend = backend; } public void enableOplog() { this.backend.enableOplog(); } public void enableSsl(PrivateKey key, String keyPassword, X509Certificate... keyCertChain) { Assert.isNull(channel, () -> "Server already started"); try { sslContext = SslContextBuilder.forServer(key, keyPassword, keyCertChain).build(); } catch (SSLException e) { throw new RuntimeException("Failed to enable SSL", e); } } public void bind(String hostname, int port) { bind(new InetSocketAddress(hostname, port)); } public void bind(SocketAddress socketAddress) { bind(socketAddress, DEFAULT_NETTY_EVENT_LOOP_THREADS, DEFAULT_NETTY_EVENT_LOOP_THREADS); } public void bind(SocketAddress socketAddress, int numberOfBossThreads, int numberOfWorkerThreads) { bossGroup = new NioEventLoopGroup(numberOfBossThreads, new MongoThreadFactory("mongo-server-boss")); workerGroup = new NioEventLoopGroup(numberOfWorkerThreads, new MongoThreadFactory("mongo-server-worker")); channelGroup = new DefaultChannelGroup("mongodb-channels", workerGroup.next()); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .localAddress(socketAddress) .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (sslContext != null) { ch.pipeline().addLast(sslContext.newHandler(ch.alloc())); } ch.pipeline().addLast(new MongoWireReplyEncoder()); ch.pipeline().addLast(new MongoWireMessageEncoder()); ch.pipeline().addLast(new MongoWireProtocolHandler()); ch.pipeline().addLast(new MongoDatabaseHandler(backend, channelGroup)); ch.pipeline().addLast(new MongoExceptionHandler()); } }); channel = bootstrap.bind().syncUninterruptibly().channel(); log.info("started {}", this); } catch (RuntimeException e) { shutdownNow(); throw e; } } /** * Starts and binds the server on a local random port * <p> * Note: For modern clients you probably want to use {@link #bindAndGetConnectionString()} instead! * * @return the random local address the server was bound to */ public InetSocketAddress bind() { bind(new InetSocketAddress("localhost", 0)); return getLocalAddress(); } /** * starts and binds the server on a local random port * * @return the MongoDB connection string to connect to this server. Example: mongodb://localhost:12345 */ public String bindAndGetConnectionString() { bind(); return getConnectionString(); } /** * @return the local address the server was bound or null if the server is not listening */ public InetSocketAddress getLocalAddress() { if (channel == null) { return null; } return (InetSocketAddress) channel.localAddress(); } /** * @return the MongoDB connection string to connect to this server. Example: mongodb://localhost:12345 */ public String getConnectionString() { final String options; if (sslContext != null) { options = "/?tls=true"; } else { options = ""; } InetSocketAddress socketAddress = getLocalAddress(); return "mongodb://" + socketAddress.getHostString() + ":" + socketAddress.getPort() + options; } /** * Stop accepting new clients. Wait until all resources (such as client * connection) are closed and then shutdown. This method blocks until all * clients are finished. Use {@link #shutdownNow()} if the shutdown should * be forced. */ public void shutdown() { stopListening(); // Shut down all event loops to terminate all threads. if (bossGroup != null) { bossGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS); } if (workerGroup != null) { workerGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS); } if (bossGroup != null) { bossGroup.terminationFuture().syncUninterruptibly(); } if (workerGroup != null) { workerGroup.terminationFuture().syncUninterruptibly(); } backend.close(); log.info("completed shutdown of {}", this); } /** * Closes the server socket. No new clients are accepted afterwards. */ public void stopListening() { if (channel != null) { log.info("closing server channel"); channel.close().syncUninterruptibly(); channel = null; } } /** * Stops accepting new clients, closes all clients and finally shuts down * the server In contrast to {@link #shutdown()}, this method should not * block. */ public void shutdownNow() { stopListening(); closeClients(); shutdown(); } private void closeClients() { if (channelGroup != null) { int numClients = channelGroup.size(); if (numClients > 0) { log.warn("Closing {} clients", numClients); } channelGroup.close().syncUninterruptibly(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName()); sb.append("("); InetSocketAddress socketAddress = getLocalAddress(); if (socketAddress != null) { sb.append("port: ").append(socketAddress.getPort()); sb.append(", ssl: ").append(sslContext != null); } sb.append(")"); return sb.toString(); } /** * Use this method to simulate closing of cursors by the server, for instance due to timeout. */ public void closeCursors(List<Long> cursorIds) { backend.closeCursors(cursorIds); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/Document.java package de.bwaldvogel.mongo.bson; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import de.bwaldvogel.mongo.backend.Missing; public final class Document implements Map<String, Object>, Bson { private static final long serialVersionUID = 1L; private final LinkedHashMap<String, Object> documentAsMap = new LinkedHashMap<>(); public Document() { } public Document(String key, Object value) { this(); append(key, value); } public Document(Map<String, ?> map) { this(); putAll(map); } public void cloneInto(Document targetDocument) { for (Entry<String, Object> entry : entrySet()) { targetDocument.put(entry.getKey(), cloneDeeply(entry.getValue())); } } public Document cloneDeeply() { return cloneDeeply(this); } @SuppressWarnings("unchecked") private static <T> T cloneDeeply(T object) { if (object == null) { return null; } else if (object instanceof Document) { Document document = (Document) object; Document clone = document.clone(); for (String key : document.keySet()) { clone.put(key, cloneDeeply(clone.get(key))); } return (T) clone; } else if (object instanceof List) { List<?> list = (List<?>) object; List<?> result = list.stream() .map(Document::cloneDeeply) .collect(Collectors.toList()); return (T) result; } else if (object instanceof Set) { Set<?> set = (Set<?>) object; Set<?> result = set.stream() .map(Document::cloneDeeply) .collect(Collectors.toCollection(LinkedHashSet::new)); return (T) result; } else { return object; } } public Document append(String key, Object value) { put(key, value); return this; } public Document appendAll(Map<String, Object> map) { putAll(map); return this; } @Override public boolean containsValue(Object value) { return documentAsMap.containsValue(value); } @Override public Object get(Object key) { return documentAsMap.get(key); } public Object getOrMissing(Object key) { return getOrDefault(key, Missing.getInstance()); } @Override public void clear() { documentAsMap.clear(); } @Override public int size() { return documentAsMap.size(); } @Override public boolean isEmpty() { return documentAsMap.isEmpty(); } @Override public boolean containsKey(Object key) { return documentAsMap.containsKey(key); } @Override public Object put(String key, Object value) { return documentAsMap.put(key, value); } public void putIfNotNull(String key, Object value) { if (value != null) { put(key, value); } } @Override public void putAll(Map<? extends String, ?> m) { documentAsMap.putAll(m); } @Override public Object remove(Object key) { return documentAsMap.remove(key); } @Override @SuppressWarnings("unchecked") public Document clone() { return new Document((Map<String, Object>) documentAsMap.clone()); } @Override public Set<String> keySet() { return documentAsMap.keySet(); } @Override public Collection<Object> values() { return documentAsMap.values(); } @Override public Set<Entry<String, Object>> entrySet() { return documentAsMap.entrySet(); } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!(o instanceof Document)) { return false; } List<String> keys = new ArrayList<>(keySet()); List<String> otherKeys = new ArrayList<>(((Document) o).keySet()); if (!keys.equals(otherKeys)) { return false; } return documentAsMap.equals(o); } @Override public int hashCode() { return documentAsMap.hashCode(); } @Override public String toString() { return toString(false); } public String toString(boolean compactKey) { return toString(compactKey, "{", "}"); } public String toString(boolean compactKey, String prefix, String suffix) { return documentAsMap.entrySet().stream() .map(entry -> writeKey(entry.getKey(), compactKey) + " " + Json.toJsonValue(entry.getValue(), compactKey, prefix, suffix)) .collect(Collectors.joining(", ", prefix, suffix)); } private String writeKey(String key, boolean compact) { if (compact) { return Json.escapeJson(key) + ":"; } else { return "\"" + Json.escapeJson(key) + "\" :"; } } public void merge(Document value) { putAll(value); } } <file_sep>/settings.gradle include 'core' include 'memory-backend' include 'h2-backend' include 'postgresql-backend' include 'test-common' include 'examples' rootProject.children.each { it.name = rootProject.name + "-" + it.name } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MatchStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.stream.Stream; import de.bwaldvogel.mongo.backend.DefaultQueryMatcher; import de.bwaldvogel.mongo.backend.QueryMatcher; import de.bwaldvogel.mongo.bson.Document; public class MatchStage implements AggregationStage { private final QueryMatcher queryMatcher = new DefaultQueryMatcher(); private final Document query; public MatchStage(Document query) { this.query = query; } @Override public String name() { return "$match"; } @Override public Stream<Document> apply(Stream<Document> stream) { return stream.filter(document -> queryMatcher.matches(document, query)); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/bson/LegacyUUIDTest.java package de.bwaldvogel.mongo.bson; import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; import org.junit.jupiter.api.Test; import nl.jqno.equalsverifier.EqualsVerifier; class LegacyUUIDTest { @Test void testEqualsAndHashCode() throws Exception { EqualsVerifier.forClass(LegacyUUID.class) .withNonnullFields("uuid") .verify(); } @Test void testCompare() throws Exception { UUID uuid0 = UUID.fromString("00000000-0000-0000-0000-000000000000"); UUID uuid1 = UUID.fromString("48fe9251-9502-4d43-bd81-b8861eb69dc5"); UUID uuid2 = UUID.fromString("cb6bdaa5-d134-4244-9383-ccded62a7bb3"); UUID uuid3 = UUID.fromString("ffffffff-ffff-ffff-ffff-ffffffffffff"); assertComparesLessThan(uuid0, uuid1); assertComparesLessThan(uuid2, uuid0); assertComparesLessThan(uuid2, uuid1); assertComparesLessThan(uuid2, uuid3); assertComparesLessThan(uuid3, uuid0); } private static void assertComparesLessThan(UUID a, UUID b) { assertComparesEqual(a); assertComparesEqual(b); assertThat(new LegacyUUID(a).compareTo(new LegacyUUID(b))).as(a + " < " + b).isEqualTo(-1); assertThat(new LegacyUUID(b).compareTo(new LegacyUUID(a))).as(b + " > " + a).isEqualTo(1); } private static void assertComparesEqual(UUID uuid) { assertThat(new LegacyUUID(uuid).compareTo(new LegacyUUID(uuid))).isEqualTo(0); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/LookupStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import static java.util.stream.Collectors.toList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.bson.Document; public class LookupStage extends AbstractLookupStage { private static final String LOCAL_FIELD = "localField"; private static final String FOREIGN_FIELD = "foreignField"; private static final Set<String> CONFIGURATION_KEYS; static { CONFIGURATION_KEYS = new HashSet<>(); CONFIGURATION_KEYS.add(FROM); CONFIGURATION_KEYS.add(LOCAL_FIELD); CONFIGURATION_KEYS.add(FOREIGN_FIELD); CONFIGURATION_KEYS.add(AS); } private final String localField; private final String foreignField; private final String as; private final MongoCollection<?> collection; public LookupStage(Document configuration, MongoDatabase mongoDatabase) { String from = readStringConfigurationProperty(configuration, FROM); collection = mongoDatabase.resolveCollection(from, false); localField = readStringConfigurationProperty(configuration, LOCAL_FIELD); foreignField = readStringConfigurationProperty(configuration, FOREIGN_FIELD); as = readStringConfigurationProperty(configuration, AS); ensureAllConfigurationPropertiesAreKnown(configuration, CONFIGURATION_KEYS); } @Override public Stream<Document> apply(Stream<Document> stream) { return stream.map(this::resolveRemoteField); } private Document resolveRemoteField(Document document) { Object value = Utils.getSubdocumentValue(document, localField); List<Document> documents = lookupValue(value); Document result = document.clone(); result.put(as, documents); return result; } private List<Document> lookupValue(Object value) { if (collection == null) { return Collections.emptyList(); } if (value instanceof List) { return ((List<?>) value).stream() .flatMap(item -> lookupValue(item).stream()) .collect(toList()); } Document query = new Document(foreignField, value); return collection.handleQueryAsStream(query).collect(toList()); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/DocumentComparatorTest.java package de.bwaldvogel.mongo.backend; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; class DocumentComparatorTest { @Test void testCompareSingleKey() { DocumentComparator comparator = new DocumentComparator(json("a: 1")); List<Document> list = Stream.of( json("a: 10"), json("a: 15"), json("a: 5"), json("b: 1")) .sorted(comparator) .collect(Collectors.toList()); assertThat(list).containsExactly( json("b: 1"), json("a: 5"), json("a: 10"), json("a: 15")); } @Test void testCompareMultiKey() { DocumentComparator comparator = new DocumentComparator(json("a: 1, b: -1")); List<Document> list = new ArrayList<>(List.of( json("a: 15, b: 3"), json("a: 15, b: 2"), json("a: 5"), json("b: 1"), json("b: 2"), json("b: 3"))); Random rnd = new Random(4711); for (int i = 0; i < 10; i++) { Collections.shuffle(list, rnd); list.sort(comparator); assertThat(list).containsExactly( json("b: 3"), json("b: 2"), json("b: 1"), json("a: 5"), json("a: 15, b: 3"), json("a: 15, b: 2")); } } @Test void testCompareCompoundKey() throws Exception { DocumentComparator comparator = new DocumentComparator(json("'a.b': 1, c: -1")); Document a = json("a: {b: 10}"); Document b = json("a: {b: 15}"); Document c = json("a: {b: 15, x: 70}"); assertThat(comparator.compare(a, b)).isLessThan(0); assertThat(comparator.compare(b, a)).isGreaterThan(0); assertThat(comparator.compare(b, c)).isZero(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/Index.java package de.bwaldvogel.mongo.backend; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.CannotIndexParallelArraysError; import de.bwaldvogel.mongo.exception.KeyConstraintError; public abstract class Index<P> { private final String name; private final List<IndexKey> keys; private final boolean sparse; protected Index(String name, List<IndexKey> keys, boolean sparse) { this.name = name; this.keys = keys; this.sparse = sparse; } protected boolean isSparse() { return sparse; } public List<IndexKey> getKeys() { return keys; } public boolean hasSameOptions(Index<?> other) { return sparse == other.sparse; } public String getName() { return name; } protected List<String> keys() { return keys.stream() .map(IndexKey::getKey) .collect(Collectors.toList()); } protected Set<String> keySet() { return keys.stream() .map(IndexKey::getKey) .collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<KeyValue> getKeyValues(Document document) { return getKeyValues(document, true); } Set<KeyValue> getKeyValues(Document document, boolean normalize) { Map<String, Object> valuesPerKey = collectValuesPerKey(document); if (normalize) { valuesPerKey.replaceAll((key, value) -> Utils.normalizeValue(value)); } List<Collection<Object>> collectionValues = valuesPerKey.values().stream() .filter(value -> value instanceof Collection) .map(value -> (Collection<Object>) value) .collect(Collectors.toList()); if (collectionValues.size() > 0) { validateHasNoParallelArrays(document); return CollectionUtils.multiplyWithOtherElements(valuesPerKey.values(), collectionValues).stream() .map(KeyValue::new) .collect(StreamUtils.toLinkedHashSet()); } else { return Set.of(new KeyValue(valuesPerKey.values())); } } private void validateHasNoParallelArrays(Document document) { Set<List<String>> arrayPaths = new LinkedHashSet<>(); for (String key : keys()) { List<String> pathToFirstCollection = getPathToFirstCollection(document, key); if (pathToFirstCollection != null) { arrayPaths.add(pathToFirstCollection); } } if (arrayPaths.size() > 1) { List<String> parallelArraysPaths = arrayPaths.stream() .map(path -> path.get(path.size() - 1)) .collect(Collectors.toList()); throw new CannotIndexParallelArraysError(parallelArraysPaths); } } private static List<String> getPathToFirstCollection(Document document, String key) { List<String> fragments = Utils.splitPath(key); List<String> remainingFragments = Utils.getTail(fragments); return getPathToFirstCollection(document, remainingFragments, List.of(fragments.get(0))); } private static List<String> getPathToFirstCollection(Document document, List<String> remainingFragments, List<String> path) { Object value = Utils.getSubdocumentValue(document, Utils.joinPath(path)); if (value instanceof Collection) { return path; } if (remainingFragments.isEmpty()) { return null; } List<String> newPath = new ArrayList<>(path); newPath.add(remainingFragments.get(0)); return getPathToFirstCollection(document, Utils.getTail(remainingFragments), newPath); } private Map<String, Object> collectValuesPerKey(Document document) { Map<String, Object> valuesPerKey = new LinkedHashMap<>(); for (String key : keys()) { Object value = Utils.getSubdocumentValueCollectionAware(document, key); valuesPerKey.put(key, value); } return valuesPerKey; } public abstract P getPosition(Document document); public abstract void checkAdd(Document document, MongoCollection<P> collection); public abstract void add(Document document, P position, MongoCollection<P> collection); public abstract P remove(Document document); public abstract boolean canHandle(Document query); public abstract Iterable<P> getPositions(Document query); public abstract long getCount(); public boolean isEmpty() { return getCount() == 0; } public abstract long getDataSize(); public abstract void checkUpdate(Document oldDocument, Document newDocument, MongoCollection<P> collection); public abstract void updateInPlace(Document oldDocument, Document newDocument, P position, MongoCollection<P> collection) throws KeyConstraintError; protected boolean isCompoundIndex() { return keys().size() > 1; } protected boolean nullAwareEqualsKeys(Document oldDocument, Document newDocument) { Set<KeyValue> oldKeyValues = getKeyValues(oldDocument); Set<KeyValue> newKeyValues = getKeyValues(newDocument); return Utils.nullAwareEquals(oldKeyValues, newKeyValues); } public abstract void drop(); @Override public String toString() { return getClass().getSimpleName() + "[name=" + getName() + "]"; } public boolean isUnique() { return false; } public Document toIndexDescription() { Document indexDescription = new Document("v", 2) .append("unique", isUnique()); Document key = new Document(); for (IndexKey indexKey : getKeys()) { key.put(indexKey.getKey(), indexKey.isAscending() ? 1 : -1); } indexDescription.put("key", key); indexDescription.put("name", getName()); if (isSparse()) { indexDescription.put("sparse", true); } return indexDescription; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/BucketStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import de.bwaldvogel.mongo.backend.Assert; import de.bwaldvogel.mongo.backend.CollectionUtils; import de.bwaldvogel.mongo.backend.Constants; import de.bwaldvogel.mongo.backend.Missing; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.backend.ValueComparator; import de.bwaldvogel.mongo.backend.aggregation.Expression; import de.bwaldvogel.mongo.backend.aggregation.accumulator.Accumulator; import de.bwaldvogel.mongo.backend.aggregation.accumulator.SumAccumulator; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.Json; import de.bwaldvogel.mongo.exception.MongoServerError; public class BucketStage implements AggregationStage { private final Object groupByExpression; private final List<?> boundaries; private final Object defaultValue; private final Document output; public BucketStage(Document document) { groupByExpression = validateGroupBy(document.get("groupBy")); boundaries = getAndValidateBoundaries(document.get("boundaries")); defaultValue = getAndValidateDefault(document.getOrMissing("default")); output = getAndValidateOutput(document.get("output")); } @Override public String name() { return "$bucket"; } private void validateValuePresent(Object value) { if (value == null) { throw new MongoServerError(40198, "$bucket requires 'groupBy' and 'boundaries' to be specified."); } } private Object validateGroupBy(Object groupBy) { validateValuePresent(groupBy); if (!(groupBy instanceof String || groupBy instanceof Document)) { String value = Json.toJsonValue(groupBy); throw new MongoServerError(40202, "The $bucket 'groupBy' field must be defined as a $-prefixed path or an expression, but found: " + value + "."); } return groupBy; } private List<?> getAndValidateBoundaries(Object boundaries) { validateValuePresent(boundaries); if (!(boundaries instanceof List)) { String type = Utils.describeType(boundaries); throw new MongoServerError(40200, "The $bucket 'boundaries' field must be an array, but found type: " + type + "."); } List<?> boundaryValues = (List<?>) boundaries; if (boundaryValues.size() < 2) { throw new MongoServerError(40192, "The $bucket 'boundaries' field must have at least 2 values, but found " + boundaryValues.size() + " value(s)."); } for (int i = 1; i < boundaryValues.size(); i++) { Object value1 = boundaryValues.get(i - 1); Object value2 = boundaryValues.get(i); validateTypesAreCompatible(value1, value2); if (compare(value1, value2) >= 0) { int index1 = i - 1; int index2 = i; throw new MongoServerError(40194, "The 'boundaries' option to $bucket must be sorted, but elements " + index1 + " and " + index2 + " are not in ascending order (" + value1 + " is not less than " + value2 + ")."); } } return boundaryValues; } private Object getAndValidateDefault(Object defaultValue) { Assert.notEmpty(boundaries); if (!(compare(defaultValue, boundaries.get(0)) < 0 || compare(defaultValue, CollectionUtils.getLastElement(boundaries)) >= 0)) { throw new MongoServerError(40199, "The $bucket 'default' field must be less than the lowest boundary or greater than or equal to the highest boundary."); } return defaultValue; } private void validateTypesAreCompatible(Object value1, Object value2) { if (value1 instanceof Number && value2 instanceof Number) { return; } String type1 = Utils.describeType(value1); String type2 = Utils.describeType(value2); if (!type1.equals(type2)) { throw new MongoServerError(40193, "All values in the the 'boundaries' option to $bucket must have the same type. Found conflicting types " + type1 + " and " + type2 + "."); } } private Document getAndValidateOutput(Object output) { if (output == null) { return null; } if (!(output instanceof Document)) { throw new MongoServerError(40196, "The $bucket 'output' field must be an object, but found type: " + Utils.describeType(output) + "."); } return (Document) output; } @Override public Stream<Document> apply(Stream<Document> stream) { Map<Object, List<Accumulator>> accumulatorsPerBucket = new TreeMap<>(ValueComparator.asc()); stream.forEach(document -> { Object key = Expression.evaluateDocument(groupByExpression, document); Object bucket = findBucket(key); List<Accumulator> accumulators = accumulatorsPerBucket.computeIfAbsent(bucket, k -> getAccumulators()); for (Accumulator accumulator : accumulators) { Object expression = accumulator.getExpression(); accumulator.aggregate(Expression.evaluateDocument(expression, document)); } }); List<Document> result = new ArrayList<>(); for (Entry<Object, List<Accumulator>> entry : accumulatorsPerBucket.entrySet()) { Document groupResult = new Document(); groupResult.put(Constants.ID_FIELD, entry.getKey()); for (Accumulator accumulator : entry.getValue()) { groupResult.put(accumulator.getField(), accumulator.getResult()); } result.add(groupResult); } return result.stream(); } private List<Accumulator> getAccumulators() { if (output == null) { return List.of(new SumAccumulator("count", new Document("$sum", 1))); } return Accumulator.parse(output).values().stream() .map(Supplier::get) .collect(Collectors.toList()); } private Object findBucket(Object key) { if (compare(key, boundaries.get(0)) < 0) { return getDefaultValue(); } for (int i = 1; i < boundaries.size(); i++) { Object boundary = boundaries.get(i); if (compare(key, boundary) < 0) { return boundaries.get(i - 1); } } return getDefaultValue(); } private static int compare(Object a, Object b) { return ValueComparator.asc().compare(a, b); } private Object getDefaultValue() { if (defaultValue instanceof Missing) { throw new MongoServerError(40066, "$switch could not find a matching branch for an input, and no default was specified."); } return defaultValue; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/MongoServerNotYetImplementedException.java package de.bwaldvogel.mongo.exception; public class MongoServerNotYetImplementedException extends MongoServerException { private static final long serialVersionUID = 1L; private static final String ISSUES_URL = "https://github.com/bwaldvogel/mongo-java-server/issues/"; public MongoServerNotYetImplementedException(int gitHubIssueNumber, String prefix) { super(prefix + " is not yet implemented. See " + ISSUES_URL + gitHubIssueNumber); } } <file_sep>/postgresql-backend/src/main/java/de/bwaldvogel/mongo/backend/postgresql/LegacyUUIDJsonMixIn.java package de.bwaldvogel.mongo.backend.postgresql; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; abstract class LegacyUUIDJsonMixIn { @JsonCreator LegacyUUIDJsonMixIn(@JsonProperty("uuid") UUID uuid) {} } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/InMemoryCursor.java package de.bwaldvogel.mongo.backend; import java.util.Collections; import java.util.List; import de.bwaldvogel.mongo.bson.Document; public class InMemoryCursor extends AbstractCursor { private List<Document> remainingDocuments; public InMemoryCursor(long cursorId, List<Document> remainingDocuments) { super(cursorId); Assert.notEmpty(remainingDocuments); this.remainingDocuments = Collections.unmodifiableList(remainingDocuments); } @Override public boolean isEmpty() { return remainingDocuments.isEmpty(); } @Override public List<Document> takeDocuments(int numberToReturn) { Assert.isTrue(numberToReturn > 0, () -> "Illegal number to return: " + numberToReturn); int toIndex = Math.min(remainingDocuments.size(), numberToReturn); List<Document> documents = remainingDocuments.subList(0, toIndex); remainingDocuments = remainingDocuments.subList(documents.size(), remainingDocuments.size()); return documents; } } <file_sep>/test-common/src/test/java/de/bwaldvogel/mongo/RealMongoAggregationTest.java package de.bwaldvogel.mongo; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import de.bwaldvogel.mongo.backend.AbstractAggregationTest; public class RealMongoAggregationTest extends AbstractAggregationTest { @RegisterExtension static RealMongoContainer realMongoContainer = new RealMongoContainer(); @Override protected void setUpBackend() throws Exception { connectionString = realMongoContainer.getConnectionString(); } @Override protected MongoBackend createBackend() throws Exception { throw new UnsupportedOperationException(); } @Test @Override @Disabled public void testAggregateWithGeoNear() throws Exception { super.testAggregateWithGeoNear(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/ArrayFilters.java package de.bwaldvogel.mongo.backend; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.Json; import de.bwaldvogel.mongo.exception.BadValueException; import de.bwaldvogel.mongo.exception.FailedToParseException; public class ArrayFilters { private final Map<String, Object> values; private ArrayFilters(Map<String, Object> values) { this.values = values; } static ArrayFilters parse(Document query, Document updateQuery) { @SuppressWarnings("unchecked") List<Document> arrayFilters = (List<Document>) query.getOrDefault("arrayFilters", Collections.emptyList()); return parse(arrayFilters, updateQuery); } private static ArrayFilters parse(List<Document> arrayFilters, Document updateQuery) { Map<String, Object> arrayFilterMap = new LinkedHashMap<>(); for (Document arrayFilter : arrayFilters) { if (arrayFilter.isEmpty()) { throw new FailedToParseException("Cannot use an expression without a top-level field name in arrayFilters"); } List<String> topLevelFieldNames = arrayFilter.keySet().stream() .map(Utils::firstFragment) .distinct() .collect(Collectors.toList()); if (topLevelFieldNames.size() > 1) { throw new FailedToParseException("Error parsing array filter :: caused by ::" + " Expected a single top-level field name, found '" + topLevelFieldNames.get(0) + "' and '" + topLevelFieldNames.get(1) + "'"); } String topLevelFieldName = CollectionUtils.getSingleElement(topLevelFieldNames); if (!topLevelFieldName.matches("^[a-zA-Z0-9]+$")) { throw new BadValueException("Error parsing array filter :: caused by :: The top-level field name must be an alphanumeric string beginning with a lowercase letter, found '" + topLevelFieldName + "'"); } Object filter = createFilter(arrayFilter); if (arrayFilterMap.put(topLevelFieldName, filter) != null) { throw new FailedToParseException("Found multiple array filters with the same top-level field name " + topLevelFieldName); } } if (!arrayFilterMap.isEmpty()) { validate(updateQuery, arrayFilterMap); } return new ArrayFilters(arrayFilterMap); } private static Object createFilter(Document arrayFilter) { Document filter = new Document(); for (Entry<String, Object> entry : arrayFilter.entrySet()) { List<String> pathFragments = Utils.splitPath(entry.getKey()); String tailPath = Utils.joinTail(pathFragments); Object query = entry.getValue(); if (tailPath.isEmpty()) { Assert.hasSize(arrayFilter.keySet(), 1); return query; } else { filter.put(tailPath, query); } } return filter; } private static Object createFilter(List<String> pathFragments, Object query) { List<String> tail = Utils.getTail(pathFragments); if (tail.isEmpty()) { return query; } else { return new Document(Utils.joinPath(tail), query); } } private static void validate(Document updateQuery, Map<String, ?> arrayFilterMap) { Set<String> allKeys = updateQuery.values().stream() .filter(Document.class::isInstance) .map(Document.class::cast) .flatMap(d -> d.keySet().stream()) .collect(Collectors.toSet()); for (String identifier : arrayFilterMap.keySet()) { if (allKeys.stream().noneMatch(key -> key.contains(toPositionalOperator(identifier)))) { throw new FailedToParseException("The array filter for identifier '" + identifier + "' was not used in the update " + updateQuery.toString(true, "{ ", " }")); } } } public static ArrayFilters empty() { return new ArrayFilters(Collections.emptyMap()); } @VisibleForExternalBackends public boolean isEmpty() { return getValues().isEmpty(); } @Override public String toString() { return Json.toJsonValue(getValues()); } private Object getArrayFilterQuery(String key) { if (isPositionalAll(key)) { return new Document(QueryOperator.EXISTS.getValue(), true); } return values.get(extractKeyFromPositionalOperator(key)); } private static String toPositionalOperator(String key) { return "$[" + key + "]"; } private static String extractKeyFromPositionalOperator(String operator) { if (!isPositionalOperator(operator)) { throw new IllegalArgumentException("Illegal key: " + operator); } return operator.substring("$[".length(), operator.length() - "]".length()); } private static boolean isPositionalOperator(String key) { return key.startsWith("$[") && key.endsWith("]"); } List<String> calculateKeys(Document document, String key) { if (isPositionalOperator(key)) { throw new BadValueException("Cannot have array filter identifier (i.e. '$[<id>]') element in the first position in path '" + key + "'", false); } List<String> pathFragments = Utils.splitPath(key); return calculateKeys(document, pathFragments, ""); } private List<String> calculateKeys(Object object, List<String> pathFragments, String path) { if (pathFragments.isEmpty()) { return List.of(path); } String fragment = pathFragments.get(0); if (!isPositionalOperator(fragment)) { String nextPath = Utils.joinPath(path, fragment); List<String> tail = Utils.getTail(pathFragments); Object subObject = Utils.getFieldValueListSafe(object, fragment); return calculateKeys(subObject, tail, nextPath); } if (object instanceof Missing) { throw new BadValueException("The path '" + path + "' must exist in the document in order to apply array updates."); } else if (!(object instanceof List)) { String previousKey = Utils.getLastFragment(path); String element = Json.toCompactJsonValue(object); throw new BadValueException("Cannot apply array updates to non-array element " + previousKey + ": " + element); } List<?> values = (List<?>) object; Object arrayFilterQuery = getArrayFilterQuery(fragment); QueryMatcher queryMatcher = new DefaultQueryMatcher(); List<String> keys = new ArrayList<>(); for (int i = 0; i < values.size(); i++) { Object value = values.get(i); if (queryMatcher.matchesValue(arrayFilterQuery, value)) { List<String> remaining = Utils.getTail(pathFragments); String nextPath = Utils.joinPath(path, String.valueOf(i)); List<String> subKeys = calculateKeys(value, remaining, nextPath); keys.addAll(subKeys); } } return keys; } private static boolean isPositionalAll(String key) { return key.equals("$[]"); } Map<String, Object> getValues() { return values; } boolean canHandle(String key) { if (!isEmpty()) { return true; } else { return Utils.splitPath(key).stream().anyMatch(ArrayFilters::isPositionalAll); } } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/CursorRegistry.java package de.bwaldvogel.mongo.backend; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import de.bwaldvogel.mongo.exception.CursorNotFoundException; public class CursorRegistry { private final ConcurrentMap<Long, Cursor> cursors = new ConcurrentHashMap<>(); private final AtomicLong cursorIdCounter = new AtomicLong(); public long generateCursorId() { return cursorIdCounter.incrementAndGet(); } public Cursor getCursor(long cursorId) { Cursor cursor = cursors.get(cursorId); if (cursor == null) { throw new CursorNotFoundException(cursorId); } return cursor; } public boolean remove(Cursor cursor) { return remove(cursor.getId()); } public boolean remove(long cursorId) { return cursors.remove(cursorId) != null; } public void add(Cursor cursor) { Cursor previousValue = cursors.put(cursor.getId(), cursor); Assert.isNull(previousValue); } public int size() { return cursors.size(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/NoReplicationEnabledException.java package de.bwaldvogel.mongo.exception; public class NoReplicationEnabledException extends MongoServerError { private static final long serialVersionUID = 1L; public NoReplicationEnabledException() { super(76, "NoReplicationEnabled", "not running with --replSet"); setLogError(false); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/wire/bson/BsonDecoderTest.java package de.bwaldvogel.mongo.wire.bson; import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.MaxKey; import de.bwaldvogel.mongo.bson.MinKey; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class BsonDecoderTest { @Test void testDecodeStringUnicode() throws Exception { String string = "\u0442\u0435\u0441\u0442"; byte[] bytes = string.getBytes(StandardCharsets.UTF_8); ByteBuf buffer = Unpooled.buffer(); try { buffer.writeBytes(bytes); buffer.writeByte(0); assertThat(BsonDecoder.decodeCString(buffer)).isEqualTo(string); } finally { buffer.release(); } } @Test void testEncodeDecodeRoundtrip() throws Exception { List<Document> objects = new ArrayList<>(); objects.add(new Document("key", MaxKey.getInstance()).append("foo", "bar")); objects.add(new Document("key", MinKey.getInstance()).append("test", MaxKey.getInstance())); for (Document document : objects) { ByteBuf buffer = Unpooled.buffer(); try { BsonEncoder.encodeDocument(document, buffer); Document decodedObject = BsonDecoder.decodeBson(buffer); assertThat(decodedObject).isEqualTo(document); } finally { buffer.release(); } } } } <file_sep>/memory-backend/build.gradle dependencies { api project(':mongo-java-server-core') testImplementation project(':mongo-java-server-test-common') } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/KeyConstraintError.java package de.bwaldvogel.mongo.exception; public class KeyConstraintError extends MongoServerError { private static final long serialVersionUID = 1L; KeyConstraintError(ErrorCode errorCode, String message) { super(errorCode, message); } } <file_sep>/test-common/src/main/java/de/bwaldvogel/mongo/backend/TestUtils.java package de.bwaldvogel.mongo.backend; import java.net.InetSocketAddress; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bson.Document; import com.mongodb.ConnectionString; import com.mongodb.client.MongoDatabase; public class TestUtils { private TestUtils() { } public static <T> List<T> toArray(Iterable<T> iterable) { List<T> array = new ArrayList<>(); for (T obj : iterable) { array.add(obj); } return array; } public static Document json(String string) { string = string.trim(); if (!string.startsWith("{")) { string = "{" + string + "}"; } return Document.parse(string); } public static List<Document> jsonList(String... json) { return Stream.of(json) .map(TestUtils::json) .collect(Collectors.toList()); } public static Document getCollectionStatistics(MongoDatabase database, String collectionName) { Document collStats = new Document("collStats", collectionName); return database.runCommand(collStats); } static Instant instant(String value) { return Instant.parse(value); } static Date date(String value) { return Date.from(instant(value)); } public static InetSocketAddress toInetSocketAddress(String connectionString) { return toInetSocketAddress(new ConnectionString(connectionString)); } public static InetSocketAddress toInetSocketAddress(ConnectionString connectionString) { String hostAndPort = CollectionUtils.getSingleElement(connectionString.getHosts()); String[] hostAndPortArray = hostAndPort.split(":"); String hostname = hostAndPortArray[0]; int port = Integer.parseInt(hostAndPortArray[1]); return new InetSocketAddress(hostname, port); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/message/ClientRequest.java package de.bwaldvogel.mongo.wire.message; import de.bwaldvogel.mongo.backend.Utils; import io.netty.channel.Channel; public abstract class ClientRequest implements Message { private final MessageHeader header; private final String fullCollectionName; private final Channel channel; protected ClientRequest(Channel channel, MessageHeader header, String fullCollectionName) { this.channel = channel; this.header = header; this.fullCollectionName = fullCollectionName; } public Channel getChannel() { return channel; } public MessageHeader getHeader() { return header; } @Override public String getDatabaseName() { return Utils.getDatabaseNameFromFullName(fullCollectionName); } public String getCollectionName() { return Utils.getCollectionNameFromFullName(fullCollectionName); } public String getFullCollectionName() { return fullCollectionName; } } <file_sep>/examples/src/main/java/SimpleJUnit5WithModernClientTest.java import static org.assertj.core.api.Assertions.assertThat; import org.bson.Document; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; class SimpleJUnit5WithModernClientTest { private MongoCollection<Document> collection; private MongoClient client; private MongoServer server; @BeforeEach void setUp() { server = new MongoServer(new MemoryBackend()); // bind on a random local port String connectionString = server.bindAndGetConnectionString(); client = MongoClients.create(connectionString); collection = client.getDatabase("testdb").getCollection("testcollection"); } @AfterEach void tearDown() { client.close(); server.shutdown(); } @Test void testSimpleInsertQuery() throws Exception { assertThat(collection.countDocuments()).isZero(); // creates the database and collection in memory and insert the object Document obj = new Document("_id", 1).append("key", "value"); collection.insertOne(obj); assertThat(collection.countDocuments()).isEqualTo(1L); assertThat(collection.find().first()).isEqualTo(obj); } } <file_sep>/h2-backend/build.gradle dependencies { api project(':mongo-java-server-core') api group: 'com.h2database', name: 'h2', version: 'latest.release' testImplementation project(':mongo-java-server-test-common') } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/LimitedList.java package de.bwaldvogel.mongo.backend; import java.util.ArrayList; public class LimitedList<E> extends ArrayList<E> { private static final long serialVersionUID = -4265811949513159615L; private final int limit; LimitedList(int limit) { this.limit = limit; } @Override public boolean add(E o) { super.add(o); while (size() > limit) { super.remove(0); } return true; } } <file_sep>/docker-compose.yml version: '2.1' services: mongodb: image: mongo:5.0.18 container_name: mongo-java-server-test tmpfs: - /data:rw ports: - 127.0.0.1:27018:27017 healthcheck: test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1 interval: 10s timeout: 5s retries: 5 postgres: image: postgres:9.6-alpine container_name: postgres-mongo-java-server-test tmpfs: - /var/lib/postgresql/data:rw environment: - POSTGRES_USER=mongo-java-server-test - POSTGRES_PASSWORD=<PASSWORD> - POSTGRES_DB=mongo-java-server-test ports: - 127.0.0.1:5432:5432 healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5 sonarqube: image: sonarqube container_name: mongo-java-server-sonarqube ports: - 127.0.0.1:9000:9000 <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/BinData.java package de.bwaldvogel.mongo.bson; import java.util.Arrays; import java.util.Objects; public final class BinData implements Comparable<BinData>, Bson { private static final long serialVersionUID = 1L; private final byte[] data; public BinData(byte[] data) { this.data = Objects.requireNonNull(data); } public byte[] getData() { return data; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BinData binData = (BinData) o; return Arrays.equals(data, binData.data); } @Override public int hashCode() { return Arrays.hashCode(data); } @Override public int compareTo(BinData other) { byte[] bytes1 = getData(); byte[] bytes2 = other.getData(); if (bytes1.length != bytes2.length) { return Integer.compare(bytes1.length, bytes2.length); } else { for (int i = 0; i < bytes1.length; i++) { int compare = compareUnsigned(bytes1[i], bytes2[i]); if (compare != 0) return compare; } return 0; } } // lexicographic byte comparison 0x00 < 0xFF private static int compareUnsigned(byte b1, byte b2) { int v1 = (int) b1 & 0xFF; int v2 = (int) b2 & 0xFF; return Integer.compare(v1, v2); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/CursorNotFoundException.java package de.bwaldvogel.mongo.exception; public class CursorNotFoundException extends MongoServerError { private static final long serialVersionUID = 1L; public CursorNotFoundException(long cursorId) { super(ErrorCode.CursorNotFound, "Cursor id " + cursorId + " does not exist"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/message/Message.java package de.bwaldvogel.mongo.wire.message; public interface Message { String getDatabaseName(); } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/BsonType.java package de.bwaldvogel.mongo.backend; import java.time.Instant; import java.util.Collection; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import de.bwaldvogel.mongo.bson.BinData; import de.bwaldvogel.mongo.bson.BsonTimestamp; import de.bwaldvogel.mongo.bson.Decimal128; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.LegacyUUID; import de.bwaldvogel.mongo.bson.MaxKey; import de.bwaldvogel.mongo.bson.MinKey; import de.bwaldvogel.mongo.bson.ObjectId; import de.bwaldvogel.mongo.exception.BadValueException; public enum BsonType { DOUBLE(1, "double", Double.class), STRING(2, "string", String.class), OBJECT(3, "object", Document.class), ARRAY(4, "array", Collection.class), BIN_DATA(5, "binData", BinData.class, LegacyUUID.class, UUID.class), OBJECT_ID(7, "objectId", ObjectId.class), BOOL(8, "bool", Boolean.class), DATE(9, "date", Instant.class), NULL(10, "null") { @Override public boolean matches(Object value) { return value == null; } }, REGEX(11, "regex", Pattern.class), INT(16, "int", Integer.class), TIMESTAMP(17, "timestamp", BsonTimestamp.class), LONG(18, "long", Long.class), DECIMAL128(19, "decimal", Decimal128.class), MIN_KEY(-1, "minKey", MinKey.class), MAX_KEY(127, "maxKey", MaxKey.class), ; private final int number; private final String alias; private final Set<Class<?>> classes; BsonType(int number, String alias, Class<?>... classes) { this.number = number; this.alias = alias; this.classes = Set.of(classes); } public static BsonType forString(String value) { for (BsonType bsonType : values()) { if (bsonType.getAlias().equals(value)) { return bsonType; } } throw new BadValueException("Unknown type name alias: " + value); } public static BsonType forNumber(Number value) { int type = value.intValue(); if ((double) type != value.doubleValue()) { throw new BadValueException("Invalid numerical type code: " + value); } for (BsonType bsonType : values()) { if (bsonType.getNumber() == type) { return bsonType; } } throw new IllegalArgumentException("Unknown type: " + value); } public boolean matches(Object value) { if (value == null) { return false; } return classes.stream().anyMatch(clazz -> clazz.isAssignableFrom(value.getClass())); } public int getNumber() { return number; } public String getAlias() { return alias; } } <file_sep>/test-common/src/main/java/de/bwaldvogel/mongo/entity/SubEntity.java package de.bwaldvogel.mongo.entity; public class SubEntity { private String data; public SubEntity() { } public SubEntity(String data) { this.data = data; } public String getData() { return data; } public void setData(String data) { this.data = data; } } <file_sep>/postgresql-backend/src/test/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlUtilsTest.java package de.bwaldvogel.mongo.backend.postgresql; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.ObjectId; class PostgresqlUtilsTest { @Test void testToDataKey() throws Exception { assertThat(PostgresqlUtils.toDataKey("foo")).isEqualTo("data ->> 'foo'"); assertThat(PostgresqlUtils.toDataKey("foo.bar")).isEqualTo("data -> 'foo' ->> 'bar'"); assertThat(PostgresqlUtils.toDataKey("foo.bar.bla")).isEqualTo("data -> 'foo' -> 'bar' ->> 'bla'"); } @Test void testToQueryValue() throws Exception { assertThat(PostgresqlUtils.toQueryValue(123)).isEqualTo("123"); assertThat(PostgresqlUtils.toQueryValue(123.0)).isEqualTo("123"); assertThat(PostgresqlUtils.toQueryValue(123.1)).isEqualTo("123.1"); assertThat(PostgresqlUtils.toQueryValue("foobar")).isEqualTo("foobar"); assertThat(PostgresqlUtils.toQueryValue("1.0")).isEqualTo("1.0"); assertThat(PostgresqlUtils.toQueryValue(new LinkedHashMap<>(Collections.singletonMap("foo", "bar")))).isEqualTo("{\"foo\":\"bar\"}"); assertThat(PostgresqlUtils.toQueryValue(List.of("foo", "bar"))).isEqualTo("[\"foo\",\"bar\"]"); assertThat(PostgresqlUtils.toQueryValue(new ObjectId("foobarfoobar".getBytes(StandardCharsets.UTF_8)))).isEqualTo("{\"@class\":\"de.bwaldvogel.mongo.bson.ObjectId\",\"data\":\"Zm9vYmFyZm9vYmFy\"}"); assertThat(PostgresqlUtils.toQueryValue(new Document("key", "value"))).isEqualTo("{\"@class\":\"de.bwaldvogel.mongo.bson.Document\",\"key\":\"value\"}"); assertThatExceptionOfType(NullPointerException.class) .isThrownBy(() -> PostgresqlUtils.toQueryValue(null)) .withMessage(null); } } <file_sep>/test-common/src/main/java/de/bwaldvogel/AbstractReadOnlyProxyTest.java package de.bwaldvogel; import static de.bwaldvogel.mongo.backend.TestUtils.json; import static de.bwaldvogel.mongo.backend.TestUtils.jsonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.List; import org.bson.Document; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.platform.commons.util.CollectionUtils; import com.mongodb.MongoCommandException; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.Updates; import com.mongodb.connection.ServerDescription; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.ReadOnlyProxy; public abstract class AbstractReadOnlyProxyTest { private MongoClient readOnlyClient; private MongoServer mongoServer; private MongoServer writeableServer; private MongoClient writeClient; protected abstract MongoBackend createBackend() throws Exception; @BeforeEach public void setUp() throws Exception { MongoBackend mongoBackend = createBackend(); writeableServer = new MongoServer(mongoBackend); writeClient = MongoClients.create(writeableServer.bindAndGetConnectionString()); mongoServer = new MongoServer(new ReadOnlyProxy(mongoBackend)); readOnlyClient = MongoClients.create(mongoServer.bindAndGetConnectionString()); } @AfterEach public void tearDown() { writeClient.close(); readOnlyClient.close(); mongoServer.shutdownNow(); writeableServer.shutdownNow(); } @Test void testMaxDocumentSize() throws Exception { ServerDescription serverDescription = CollectionUtils.getOnlyElement(readOnlyClient.getClusterDescription().getServerDescriptions()); assertThat(serverDescription.getMaxDocumentSize()).isEqualTo(16777216); } @Test void testServerStatus() throws Exception { readOnlyClient.getDatabase("admin").runCommand(new Document("serverStatus", 1)); } @Test void testCurrentOperations() throws Exception { Document currentOperations = readOnlyClient.getDatabase("admin").getCollection("$cmd.sys.inprog").find().first(); assertThat(currentOperations).isNotNull(); } @Test void testStats() throws Exception { Document stats = readOnlyClient.getDatabase("testdb").runCommand(json("dbStats:1")); assertThat(((Number) stats.get("objects")).longValue()).isZero(); } @Test void testListDatabaseNames() throws Exception { assertThat(readOnlyClient.listDatabaseNames()).isEmpty(); writeClient.getDatabase("testdb").getCollection("testcollection").insertOne(new Document()); assertThat(readOnlyClient.listDatabaseNames()).containsExactly("testdb"); writeClient.getDatabase("bar").getCollection("testcollection").insertOne(new Document()); assertThat(readOnlyClient.listDatabaseNames()).containsExactly("bar", "testdb"); } @Test void testIllegalCommand() throws Exception { assertThatExceptionOfType(MongoException.class) .isThrownBy(() -> readOnlyClient.getDatabase("testdb").runCommand(json("foo:1"))) .withMessageContaining("Command failed with error 59 (CommandNotFound): 'no such command: 'foo'"); assertThatExceptionOfType(MongoException.class) .isThrownBy(() -> readOnlyClient.getDatabase("bar").runCommand(json("foo:1"))) .withMessageContaining("Command failed with error 59 (CommandNotFound): 'no such command: 'foo'"); } @Test void testQuery() throws Exception { MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); Document obj = collection.find(json("_id: 1")).first(); assertThat(obj).isNull(); assertThat(collection.countDocuments()).isEqualTo(0); } @Test void testDistinctQuery() { MongoCollection<Document> collection = writeClient.getDatabase("testdb").getCollection("testcollection"); collection.insertOne(new Document("n", 1)); collection.insertOne(new Document("n", 2)); collection.insertOne(new Document("n", 1)); collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); assertThat(collection.distinct("n", Integer.class)).containsExactly(1, 2); } @Test void testInsert() throws Exception { MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); assertThat(collection.countDocuments()).isZero(); assertThatExceptionOfType(MongoException.class) .isThrownBy(() -> collection.insertOne(json("{}"))); } @Test void testUpdate() throws Exception { MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); Document object = new Document("_id", 1); Document newObject = new Document("_id", 1); assertThatExceptionOfType(MongoException.class) .isThrownBy(() -> collection.replaceOne(object, newObject)) .withMessageContaining("Command failed with error 59 (CommandNotFound): 'no such command: 'update'"); } @Test void testUpsert() throws Exception { MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); assertThatExceptionOfType(MongoException.class) .isThrownBy(() -> collection.updateMany(json("{}"), Updates.set("foo", "bar"), new UpdateOptions().upsert(true))) .withMessageContaining("Command failed with error 59 (CommandNotFound): 'no such command: 'update'"); } @Test void testDropDatabase() throws Exception { MongoDatabase database = readOnlyClient.getDatabase("testdb"); assertThatExceptionOfType(MongoException.class) .isThrownBy(database::drop); } @Test void testDropCollection() throws Exception { MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("foo"); assertThatExceptionOfType(MongoException.class) .isThrownBy(collection::drop) .withMessageContaining("Command failed with error 59 (CommandNotFound): 'no such command: 'drop'"); } @Test void testHandleKillCursor() { MongoCollection<Document> collection = writeClient.getDatabase("testdb").getCollection("testcollection"); collection.insertMany(List.of(new Document(), new Document())); MongoCursor<Document> cursor = readOnlyClient.getDatabase("testdb") .getCollection("testcollection").find().batchSize(1).cursor(); assertThat(cursor.getServerCursor()).isNotNull(); while (cursor.hasNext()) { cursor.next(); } assertThat(cursor.getServerCursor()).isNull(); } @Test void testAggregateWithExpressionProjection() throws Exception { List<Document> pipeline = jsonList("$project: {_id: 0, idHex: {$toString: '$_id'}}"); MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); assertThat(collection.aggregate(pipeline)).isEmpty(); } @Test void testAggregateWithOut() { List<Document> pipeline = jsonList( "$group: {_id: '$author', books: {$push: '$title'}}", "$out : 'authors'"); MongoCollection<Document> collection = readOnlyClient.getDatabase("testdb").getCollection("testcollection"); assertThatExceptionOfType(MongoCommandException.class) .isThrownBy(() -> collection.aggregate(pipeline).first()) .withMessageContaining("Command failed with error -1: 'Aggregation contains a modifying stage and is therefore not allowed in read-only mode'"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/IllegalOperationException.java package de.bwaldvogel.mongo.exception; public class IllegalOperationException extends MongoServerError { private static final long serialVersionUID = 1L; public IllegalOperationException(String message) { super(ErrorCode.IllegalOperation, message); } } <file_sep>/postgresql-backend/build.gradle dependencies { api project(':mongo-java-server-core') implementation "com.fasterxml.jackson.core:jackson-core:latest.release" implementation "com.fasterxml.jackson.core:jackson-databind:latest.release" implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:latest.release" testRuntimeOnly "org.postgresql:postgresql:latest.release" testImplementation "com.zaxxer:HikariCP:[4.0.0, 5.0.0)" testImplementation 'org.testcontainers:testcontainers:latest.release' testImplementation project(':mongo-java-server-test-common') } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/SampleStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.security.SecureRandom; import java.util.Comparator; import java.util.stream.Stream; import de.bwaldvogel.mongo.backend.Missing; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerError; public class SampleStage implements AggregationStage { private static final SecureRandom random = new SecureRandom(); private final int size; public SampleStage(Object sample) { if (!(sample instanceof Document)) { throw new MongoServerError(28745, "the $sample stage specification must be an object"); } Document size = (Document) sample; Object sizeValue = size.getOrMissing("size"); if (sizeValue instanceof Missing) { throw new MongoServerError(28749, "$sample stage must specify a size"); } if (!(sizeValue instanceof Number)) { throw new MongoServerError(28746, "size argument to $sample must be a number"); } this.size = ((Number) sizeValue).intValue(); if (this.size < 0) { throw new MongoServerError(28747, "size argument to $sample must not be negative"); } for (String key : size.keySet()) { if (!key.equals("size")) { throw new MongoServerError(28748, "unrecognized option to $sample: " + key); } } } @Override public String name() { return "$sample"; } @Override public Stream<Document> apply(Stream<Document> stream) { return stream .sorted(Comparator.comparingDouble(key -> random.nextDouble())) .limit(size); } } <file_sep>/postgresql-backend/src/main/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlBackend.java package de.bwaldvogel.mongo.backend.postgresql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.time.Clock; import javax.sql.DataSource; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.AbstractMongoBackend; import de.bwaldvogel.mongo.exception.MongoServerException; public class PostgresqlBackend extends AbstractMongoBackend { private final DataSource dataSource; public PostgresqlBackend(DataSource dataSource) { this(dataSource, defaultClock()); } public PostgresqlBackend(DataSource dataSource, Clock clock) { super(clock); this.dataSource = dataSource; } @Override protected MongoDatabase openOrCreateDatabase(String databaseName) { String sql = "CREATE TABLE IF NOT EXISTS " + databaseName + "._meta" + " (collection_name text," + " datasize bigint," + " CONSTRAINT pk_meta PRIMARY KEY (collection_name)" + ")"; try (Connection connection = getConnection(); PreparedStatement stmt1 = connection.prepareStatement("CREATE SCHEMA IF NOT EXISTS " + databaseName); PreparedStatement stmt2 = connection.prepareStatement(sql) ) { stmt1.executeUpdate(); stmt2.executeUpdate(); } catch (SQLException e) { throw new MongoServerException("failed to open or create database", e); } return new PostgresqlDatabase(databaseName, this, getCursorRegistry()); } public Connection getConnection() throws SQLException { return dataSource.getConnection(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/MinKey.java package de.bwaldvogel.mongo.bson; public class MinKey implements Bson { private static final long serialVersionUID = 1L; private static final MinKey INSTANCE = new MinKey(); private MinKey() { } public static MinKey getInstance() { return INSTANCE; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/message/MongoQuery.java package de.bwaldvogel.mongo.wire.message; import de.bwaldvogel.mongo.bson.Document; import io.netty.channel.Channel; public class MongoQuery extends ClientRequest { private final Document query; private final Document returnFieldSelector; private final int numberToSkip; private final int numberToReturn; public MongoQuery(Channel channel, MessageHeader header, String fullCollectionName, int numberToSkip, int numberToReturn, Document query, Document returnFieldSelector) { super(channel, header, fullCollectionName); this.numberToSkip = numberToSkip; this.numberToReturn = numberToReturn; this.query = query; this.returnFieldSelector = returnFieldSelector; } public int getNumberToSkip() { return numberToSkip; } public int getNumberToReturn() { return numberToReturn; } public Document getQuery() { return query; } public Document getReturnFieldSelector() { return returnFieldSelector; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("("); sb.append("header: ").append(getHeader()); sb.append(", collection: ").append(getFullCollectionName()); sb.append(", query: ").append(query); sb.append(", returnFieldSelector: ").append(returnFieldSelector); sb.append(")"); return sb.toString(); } } <file_sep>/test-common/build.gradle dependencies { api project(':mongo-java-server-core') api 'org.mongodb:mongodb-driver-sync:latest.release' api 'org.mongodb:mongodb-driver-reactivestreams:latest.release' api "org.springframework:spring-core:latest.release" api "org.springframework:spring-beans:latest.release" api "org.springframework:spring-context:latest.release" api "org.springframework:spring-test:latest.release" api "org.springframework.data:spring-data-mongodb:latest.release" api group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: 'latest.release' api group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: 'latest.release' runtimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: 'latest.release' api group: 'org.assertj', name: 'assertj-core', version: 'latest.release' api "org.mockito:mockito-core:latest.release" api "org.mockito:mockito-junit-jupiter:latest.release" runtimeOnly group: 'ch.qos.logback', name: 'logback-classic', version: '[1.3.0, 1.4.0)' testImplementation "org.testcontainers:testcontainers:latest.release" } <file_sep>/CONTRIBUTING.md ## Contributing ## We are happy to receive pull-requests if you want to contribute new features or bugfixes to the project. Please use the code style settings that you can find in the [code-style directory](code-style/). If you use IntelliJ, please make sure it properly picks up the settings from the [EditorConfig file](.editorconfig) (this should be the default behavior though). Issues labeled [help wanted][issues-help-wanted] or [good first issue][issues-good-first-issue] can be good first contributions. If you want to thank the author for this library or want to support the maintenance work, we are happy to receive a donation. [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/BenediktWaldvogel) [issues-help-wanted]: https://github.com/bwaldvogel/mongo-java-server/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22 [issues-good-first-issue]: https://github.com/bwaldvogel/mongo-java-server/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 <file_sep>/memory-backend/src/test/java/de/bwaldvogel/mongo/MemoryBackendReadOnlyProxyTest.java package de.bwaldvogel.mongo; import de.bwaldvogel.AbstractReadOnlyProxyTest; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; class MemoryBackendReadOnlyProxyTest extends AbstractReadOnlyProxyTest { @Override protected MongoBackend createBackend() { return new MemoryBackend(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/ConflictingUpdateOperatorsException.java package de.bwaldvogel.mongo.exception; public class ConflictingUpdateOperatorsException extends MongoServerError { private static final long serialVersionUID = 1L; public ConflictingUpdateOperatorsException(String updatePath, String conflictingPath) { super(ErrorCode.ConflictingUpdateOperators, "Updating the path '" + updatePath + "' would create a conflict at '" + conflictingPath + "'"); } @Override public boolean shouldPrefixCommandContext() { return false; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/message/MessageHeader.java package de.bwaldvogel.mongo.wire.message; public class MessageHeader { private final int totalLength; private final int requestID; private final int responseTo; public MessageHeader(int requestID, int responseTo) { this(0, requestID, responseTo); } public MessageHeader(int totalLength, int requestID, int responseTo) { this.totalLength = totalLength; this.requestID = requestID; this.responseTo = responseTo; } public int getTotalLength() { return totalLength; } public int getRequestID() { return requestID; } public int getResponseTo() { return responseTo; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("("); sb.append("request: ").append(requestID); sb.append(", responseTo: ").append(responseTo); if (totalLength > 0) { sb.append(", length: ").append(totalLength); } sb.append(")"); return sb.toString(); } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/AssertTest.java package de.bwaldvogel.mongo.backend; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; public class AssertTest { @Test void testIsEmpty() throws Exception { Assert.isEmpty(Collections.emptyList()); Assert.isEmpty(Collections.emptySet()); Assert.isEmpty(new ArrayList<>()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.isEmpty(List.of("a", "b", "c"))) .withMessage("Expected [a, b, c] to be empty"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.isEmpty(List.of("a", "b", "c"), () -> "some message")) .withMessage("some message"); } @Test void testNotEmpty() throws Exception { Assert.notEmpty(List.of("a", "b", "c")); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notEmpty(Collections.emptySet())) .withMessage("Given collection must not be empty"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notEmpty(Collections.emptySet(), () -> "some message")) .withMessage("some message"); } @Test void testHasSize() throws Exception { Assert.hasSize(List.of("a", "b", "c"), 3); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.hasSize(Collections.emptySet(), 1)) .withMessage("Expected [] to have size 1 but got 0 elements"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.hasSize(Collections.emptySet(), 1, () -> "some message")) .withMessage("some message"); } @Test void testEquals() throws Exception { Assert.equals(null, null); Assert.equals("a", "a"); Assert.equals(123, 123); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.equals("a", "b")) .withMessage("Expected 'a' to be equal to 'b'"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.equals(1, 2)) .withMessage("Expected 1 to be equal to 2"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.equals("a", "b", () -> "some message")) .withMessage("some message"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.equals(1, 2, () -> "some message")) .withMessage("some message"); } @Test void testIsTrue() throws Exception { Assert.isTrue(true, () -> ""); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.isTrue(false, () -> "some message")) .withMessage("some message"); } @Test void testIsFalse() throws Exception { Assert.isFalse(false, () -> ""); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.isFalse(true, () -> "some message")) .withMessage("some message"); } @Test void testIsNull() throws Exception { Assert.isNull(null); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.isNull("abc")) .withMessage("Given value 'abc' must not be null"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.isNull(new Object(), () -> "some message")) .withMessage("some message"); } @Test void testNotNull() throws Exception { Assert.notNull(""); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notNull(null)) .withMessage("Given value must not be null"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notNull(null, () -> "some message")) .withMessage("some message"); } @Test void testStartsWith() throws Exception { Assert.startsWith("abc", "ab"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.startsWith("abc", "b")) .withMessage("'abc' must start with 'b'"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.startsWith("abc", "b", () -> "some message")) .withMessage("some message"); } @Test void testDoesNotStartWith() throws Exception { Assert.doesNotStartWith("a", "b"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.doesNotStartWith("abc", "ab")) .withMessage("'abc' must not start with 'ab'"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.doesNotStartWith("abc", "ab", () -> "some message")) .withMessage("some message"); } @Test void testNotNullOrEmpty() throws Exception { Assert.notNullOrEmpty("a"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notNullOrEmpty(null)) .withMessage("Given string 'null' must not be null or empty"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notNullOrEmpty("")) .withMessage("Given string '' must not be null or empty"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Assert.notNullOrEmpty("", () -> "some message")) .withMessage("some message"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/wire/MessageFlag.java package de.bwaldvogel.mongo.wire; public enum MessageFlag { CHECKSUM_PRESENT(0), MORE_TO_COME(1), EXHAUST_ALLOWED(16), ; private final int value; MessageFlag(int bit) { this.value = 1 << bit; } public boolean isSet(int flags) { return (flags & value) == value; } public int removeFrom(int flags) { return flags - value; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/oplog/CollectionBackedOplog.java package de.bwaldvogel.mongo.oplog; import java.util.List; import java.util.UUID; import java.util.function.Function; import java.util.stream.Stream; import de.bwaldvogel.mongo.MongoBackend; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.backend.Cursor; import de.bwaldvogel.mongo.backend.CursorRegistry; import de.bwaldvogel.mongo.backend.Utils; import de.bwaldvogel.mongo.backend.aggregation.Aggregation; import de.bwaldvogel.mongo.bson.BsonTimestamp; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.MongoServerException; public class CollectionBackedOplog implements Oplog { private static final long ELECTION_TERM = 1L; private static final String START_AT_OPERATION_TIME = "startAtOperationTime"; private static final String FULL_DOCUMENT = "fullDocument"; private static final String START_AFTER = "startAfter"; private static final String RESUME_AFTER = "resumeAfter"; private static final String OPERATION_TYPE = "operationType"; private static final String CLUSTER_TIME = "clusterTime"; private static final String DOCUMENT_KEY = "documentKey"; private final OplogClock oplogClock; private final MongoCollection<Document> collection; private final MongoBackend backend; private final CursorRegistry cursorRegistry; private final UUID ui = UUID.randomUUID(); public CollectionBackedOplog(MongoBackend backend, MongoCollection<Document> collection, CursorRegistry cursorRegistry) { this.oplogClock = new OplogClock(backend.getClock()); this.collection = collection; this.backend = backend; this.cursorRegistry = cursorRegistry; } @Override public void handleInsert(String namespace, List<Document> documents) { if (isOplogCollection(namespace)) { return; } Stream<Document> oplogInsertDocuments = documents.stream() .map(document -> toOplogInsertDocument(namespace, document)); addDocuments(oplogInsertDocuments); } @Override public void handleUpdate(String namespace, Document selector, Document query, List<Object> modifiedIds) { if (isOplogCollection(namespace)) { return; } Stream<Document> oplogUpdateDocuments = modifiedIds.stream() .map(id -> toOplogUpdateDocument(namespace, query, id)); addDocuments(oplogUpdateDocuments); } @Override public void handleDelete(String namespace, Document query, List<Object> deletedIds) { if (isOplogCollection(namespace)) { return; } Stream<Document> oplogDeleteDocuments = deletedIds.stream() .map(id -> toOplogDeleteDocument(namespace, id)); addDocuments(oplogDeleteDocuments); } private void addDocuments(Stream<Document> oplogDocuments) { collection.addDocuments(oplogDocuments); } @Override public void handleDropCollection(String namespace) { if (isOplogCollection(namespace)) { return; } final String databaseName = Utils.getDatabaseNameFromFullName(namespace); final String collectionName = Utils.getCollectionNameFromFullName(namespace); collection.addDocument(toOplogDropCollection(databaseName, collectionName)); } private Stream<Document> streamOplog(Document changeStreamDocument, OplogPosition position, Aggregation aggregation, String namespace) { return aggregation.runStagesAsStream(collection.queryAllAsStream() .filter(document -> filterNamespace(document, namespace)) .filter(document -> { BsonTimestamp timestamp = getOplogTimestamp(document); OplogPosition documentOplogPosition = new OplogPosition(timestamp); return documentOplogPosition.isAfter(position); }) .sorted((o1, o2) -> { BsonTimestamp timestamp1 = getOplogTimestamp(o1); BsonTimestamp timestamp2 = getOplogTimestamp(o2); return timestamp1.compareTo(timestamp2); }) .map(document -> toChangeStreamResponseDocument(document, changeStreamDocument))); } private static boolean filterNamespace(Document document, String namespace) { String docNS = (String) document.get(OplogDocumentFields.NAMESPACE); if (docNS.equals(namespace)) { return true; } return Utils.getDatabaseNameFromFullName(namespace).equals(Utils.getDatabaseNameFromFullName(docNS)) && Utils.getCollectionNameFromFullName(docNS).equals("$cmd"); } @Override public Cursor createCursor(Document changeStreamDocument, String namespace, Aggregation aggregation) { Document startAfter = (Document) changeStreamDocument.get(START_AFTER); Document resumeAfter = (Document) changeStreamDocument.get(RESUME_AFTER); BsonTimestamp startAtOperationTime = (BsonTimestamp) changeStreamDocument.get(START_AT_OPERATION_TIME); final OplogPosition initialOplogPosition; if (startAfter != null) { initialOplogPosition = OplogPosition.fromDocument(startAfter); } else if (resumeAfter != null) { initialOplogPosition = OplogPosition.fromDocument(resumeAfter); String databaseName = Utils.getDatabaseNameFromFullName(namespace); String collectionName = Utils.getCollectionNameFromFullName(namespace); boolean resumeAfterTerminalEvent = collection.queryAllAsStream() .filter(document -> { BsonTimestamp timestamp = getOplogTimestamp(document); OplogPosition documentOplogPosition = new OplogPosition(timestamp); return initialOplogPosition.isAfter(documentOplogPosition.inclusive()); }) .anyMatch(document -> document.get(OplogDocumentFields.OPERATION_TYPE).equals(OperationType.COMMAND.getCode()) && document.get(OplogDocumentFields.NAMESPACE).equals(String.format("%s.$cmd", databaseName)) && document.get(OplogDocumentFields.O).equals(new Document("drop", collectionName)) ); if (resumeAfterTerminalEvent) { return new InvalidateOplogCursor(initialOplogPosition); } } else if (startAtOperationTime != null) { initialOplogPosition = new OplogPosition(startAtOperationTime).inclusive(); } else { initialOplogPosition = new OplogPosition(oplogClock.now()); } Function<OplogPosition, Stream<Document>> streamSupplier = position -> streamOplog(changeStreamDocument, position, aggregation, namespace); OplogCursor cursor = new OplogCursor(cursorRegistry.generateCursorId(), streamSupplier, initialOplogPosition); cursorRegistry.add(cursor); return cursor; } private Document toOplogDocument(OperationType operationType, String namespace) { return new Document() .append(OplogDocumentFields.TIMESTAMP, oplogClock.incrementAndGet()) .append("t", ELECTION_TERM) .append("h", 0L) .append("v", 2L) .append("op", operationType.getCode()) .append(OplogDocumentFields.NAMESPACE, namespace) .append("ui", ui) .append("wall", oplogClock.instant()); } private Document toOplogInsertDocument(String namespace, Document document) { return toOplogDocument(OperationType.INSERT, namespace) .append(OplogDocumentFields.O, document.cloneDeeply()); } private Document toOplogUpdateDocument(String namespace, Document query, Object id) { return toOplogDocument(OperationType.UPDATE, namespace) .append(OplogDocumentFields.O, query) .append(OplogDocumentFields.O2, new Document(OplogDocumentFields.ID, id)); } private Document toOplogDeleteDocument(String namespace, Object deletedDocumentId) { return toOplogDocument(OperationType.DELETE, namespace) .append(OplogDocumentFields.O, new Document(OplogDocumentFields.ID, deletedDocumentId)); } private Document toOplogDropCollection(String databaseName, String collectionName) { return toOplogDocument(OperationType.COMMAND, String.format("%s.$cmd", databaseName)) .append(OplogDocumentFields.O, new Document("drop", collectionName)); } private boolean isOplogCollection(String namespace) { return collection.getFullName().equals(namespace); } private Document getFullDocument(Document changeStreamDocument, Document document, OperationType operationType) { switch (operationType) { case INSERT: return getUpdateDocument(document); case DELETE: return null; case UPDATE: return lookUpUpdateDocument(changeStreamDocument, document); } throw new IllegalArgumentException("Invalid operation type"); } private Document lookUpUpdateDocument(Document changeStreamDocument, Document document) { Document deltaUpdate = getDeltaUpdate(getUpdateDocument(document)); if (changeStreamDocument.containsKey(FULL_DOCUMENT) && changeStreamDocument.get(FULL_DOCUMENT).equals("updateLookup")) { String namespace = (String) document.get(OplogDocumentFields.NAMESPACE); String databaseName = namespace.split("\\.")[0]; String collectionName = namespace.split("\\.")[1]; return backend.resolveDatabase(databaseName) .resolveCollection(collectionName, true) .queryAllAsStream() .filter(d -> d.get(OplogDocumentFields.ID).equals(((Document) document.get(OplogDocumentFields.O2)).get(OplogDocumentFields.ID))) .findFirst() .orElse(deltaUpdate); } return deltaUpdate; } private Document getDeltaUpdate(Document updateDocument) { Document delta = new Document(); if (updateDocument.containsKey("$set")) { delta.appendAll((Document) updateDocument.get("$set")); } if (updateDocument.containsKey("$unset")) { delta.appendAll((Document) updateDocument.get("$unset")); } return delta; } private Document toChangeStreamResponseDocument(Document oplogDocument, Document changeStreamDocument) { OperationType operationType = OperationType.fromCode(oplogDocument.get(OplogDocumentFields.OPERATION_TYPE).toString()); Document documentKey = new Document(); Document document = getUpdateDocument(oplogDocument); BsonTimestamp timestamp = getOplogTimestamp(oplogDocument); OplogPosition oplogPosition = new OplogPosition(timestamp); switch (operationType) { case UPDATE: case DELETE: documentKey = document; break; case INSERT: documentKey.append(OplogDocumentFields.ID, document.get(OplogDocumentFields.ID)); break; case COMMAND: return toChangeStreamCommandResponseDocument(oplogDocument, oplogPosition, timestamp); default: throw new IllegalArgumentException("Unexpected operation type: " + operationType); } return new Document() .append(OplogDocumentFields.ID, new Document(OplogDocumentFields.ID_DATA_KEY, oplogPosition.toHexString())) .append(OPERATION_TYPE, operationType.getDescription()) .append(FULL_DOCUMENT, getFullDocument(changeStreamDocument, oplogDocument, operationType)) .append(DOCUMENT_KEY, documentKey) .append(CLUSTER_TIME, timestamp); } private Document toChangeStreamCommandResponseDocument(Document oplogDocument, OplogPosition oplogPosition, BsonTimestamp timestamp) { Document document = getUpdateDocument(oplogDocument); String operationType = document.keySet().stream().findFirst().orElseThrow( () -> new MongoServerException("Unspecified command operation type") ); return new Document() .append(OplogDocumentFields.ID, new Document(OplogDocumentFields.ID_DATA_KEY, oplogPosition.toHexString())) .append(OPERATION_TYPE, operationType) .append(CLUSTER_TIME, timestamp); } private static BsonTimestamp getOplogTimestamp(Document document) { return (BsonTimestamp) document.get(OplogDocumentFields.TIMESTAMP); } private static Document getUpdateDocument(Document document) { return (Document) document.get(OplogDocumentFields.O); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/QueryResult.java package de.bwaldvogel.mongo.backend; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import de.bwaldvogel.mongo.bson.Document; public class QueryResult implements Iterable<Document> { private final Iterable<Document> documents; private final long cursorId; public QueryResult() { this(Collections.emptyList(), EmptyCursor.get()); } public QueryResult(Iterable<Document> documents, Cursor cursor) { this(documents, cursor.getId()); } public QueryResult(Iterable<Document> documents, long cursorId) { this.documents = documents; this.cursorId = cursorId; } public QueryResult(Iterable<Document> documents) { this(documents, EmptyCursor.get()); } public List<Document> collectDocuments() { if (documents instanceof List<?>) { return Collections.unmodifiableList((List<Document>) documents); } else { List<Document> documents = new ArrayList<>(); for (Document document : this) { documents.add(document); } return documents; } } @Override public Iterator<Document> iterator() { return documents.iterator(); } public long getCursorId() { return cursorId; } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/AbstractMongoCollectionTest.java package de.bwaldvogel.mongo.backend; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.ObjectId; import de.bwaldvogel.mongo.exception.ConflictingUpdateOperatorsException; public class AbstractMongoCollectionTest { private static class TestCollection extends AbstractMongoCollection<Object> { TestCollection(MongoDatabase database, String collectionName) { super(database, collectionName, CollectionOptions.withDefaults(), new CursorRegistry()); } @Override protected Object addDocumentInternal(Document document) { throw new UnsupportedOperationException(); } @Override public int count() { throw new UnsupportedOperationException(); } @Override protected Document getDocument(Object position) { throw new UnsupportedOperationException(); } @Override protected void removeDocument(Object position) { throw new UnsupportedOperationException(); } @Override protected QueryResult matchDocuments(Document query, Document orderBy, int numberToSkip, int numberToReturn, int batchSize, Document fieldSelector) { throw new UnsupportedOperationException(); } @Override protected void updateDataSize(int sizeDelta) { } @Override protected int getDataSize() { throw new UnsupportedOperationException(); } @Override protected void handleUpdate(Object position, Document oldDocument, Document newDocument) { // noop } @Override protected Stream<DocumentWithPosition<Object>> streamAllDocumentsWithPosition() { throw new UnsupportedOperationException(); } } private TestCollection collection; @BeforeEach void setUp() { MongoDatabase database = Mockito.mock(MongoDatabase.class); this.collection = new TestCollection(database, "some collection"); } @Test void testConvertSelector() throws Exception { assertThat(collection.convertSelectorToDocument(json(""))) .isEqualTo(json("")); assertThat(collection.convertSelectorToDocument(json("_id: 1"))) .isEqualTo(json("_id: 1")); assertThat(collection.convertSelectorToDocument(json("_id: 1, $set: {foo: 'bar'}"))) .isEqualTo(json("_id: 1")); assertThat(collection.convertSelectorToDocument(json("_id: 1, 'e.i': 14"))) .isEqualTo(json("_id: 1, e: {i: 14}")); assertThat(collection.convertSelectorToDocument(json("_id: 1, 'e.i.y': {foo: 'bar'}"))) .isEqualTo(json("_id: 1, e: {i: {y: {foo: 'bar'}}}")); } @Test void testDeriveDocumentId() throws Exception { assertThat(collection.deriveDocumentId(json(""))).isInstanceOf(ObjectId.class); assertThat(collection.deriveDocumentId(json("a: 1"))).isInstanceOf(ObjectId.class); assertThat(collection.deriveDocumentId(json("_id: 1"))).isEqualTo(1); assertThat(collection.deriveDocumentId(json("_id: {$in: [1]}"))).isEqualTo(1); assertThat(collection.deriveDocumentId(json("_id: {$in: []}"))).isInstanceOf(ObjectId.class); } @Test void testValidateUpdateQuery() throws Exception { AbstractMongoCollection.validateUpdateQuery(new Document()); AbstractMongoCollection.validateUpdateQuery(json("$set: {a: 1, b: 1}")); AbstractMongoCollection.validateUpdateQuery(json("$set: {a: 1, b: 1}, $inc: {c: 1}")); AbstractMongoCollection.validateUpdateQuery(json("$set: {'a.b.c': 1}, $inc: {'a.b.d': 1}")); AbstractMongoCollection.validateUpdateQuery(json("$set: {'a.b.c': 1}, $inc: {'a.c': 1}")); AbstractMongoCollection.validateUpdateQuery(json("$inc: {'a.$.y': 1, 'a.$.x': 1}")); AbstractMongoCollection.validateUpdateQuery(json("$inc: {'a.$.deleted': 1, 'a.$.deletedBy': 1}")); assertThatExceptionOfType(ConflictingUpdateOperatorsException.class) .isThrownBy(() -> AbstractMongoCollection.validateUpdateQuery(json("$set: {a: 1, b: 1}, $inc: {b: 1}"))) .withMessage("[Error 40] Updating the path 'b' would create a conflict at 'b'"); assertThatExceptionOfType(ConflictingUpdateOperatorsException.class) .isThrownBy(() -> AbstractMongoCollection.validateUpdateQuery(json("$set: {'a.b.c': 1}, $inc: {'a.b': 1}"))) .withMessage("[Error 40] Updating the path 'a.b' would create a conflict at 'a.b'"); } } <file_sep>/memory-backend/src/main/java/de/bwaldvogel/mongo/backend/memory/DocumentIterable.java package de.bwaldvogel.mongo.backend.memory; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import de.bwaldvogel.mongo.bson.Document; class DocumentIterable implements Iterable<Document> { private final List<Document> documents; private final boolean reversed; DocumentIterable(List<Document> documents) { this(documents, false); } private DocumentIterable(List<Document> documents, boolean reversed) { this.documents = documents; this.reversed = reversed; } DocumentIterable reversed() { return new DocumentIterable(documents, !reversed); } @Override public Iterator<Document> iterator() { if (!reversed) { return new DocumentIterator(documents); } else { return new ReverseDocumentIterator(documents); } } private abstract static class AbstractDocumentIterator implements Iterator<Document> { int pos; final List<Document> documents; Document current; AbstractDocumentIterator(List<Document> documents, int pos) { this.documents = documents; this.pos = pos; } protected abstract Document getNext(); @Override public boolean hasNext() { if (current == null) { current = getNext(); } return (current != null); } @Override public Document next() { if (!hasNext()) { throw new NoSuchElementException(); } Document document = current; current = getNext(); return document; } @Override public void remove() { throw new UnsupportedOperationException(); } } private static class DocumentIterator extends AbstractDocumentIterator { private DocumentIterator(List<Document> documents) { super(documents, 0); } @Override protected Document getNext() { while (pos < documents.size()) { Document document = documents.get(pos++); if (document != null) { return document; } } return null; } } private static class ReverseDocumentIterator extends AbstractDocumentIterator { private ReverseDocumentIterator(List<Document> documents) { super(documents, documents.size() - 1); } @Override protected Document getNext() { while (pos >= 0) { Document document = documents.get(pos--); if (document != null) { return document; } } return null; } } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/backend/aggregation/stage/RedactStageTest.java package de.bwaldvogel.mongo.backend.aggregation.stage; import static de.bwaldvogel.mongo.TestUtils.json; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import de.bwaldvogel.mongo.bson.Document; class RedactStageTest { @Test void testRedact() { assertThat(redact( json("_id: 1"), json("$cond: {if: {$eq: [\"$_id\", 1]}, then: \"$$KEEP\", else: \"$$PRUNE\"}")) ).contains(json("_id: 1")); assertThat(redact( json("_id: 1"), json("$cond: {if: {$eq: [\"$_id\", 0]}, then: \"$$PRUNE\", else: \"$$KEEP\"}")) ).contains(json("_id: 1")); assertThat(redact( json("_id: 1"), json("$cond: {if: {$eq: [\"$_id\", 1]}, then: \"$$PRUNE\", else: \"$$KEEP\"}")) ).isEmpty(); assertThat(redact( json("_id: 1"), json("$cond: {if: {$eq: [\"$_id\", 0]}, then: \"$$KEEP\", else: \"$$PRUNE\"}")) ).isEmpty(); } private static List<Document> redact(Document input, Document redact) { return new RedactStage(redact).apply(Stream.of(input)).collect(Collectors.toList()); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractCursor.java package de.bwaldvogel.mongo.backend; public abstract class AbstractCursor implements Cursor { protected final long id; protected AbstractCursor(long id) { this.id = id; } @Override public long getId() { return id; } @Override public String toString() { return getClass().getSimpleName() + "(id: " + id + ")"; } } <file_sep>/core/src/test/java/de/bwaldvogel/mongo/bson/Decimal128Test.java package de.bwaldvogel.mongo.bson; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.math.BigDecimal; import org.junit.jupiter.api.Test; import nl.jqno.equalsverifier.EqualsVerifier; class Decimal128Test { @Test void testEqualsAndHashCodeContract() throws Exception { EqualsVerifier.forClass(Decimal128.class).verify(); } @Test void testFromAndToBigDecimal() throws Exception { assertThat(new Decimal128(new BigDecimal("1.2345")).toBigDecimal().toString()).isEqualTo("1.2345"); assertThat(new Decimal128(new BigDecimal("1.2345678901234567890123465789")).toBigDecimal().toString()).isEqualTo("1.2345678901234567890123465789"); assertThat(new Decimal128(new BigDecimal("12345678901234567890123465789")).toBigDecimal().toString()).isEqualTo("12345678901234567890123465789"); assertThat(new Decimal128(new BigDecimal("-1.2345")).toBigDecimal().toString()).isEqualTo("-1.2345"); assertThat(new Decimal128(new BigDecimal("0.0")).toBigDecimal().toString()).isEqualTo("0.0"); assertThat(new Decimal128(new BigDecimal("0").scaleByPowerOfTen(100)).toBigDecimal().toString()).isEqualTo("0E+100"); assertThat(new Decimal128(new BigDecimal("-0")).toBigDecimal().toString()).isEqualTo("0"); } @Test void testFromBigDecimal_NumberFormatException() { assertThatExceptionOfType(NumberFormatException.class) .isThrownBy(() -> new Decimal128(new BigDecimal("2").scaleByPowerOfTen(10000))) .withMessage("Exponent is out of range for Decimal128 encoding of 2E+10000"); assertThatExceptionOfType(NumberFormatException.class) .isThrownBy(() -> new Decimal128(new BigDecimal("1.23456789012345678901234657890123456789"))) .withMessage("Conversion to Decimal128 would require inexact rounding of 1.23456789012345678901234657890123456789"); assertThatExceptionOfType(NumberFormatException.class) .isThrownBy(() -> new Decimal128(new BigDecimal("2").scaleByPowerOfTen(-10000))) .withMessage("Conversion to Decimal128 would require inexact rounding of 2E-10000"); } @Test void testToInt() throws Exception { assertThat(Decimal128.ONE.intValue()).isEqualTo(1); assertThat(Decimal128.POSITIVE_ZERO.intValue()).isEqualTo(0); assertThat(Decimal128.NEGATIVE_ZERO.intValue()).isEqualTo(0); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(Decimal128.NaN::intValue) .withMessage("NaN cannot be converted to BigDecimal"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(Decimal128.POSITIVE_INFINITY::intValue) .withMessage("Infinity cannot be converted to BigDecimal"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(Decimal128.NEGATIVE_INFINITY::intValue) .withMessage("-Infinity cannot be converted to BigDecimal"); } @Test void testToLong() throws Exception { assertThat(Decimal128.ONE.longValue()).isEqualTo(1L); assertThat(Decimal128.POSITIVE_ZERO.longValue()).isEqualTo(0L); assertThat(Decimal128.NEGATIVE_ZERO.longValue()).isEqualTo(0L); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(Decimal128.NaN::longValue) .withMessage("NaN cannot be converted to BigDecimal"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(Decimal128.POSITIVE_INFINITY::longValue) .withMessage("Infinity cannot be converted to BigDecimal"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(Decimal128.NEGATIVE_INFINITY::longValue) .withMessage("-Infinity cannot be converted to BigDecimal"); } @Test void testToFloat() throws Exception { assertThat(Decimal128.ONE.floatValue()).isEqualTo(1.0f); assertThat(Decimal128.POSITIVE_ZERO.floatValue()).isEqualTo(0.0f); assertThat(Decimal128.NEGATIVE_ZERO.floatValue()).isEqualTo(0.0f); assertThat(Decimal128.NaN.floatValue()).isNaN(); assertThat(Decimal128.POSITIVE_INFINITY.floatValue()).isEqualTo(Float.POSITIVE_INFINITY); assertThat(Decimal128.NEGATIVE_INFINITY.floatValue()).isEqualTo(Float.NEGATIVE_INFINITY); } @Test void testToDouble() throws Exception { assertThat(Decimal128.ONE.doubleValue()).isEqualTo(1.0); assertThat(Decimal128.POSITIVE_ZERO.doubleValue()).isEqualTo(0.0); assertThat(Decimal128.NEGATIVE_ZERO.doubleValue()).isEqualTo(0.0); assertThat(Decimal128.NaN.doubleValue()).isNaN(); assertThat(Decimal128.POSITIVE_INFINITY.doubleValue()).isEqualTo(Double.POSITIVE_INFINITY); assertThat(Decimal128.NEGATIVE_INFINITY.doubleValue()).isEqualTo(Double.NEGATIVE_INFINITY); } @Test void testToString() throws Exception { assertThat(new Decimal128(new BigDecimal("1e1000"))).hasToString("1E+1000"); assertThat(new Decimal128(new BigDecimal("1000"))).hasToString("1000"); assertThat(new Decimal128(new BigDecimal("1000.987654321"))).hasToString("1000.987654321"); assertThat(new Decimal128(new BigDecimal("1000").scaleByPowerOfTen(2))).hasToString("1.000E+5"); assertThat(Decimal128.POSITIVE_INFINITY).hasToString("Infinity"); assertThat(Decimal128.NEGATIVE_INFINITY).hasToString("-Infinity"); assertThat(Decimal128.NaN).hasToString("NaN"); } } <file_sep>/test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractOplogTest.java package de.bwaldvogel.mongo.backend; import static com.mongodb.client.model.Aggregates.match; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Updates.set; import static com.mongodb.client.model.Updates.unset; import static de.bwaldvogel.mongo.backend.TestUtils.json; import static de.bwaldvogel.mongo.backend.TestUtils.toArray; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.NoSuchElementException; import java.util.UUID; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonTimestamp; import org.bson.Document; import org.bson.conversions.Bson; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import com.mongodb.client.ChangeStreamIterable; import com.mongodb.client.MongoChangeStreamCursor; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.ReplaceOptions; import com.mongodb.client.model.changestream.ChangeStreamDocument; import com.mongodb.client.model.changestream.FullDocument; import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.UpdateResult; import de.bwaldvogel.mongo.oplog.OperationType; public abstract class AbstractOplogTest extends AbstractTest { protected static final String LOCAL_DATABASE = "local"; protected static final String OPLOG_COLLECTION_NAME = "oplog.rs"; @BeforeEach void beforeEach() { backend.enableOplog(); } @Override protected void dropAllDatabases() { super.dropAllDatabases(); clearOplog(); } protected void clearOplog() { getOplogCollection().deleteMany(json("")); } protected MongoCollection<Document> getOplogCollection() { MongoDatabase localDb = syncClient.getDatabase(LOCAL_DATABASE); return localDb.getCollection(OPLOG_COLLECTION_NAME); } @Test void testListDatabaseNames() throws Exception { assertThat(listDatabaseNames()).contains(LOCAL_DATABASE); collection.insertOne(json("")); assertThat(listDatabaseNames()).containsExactlyInAnyOrder(db.getName(), LOCAL_DATABASE); syncClient.getDatabase("bar").getCollection("some-collection").insertOne(json("")); assertThat(listDatabaseNames()).containsExactlyInAnyOrder("bar", db.getName(), LOCAL_DATABASE); } @Test void testOplogInsertUpdateAndDelete() { Document document = json("_id: 1, name: 'testUser1'"); collection.insertOne(document); clock.windForward(Duration.ofSeconds(1)); collection.updateOne(json("_id: 1"), json("$set: {name: 'user 2'}")); clock.windForward(Duration.ofSeconds(1)); collection.deleteOne(json("_id: 1")); List<Document> oplogDocuments = toArray(getOplogCollection().find().sort(json("ts: 1"))); assertThat(oplogDocuments).hasSize(3); Document insertOplogDocument = oplogDocuments.get(0); assertThat(insertOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o"); assertThat(insertOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(insertOplogDocument.get("t")).isEqualTo(1L); assertThat(insertOplogDocument.get("h")).isEqualTo(0L); assertThat(insertOplogDocument.get("v")).isEqualTo(2L); assertThat(insertOplogDocument.get("op")).isEqualTo(OperationType.INSERT.getCode()); assertThat(insertOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(insertOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(insertOplogDocument.get("wall")).isEqualTo(Date.from(Instant.parse("2019-05-23T12:00:00.123Z"))); assertThat(insertOplogDocument.get("o")).isEqualTo(document); Document updateOplogDocument = oplogDocuments.get(1); assertThat(updateOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o", "o2"); assertThat(updateOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(updateOplogDocument.get("t")).isEqualTo(1L); assertThat(updateOplogDocument.get("h")).isEqualTo(0L); assertThat(updateOplogDocument.get("v")).isEqualTo(2L); assertThat(updateOplogDocument.get("op")).isEqualTo(OperationType.UPDATE.getCode()); assertThat(updateOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(updateOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(updateOplogDocument.get("wall")).isEqualTo(Date.from(Instant.parse("2019-05-23T12:00:01.123Z"))); assertThat(updateOplogDocument.get("o2")).isEqualTo(json("_id: 1")); assertThat(updateOplogDocument.get("o")).isEqualTo(json("$set: {name: 'user 2'}")); Document deleteOplogDocument = oplogDocuments.get(2); assertThat(deleteOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o"); assertThat(deleteOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(deleteOplogDocument.get("t")).isEqualTo(1L); assertThat(deleteOplogDocument.get("h")).isEqualTo(0L); assertThat(deleteOplogDocument.get("v")).isEqualTo(2L); assertThat(deleteOplogDocument.get("op")).isEqualTo(OperationType.DELETE.getCode()); assertThat(deleteOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(deleteOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(deleteOplogDocument.get("wall")).isEqualTo(Date.from(Instant.parse("2019-05-23T12:00:02.123Z"))); assertThat(deleteOplogDocument.get("o")).isEqualTo(json("_id: 1")); } @Test void testQueryOplogWhenOplogIsDisabled() throws Exception { backend.disableOplog(); collection.insertOne(json("_id: 1")); assertThat(getOplogCollection().find()).isEmpty(); } @Test void testSetOplogReplaceOneById() { collection.insertOne(json("_id: 1, b: 6")); collection.replaceOne(json("_id: 1"), json("a: 5, b: 7")); List<Document> oplogDocuments = toArray(getOplogCollection().find().sort(json("ts: 1"))); Document updateOplogEntry = oplogDocuments.get(1); assertThat(updateOplogEntry.get("op")).isEqualTo(OperationType.UPDATE.getCode()); assertThat(updateOplogEntry.get("ns")).isEqualTo(collection.getNamespace().toString()); assertThat(updateOplogEntry.get("o")).isEqualTo(json("_id: 1, a: 5, b: 7")); assertThat(updateOplogEntry.get("o2")).isEqualTo(json("_id: 1")); } @Test void testSetOplogUpdateOneById() { collection.insertOne(json("_id: 34, b: 6")); collection.updateOne(eq("_id", 34), set("a", 6)); List<Document> oplogDocuments = toArray(getOplogCollection().find(json("op: 'u'")).sort(json("ts: 1"))); Document updateOplogDocument = CollectionUtils.getSingleElement(oplogDocuments); assertThat(updateOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o", "o2"); assertThat(updateOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(updateOplogDocument.get("t")).isEqualTo(1L); assertThat(updateOplogDocument.get("h")).isEqualTo(0L); assertThat(updateOplogDocument.get("v")).isEqualTo(2L); assertThat(updateOplogDocument.get("op")).isEqualTo(OperationType.UPDATE.getCode()); assertThat(updateOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(updateOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(updateOplogDocument.get("o2")).isEqualTo(json("_id: 34")); assertThat(updateOplogDocument.get("o")).isEqualTo(json("$set: {a: 6}")); } @Test @Disabled("This test represents a missing feature") void testSetOplogUpdateOneByIdMultipleFields() { collection.insertOne(json("_id: 1, b: 6")); collection.updateOne(eq("_id", 1), List.of(set("a", 7), set("b", 7))); List<Document> oplogDocuments = toArray(getOplogCollection().find().sort(json("ts: 1"))); Document updateOplogDocument = oplogDocuments.get(1); assertThat(updateOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o", "o2"); assertThat(updateOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(updateOplogDocument.get("t")).isEqualTo(1L); assertThat(updateOplogDocument.get("h")).isEqualTo(0L); assertThat(updateOplogDocument.get("v")).isEqualTo(2L); assertThat(updateOplogDocument.get("op")).isEqualTo(OperationType.UPDATE.getCode()); assertThat(updateOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(updateOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(updateOplogDocument.get("o2")).isEqualTo(json("_id: 1")); assertThat(updateOplogDocument.get("o")).isEqualTo(json("$set: {a: 7, b: 7}")); } @Test void testSetOplogUpdateMany() { collection.insertMany(List.of(json("_id: 1, b: 6"), json("_id: 2, b: 6"))); collection.updateMany(eq("b", 6), set("a", 7)); List<Document> oplogDocuments = toArray(getOplogCollection().find(json("op: 'u'")).sort(json("ts: 1, 'o2._id': 1"))); assertThat(oplogDocuments).hasSize(2); for (int i = 0; i < 2; i++) { Document updateOplogDocument = oplogDocuments.get(i); assertThat(updateOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o", "o2"); assertThat(updateOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(updateOplogDocument.get("t")).isEqualTo(1L); assertThat(updateOplogDocument.get("h")).isEqualTo(0L); assertThat(updateOplogDocument.get("v")).isEqualTo(2L); assertThat(updateOplogDocument.get("op")).isEqualTo(OperationType.UPDATE.getCode()); assertThat(updateOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(updateOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(updateOplogDocument.get("o2")).isEqualTo(json(String.format("_id: %d", i + 1))); assertThat(updateOplogDocument.get("o")).isEqualTo(json("$set: {a: 7}")); } } @Test void testSetOplogDeleteMany() { collection.insertMany(List.of(json("_id: 1, b: 6"), json("_id: 2, b: 6"))); collection.deleteMany(eq("b", 6)); List<Document> oplogDocuments = toArray(getOplogCollection().find(json("op: 'd'")).sort(json("ts: 1, 'o._id': 1"))); assertThat(oplogDocuments).hasSize(2); for (int i = 0; i < 2; i++) { Document updateOplogDocument = oplogDocuments.get(i); assertThat(updateOplogDocument).containsKeys("ts", "t", "h", "v", "op", "ns", "ui", "wall", "o"); assertThat(updateOplogDocument.get("ts")).isInstanceOf(BsonTimestamp.class); assertThat(updateOplogDocument.get("t")).isEqualTo(1L); assertThat(updateOplogDocument.get("h")).isEqualTo(0L); assertThat(updateOplogDocument.get("v")).isEqualTo(2L); assertThat(updateOplogDocument.get("op")).isEqualTo(OperationType.DELETE.getCode()); assertThat(updateOplogDocument.get("ns")).isEqualTo(collection.getNamespace().getFullName()); assertThat(updateOplogDocument.get("ui")).isInstanceOf(UUID.class); assertThat(updateOplogDocument.get("o")).isEqualTo(json(String.format("_id: %d", i + 1))); } } @Test void testChangeStreamInsertAndUpdateFullDocumentLookup() { collection.insertOne(json("b: 1")); int numberOfDocs = 10; List<Document> insert = new ArrayList<>(); List<Document> update = new ArrayList<>(); List<ChangeStreamDocument<Document>> changeStreamsResult = new ArrayList<>(); List<Bson> pipeline = List.of(match(Filters.or( Document.parse("{'fullDocument.b': 1}"))) ); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch(pipeline).fullDocument(FullDocument.UPDATE_LOOKUP).cursor()) { final long cursorId = cursor.getServerCursor().getId(); for (int i = 1; i < numberOfDocs + 1; i++) { Document doc = json(String.format("a: %d, b: 1", i)); collection.insertOne(doc); collection.updateOne(eq("a", i), set("c", i * 10)); assertThat(cursor.hasNext()).isTrue(); ChangeStreamDocument<Document> insertDocument = cursor.next(); assertThat(cursor.getServerCursor().getId()).isEqualTo(cursorId); assertThat(cursor.hasNext()).isTrue(); ChangeStreamDocument<Document> updateDocument = cursor.next(); assertThat(cursor.getServerCursor().getId()).isEqualTo(cursorId); assertThat(insertDocument.getFullDocument().get("a")).isEqualTo(i); insert.add(insertDocument.getFullDocument()); assertThat(updateDocument.getFullDocument().get("a")).isEqualTo(i); update.add(updateDocument.getFullDocument()); changeStreamsResult.addAll(List.of(insertDocument, updateDocument)); } } assertThat(insert.size()).isEqualTo(numberOfDocs); assertThat(update.size()).isEqualTo(numberOfDocs); assertThat(changeStreamsResult.size()).isEqualTo(numberOfDocs * 2); } @Test void testChangeStreamUpdateDefault() { collection.insertOne(json("a: 1, b: 2, c: 3")); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor()) { collection.updateOne(eq("a", 1), json("$set: {b: 0, c: 10}")); ChangeStreamDocument<Document> updateDocument = cursor.next(); Document fullDoc = updateDocument.getFullDocument(); assertThat(fullDoc).isNotNull(); assertThat(fullDoc.get("b")).isEqualTo(0); assertThat(fullDoc.get("c")).isEqualTo(10); collection.updateOne(eq("a", 1), unset("b")); updateDocument = cursor.next(); fullDoc = updateDocument.getFullDocument(); assertThat(fullDoc).isNotNull(); assertThat(fullDoc.get("b")).isEqualTo(""); } } @Test void testChangeStreamDelete() { collection.insertOne(json("_id: 1")); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor()) { collection.deleteOne(json("_id: 1")); ChangeStreamDocument<Document> deleteDocument = cursor.next(); assertThat(deleteDocument.getDocumentKey().get("_id")).isEqualTo(new BsonInt32(1)); } } @Test void testChangeStreamStartAfter() { collection.insertOne(json("a: 1")); // This is needed to initialize the collection in the server. try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor()) { collection.insertOne(json("a: 2")); collection.insertOne(json("a: 3")); ChangeStreamDocument<Document> document = cursor.next(); BsonDocument resumeToken = document.getResumeToken(); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor2 = collection.watch().startAfter(resumeToken).cursor()) { ChangeStreamDocument<Document> document2 = cursor2.next(); assertThat(document2.getFullDocument().get("a")).isEqualTo(3); } } } @Test void testChangeStreamResumeAfter() throws Exception { collection.insertOne(json("a: 1")); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor()) { awaitNumberOfOpenCursors(1); collection.insertOne(json("a: 2")); collection.insertOne(json("a: 3")); ChangeStreamDocument<Document> document = cursor.next(); BsonDocument resumeToken = document.getResumeToken(); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor2 = collection.watch().resumeAfter(resumeToken).cursor()) { awaitNumberOfOpenCursors(2); ChangeStreamDocument<Document> document2 = cursor2.next(); assertThat(document2.getFullDocument().get("a")).isEqualTo(3); } } } @Test void testChangeStreamResumeAfterTerminalEvent() { MongoCollection<Document> col = db.getCollection("test-collection"); ChangeStreamIterable<Document> watch = col.watch().fullDocument(FullDocument.UPDATE_LOOKUP).batchSize(1); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = watch.cursor()) { col.insertOne(json("a: 1")); cursor.next(); col.drop(); ChangeStreamDocument<Document> document = cursor.next(); BsonDocument resumeToken = document.getResumeToken(); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> resumeAfterCursor = watch.resumeAfter(resumeToken).cursor();) { document = resumeAfterCursor.next(); assertThat(document).isNotNull(); assertThat(document.getOperationType()) .isEqualTo(com.mongodb.client.model.changestream.OperationType.INVALIDATE); assertThatExceptionOfType(NoSuchElementException.class) .isThrownBy(resumeAfterCursor::next); } } } @Test void testChangeStreamStartAtOperationTime() { collection.insertOne(json("a: 1")); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor = collection.watch().cursor()) { collection.insertOne(json("a: 2")); collection.insertOne(json("a: 3")); ChangeStreamDocument<Document> document = cursor.next(); BsonTimestamp startAtOperationTime = document.getClusterTime(); try (MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor2 = collection.watch().startAtOperationTime(startAtOperationTime).cursor()) { ChangeStreamDocument<Document> document2 = cursor2.next(); assertThat(document2.getFullDocument().get("a")).isEqualTo(2); document2 = cursor2.next(); assertThat(document2.getFullDocument().get("a")).isEqualTo(3); } } } @Test void testChangeStreamAndReplaceOneWithUpsertTrue() throws Exception { TestSubscriber<ChangeStreamDocument<Document>> streamSubscriber = new TestSubscriber<>(); asyncCollection.watch().fullDocument(FullDocument.UPDATE_LOOKUP).subscribe(streamSubscriber); awaitNumberOfOpenCursors(1); TestSubscriber<UpdateResult> replaceOneSubscriber = new TestSubscriber<>(); asyncCollection.replaceOne(json("a: 1"), json("a: 1"), new ReplaceOptions().upsert(true)) .subscribe(replaceOneSubscriber); replaceOneSubscriber.awaitSingleValue(); TestSubscriber<Document> findSubscriber = new TestSubscriber<>(); asyncCollection.find(json("a:1")).subscribe(findSubscriber); assertThat(findSubscriber.awaitSingleValue().get("a")).isEqualTo(1); ChangeStreamDocument<Document> value = streamSubscriber.awaitSingleValue(); assertThat(value.getOperationType().getValue()).isEqualTo("insert"); assertThat(value.getFullDocument()).isEqualTo(findSubscriber.awaitSingleValue()); } @Test void testSimpleChangeStreamWithFilter() throws Exception { insertOne(asyncCollection, json("_id: 1")); Bson filter = match(Filters.eq("fullDocument.bu", "abc")); List<Bson> pipeline = List.of(filter); super.assertNoOpenCursors(); TestSubscriber<ChangeStreamDocument<Document>> streamSubscriber = new TestSubscriber<>(); asyncCollection.watch(pipeline).subscribe(streamSubscriber); awaitNumberOfOpenCursors(1); insertOne(asyncCollection, json("_id: 2, bu: 'abc'")); insertOne(asyncCollection, json("_id: 3, bu: 'xyz'")); ChangeStreamDocument<Document> changeStreamDocument = streamSubscriber.awaitSingleValue(); assertThat(changeStreamDocument.getFullDocument().get("bu")).isEqualTo("abc"); } @Test void testOplogSubscription() throws Exception { super.assertNoOpenCursors(); TestSubscriber<ChangeStreamDocument<Document>> streamSubscriber = new TestSubscriber<>(); asyncCollection.watch().subscribe(streamSubscriber); awaitNumberOfOpenCursors(1); insertOne(asyncCollection, json("_id: 1")); ChangeStreamDocument<Document> changeStreamDocument = streamSubscriber.awaitSingleValue(); assertThat(changeStreamDocument.getOperationType()).isEqualTo(com.mongodb.client.model.changestream.OperationType.INSERT); assertThat(changeStreamDocument.getFullDocument()).isEqualTo(json("_id: 1")); } @Test void testOplogShouldFilterNamespaceOnChangeStreams() throws Exception { com.mongodb.reactivestreams.client.MongoCollection<Document> asyncCollection1 = asyncDb.getCollection(asyncCollection.getNamespace().getCollectionName() + "1"); insertOne(asyncCollection, json("_id: 1")); insertOne(asyncCollection1, json("_id: 1")); super.assertNoOpenCursors(); TestSubscriber<ChangeStreamDocument<Document>> streamSubscriber = new TestSubscriber<>(); asyncCollection.watch().subscribe(streamSubscriber); awaitNumberOfOpenCursors(1); insertOne(asyncCollection1, json("_id: 2")); insertOne(asyncCollection, json("_id: 2")); streamSubscriber.awaitSingleValue(); } private static void insertOne(com.mongodb.reactivestreams.client.MongoCollection<Document> collection, Document document) throws Exception { TestSubscriber<InsertOneResult> insertSubscriber = new TestSubscriber<>(); collection.insertOne(document).subscribe(insertSubscriber); insertSubscriber.awaitSingleValue(); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/VisibleForExternalBackends.java package de.bwaldvogel.mongo.backend; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.SOURCE) @interface VisibleForExternalBackends { } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/NamespaceExistsException.java package de.bwaldvogel.mongo.exception; public class NamespaceExistsException extends MongoServerError { private static final long serialVersionUID = 1L; public NamespaceExistsException(String message) { super(ErrorCode.NamespaceExists, message); } } <file_sep>/examples/build.gradle dependencies { api project(':mongo-java-server-memory-backend') api 'org.mongodb:mongo-java-driver:latest.release' api group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: 'latest.release' api group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: 'latest.release' api group: 'org.assertj', name: 'assertj-core', version: 'latest.release' runtimeOnly group: 'ch.qos.logback', name: 'logback-classic', version: '[1.3.0, 1.4.0)' } sourceSets { test { java.srcDirs += [ sourceSets.main.allJava ] } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/LegacyUUID.java package de.bwaldvogel.mongo.bson; import java.util.Objects; import java.util.UUID; public final class LegacyUUID implements Comparable<LegacyUUID>, Bson { private static final long serialVersionUID = 1L; private final UUID uuid; public LegacyUUID(UUID uuid) { this.uuid = Objects.requireNonNull(uuid); } public LegacyUUID(long mostSigBits, long leastSigBits) { this(new UUID(mostSigBits, leastSigBits)); } public UUID getUuid() { return uuid; } public static LegacyUUID fromString(String value) { return new LegacyUUID(UUID.fromString(value)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LegacyUUID that = (LegacyUUID) o; return getUuid().equals(that.getUuid()); } @Override public int hashCode() { return Objects.hash(getUuid()); } @Override public int compareTo(LegacyUUID o) { return getUuid().compareTo(o.getUuid()); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/AggregationStage.java package de.bwaldvogel.mongo.backend.aggregation.stage; import java.util.stream.Stream; import de.bwaldvogel.mongo.bson.Document; public interface AggregationStage { String name(); Stream<Document> apply(Stream<Document> stream); default boolean isModifying() { return false; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/AbstractUniqueIndex.java package de.bwaldvogel.mongo.backend; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; import java.util.regex.Matcher; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.bson.BsonRegularExpression; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.DuplicateKeyError; import de.bwaldvogel.mongo.exception.KeyConstraintError; public abstract class AbstractUniqueIndex<P> extends Index<P> { private static final Logger log = LoggerFactory.getLogger(AbstractUniqueIndex.class); protected AbstractUniqueIndex(String name, List<IndexKey> keys, boolean sparse) { super(name, keys, sparse); } protected abstract P removeDocument(KeyValue keyValue); protected boolean containsKey(KeyValue keyValue) { return getPosition(keyValue) != null; } protected abstract boolean putKeyPosition(KeyValue keyValue, P position); protected abstract Iterable<Entry<KeyValue, P>> getIterable(); protected abstract P getPosition(KeyValue keyValue); private boolean isSparseAndHasNoValueForKeys(Document document) { return isSparse() && hasNoValueForKeys(document); } private boolean hasNoValueForKeys(Document document) { return keys().stream().noneMatch(key -> Utils.hasSubdocumentValue(document, key)); } @Override public synchronized P remove(Document document) { if (isSparseAndHasNoValueForKeys(document)) { return null; } return apply(document, this::removeDocument); } @Override public P getPosition(Document document) { return apply(document, this::getPosition); } private P apply(Document document, Function<KeyValue, P> keyToPositionFunction) { Set<KeyValue> keyValues = getKeyValues(document); Set<P> positions = keyValues.stream() .map(keyToPositionFunction) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (positions.isEmpty()) { return null; } else { return CollectionUtils.getSingleElement(positions); } } @Override public synchronized void checkAdd(Document document, MongoCollection<P> collection) { if (isSparseAndHasNoValueForKeys(document)) { return; } for (KeyValue key : getKeyValues(document, false)) { KeyValue normalizedKey = key.normalized(); if (containsKey(normalizedKey)) { throw new DuplicateKeyError(this, collection, getKeys(), key); } } } @Override public synchronized void add(Document document, P position, MongoCollection<P> collection) { checkAdd(document, collection); if (isSparseAndHasNoValueForKeys(document)) { return; } Set<KeyValue> keyValues = getKeyValues(document); for (KeyValue keyValue : keyValues) { boolean added = putKeyPosition(keyValue, position); Assert.isTrue(added, () -> "Key " + keyValue + " already exists. Concurrency issue?"); } } @Override public synchronized void checkUpdate(Document oldDocument, Document newDocument, MongoCollection<P> collection) { if (nullAwareEqualsKeys(oldDocument, newDocument)) { return; } if (isSparseAndHasNoValueForKeys(newDocument)) { return; } P oldPosition = getDocumentPosition(oldDocument); for (KeyValue key : getKeyValues(newDocument, false)) { KeyValue normalizedKey = key.normalized(); P position = getPosition(normalizedKey); if (position != null && !position.equals(oldPosition)) { throw new DuplicateKeyError(this, collection, getKeys(), key); } } } private P getDocumentPosition(Document oldDocument) { Set<P> positions = getKeyValues(oldDocument).stream() .map(this::getPosition) .collect(StreamUtils.toLinkedHashSet()); return CollectionUtils.getSingleElement(positions); } @Override public void updateInPlace(Document oldDocument, Document newDocument, P position, MongoCollection<P> collection) throws KeyConstraintError { if (!nullAwareEqualsKeys(oldDocument, newDocument)) { P removedPosition = remove(oldDocument); if (removedPosition != null) { Assert.equals(removedPosition, position); } add(newDocument, position, collection); } } @Override public synchronized boolean canHandle(Document query) { if (!query.keySet().equals(keySet())) { return false; } if (isSparse() && query.values().stream().allMatch(Objects::isNull)) { return false; } for (String key : keys()) { Object queryValue = query.get(key); if (queryValue instanceof Document) { if (isCompoundIndex()) { // https://github.com/bwaldvogel/mongo-java-server/issues/80 // Not yet supported. Use some other index, or none: return false; } if (BsonRegularExpression.isRegularExpression(queryValue)) { return true; } for (String queriedKeys : ((Document) queryValue).keySet()) { if (isInQuery(queriedKeys)) { // okay } else if (queriedKeys.startsWith("$")) { // not yet supported return false; } } } } return true; } private static boolean isInQuery(String key) { return key.equals(QueryOperator.IN.getValue()); } @Override public synchronized Iterable<P> getPositions(Document query) { KeyValue queriedKeyValues = getQueriedKeyValues(query); for (Object queriedValue : queriedKeyValues) { if (BsonRegularExpression.isRegularExpression(queriedValue)) { if (isCompoundIndex()) { throw new UnsupportedOperationException("Not yet implemented"); } List<P> positions = new ArrayList<>(); for (Entry<KeyValue, P> entry : getIterable()) { KeyValue obj = entry.getKey(); if (obj.size() == 1) { Object o = obj.get(0); if (o instanceof String) { BsonRegularExpression regularExpression = BsonRegularExpression.convertToRegularExpression(queriedValue); Matcher matcher = regularExpression.matcher(o.toString()); if (matcher.find()) { positions.add(entry.getValue()); } } } } return positions; } else if (queriedValue instanceof Document) { if (isCompoundIndex()) { throw new UnsupportedOperationException("Not yet implemented"); } Document keyObj = (Document) queriedValue; if (Utils.containsQueryExpression(keyObj)) { String expression = CollectionUtils.getSingleElement(keyObj.keySet(), () -> new UnsupportedOperationException("illegal query key: " + queriedKeyValues)); if (expression.startsWith("$")) { return getPositionsForExpression(keyObj, expression); } } } else if (queriedValue instanceof Collection) { Collection<?> values = (Collection<?>) queriedValue; return values.stream() .map(KeyValue::new) .map(this::getPosition) .filter(Objects::nonNull) .collect(StreamUtils.toLinkedHashSet()); } } P position = getPosition(queriedKeyValues); if (position == null) { return List.of(); } return List.of(position); } private KeyValue getQueriedKeyValues(Document query) { return new KeyValue(keys().stream() .map(query::get) .map(Utils::normalizeValue) .collect(Collectors.toList())); } private Iterable<P> getPositionsForExpression(Document keyObj, String operator) { if (isInQuery(operator)) { @SuppressWarnings("unchecked") Collection<Object> objects = (Collection<Object>) keyObj.get(operator); Collection<Object> queriedObjects = new TreeSet<>(ValueComparator.asc()); queriedObjects.addAll(objects); List<P> allKeys = new ArrayList<>(); for (Object object : queriedObjects) { Object keyValue = Utils.normalizeValue(object); P key = getPosition(new KeyValue(keyValue)); if (key != null) { allKeys.add(key); } } return allKeys; } else { throw new UnsupportedOperationException("unsupported query expression: " + operator); } } @Override public boolean isUnique() { return true; } @Override public void drop() { log.debug("Dropping {}", this); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/KeyValue.java package de.bwaldvogel.mongo.backend; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import de.bwaldvogel.mongo.bson.Json; public final class KeyValue implements Serializable, Iterable<Object> { private static final long serialVersionUID = 1L; private final List<Object> values; public KeyValue(Object... values) { this(Arrays.asList(values)); } public KeyValue(Collection<?> values) { Assert.notEmpty(values); this.values = new ArrayList<>(values); } public int size() { return values.size(); } public Object get(int index) { return values.get(index); } @Override public Iterator<Object> iterator() { return values.iterator(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KeyValue keyValue = (KeyValue) o; return Objects.equals(values, keyValue.values); } @Override public int hashCode() { return Objects.hash(values); } @Override public String toString() { return values.stream() .map(value -> ": " + Json.toCompactJsonValue(value)) .collect(Collectors.joining(", ", "{ ", " }")); } public Stream<Object> stream() { return values.stream(); } public KeyValue normalized() { return new KeyValue(values.stream() .map(Utils::normalizeValue) .collect(Collectors.toList())); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/ExpressionTraits.java package de.bwaldvogel.mongo.backend.aggregation; import static de.bwaldvogel.mongo.backend.Missing.isNullOrMissing; import static de.bwaldvogel.mongo.backend.Utils.describeType; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.function.IntPredicate; import de.bwaldvogel.mongo.backend.CollectionUtils; import de.bwaldvogel.mongo.backend.ValueComparator; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.bson.ObjectId; import de.bwaldvogel.mongo.exception.ErrorCode; import de.bwaldvogel.mongo.exception.MongoServerError; interface ExpressionTraits { String name(); default Object requireSingleValue(List<?> list) { requireCollectionInSize(list, 1); return CollectionUtils.getSingleElement(list); } default String requireSingleStringValue(List<?> expressionValue) { Object value = requireSingleValue(expressionValue); if (!(value instanceof String)) { throw new MongoServerError(ErrorCode._34471, name() + " requires a string argument, found: " + describeType(value)); } return (String) value; } default Number evaluateNumericValue(List<?> expressionValue, Function<Double, ? extends Number> function) { Object value = requireSingleValue(expressionValue); if (isNullOrMissing(value)) { return null; } if (!(value instanceof Number)) { throw new MongoServerError(28765, name() + " only supports numeric types, not " + describeType(value)); } Number number = (Number) value; if (Double.isNaN(number.doubleValue())) { return number; } return function.apply(number.doubleValue()); } default int evaluateComparison(List<?> expressionValue) { TwoParameters parameters = requireTwoParameters(expressionValue); return ValueComparator.ascWithoutListHandling().compare(parameters.getFirst(), parameters.getSecond()); } default boolean evaluateComparison(List<?> expressionValue, IntPredicate comparison) { int comparisonResult = evaluateComparison(expressionValue); return comparison.test(comparisonResult); } default <T> T evaluateDateTime(List<?> expressionValue, Function<ZonedDateTime, T> dateFunction, Document document) { Object value = requireSingleValue(expressionValue); if (isNullOrMissing(value)) { return null; } ZonedDateTime zonedDateTime = getZonedDateTime(value, document); return dateFunction.apply(zonedDateTime); } default <T> T evaluateDate(List<?> expressionValue, Function<LocalDate, T> dateFunction, Document document) { return evaluateDateTime(expressionValue, zonedDateTime -> dateFunction.apply(zonedDateTime.toLocalDate()), document); } default <T> T evaluateTime(List<?> expressionValue, Function<LocalTime, T> timeFunction, Document document) { return evaluateDateTime(expressionValue, zonedDateTime -> timeFunction.apply(zonedDateTime.toLocalTime()), document); } default void requireCollectionInSize(List<?> value, int expectedCollectionSize) { if (value.size() != expectedCollectionSize) { throw new MongoServerError(16020, "Expression " + name() + " takes exactly " + expectedCollectionSize + " arguments. " + value.size() + " were passed in."); } } default TwoParameters requireTwoParameters(List<?> parameters) { requireCollectionInSize(parameters, 2); return new TwoParameters(parameters.get(0), parameters.get(1)); } default TwoNumericParameters requireTwoNumericParameters(List<?> value, int errorCode) { TwoParameters parameters = requireTwoParameters(value); Object one = parameters.getFirst(); Object other = parameters.getSecond(); if (parameters.isAnyNull()) { return null; } if (!(one instanceof Number && other instanceof Number)) { throw new MongoServerError(errorCode, name() + " only supports numeric types, not " + describeType(one) + " and " + describeType(other)); } return new TwoNumericParameters((Number) one, (Number) other); } default ZonedDateTime getZonedDateTime(Object value, Document document) { ZoneId timezone = ZoneId.systemDefault(); if (value instanceof Document) { Document valueAsDocument = (Document) value; if (!valueAsDocument.containsKey("date")) { throw new MongoServerError(40539, "missing 'date' argument to " + name() + ", provided: " + value); } value = Expression.evaluate(valueAsDocument.get("date"), document); Object timezoneExpression = Expression.evaluate(valueAsDocument.get("timezone"), document); if (timezoneExpression != null) { timezone = ZoneId.of(timezoneExpression.toString()); } } if (!(value instanceof Instant)) { throw new MongoServerError(16006, "can't convert from " + describeType(value) + " to Date"); } Instant instant = (Instant) value; return ZonedDateTime.ofInstant(instant, timezone); } default int requireIntegral(Object value, String name) { if (!(value instanceof Number)) { throw new MongoServerError(40096, name() + " requires an integral " + name + ", found a value of type: " + describeType(value) + ", with value: \"" + value + "\""); } Number number = (Number) value; int intValue = number.intValue(); if (intValue < 0) { throw new MongoServerError(40097, name() + " requires a nonnegative " + name + ", found: " + intValue); } return intValue; } default Object assertTwoToFourArguments(List<?> expressionValue) { if (expressionValue.size() < 2 || expressionValue.size() > 4) { throw new MongoServerError(28667, "Expression " + name() + " takes at least 2 arguments, and at most 4, but " + expressionValue.size() + " were passed in."); } Object first = expressionValue.get(0); if (isNullOrMissing(first)) { return null; } return first; } default <T> Object evaluateIndexOf(List<?> expressionValue, Function<String, List<T>> toList, int errorCodeFirstParameterTypeMismatch, int errorCodeSecondParameterTypeMismatch) { Object first = assertTwoToFourArguments(expressionValue); if (first == null) { return null; } if (!(first instanceof String)) { throw new MongoServerError(errorCodeFirstParameterTypeMismatch, name() + " requires a string as the first argument, found: " + describeType(first)); } List<T> elementsToSearchIn = toList.apply((String) first); Object searchValue = expressionValue.get(1); if (!(searchValue instanceof String)) { throw new MongoServerError(errorCodeSecondParameterTypeMismatch, name() + " requires a string as the second argument, found: " + describeType(searchValue)); } List<T> search = toList.apply((String) searchValue); Range range = indexOf(expressionValue, elementsToSearchIn.size()); elementsToSearchIn = elementsToSearchIn.subList(range.getStart(), range.getEnd()); int index = Collections.indexOfSubList(elementsToSearchIn, search); if (index >= 0) { return index + range.getStart(); } return index; } default Range indexOf(List<?> expressionValue, int size) { int start = 0; if (expressionValue.size() >= 3) { Object startValue = expressionValue.get(2); start = requireIntegral(startValue, "starting index"); start = Math.min(start, size); } int end = size; if (expressionValue.size() >= 4) { Object endValue = expressionValue.get(3); end = requireIntegral(endValue, "ending index"); end = Math.min(Math.max(start, end), size); } return new Range(start, end); } default Collection<?> requireArray(int errorCode, Object value) { if (!(value instanceof Collection)) { throw new MongoServerError(errorCode, "The argument to " + name() + " must be an array, but was of type: " + describeType(value)); } return (Collection<?>) value; } default Document requireDocument(Object expressionValue, int errorCode) { if (!(expressionValue instanceof Document)) { throw new MongoServerError(errorCode, name() + " only supports an object as its argument"); } return (Document) expressionValue; } default String evaluateString(List<?> expressionValue, Function<String, String> function) { Object value = requireSingleValue(expressionValue); value = convertToString(value); if (value == null) return null; return function.apply((String) value); } default String convertToString(Object value) { if (isNullOrMissing(value)) { return null; } else if (value instanceof String) { return (String) value; } else if (value instanceof Number) { return value.toString(); } else if (value instanceof ObjectId) { return ((ObjectId) value).getHexData(); } throw new MongoServerError(16007, "can't convert from BSON type " + describeType(value) + " to String"); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/IndexKey.java package de.bwaldvogel.mongo.backend; public class IndexKey { private final String key; private final boolean ascending; public IndexKey(String key, boolean ascending) { this.key = key; this.ascending = ascending; } public String getKey() { return key; } public boolean isAscending() { return ascending; } @Override public String toString() { return getClass().getSimpleName() + "[key=" + key + " " + (ascending ? "ASC" : "DESC") + "]"; } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/MongoBackend.java package de.bwaldvogel.mongo; import java.time.Clock; import java.util.Collection; import java.util.List; import de.bwaldvogel.mongo.backend.QueryResult; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.wire.message.MongoMessage; import de.bwaldvogel.mongo.wire.message.MongoQuery; import io.netty.channel.Channel; public interface MongoBackend { void handleClose(Channel channel); Document handleCommand(Channel channel, String database, String command, Document query); QueryResult handleQuery(MongoQuery query); Document handleMessage(MongoMessage message); void dropDatabase(String database); Collection<Document> getCurrentOperations(MongoQuery query); Document getServerStatus(); void close(); void closeCursors(List<Long> cursorIds); Clock getClock(); void enableOplog(); void disableOplog(); MongoDatabase resolveDatabase(String database); MongoBackend version(ServerVersion version); } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/bson/BsonJavaScript.java package de.bwaldvogel.mongo.bson; import java.util.Objects; public final class BsonJavaScript implements Bson { private static final long serialVersionUID = 1L; private final String code; public BsonJavaScript(String code) { this.code = code; } public String getCode() { return code; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BsonJavaScript that = (BsonJavaScript) o; return Objects.equals(getCode(), that.getCode()); } @Override public int hashCode() { return Objects.hash(getCode()); } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/EmptyIndex.java package de.bwaldvogel.mongo.backend; import java.util.List; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.KeyConstraintError; public class EmptyIndex<P> extends Index<P> { public EmptyIndex(String name, List<IndexKey> keys) { super(name, keys, true); } @Override public P getPosition(Document document) { return null; } @Override public void checkAdd(Document document, MongoCollection<P> collection) { // ignore } @Override public void add(Document document, P position, MongoCollection<P> collection) { // ignore } @Override public P remove(Document document) { return null; } @Override public boolean canHandle(Document query) { return false; } @Override public Iterable<P> getPositions(Document query) { throw new UnsupportedOperationException(); } @Override public long getCount() { return 0; } @Override public long getDataSize() { return 0; } @Override public void checkUpdate(Document oldDocument, Document newDocument, MongoCollection<P> collection) { // ignore } @Override public void updateInPlace(Document oldDocument, Document newDocument, P position, MongoCollection<P> collection) throws KeyConstraintError { // ignore } @Override public void drop() { } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/Aggregation.java package de.bwaldvogel.mongo.backend.aggregation; import static de.bwaldvogel.mongo.backend.Constants.ID_FIELD; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.bwaldvogel.mongo.MongoCollection; import de.bwaldvogel.mongo.MongoDatabase; import de.bwaldvogel.mongo.backend.Assert; import de.bwaldvogel.mongo.backend.CollectionUtils; import de.bwaldvogel.mongo.backend.DatabaseResolver; import de.bwaldvogel.mongo.backend.aggregation.stage.AddFieldsStage; import de.bwaldvogel.mongo.backend.aggregation.stage.AggregationStage; import de.bwaldvogel.mongo.backend.aggregation.stage.BucketStage; import de.bwaldvogel.mongo.backend.aggregation.stage.FacetStage; import de.bwaldvogel.mongo.backend.aggregation.stage.GraphLookupStage; import de.bwaldvogel.mongo.backend.aggregation.stage.GroupStage; import de.bwaldvogel.mongo.backend.aggregation.stage.IndexStatsStage; import de.bwaldvogel.mongo.backend.aggregation.stage.LimitStage; import de.bwaldvogel.mongo.backend.aggregation.stage.LookupStage; import de.bwaldvogel.mongo.backend.aggregation.stage.LookupWithPipelineStage; import de.bwaldvogel.mongo.backend.aggregation.stage.MatchStage; import de.bwaldvogel.mongo.backend.aggregation.stage.MergeStage; import de.bwaldvogel.mongo.backend.aggregation.stage.OutStage; import de.bwaldvogel.mongo.backend.aggregation.stage.ProjectStage; import de.bwaldvogel.mongo.backend.aggregation.stage.RedactStage; import de.bwaldvogel.mongo.backend.aggregation.stage.ReplaceRootStage; import de.bwaldvogel.mongo.backend.aggregation.stage.SampleStage; import de.bwaldvogel.mongo.backend.aggregation.stage.SkipStage; import de.bwaldvogel.mongo.backend.aggregation.stage.SortStage; import de.bwaldvogel.mongo.backend.aggregation.stage.TerminalStage; import de.bwaldvogel.mongo.backend.aggregation.stage.UnsetStage; import de.bwaldvogel.mongo.backend.aggregation.stage.UnwindStage; import de.bwaldvogel.mongo.bson.Document; import de.bwaldvogel.mongo.exception.ErrorCode; import de.bwaldvogel.mongo.exception.FailedToOptimizePipelineError; import de.bwaldvogel.mongo.exception.FailedToParseException; import de.bwaldvogel.mongo.exception.MongoServerError; import de.bwaldvogel.mongo.exception.MongoServerNotYetImplementedException; import de.bwaldvogel.mongo.exception.TypeMismatchException; import de.bwaldvogel.mongo.oplog.Oplog; public class Aggregation { private static final Logger log = LoggerFactory.getLogger(Aggregation.class); private final MongoCollection<?> collection; private final List<AggregationStage> stages = new ArrayList<>(); private Map<String, Object> variables = Collections.emptyMap(); private Aggregation(MongoCollection<?> collection) { this.collection = collection; } public static List<Document> parse(Object pipelineObject) { if (!(pipelineObject instanceof List)) { throw new TypeMismatchException("'pipeline' option must be specified as an array"); } List<Document> pipeline = new ArrayList<>(); for (Object pipelineElement : (List<?>) pipelineObject) { if (!(pipelineElement instanceof Document)) { throw new TypeMismatchException("Each element of the 'pipeline' array must be an object"); } pipeline.add((Document) pipelineElement); } return pipeline; } public static Aggregation fromPipeline(Object pipelineObject, DatabaseResolver databaseResolver, MongoDatabase database, MongoCollection<?> collection, Oplog oplog) { List<Document> pipeline = parse(pipelineObject); return fromPipeline(pipeline, databaseResolver, database, collection, oplog); } public static Aggregation fromPipeline(List<Document> pipeline, DatabaseResolver databaseResolver, MongoDatabase database, MongoCollection<?> collection, Oplog oplog) { Aggregation aggregation = new Aggregation(collection); for (Document stage : pipeline) { String stageOperation = CollectionUtils.getSingleElement(stage.keySet(), () -> { throw new MongoServerError(40323, "A pipeline stage specification object must contain exactly one field."); }); switch (stageOperation) { case "$match": Document matchQuery = (Document) stage.get(stageOperation); aggregation.addStage(new MatchStage(matchQuery)); break; case "$skip": Number numSkip = (Number) stage.get(stageOperation); aggregation.addStage(new SkipStage(numSkip.longValue())); break; case "$limit": Number numLimit = (Number) stage.get(stageOperation); aggregation.addStage(new LimitStage(numLimit.longValue())); break; case "$sort": Document orderBy = (Document) stage.get(stageOperation); aggregation.addStage(new SortStage(orderBy)); break; case "$project": Object projection = stage.get(stageOperation); aggregation.addStage(new ProjectStage(projection)); break; case "$count": String count = (String) stage.get(stageOperation); aggregation.addStage(new GroupStage(new Document(ID_FIELD, null).append(count, new Document("$sum", 1)))); aggregation.addStage(new ProjectStage(new Document(ID_FIELD, 0))); break; case "$group": Document groupDetails = (Document) stage.get(stageOperation); aggregation.addStage(new GroupStage(groupDetails)); break; case "$addFields": Document addFieldsDetails = (Document) stage.get(stageOperation); aggregation.addStage(new AddFieldsStage(addFieldsDetails)); break; case "$unwind": Object unwind = stage.get(stageOperation); aggregation.addStage(new UnwindStage(unwind)); break; case "$graphLookup": Document graphLookup = (Document) stage.get(stageOperation); aggregation.addStage(new GraphLookupStage(graphLookup, database)); break; case "$lookup": Document lookup = (Document) stage.get(stageOperation); if (lookup.containsKey(LookupWithPipelineStage.PIPELINE_FIELD)) { aggregation.addStage(new LookupWithPipelineStage(lookup, database, databaseResolver, oplog)); } else { aggregation.addStage(new LookupStage(lookup, database)); } break; case "$replaceRoot": Document replaceRoot = (Document) stage.get(stageOperation); aggregation.addStage(new ReplaceRootStage(replaceRoot)); break; case "$sample": Object sample = stage.get(stageOperation); aggregation.addStage(new SampleStage(sample)); break; case "$sortByCount": Object expression = stage.get(stageOperation); aggregation.addStage(new GroupStage(new Document(ID_FIELD, expression).append("count", new Document("$sum", 1)))); aggregation.addStage(new SortStage(new Document("count", -1).append(ID_FIELD, 1))); break; case "$bucket": Document bucket = (Document) stage.get(stageOperation); aggregation.addStage(new BucketStage(bucket)); break; case "$facet": Document facet = (Document) stage.get(stageOperation); aggregation.addStage(new FacetStage(facet, databaseResolver, database, collection, oplog)); break; case "$unset": Object unset = stage.get(stageOperation); aggregation.addStage(new UnsetStage(unset)); break; case "$indexStats": aggregation.addStage(new IndexStatsStage(collection)); break; case "$out": Object outCollection = stage.get(stageOperation); aggregation.addStage(new OutStage(database, outCollection)); break; case "$redact": Document redactExpression = (Document) stage.get(stageOperation); aggregation.addStage(new RedactStage(redactExpression)); break; case "$merge": Object mergeParams = stage.get(stageOperation); aggregation.addStage(new MergeStage(databaseResolver, database, mergeParams)); break; case "$geoNear": throw new MongoServerNotYetImplementedException(138, stageOperation); default: throw new MongoServerError(40324, "Unrecognized pipeline stage name: '" + stageOperation + "'"); } } return aggregation; } private List<Document> runStages() { return runStages(collection.queryAllAsStream()); } public List<Document> runStages(Stream<Document> stream) { return runStagesAsStream(stream).collect(Collectors.toList()); } public Stream<Document> runStagesAsStream(Stream<Document> stream) { if (hasVariables()) { stream = stream.map(this::addAllVariables); } for (AggregationStage stage : stages) { stream = stage.apply(stream); } if (hasVariables()) { stream = stream.map(this::removeAllVariables); } return stream; } private boolean hasVariables() { return !variables.isEmpty(); } private Document addAllVariables(Document document) { Document clone = document.clone(); clone.putAll(variables); return clone; } private Document removeAllVariables(Document document) { return CollectionUtils.removeAll(document, variables.keySet()); } private void addStage(AggregationStage stage) { this.stages.add(stage); } public List<Document> computeResult() { if (collection == null) { return Collections.emptyList(); } try { return runStages(); } catch (TypeMismatchException | FailedToOptimizePipelineError | ProjectStage.InvalidProjectException e) { throw e; } catch (MongoServerError e) { if (e.hasCode(ErrorCode._15998, ErrorCode._40353)) { throw e; } throw new PlanExecutorError(e); } } public void setVariables(Map<String, Object> variables) { this.variables = Collections.unmodifiableMap(variables); } public void validate(Document query) { stages.stream() .filter(stage -> stage instanceof TerminalStage) .map(TerminalStage.class::cast) .filter(terminalStage -> !isLastStage(terminalStage)) .findFirst() .ifPresent(nonFinalTerminalStage -> { throw new MongoServerError(40601, nonFinalTerminalStage.name() + " can only be the final stage in the pipeline"); }); Document cursor = (Document) query.get("cursor"); if (cursor == null) { throw new FailedToParseException("The 'cursor' option is required, except for aggregate with the explain argument"); } else if (!cursor.isEmpty()) { log.warn("Non-empty cursor is not yet implemented. Ignoring."); } } private boolean isLastStage(TerminalStage stage) { Assert.notEmpty(stages); return stages.indexOf(stage) == stages.size() - 1; } public List<AggregationStage> getStages() { return stages; } public boolean isModifying() { return stages.stream().anyMatch(AggregationStage::isModifying); } private static class PlanExecutorError extends MongoServerError { private static final long serialVersionUID = 1L; private static final String MESSAGE_PREFIX = "PlanExecutor error during aggregation :: caused by :: "; private PlanExecutorError(MongoServerError cause) { super(cause.getCode(), cause.getCodeName(), MESSAGE_PREFIX + cause.getMessageWithoutErrorCode(), cause); } } } <file_sep>/core/src/main/java/de/bwaldvogel/mongo/exception/InvalidOptionsException.java package de.bwaldvogel.mongo.exception; public class InvalidOptionsException extends MongoServerError { private static final long serialVersionUID = 1L; public InvalidOptionsException(String message) { super(ErrorCode.InvalidOptions, message); } }
0aed56d5eef24f34a91ad3c6fd99317ee69e228e
[ "YAML", "Markdown", "Gradle", "Java", "Shell" ]
124
Java
bwaldvogel/mongo-java-server
03b38aaeab892db986ef61084ada7ea581ca7300
0b508f5378f06d868ca5d663540f57d6d4336a0c
refs/heads/master
<repo_name>luciamata/square_array-ruby-apply-000<file_sep>/square_array.rb def square_array(array) new_array = [] array.each { |number| new_array<<number*number} new_array end
07a14d3e9a7182a8fd204639ffa6c494021275f4
[ "Ruby" ]
1
Ruby
luciamata/square_array-ruby-apply-000
55eac263bdeed9ae7b1a9e9a02ea99add7993ca8
e814ffcb290812c0d40ba9289dad4462530d8f4a
refs/heads/master
<repo_name>adamkowal001/hackathonWebServerMail<file_sep>/WebMail/Server/src/main/java/http/Request.java package http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.json.JSONObject; import DB.DBsupport; import DB.User; import email.Email; public class Request { private InputStream is; private BufferedReader br; private String method; private String author; public String getMethod() { return method; } public String getAuthor() { return author; } public Email getEmail() { return email; } public User getUser() { return user; } private JSONObject data; private Email email; private User user; private JSONObject json; public Request(InputStream is) { this.is = is; br = new BufferedReader(new InputStreamReader(is)); try { System.out.println("przed readline"); this.json = new JSONObject(br.readLine()); System.out.println(this.json.toString()); this.method = json.getString("method"); if (this.method.equals("read")) { author = json.getString("author"); }else if(this.method.equals("write")) { JsonToEmail(); }else if(this.method.equals("login")) { JsonToUser(); } } catch (IOException e) { e.printStackTrace(); } } public void JsonToEmail(){ this.data = json.getJSONObject("data"); email = new Email(json.getString("author"), json.getString("to"), json.getString("text")); } public void JsonToUser(){ this.data = json.getJSONObject("data"); user = new User(json.getString("author"), data.getString("password")); } }<file_sep>/WebMail/Client/src/main/java/email/Email.java package email; import org.json.JSONObject; public class Email { private String from; private String to; private String content; public Email(String from, String to, String content){ this.from = from; this.to = to; this.content = content; } public Email(JSONObject obj){ this.from = obj.getString("from"); this.to = obj.getString("to"); this.content = obj.getString("content"); } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } <file_sep>/WebMail/Server/src/main/java/Server.java import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import http.RequestHandler; public class Server { public static void main(String[] args){ ExecutorService es = Executors.newFixedThreadPool(5); try{ ServerSocket ss = new ServerSocket(3000); boolean finish = false; while(!finish) { System.out.println("Server start"); Socket s = ss.accept(); System.out.println("someone connect"); Future<Boolean> val = es.submit(new RequestHandler(s)); System.out.println(val.get()); } ss.close(); } catch(Exception e){ e.printStackTrace(); } } } <file_sep>/WebMail/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>hackathon</groupId> <artifactId>WebMail</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk.version>1.8</jdk.version> </properties> <dependencies> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20171018</version> </dependency> <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.21.0.1</version> </dependency> </dependencies> <modules> <module>Server</module> <module>Client</module> </modules> </project>
7014ac6ab6e6569fece20557437c21fe8c34c6b2
[ "Java", "Maven POM" ]
4
Java
adamkowal001/hackathonWebServerMail
fd22ec18f642a9b3c3dbc06ac160d748fe0fca50
302b1c7383271cdcac3ac10cca2ce0847b550c71
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/2 9:36 # @Author : <NAME> # @File : settings.py # @Role : 配置文件 #腾讯企业邮箱 EMAIL_INFO = { 'host': 'smtp.exmail.qq.com', 'user': 'user@domain', 'password': '<PASSWORD>' } DB_INFO = { 'host': '172.16.0.101', 'user': 'root', 'port': 3306, 'password': '<PASSWORD>', 'db': 'EventReminder' } <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/2 17:36 # @Author : <NAME> # @File : models.py # @Role : 数据库信息 import time from datetime import datetime from database import Base from sqlalchemy import Column from sqlalchemy import String, Integer, DateTime, TIMESTAMP class EventReminder(Base): __tablename__ = 'event_reminder' id = Column(Integer, primary_key=True, autoincrement=True) # ID 自增长 name = Column(String(100), nullable=True) # 事件名称 content = Column(String(100), nullable=True) # 事件的描述 email = Column(String(100), nullable=True) # 通知人员email advance_at = Column(Integer, nullable=True) # 提前多少天提醒 expire_at = Column(DateTime, nullable=True) # 事件过期时间 create_at = Column(DateTime, nullable=False, default=datetime.now()) # 记录创建时间 update_at = Column(TIMESTAMP, nullable=False, default=datetime.now()) # 记录更新时间 <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/10/24 17:00 # @Author : <NAME> # @File : app.py # @Role : 事件提醒 import tornado.web import tornado.httpserver import tornado.options import tornado.ioloop from tornado.options import define, options from controller.event import EventHandler from database import init_db define("port", default=8888, help='run on the given port', type=int) class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/event', EventHandler) ] settings = dict( # template_path=os.path.join(os.path.dirname(__file__), "templates"), # cookie_secret="<KEY> # xsrf_cookies=True, # login_url="/login", debug=False, ) tornado.web.Application.__init__(self, handlers, **settings) def main(): #nit_db() #第一次初始化使用 tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': main() <file_sep>tornado SQLAlchemy mysql-connector apscheduler<file_sep>Table of Contents ================= * [事件提醒](#事件提醒) * [表结构](#表结构) * [参数介绍](#参数介绍) * [API接口](#api接口) * [Python示例](#python示例) * [安装使用(手动安装)](#安装使用手动安装) * [安装使用(Docker-compose)](#安装使用docker-compose) # 事件提醒 - 使用人员请先修改settins里面配置信息 - 第一次使用,请打开app.py里面的`init_db`函数用于自动创建表 - 检测颗粒度默认为每小时,也可在`event_task.py`脚本自行修改 ## 表结构 ```mysql +------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+-------------------+-----------------------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(100) | YES | | NULL | | | content | varchar(100) | YES | | NULL | | | email | varchar(100) | YES | | NULL | | | advance_at | int(11) | YES | | NULL | | | expire_at | datetime | YES | | NULL | | | create_at | datetime | NO | | NULL | | | update_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | +------------+--------------+------+-----+-------------------+-----------------------------+ ``` ## 参数介绍 - ID: 自增长 - name: 事件名称 - content: 事件内容描述 - Email: 需要通知人员的Email地址 - advance: 提前多少天进行提醒 - expire_at: 事件过期/到期时间 - create_at: 记录事件创建时间 - update_at: 记录事件更新时间 ## API接口 - URL: http://172.16.0.101:8888/event - 工具: Postman - 支持: POST/PUT/DELETE ### Python示例 ```python # Body内容,根据name判断 { "name": "Ec2", #名字 "content": "服务器到期提醒", #内容备注 "email": "<EMAIL>, <EMAIL>", #Email通知 "advance_at": "100", #提前多少天 "expire_at": "2018-11-30" #到期时间 } ``` ## 安装使用(手动安装) - 请修改对应settings里面的内容 - 创建数据库 ```mysql create database EventReminder character set utf8; #数据表由ORM自动生成 ``` - Python3环境 ```bash $ yum install xz wget -y $ wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz $ xz -d Python-3.6.3.tar.xz $ tar xvf Python-3.6.3.tar $ cd Python-3.6.3/ $ ./configure $ make && make install # 查看安装 $ python3 -V ``` - 安装依赖 ```bash $ pip3 install -r requirements.txt ``` - 守护进程 ```bash $ cp supervisord.conf /etc/supervisord.conf $ /usr/bin/supervisord #后台运行使用/usr/bin/supervisord & ``` ## 安装使用(Docker-compose) - 请修改对应settings里面的内容 - 首先要具有docker环境,docker推荐使用`docker-ce` - 进入到项目目录,制作镜像启动 ```bash docker build -t event_reminder . docker-compose up -d ```
78c9e9de9dc184dc6c079d296878063cfac323b7
[ "Markdown", "Python", "Text" ]
5
Python
chen-github-test/EventReminder
1cfe6d7ba2b432bcbb53342a5b24b10deadd2270
04d0f1d2008c5360b97bea7b6d97af5f770c0522
refs/heads/master
<file_sep>package org.dyndns.fzoli.mill.server.model.dao; import java.util.Date; import java.util.List; import javax.persistence.EntityTransaction; import javax.persistence.PersistenceException; import javax.persistence.TypedQuery; import org.apache.commons.lang.time.DateUtils; import org.dyndns.fzoli.mill.common.InputValidator; import org.dyndns.fzoli.mill.common.Permission; import org.dyndns.fzoli.mill.common.key.PlayerBuilderReturn; import org.dyndns.fzoli.mill.common.key.PlayerReturn; import org.dyndns.fzoli.mill.common.model.entity.Sex; import org.dyndns.fzoli.mill.server.model.entity.Message; import org.dyndns.fzoli.mill.server.model.entity.Player; /** * * @author zoli */ public class PlayerDAO extends AbstractObjectDAO { private static final int MAX_RES = 25; private static final boolean DELETE_MESSAGES = true; public List<Player> getPossibleFriends(Player player) { try { return getEntityManager().createQuery("SELECT p FROM Player p WHERE :player MEMBER OF p.friendWishList", Player.class).setParameter("player", player).getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); return null; } } public List<Message> getMessages(Player address) { try { TypedQuery<Message> query = getEntityManager().createQuery("SELECT m FROM Message m WHERE m.address = :address", Message.class); return query.setParameter("address", address).getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); return null; } } public boolean removeMessages(Player p1, Player p2) { if (p1 == null || p2 == null) return false; try { List<Message> messages = getEntityManager().createQuery("SELECT m FROM Message m WHERE (m.sender.playerName = :p1 AND m.address.playerName = :p2) OR (m.sender.playerName = :p2 AND m.address.playerName = :p1)", Message.class) .setParameter("p1", p1.getPlayerName()) .setParameter("p2", p2.getPlayerName()) .getResultList(); if (DELETE_MESSAGES) { EntityTransaction tr = getEntityManager().getTransaction(); tr.begin(); getEntityManager().createQuery("DELETE FROM Message m WHERE (m.sender.playerName = :p1 AND m.address.playerName = :p2) OR (m.sender.playerName = :p2 AND m.address.playerName = :p1)") .setParameter("p1", p1.getPlayerName()) .setParameter("p2", p2.getPlayerName()) .executeUpdate(); tr.commit(); } for (Message m : messages) { Player p = m.getSender(); p.getPostedMessages().remove(m); save(p); } return true; } catch (PersistenceException ex) { return false; } } public List<Player> getPlayers() { try { return getEntityManager().createQuery("SELECT p FROM Player p", Player.class).getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); return null; } } public int getLastPage(long count) { double d = count / (double)MAX_RES; if (d != (int)d) d = 1 + (int)d; return (int)d; } public long getPlayerCount(Player asker, String names, String age, String sexName, String country, String region, String city) { InputValidator.AgeInterval ages = InputValidator.getAges(age); return getPlayerCount(asker, names, ages.getFrom(), ages.getTo(), getSex(sexName), country, region, city); } public List<Player> getPlayers(int page, Player asker, String names, String age, String sexName, String country, String region, String city) { InputValidator.AgeInterval ages = InputValidator.getAges(age); return getPlayers(page, asker, names, ages.getFrom(), ages.getTo(), getSex(sexName), country, region, city); } public long getPlayerCount(Player asker, String names, Integer ageFrom, Integer ageTo, Sex sex, String country, String region, String city) { try { List<Long> l = getPlayers(Long.class, asker, null, names, ageFrom, ageTo, sex, country, region, city); if (l.isEmpty()) return 0; return l.get(0); } catch (Exception ex) { ex.printStackTrace(); return -1; } } public List<Player> getPlayers(int page, Player asker, String names, Integer ageFrom, Integer ageTo, Sex sex, String country, String region, String city) { return getPlayers(Player.class, asker, page, names, ageFrom, ageTo, sex, country, region, city); } private <T> List<T> getPlayers(Class<T> clazz, Player asker, Integer page, String names, Integer ageFrom, Integer ageTo, Sex sex, String country, String region, String city) { if (country == null || country.trim().isEmpty()) country = region = city = null; else if (region == null || region.trim().isEmpty()) region = city = null; else if (city != null && city.trim().isEmpty()) city = null; try { return getEntityManager().createQuery("SELECT " + (clazz.equals(Player.class) ? "p" : "count(p)") + " FROM Player p WHERE " + "(:name IS NULL OR :name = '' OR upper(p.playerName) LIKE upper(:name) OR upper(p.personalData.firstName) LIKE upper(:name) OR upper(p.personalData.lastName) LIKE upper(:name)) AND " + "(:dateFrom IS NULL OR :dateTo IS NULL OR p.personalData.birthDate BETWEEN :dateFrom AND :dateTo) AND " + "(:sex IS NULL OR p.personalData.sex = :sex) AND " + "((:country IS NULL OR :country = '' OR p.personalData.country = :country) AND " + "(:region IS NULL OR :region = '' OR p.personalData.region = :region) AND " + "(:city IS NULL OR :city = '' OR p.personalData.city = :city)) AND " + "(p.activePermission NOT MEMBER OF :perms OR (:perm = :root AND NOT p.permission = :root) OR (:shield)) AND " + "(NOT p = :asker)", clazz) .setMaxResults(MAX_RES) .setFirstResult(clazz.equals(Player.class) && page > 0 ? (page - 1) * MAX_RES : 0) .setParameter("name", names) .setParameter("dateFrom", ageTo == null ? null : DateUtils.addYears(new Date(), -1 * ageTo)) .setParameter("dateTo", ageFrom == null ? null : DateUtils.addYears(new Date(), -1 * ageFrom)) .setParameter("sex", sex) .setParameter("country", country) .setParameter("region", region) .setParameter("city", city) .setParameter("asker", asker) .setParameter("root", Permission.ROOT) .setParameter("shield", asker == null? false : Permission.hasPermission(asker.getPermissionMask(false), Permission.SHIELD_MODE)) .setParameter("perm", asker == null ? 0 : asker.getPermissionMask(false)) .setParameter("perms", Permission.getMasks(Permission.HIDDEN_MODE)) .getResultList(); } catch (PersistenceException ex) { ex.printStackTrace(); return null; } } public Player getPlayer(String name) { if (name == null) return null; try { TypedQuery<Player> query = getEntityManager().createQuery("SELECT p FROM Player p WHERE upper(p.playerName) = upper(:name)", Player.class); return query.setParameter("name", name).getSingleResult(); } catch (PersistenceException ex) { ex.printStackTrace(); return null; } } public PlayerReturn verify(String name, String password, boolean hash) { if (name == null || password == null) return PlayerReturn.NULL; if (!InputValidator.isUserIdValid(name) || !InputValidator.isPasswordValid(password, hash)) return PlayerReturn.INVALID; Player p = getPlayer(name); if (p != null) { if (!hash) password = InputValidator.md5Hex(password); if (password.equals(p.getPassword())) return PlayerReturn.OK; } return PlayerReturn.NOT_OK; } public boolean isPlayerNameExists(String name) { return isExists(name, "playerName"); } public boolean isEmailExists(String email) { if (email == null || email != null && email.isEmpty()) return false; TypedQuery<Boolean> query = getEntityManager().createQuery("SELECT count(p) > 0 FROM Player p WHERE upper(p.email) = upper(:value) AND p.validated = true", Boolean.class); query.setParameter("value", email); return isExists(query); } private boolean isExists(String value, String property) { if (value == null || property == null) return false; TypedQuery<Boolean> query = getEntityManager().createQuery("SELECT count(p) > 0 FROM Player p WHERE upper(p." + property + ") = upper(:value)", Boolean.class); query.setParameter("value", value); return isExists(query); } private boolean isExists(TypedQuery<Boolean> query) { try { return query.getSingleResult(); } catch (PersistenceException ex) { return false; } } public long getPlayerCount() { try { return getEntityManager().createQuery("SELECT count(p) FROM Player p", Long.class).getSingleResult(); } catch (PersistenceException ex) { return 0; } } public PlayerBuilderReturn createPlayer(Player player, boolean hash) { if (player == null) { return PlayerBuilderReturn.NULL; } if (!InputValidator.isUserIdValid(player.getPlayerName())) { return PlayerBuilderReturn.INVALID_USER; } if (!hash && !InputValidator.isPasswordValid(player.getPassword())) { return PlayerBuilderReturn.INVALID_PASSWORD; } if (hash && !InputValidator.isPasswordHashValid(player.getPassword())) { return PlayerBuilderReturn.INVALID_PASSWORD; } if (player.getPassword().equals(player.getPlayerName())) { return PlayerBuilderReturn.PASSWORD_NOT_USER; } if (!InputValidator.isEmailValid(player.getEmail())) { return PlayerBuilderReturn.INVALID_EMAIL; } if (isEmailExists(player.getEmail())) { return PlayerBuilderReturn.EMAIL_EXISTS; } if (isPlayerNameExists(player.getPlayerName())) { return PlayerBuilderReturn.USER_EXISTS; } if (!hash) { player.setPassword(InputValidator.md5Hex(player.getPassword())); } player.setEmail(player.getEmail().toLowerCase()); if (!save(player)) return PlayerBuilderReturn.EXCEPTION; return PlayerBuilderReturn.OK; } public boolean save(Player player) { return save(player, Player.class); } public boolean save(Message message) { return save(message, Message.class); } private Sex getSex(String name) { try { return Sex.valueOf(name); } catch (Exception ex) { return null; } } }<file_sep>package org.dyndns.fzoli.mill.server.model.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.*; import org.dyndns.fzoli.mill.common.model.entity.MessageType; import org.dyndns.fzoli.mill.common.model.entity.MessageType.SystemMessage; /** * * @author zoli */ @Entity public class Message implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Temporal(TemporalType.TIMESTAMP) private Date sendDate = new Date(); private String text; @Enumerated(EnumType.STRING) private MessageType type = MessageType.CHAT; @Enumerated(EnumType.STRING) private SystemMessage msg; @OneToMany(/*fetch=FetchType.LAZY, cascade=CascadeType.ALL, */mappedBy="postedMessages") private Player sender; @ManyToOne private Player address; protected Message() { } public Message(Player address, SystemMessage msg) { this(address, null, msg); this.type = MessageType.SYSTEM; } public Message(Player address, String text) { this(address, text, false); } public Message(Player address, String text, boolean support) { this(address, text, null); this.type = support ? MessageType.SUPPORT : MessageType.CHAT; } private Message(Player address, String text, SystemMessage msg) { this.address = address; this.text = text; this.msg = msg; } public Long getId() { return id; } public MessageType getType() { return type; } public SystemMessage getSystemMessage() { return msg; } public String getText() { return text; } public Date getSendDate() { return sendDate; } public Player getSender() { return sender; } public Player getAddress() { return address; } public void setType(MessageType type) { this.type = type; } public void setSystemMessage(SystemMessage msg) { this.msg = msg; } public void setText(String text) { this.text = text; } public Message setSender(Player sender) { this.sender = sender; return this; } @Override public String toString() { return super.toString() + '#' + getId(); } }<file_sep>package org.dyndns.fzoli.mill.common.key; /** * * @author zoli */ public interface PlayerBuilderKeys { String REQ_SET_USER = "set_user"; String REQ_SET_EMAIL = "set_email"; String REQ_CREATE = "create"; String REQ_SAFE_CREATE = "safe_create"; String REQ_VALIDATE = "validate"; }<file_sep>package org.dyndns.fzoli.mill.server.model.entity; import java.io.Serializable; import javax.persistence.Embeddable; /** * * @author zoli */ @Embeddable public class Point implements Serializable { private static final long serialVersionUID = 1L; private int x, y; public Point() { } public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }<file_sep>package org.dyndns.fzoli.mill.server.model; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.dyndns.fzoli.email.GMailSender; import org.dyndns.fzoli.location.entity.Location; import org.dyndns.fzoli.mill.common.InputValidator; import org.dyndns.fzoli.mill.common.Permission; import org.dyndns.fzoli.mill.common.key.ModelKeys; import org.dyndns.fzoli.mill.common.key.PersonalDataType; import org.dyndns.fzoli.mill.common.key.PlayerKeys; import org.dyndns.fzoli.mill.common.key.PlayerReturn; import org.dyndns.fzoli.mill.common.model.entity.BasePlayer; import org.dyndns.fzoli.mill.common.model.entity.MessageType; import org.dyndns.fzoli.mill.common.model.entity.OnlineStatus; import org.dyndns.fzoli.mill.common.model.entity.Sex; import org.dyndns.fzoli.mill.common.model.pojo.BaseOnlinePojo; import org.dyndns.fzoli.mill.common.model.pojo.PlayerData; import org.dyndns.fzoli.mill.common.model.pojo.PlayerEvent; import org.dyndns.fzoli.mill.server.model.dao.CityDAO; import org.dyndns.fzoli.mill.server.model.dao.PlayerAvatarDAO; import org.dyndns.fzoli.mill.server.model.dao.PlayerDAO; import org.dyndns.fzoli.mill.server.model.dao.ValidatorDAO; import org.dyndns.fzoli.mill.server.model.entity.ConvertUtil; import org.dyndns.fzoli.mill.server.model.entity.Message; import org.dyndns.fzoli.mill.server.model.entity.PersonalData; import org.dyndns.fzoli.mill.server.model.entity.Player; import org.dyndns.fzoli.mill.server.model.entity.PlayerAvatar; import org.dyndns.fzoli.mill.server.servlet.MillControllerServlet; import org.dyndns.fzoli.mill.server.servlet.ValidatorServlet; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; import org.dyndns.fzoli.mvc.server.model.Model; /** * * @author zoli */ public class PlayerModel extends AbstractOnlineModel<PlayerEvent, PlayerData> implements PlayerKeys { public static enum SignOutType { RESIGN, KICK, DISCONNECT, NORMAL } private final static CityDAO CDAO = new CityDAO(); private final static PlayerDAO DAO = new PlayerDAO(); private final static ValidatorDAO VDAO = new ValidatorDAO(); private final static PlayerAvatarDAO ADAO = new PlayerAvatarDAO(); private Player player; private org.dyndns.fzoli.mill.common.model.entity.Player commonPlayer; private final HashMap<Player, PlayerChangeType> changedPlayers = new HashMap<Player, PlayerChangeType>(); @Override public Player getPlayer() { return player; } @Override public void reinitPlayer() { if (player != null) { player = DAO.getPlayer(player.getPlayerName()); commonPlayer = ConvertUtil.createPlayer(this); } } @Override public org.dyndns.fzoli.mill.common.model.entity.Player getCommonPlayer() { return commonPlayer; } public boolean isEmailFree(String email) { return !DAO.isEmailExists(email); } public PlayerReturn signIn(String name, String password, boolean hash) { PlayerReturn ret = DAO.verify(name, password, hash); if (ret == PlayerReturn.OK) { if (player != null) signOut(SignOutType.RESIGN); player = DAO.getPlayer(name); boolean unsuspend = player.isSuspended(); if (unsuspend) player.setSuspended(false); player.updateSignInDate(); DAO.save(player); commonPlayer = ConvertUtil.createPlayer(this); if (unsuspend) callOnPlayerChanged(player, PlayerChangeType.UNSUSPEND); getModelMap().remove(ModelKeys.PLAYER_BUILDER); boolean wasKick = false; List<PlayerModel> models = findModels(getKey(), PlayerModel.class); for (PlayerModel model : models) { String n = model.getPlayerName(); if (n == null || model == this) continue; if (n.equals(name)) { // ha másik sessionben be van már lépve, kijelentkeztetés model.signOut(SignOutType.KICK); wasKick = true; break; } } if (!wasKick) { // bejelentkezés jelzés ha nem volt már bejelentkezve callOnPlayerChanged(player, PlayerChangeType.SIGN_IN); } } else { try { Thread.sleep(2000); } catch (InterruptedException ex) { ; } } return ret; } public PlayerReturn signOut(SignOutType type) { if (player == null) return PlayerReturn.NULL; if (type != SignOutType.KICK) { // ha nem történt másik sessionben bejelentkezés callOnPlayerChanged(player, PlayerChangeType.SIGN_OUT); } player = null; commonPlayer = null; if (type == SignOutType.KICK || type == SignOutType.DISCONNECT) { // ha másik sessionben bejelentkeztek vagy megszakadt a klienssel a kapcsolat iterateBeanModels(new ModelIterator() { @Override public void handler(String key, Model model) { if (model instanceof AbstractOnlineModel) { // a session minden online modeljének jelzés a kijelentkeztetésről ((AbstractOnlineModel)model).addEvent(new BaseOnlinePojo(commonPlayer)); } } }); } createCaptcha(); return PlayerReturn.OK; } private PlayerReturn setActivePermission(int mask) { if (player != null && isCaptchaValidated()) { player.setActivePermissionMask(mask); DAO.save(player); commonPlayer = ConvertUtil.createPlayer(this); return PlayerReturn.OK; } return PlayerReturn.NOT_OK; } private PlayerReturn setPlayerState(String state) { if (player != null) { try { OnlineStatus ps = OnlineStatus.valueOf(state); OnlineStatus old = player.getOnlineStatus(); if (!old.equals(ps)) { player.setOnlineStatus(ps); commonPlayer.setOnline(ps.equals(OnlineStatus.ONLINE)); DAO.save(player); callOnPlayerChanged(player, commonPlayer.isOnline() ? PlayerChangeType.STATE_ONLINE : PlayerChangeType.STATE_INVISIBLE); return PlayerReturn.OK; } } catch (IllegalArgumentException ex) { return PlayerReturn.INVALID; } } return PlayerReturn.NULL; } private PlayerReturn setPassword(String oldPassword, String newPassword, boolean safe) { if (!isCaptchaValidated()) return PlayerReturn.NOT_OK; if (player == null) return PlayerReturn.NULL; if (!InputValidator.isPasswordValid(newPassword, safe) || !InputValidator.isPasswordValid(oldPassword, safe)) return PlayerReturn.INVALID; if (!safe) { oldPassword = <PASSWORD>.<PASSWORD>(oldPassword); newPassword = <PASSWORD>Validator.<PASSWORD>(newPassword); } if (oldPassword.equals(newPassword)) { return PlayerReturn.NO_CHANGE; } if (oldPassword.equals(player.getPassword())) { player.setPassword(newPassword); DAO.save(player); return PlayerReturn.OK; } else { return PlayerReturn.NOT_OK; } } private PlayerReturn setEmail(HttpServletRequest hsr, String password, String email, boolean safe) { if (isRequestWrong(password, safe)) return getError(password, safe); if (DAO.isEmailExists(email)) return PlayerReturn.EMAIL_NOT_FREE; commonPlayer.setEmail(email); player.setEmail(email); player.setValidated(false); DAO.save(player); validateEmail(hsr, password, safe); return PlayerReturn.OK; } private PlayerReturn validateEmail(HttpServletRequest hsr, String password, boolean safe) { if (isRequestWrong(password, safe)) return getError(password, safe); return validateEmail(hsr, player); } public PlayerReturn validateEmail(HttpServletRequest hsr, Player player) { if (player != null && player.getEmail() != null) { if (player.isValidated()) return PlayerReturn.NO_CHANGE; if (player.getEmail().isEmpty()) return PlayerReturn.NULL; File config = MillControllerServlet.getEmailConfig(hsr); try { String key = InputValidator.md5Hex(player.getEmail() + new Date().getTime() + Math.random()); GMailSender.sendEmail(config, player.getEmail(), ValidatorServlet.getEmailValidationSubject(hsr), ValidatorServlet.createValidationEmail(hsr, key, player)); VDAO.setKey(player, key); removeCaptcha(); List<Player> players = DAO.getPlayers(); for (Player p : players) { if (!player.getPlayerName().equals(p.getPlayerName()) && player.getEmail().equals(p.getEmail())) p.setEmail(""); } return PlayerReturn.OK; } catch (Exception ex) { ex.printStackTrace(); return PlayerReturn.ERROR; } } return PlayerReturn.NULL; } private PlayerReturn suspendAccount(String password, boolean safe) { if (isRequestWrong(password, safe)) return getError(password, safe); if (player.getPermissionMask(false) == Permission.ROOT) return PlayerReturn.NO_CHANGE; player.setPersonalData(new PersonalData()); player.setSuspended(true); player.setOnlineStatus(OnlineStatus.ONLINE); player.setPermissionMask(0); DAO.save(player); PlayerAvatar avatar = ADAO.getPlayerAvatar(player.getPlayerName()); if (avatar != null) { avatar.reset(); ADAO.save(avatar); } Player tmp = player; signOut(SignOutType.KICK); callOnPlayerChanged(tmp, PlayerChangeType.SUSPEND); return PlayerReturn.OK; } private PlayerReturn setPersonalData(PersonalDataType request, String value) { if (!isCaptchaValidated()) return PlayerReturn.NOT_OK; if (player == null || request == null) return PlayerReturn.NULL; PlayerReturn ret = PlayerReturn.NOT_OK; if (request.equals(PersonalDataType.CLEAR)) { player.setPersonalData(new PersonalData()); ret = PlayerReturn.OK; } else { if (value == null) return PlayerReturn.NULL; } PersonalData data = player.getPersonalData(); try { switch(request) { case FIRST_NAME: if (InputValidator.isNameValid(value) && !value.equals(data.getFirstName())) { data.setFirstName(value); ret = PlayerReturn.OK; } break; case LAST_NAME: if (InputValidator.isNameValid(value) && !value.equals(data.getLastName())) { data.setLastName(value); ret = PlayerReturn.OK; } break; case INVERSE_NAME: boolean b = Boolean.parseBoolean(value); if (b != data.isInverseName()) { data.setInverseName(b); ret = PlayerReturn.OK; } break; case BIRTH_DATE: Date date = new Date(Long.parseLong(value)); if (InputValidator.isBirthDateValid(date)) { data.setBirthDate(date); ret = PlayerReturn.OK; } break; case SEX: Sex s = Sex.valueOf(value); if (!s.equals(data.getSex())) { data.setSex(s); ret = PlayerReturn.OK; } break; case COUNTRY: String country = data.getCountry(); if ((country == null || !country.equals(value)) && CDAO.getCountryByName(value) != null) { data.setCountry(value); data.setRegion(null); data.setCity(null); ret = PlayerReturn.OK; } break; case REGION: String region = data.getRegion(); country = data.getCountry(); if (country != null && (region == null || !region.equals(value)) && !CDAO.getRegions(country, value).isEmpty()) { data.setRegion(value); data.setCity(null); ret = PlayerReturn.OK; } break; case CITY: String city = data.getCity(); region = data.getRegion(); if (region != null && (city == null || !city.equals(value)) && !CDAO.getCities(data.getCountry(), region, value).isEmpty()) { data.setCity(value); ret = PlayerReturn.OK; } break; } } catch (Exception ex) { ex.printStackTrace(); } if (ret.equals(PlayerReturn.OK)) { commonPlayer = ConvertUtil.createPlayer(this); DAO.save(player); callOnPlayerChanged(player, PlayerChangeType.PERSONAL_DATA); } return ret; } private boolean isRequestWrong(String password, boolean safe) { return getError(password, safe) != null; } private PlayerReturn getError(String password, boolean safe) { if (!isCaptchaValidated()) return PlayerReturn.NOT_OK; if (player == null) return PlayerReturn.NULL; if (!InputValidator.isPasswordValid(password, safe)) return PlayerReturn.INVALID; if (!safe) password = <PASSWORD>(password); if (!password.equals(player.getPassword())) return PlayerReturn.NOT_OK; return null; } @Override public void onPlayerChanged(Player p, PlayerChangeType type) { super.onPlayerChanged(p, type); switch (type) { case SIGN_IN: onSignInOut(p, true, true); break; case SIGN_OUT: onSignInOut(p, false, true); break; case STATE_INVISIBLE: onSignInOut(p, false, false); break; case STATE_ONLINE: if (changedPlayers.containsKey(p)) { synchronized(changedPlayers) { switch (changedPlayers.get(p)) { case PERSONAL_DATA: onPersonalDataChanged(p); break; case AVATAR_CHANGE: onAvatarChange(p); break; } changedPlayers.remove(p); } } onSignInOut(p, true, false); break; case SUSPEND: onSuspend(p); break; case UNSUSPEND: onUnsuspend(p); break; case AVATAR_CHANGE: onAvatarChange(p); break; case AVATAR_ENABLE: onAvatarEnabled(true); break; case AVATAR_DISABLE: onAvatarEnabled(false); break; case PERSONAL_DATA: onPersonalDataChanged(p); break; } } public static boolean isEventImportant(Player me, Player p) { if (me != null && me != p) { if (p.getFriendList().contains(me) && (p.getOnlineStatus().equals(OnlineStatus.ONLINE) || me.canUsePermission(p, Permission.DETECT_INVISIBLE_STATUS))) { return true; } } return false; } public void onValidate(boolean add) { commonPlayer = ConvertUtil.createPlayer(this); addEvent(new PlayerEvent(commonPlayer, add ? PlayerEvent.PlayerEventType.VALIDATE : PlayerEvent.PlayerEventType.INVALIDATE)); } private void onPersonalDataChanged(Player p) { if (player != p) { if (isEventImportant(player, p)) { commonPlayer = ConvertUtil.createPlayer(this); addEvent(new PlayerEvent(commonPlayer, p.getPlayerName(), PlayerEvent.PlayerEventType.PERSONAL_DATA_CHANGE)); } else { synchronized(changedPlayers) { changedPlayers.put(p, PlayerChangeType.PERSONAL_DATA); } } } } private void onAvatarChange(Player p) { if (isEventImportant(getPlayer(), p)) { addEvent(new PlayerEvent(commonPlayer, p.getPlayerName(), PlayerEvent.PlayerEventType.AVATAR_CHANGE)); } else { synchronized(changedPlayers) { changedPlayers.put(p, PlayerChangeType.AVATAR_CHANGE); } } } private void onSuspend(Player p) { addSuspendEvent(p, true); commonPlayer = ConvertUtil.createPlayer(this); } private void onUnsuspend(Player p) { commonPlayer = ConvertUtil.createPlayer(this); addSuspendEvent(p, false); } private void onAvatarEnabled(boolean enabled) { commonPlayer = ConvertUtil.createPlayer(this); addEvent(new PlayerEvent(commonPlayer, enabled ? PlayerEvent.PlayerEventType.AVATAR_ENABLE : PlayerEvent.PlayerEventType.AVATAR_DISABLE)); } private void sendSystemMessage(Player sender, MessageType.SystemMessage type) { Object model = getModelMap().get(ModelKeys.CHAT, false); if (model != null && player != null && sender != null) { ((ChatModel) model).sendMessage(new Message(player, type).setSender(sender)); } } private void onSignInOut(Player p, boolean signIn, boolean sign) { if (player != null) { boolean canDetect = player.canUsePermission(p, Permission.DETECT_INVISIBLE_STATUS); if (sign && p.getOnlineStatus().equals(OnlineStatus.INVISIBLE) && !canDetect) return; //ha be/ki-jelentkezés van és láthatatlan és nincs láthatatlanság detektáló jog, akkor nem kell jelezni if (!sign && canDetect) return; // ha állapot váltás történt (tehát nem be/ki-jelentkezés) és van láthatatlanság detektáló jog, nem kell jelezni System.out.print("sign " + p.getPlayerName() + " " + (signIn ? "in" : "out") + " detected on session of " + player.getPlayerName() + "..."); if (canDetect || (p.isFriend(player) && player.isFriend(p))) { System.out.println("sent."); BasePlayer bp = commonPlayer.findPlayer(p.getPlayerName()); bp.setOnline(signIn); addEvent(new PlayerEvent(commonPlayer, p.getPlayerName(), signIn)); sendSystemMessage(p, signIn ? MessageType.SystemMessage.SIGN_IN : MessageType.SystemMessage.SIGN_OUT); } else { System.out.println("not sent."); } } } public void onDisconnect() { signOut(SignOutType.DISCONNECT); } private void addSuspendEvent(Player p, boolean suspend) { if (findPlayer(p.getPlayerName()) != null) { if (!player.canUsePermission(p, Permission.DETECT_SUSPENDED_PLAYER)) { addEvent(new PlayerEvent(commonPlayer, p.getPlayerName(), suspend ? PlayerEvent.PlayerEventType.SUSPEND : PlayerEvent.PlayerEventType.UNSUSPEND)); } else { addEvent(new PlayerEvent(commonPlayer, p.getPlayerName(), PlayerEvent.PlayerEventType.RELOAD)); } } } private BasePlayer findPlayer(String playerName) { if (commonPlayer == null) return null; return findPlayer(playerName, commonPlayer.createMergedPlayerList()); } private BasePlayer findPlayer(String playerName, List<BasePlayer> l) { for (BasePlayer bp : l) { if (bp.getPlayerName().equals(playerName)) { return bp; } } return null; } private PlayerData.PlayerList findPlayerList(String playerName) { if (commonPlayer != null) { if (findPlayer(playerName, commonPlayer.getBlockedUserList()) != null) return PlayerData.PlayerList.BLOCKED_PLAYERS; if (findPlayer(playerName, commonPlayer.getFriendWishList()) != null) return PlayerData.PlayerList.WISHED_FRIENDS; if (findPlayer(playerName, commonPlayer.getPossibleFriends()) != null) return PlayerData.PlayerList.POSSIBLE_FRIENDS; } return PlayerData.PlayerList.FRIENDS; } @Override protected int askModel(HttpServletRequest hsr, RequestMap rm) { int ret = super.askModel(hsr, rm); String action = rm.getFirst(KEY_REQUEST); if (action != null) { if (action.equals(REQ_SIGN_OUT)) return signOut(SignOutType.NORMAL).ordinal(); if (action.equals(REQ_SIGN_IN)) return signIn(rm.getFirst(KEY_USER), rm.getFirst(KEY_PASSWORD), false).ordinal(); if (action.equals(REQ_SAFE_SIGN_IN)) return signIn(rm.getFirst(KEY_USER), rm.getFirst(KEY_PASSWORD), true).ordinal(); String value = rm.getFirst(KEY_VALUE); if (value != null) { if (action.equals(REQ_IS_EMAIL_FREE)) return isEmailFree(value) ? 1 : 0; } String passwd = rm.getFirst(KEY_PASSWORD); if (passwd != null) { if (action.equals(REQ_REVALIDATE_EMAIL)) return validateEmail(hsr, passwd, false).ordinal(); if (action.equals(REQ_SAFE_REVALIDATE_EMAIL)) return validateEmail(hsr, passwd, true).ordinal(); if (action.equals(REQ_SUSPEND_ACCOUNT)) return suspendAccount(passwd, false).ordinal(); if (action.equals(REQ_SAFE_SUSPEND_ACCOUNT)) return suspendAccount(passwd, true).ordinal(); } } return ret == -1 ? PlayerReturn.NULL.ordinal() : ret; } @Override protected int setProperty(HttpServletRequest hsr, RequestMap rm) { String action = rm.getFirst(KEY_REQUEST); if (action != null) { String value = rm.getFirst(KEY_VALUE); if (value != null) { try { PersonalDataType request = PersonalDataType.valueOf(action); return setPersonalData(request, value).ordinal(); } catch (IllegalArgumentException ex) { ; } try { if (action.equals(REQ_SET_ACTIVE_PERMISSION)) return setActivePermission(Integer.parseInt(value)).ordinal(); } catch (NumberFormatException ex) { ; } if (action.equals(REQ_SET_ONLINE_STATUS)) return setPlayerState(value).ordinal(); String passwd = rm.getFirst(KEY_PASSWORD); if (passwd != null) { if (action.equals(REQ_SET_EMAIL)) return setEmail(hsr, passwd, value, false).ordinal(); if (action.equals(REQ_SAFE_SET_EMAIL)) return setEmail(hsr, passwd, value, true).ordinal(); if (action.equals(REQ_SET_PASSWORD)) return setPassword(passwd, value, false).ordinal(); if (action.equals(REQ_SET_SAFE_PASSWORD)) return setPassword(passwd, value, true).ordinal(); } } } return PlayerReturn.NULL.ordinal(); } @Override protected PlayerData getProperties(HttpServletRequest hsr, RequestMap rm) { String user = rm.getFirst(KEY_USER); if (user != null && player != null) { if (user.equals(player.getPlayerName())) return new PlayerData(commonPlayer, null); else return new PlayerData(findPlayer(user), findPlayerList(user)); } String value = rm.getFirst(KEY_VALUE); String action = rm.getFirst(KEY_REQUEST); if (player != null && value != null && action != null) { PersonalData data = player.getPersonalData(); if (action.equals(REQ_GET_COUNTRIES)) return new PlayerData(createList(CDAO.findCountriesByName(value))); if (action.equals(REQ_GET_REGIONS)) return new PlayerData(createList(CDAO.findRegions(data.getCountry(), value))); if (action.equals(REQ_GET_CITIES)) return new PlayerData(createList(CDAO.findCities(data.getCountry(), data.getRegion(), value))); } return new PlayerData(commonPlayer, isCaptchaValidated(), getCaptchaWidth()); } public static List<String> createList(List<? extends Location> l) { List<String> ls = new ArrayList<String>(); for (Location o : l) { ls.add(o.getDisplay()); } return ls; } }<file_sep>package org.dyndns.fzoli.mill.common.model.pojo; import org.dyndns.fzoli.mill.common.model.entity.Player; /** * * @author zoli */ public class PlayerEvent extends BaseOnlinePojo { public enum PlayerEventType { COMMON, SIGNIN, SIGNOUT, VALIDATE, INVALIDATE, SUSPEND, UNSUSPEND, RELOAD, AVATAR_CHANGE, AVATAR_ENABLE, AVATAR_DISABLE, PERSONAL_DATA_CHANGE } private PlayerEventType type; private String changedPlayer; public PlayerEvent(Player player) { super(player); type = PlayerEventType.COMMON; } public PlayerEvent(Player player, PlayerEventType type) { super(player); this.type = type; } public PlayerEvent(Player player, String changedPlayer, PlayerEventType type) { super(player); this.changedPlayer = changedPlayer; this.type = type; } public PlayerEvent(Player player, String changedPlayer, boolean signIn) { this(player, changedPlayer, signIn ? PlayerEventType.SIGNIN : PlayerEventType.SIGNOUT); } public PlayerEventType getType() { return type; } public String getChangedPlayer() { return changedPlayer; } }<file_sep>package org.dyndns.fzoli.mill.server.model.dao; /** * * @author zoli */ public class CityDAO extends org.dyndns.fzoli.location.dao.CityDAO { @Override protected String getLocation() { return "tcp://localhost/~/cities"; } }<file_sep>package org.dyndns.fzoli.mill.server.model; import javax.servlet.http.HttpServletRequest; import org.dyndns.fzoli.mill.common.key.PlayerRegistryKeys; import org.dyndns.fzoli.mill.common.model.pojo.PlayerRegistryData; import org.dyndns.fzoli.mill.common.model.pojo.PlayerRegistryEvent; import static org.dyndns.fzoli.mill.server.model.PlayerModel.createList; import org.dyndns.fzoli.mill.server.model.dao.CityDAO; import org.dyndns.fzoli.mill.server.model.dao.PlayerDAO; import org.dyndns.fzoli.mill.server.model.entity.ConvertUtil; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; /** * * @author zoli */ public class PlayerRegistryModel extends AbstractOnlineModel<PlayerRegistryEvent, PlayerRegistryData> implements PlayerRegistryKeys { private final static PlayerDAO DAO = new PlayerDAO(); private final static CityDAO CDAO = new CityDAO(); private int page = 1; private String names, ages, sexName, country, region, city; private void setPage(String action, String value) { if (action.equals(REQ_GET_PAGE) && value != null) { try { page = Integer.parseInt(value); } catch (NumberFormatException ex) { page = 1; } } if (action.equals(REQ_PREV_PAGE)) { page--; } if (action.equals(REQ_NEXT_PAGE)) { page++; } } private PlayerRegistryData findPlayers() { long count = DAO.getPlayerCount(getPlayer(), names, ages, sexName, country, region, city); int lastPage = DAO.getLastPage(count); if (page < 1) page = 1; if (page > lastPage) page = lastPage; return new PlayerRegistryData(ConvertUtil.createPlayerList(this, DAO.getPlayers(page, getPlayer(), names, ages, sexName, country, region, city)), count, page, lastPage); } @Override protected PlayerRegistryData getProperties(HttpServletRequest hsr, RequestMap rm) { String action = rm.getFirst(KEY_REQUEST); if (action != null) { String value = rm.getFirst(KEY_VALUE); if (action.equals(REQ_NEXT_PAGE) || action.equals(REQ_PREV_PAGE) || action.equals(REQ_GET_PAGE)) { setPage(action, value); return findPlayers(); } if (value != null) { if (action.equals(REQ_GET_COUNTRIES)) return new PlayerRegistryData(createList(CDAO.findCountriesByName(value))); if (action.equals(REQ_GET_REGIONS)) return new PlayerRegistryData(createList(CDAO.findRegions(country, value))); if (action.equals(REQ_GET_CITIES)) return new PlayerRegistryData(createList(CDAO.findCities(country, region, value))); } } return new PlayerRegistryData(getPlayerName(), names, ages, sexName, country, region, city); } @Override protected int setProperty(HttpServletRequest hsr, RequestMap rm) { String action = rm.getFirst(KEY_REQUEST); if (action != null) { if (action.equals(REQ_SET_FILTER)) { names = rm.getFirst(KEY_NAMES); ages = rm.getFirst(KEY_AGES); sexName = rm.getFirst(KEY_SEX); country = rm.getFirst(KEY_COUNTRY); region = rm.getFirst(KEY_REGION); city = rm.getFirst(KEY_CITY); return 1; } } return 0; } }<file_sep>package org.dyndns.fzoli.mill.server.test.objectdb; import java.util.Arrays; import java.util.Collection; import javax.persistence.EntityManager; import static org.dyndns.fzoli.mill.server.test.objectdb.Util.*; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * ObjectDB first test. * 1. Open database connection and clear database. * 2. Creating players. * 3. a) Add player2 to player1's list. * b) Add player1 to player2's list. * 4. Recreate database connection. * 5. Try read players. * 6. Close database connection. * @author zoli */ @RunWith(value = Parameterized.class) public class FirstTest { private static EntityManager db; private boolean inverseAdd; public FirstTest(boolean inverseAdd) { this.inverseAdd = inverseAdd; } @Parameters public static Collection<Boolean[]> data() { Boolean[][] data = new Boolean[][] { { false }, { true } }; return Arrays.asList(data); } @BeforeClass public static void openDatabase() throws Exception { System.out.println("Open database connection."); db = createEntityManager(); } @Before public void initTest() throws Exception { System.out.println("Clear database."); clearDatabase(db); } @AfterClass public static void closeDatabase() throws Exception { System.out.println("Close database connection."); db.close(); } @Test(timeout=10000) public void testOne() { System.out.println("Creating players."); Player p1 = new Player(PLAYER1); Player p2 = new Player(PLAYER2); assertTrue(save(db, p1)); assertTrue(save(db, p2)); System.out.println("Add player2 to player1's list."); p1.getFriendWishList().add(p2); assertTrue(save(db, p1)); if (inverseAdd) { System.out.println("Add player1 to player2's list."); p2.getFriendWishList().add(p1); assertTrue(save(db, p2)); } System.out.println("Recreate database connection."); db.close(); db = createEntityManager(); System.out.println("Try read players..."); System.out.println("Read " + PLAYER1 + '.'); assertNotNull(getPlayer(db, PLAYER1)); System.out.println("Read " + PLAYER2 + '.'); assertNotNull(getPlayer(db, PLAYER2)); } }<file_sep>package org.dyndns.fzoli.mill.client.model; import java.util.Date; import org.dyndns.fzoli.mill.common.DateUtil; import org.dyndns.fzoli.mill.common.key.ChatKeys; import org.dyndns.fzoli.mill.common.key.ModelKeys; import org.dyndns.fzoli.mill.common.model.pojo.ChatData; import org.dyndns.fzoli.mill.common.model.pojo.ChatEvent; import org.dyndns.fzoli.mvc.client.connection.Connection; import org.dyndns.fzoli.mvc.client.event.ModelActionListener; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; /** * * @author zoli */ public class ChatModel extends AbstractOnlineModel<ChatEvent, ChatData> implements ChatKeys { public ChatModel(Connection<Object, Object> connection) { super(connection, ModelKeys.CHAT, ChatEvent.class, ChatData.class); getCache().setSync(getSync()); } public int getSync() { try { return askModel(new RequestMap().setFirst(KEY_REQUEST, REQ_SYNC).setFirst(KEY_DATE, Long.toString(DateUtil.getDateInTimeZone(new Date(), "GMT").getTime()))); } catch (Exception ex) { return 0; } } public void loadUnreadedMessages(String playerName, ModelActionListener<ChatData> callback) { loadMessages(playerName, null, callback); } public void loadMessages(String playerName, Date startDate, ModelActionListener<ChatData> callback) { RequestMap map = new RequestMap().setFirst(KEY_REQUEST, REQ_GET_MESSAGES).setFirst(KEY_PLAYER, playerName); if (startDate != null) map.setFirst(KEY_DATE, Long.toString(startDate.getTime())); getProperties(map, callback); } public void removeMessages(String playerName, ModelActionListener<Integer> callback) { askModel(new RequestMap().setFirst(KEY_REQUEST, REQ_REMOVE_MESSAGES).setFirst(KEY_PLAYER, playerName), callback); } public void updateReadDate(String playerName, ModelActionListener<Integer> callback) { askModel(new RequestMap().setFirst(KEY_REQUEST, REQ_UPDATE_READ_DATE).setFirst(KEY_PLAYER, playerName), callback); } public void sendMessage(String playerName, String text, ModelActionListener<Integer> callback) { askModel(new RequestMap().setFirst(KEY_REQUEST, REQ_SEND_MESSAGE).setFirst(KEY_PLAYER, playerName).setFirst(KEY_VALUE, text), callback); } }<file_sep>package org.dyndns.fzoli.mill.server.model.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; /** * * @author zoli */ @Entity public class Validator implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @OneToOne private Player player; private String validatorKey; public Validator() { } public Validator(Player player, String validatorKey) { this.player = player; this.validatorKey = validatorKey; } public Player getPlayer() { return player; } public String getValidatorKey() { return validatorKey; } public void setPlayer(Player player) { this.player = player; } public void setValidatorKey(String validatorKey) { this.validatorKey = validatorKey; } }<file_sep>package org.dyndns.fzoli.mill.common.model.entity; import java.util.Date; /** * * @author zoli */ public class PersonalData { private String firstName, lastName, country, region, city; private boolean inverseName; private Date birthDate; protected Long birth; private Sex sex; public PersonalData(String firstName, String lastName, boolean inverseName, Date birthDate, Sex sex, String country, String region, String city) { this.firstName = firstName; this.lastName = lastName; this.country = country; this.region = region; this.city = city; this.inverseName = inverseName; this.birthDate = birthDate; this.sex = sex; if (birthDate != null) birth = birthDate.getTime(); } public String getName() { return getFirstName() == null || getLastName() == null ? null : (!isInverseName() ? getFirstName() + " " + getLastName() : getLastName() + " " + getFirstName()).trim(); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public boolean isInverseName() { return inverseName; } public void setInverseName(boolean inverseName) { this.inverseName = inverseName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; if (birthDate != null) this.birth = birthDate.getTime(); } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public void clear() { setFirstName(null); setLastName(null); setInverseName(false); setSex(null); setBirthDate(null); setCity(null); setRegion(null); setCountry(null); } }<file_sep>package org.dyndns.fzoli.mill.common.model.entity; /** * * @author zoli */ public enum OnlineStatus { ONLINE, INVISIBLE }<file_sep>package org.dyndns.fzoli.mill.server.model.entity; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Serializable; import javax.imageio.ImageIO; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * * @author zoli */ @Entity public class PlayerAvatar implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; private String playerName; private byte[] avatar; private int scale; @Embedded private Point topLeftPoint; public PlayerAvatar() { } public PlayerAvatar(String playerName, BufferedImage avatar, Point topLeftPoint, int scale) { this(playerName, imageToByteArray(avatar), topLeftPoint, scale); } public PlayerAvatar(String playerName, byte[] avatar, Point topLeftPoint, int scale) { this.playerName = playerName; this.avatar = avatar; this.scale = scale; this.topLeftPoint = topLeftPoint; } public Long getId() { return id; } public String getPlayerName() { return playerName; } public byte[] getAvatarArray() { return avatar; } public BufferedImage createAvatarImage() { try { Point p = getTopLeftPoint(); return getAvatarImage().getSubimage(p.getX(), p.getY(), getScale(), getScale()); } catch (Exception ex) { return null; } } public BufferedImage getAvatarImage() { return byteArrayToImage(getAvatarArray()); } public Point getTopLeftPoint() { return topLeftPoint; } public int getScale() { return scale; } public void setAvatar(byte[] avatar) { this.avatar = avatar; } public void setAvatar(BufferedImage avatar) { this.avatar = imageToByteArray(avatar); } public void setTopLeftPoint(Point topLeftPoint) { this.topLeftPoint = topLeftPoint; } public void setScale(int scale) { this.scale = scale; } public void reset() { this.avatar = null; this.topLeftPoint = null; this.scale = 0; } public static byte[] imageToByteArray(BufferedImage img) { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", os); } catch (IOException ex) { return null; } return os.toByteArray(); } public static BufferedImage byteArrayToImage(byte[] array) { try { return ImageIO.read(new ByteArrayInputStream(array)); } catch (IOException ex) { return null; } } }<file_sep>package org.dyndns.fzoli.mill.server.model; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.dyndns.fzoli.mill.common.InputValidator; import org.dyndns.fzoli.mill.common.key.PlayerBuilderKeys; import org.dyndns.fzoli.mill.common.key.PlayerBuilderReturn; import org.dyndns.fzoli.mill.common.model.pojo.PlayerBuilderData; import org.dyndns.fzoli.mill.common.model.pojo.PlayerBuilderEvent; import org.dyndns.fzoli.mill.server.model.dao.PlayerDAO; import org.dyndns.fzoli.mill.server.model.entity.Player; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; /** * * @author zoli */ public class PlayerBuilderModel extends AbstractMillModel<PlayerBuilderEvent, PlayerBuilderData> implements PlayerBuilderKeys { private final static int TIMEOUT = 600000; // 10 minutes private long initTime = new Date().getTime(); private String user = "", email = ""; private final static PlayerDAO DAO = new PlayerDAO(); public List<PlayerBuilderModel> findModels() { return findModels(getKey(), PlayerBuilderModel.class); } public boolean isTimeout(long time) { return time - initTime >= TIMEOUT; } public boolean isUserFree(String user) { if (user == null) return true; if (DAO.isPlayerNameExists(user)) return false; List<PlayerBuilderModel> models = findModels(); long time = new Date().getTime(); for (PlayerBuilderModel model : models) { if (!model.isTimeout(time) && user.equals(model.user)) return false; } return true; } public boolean isEmailFree(String email) { return !DAO.isEmailExists(email); } public PlayerBuilderReturn setUser(String user) { if (user.equals(this.user)) return PlayerBuilderReturn.OK; if (InputValidator.isUserIdValid(user)) { if (!isUserFree(user)) return PlayerBuilderReturn.USER_EXISTS; this.user = user; return PlayerBuilderReturn.OK; } return PlayerBuilderReturn.INVALID_USER; } public PlayerBuilderReturn setEmail(String email) { if (email.equals(this.email)) return PlayerBuilderReturn.OK; if (InputValidator.isEmailValid(email)) { if (!isEmailFree(email)) return PlayerBuilderReturn.EMAIL_EXISTS; this.email = email; return PlayerBuilderReturn.OK; } return PlayerBuilderReturn.INVALID_EMAIL; } public PlayerBuilderReturn createUser(HttpServletRequest sr, String password, boolean hash) { if (!isCaptchaValidated()) return PlayerBuilderReturn.WRONG_CAPTCHA; if (validate(false)) return PlayerBuilderReturn.VALIDATED; if (InputValidator.isPasswordValid(password, hash) && InputValidator.isUserIdValid(user) && InputValidator.isEmailValid(email)) { Player player = new Player(user, password, email); PlayerBuilderReturn ret = DAO.createPlayer(player, hash); if (ret == PlayerBuilderReturn.OK) { addStaticEvent(); validate(true); removeCaptcha(); getPlayerModel(true).signIn(user, password, hash); getPlayerModel().validateEmail(sr, player); } return ret; } return PlayerBuilderReturn.INVALID; } @Override protected int askModel(HttpServletRequest sr, RequestMap m) { String action = m.getFirst(KEY_REQUEST); String value = m.getFirst(KEY_VALUE); if (action != null) { if (action.equals(REQ_VALIDATE)) return (validate(true) ? PlayerBuilderReturn.VALIDATED : PlayerBuilderReturn.NOT_VALIDATED).ordinal(); if (action.equals(REQ_CREATE)) return createUser(sr, value, false).ordinal(); if (action.equals(REQ_SAFE_CREATE)) return createUser(sr, value, true).ordinal(); } return super.askModel(sr, m); } @Override protected PlayerBuilderData getProperties(HttpServletRequest sr, RequestMap m) { validate(false); return new PlayerBuilderData(user, email, new Date().getTime(), initTime, TIMEOUT, DAO.getPlayerCount(), isCaptchaValidated(), getCaptchaWidth()); } @Override protected int setProperty(HttpServletRequest hsr, RequestMap rm) { String action = rm.getFirst(KEY_REQUEST); String value = rm.getFirst(KEY_VALUE); if (action != null && value != null) { if (action.equals(REQ_SET_USER)) return setUser(value).ordinal(); if (action.equals(REQ_SET_EMAIL)) return setEmail(value).ordinal(); } return PlayerBuilderReturn.NULL.ordinal(); } private boolean validate(boolean force) { long time = new Date().getTime(); if (force || isTimeout(time)) { user = ""; email = ""; initTime = time; addEvent(true); return true; } return false; } private void addEvent(boolean reset) { addEvent(new PlayerBuilderEvent(reset, DAO.getPlayerCount())); } private void addStaticEvent() { addStaticEvent(new PlayerBuilderEvent(false, DAO.getPlayerCount())); } }<file_sep>package org.dyndns.fzoli.mill.common.model.pojo; import org.dyndns.fzoli.mill.common.model.entity.Message; /** * * @author zoli */ public class ChatEvent extends BaseOnlinePojo { private Message message; private String clearPlayer; private Boolean clear; public ChatEvent(String playerName) { super(playerName); } public ChatEvent(String playerName, String clearPlayer) { super(playerName); this.clear = true; this.clearPlayer = clearPlayer; } public ChatEvent(String playerName, Message message) { super(playerName); this.message = message; } public boolean isClear() { if (clear == null) return false; return clear; } public String getClearPlayer() { return clearPlayer; } public Message getMessage() { return message; } } <file_sep>package org.dyndns.fzoli.mill.server.servlet; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.dyndns.fzoli.mill.common.key.MillServletURL; import org.dyndns.fzoli.mill.common.key.ModelKeys; import org.dyndns.fzoli.mill.server.model.PlayerModel; import org.dyndns.fzoli.mvc.server.model.bean.ModelBean; import org.dyndns.fzoli.mvc.server.model.bean.ModelBeanRegister; import org.dyndns.fzoli.mvc.server.servlet.listener.JSONListenerServlet; /** * * @author zoli */ @WebServlet( urlPatterns={MillServletURL.LISTENER}, initParams ={ @WebInitParam(name=MillListenerServlet.PARAM_EVENT_DELAY, value="50"), @WebInitParam(name=MillListenerServlet.PARAM_EVENT_TIMEOUT, value="20000"), @WebInitParam(name=MillListenerServlet.PARAM_GC_DELAY, value="60000") } ) public final class MillListenerServlet extends JSONListenerServlet { private static Date lastTime; @Override protected void printResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final Date now = new Date(); if (lastTime == null) lastTime = now; if (new Date().getTime() - lastTime.getTime() >= 60000) { new Thread(new Runnable() { @Override public void run() { List<ModelBean> beans = ModelBeanRegister.getModelBeans(); for (ModelBean bean : beans) { HttpSession s = bean.getSession(); if (s == null) continue; try { if (now.getTime() - s.getLastAccessedTime() >= getServletUtils().getEventTimeout() + getServletUtils().getReconnectWait()) { PlayerModel m = (PlayerModel) bean.getModel(ModelKeys.PLAYER); if (m == null) continue; m.onDisconnect(); } } catch (Exception ex) { continue; } } } }).start(); lastTime = now; } super.printResponse(request, response); } }<file_sep>package org.dyndns.fzoli.mill.server.model.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import java.util.List; import javax.persistence.EntityTransaction; import org.dyndns.fzoli.mill.server.model.entity.City; import org.dyndns.fzoli.mill.server.model.entity.Country; import org.dyndns.fzoli.mill.server.model.entity.Region; /** * * @author zoli */ public class City2DAO extends AbstractObjectDAO { @Override protected String getPath() { return "cities.odb"; } public boolean save(Country country) { return save(country, Country.class); } public boolean save(Region region) { return save(region, Region.class); } public boolean save(City city) { return save(city, City.class); } private List<Region> getRegions() { return getEntityManager().createQuery("SELECT o FROM Region o", Region.class).getResultList(); } private static String createSql(long from, int count) { return "SELECT city.name, city.accent_name, city.latitude, city.longitude, region_code FROM city LEFT JOIN region ON (region.id = city.region) LIMIT " + from + ", " + count; } private static Region find(List<Region> rs, String code) { for (Region r : rs) { if (r.getRegionCode().equals(code)) { return r; } } return null; } private static int count = 3000000; private static void load(long from, Statement s, List<Region> regions, City2DAO dao2) throws SQLException { System.out.print(new Date() + ": read from " + from + " ."); ResultSet result = s.executeQuery(createSql(from, count)); dao2.getEntityManager().getTransaction().begin(); System.out.print("."); while (result.next()) { Region region = find(regions, result.getString("REGION_CODE")); City c = new City(region, result.getString("NAME"), result.getString("ACCENT_NAME"), result.getDouble("LATITUDE"), result.getDouble("LONGITUDE")); dao2.getEntityManager().persist(c); } System.out.print("."); dao2.getEntityManager().getTransaction().commit(); result.close(); System.out.println(" done " + (int)((from / 2533120.0) * 100) + " %"); load(from + count, s, regions, dao2); } private static void prepare(CityDAO dao1, City2DAO dao2) { List<org.dyndns.fzoli.mill.common.model.entity.Country> countries = dao1.getCountries(); int i = 0; int countriesSize = countries.size(); for (org.dyndns.fzoli.mill.common.model.entity.Country country : countries) { Country c = new Country(country.getID(), country.getName()); dao2.save(c); List<org.dyndns.fzoli.mill.common.model.entity.Region> regions = dao1.getRegionsByCountry(c.getId()); for (org.dyndns.fzoli.mill.common.model.entity.Region region : regions) { Region r = new Region(c, region.getRegionCode(), region.getName()); dao2.save(r); } i++; System.out.println("country "+i+" / "+countriesSize); } } private static void fill(CityDAO dao1, City2DAO dao2) throws SQLException { System.out.println("started"); List<Region> regions = dao2.getRegions(); Statement s = dao1.getConnection().createStatement(); System.out.println("connected"); long start = 0; try { start = dao2.getEntityManager().createQuery("select count(c) from City c", Long.class).getSingleResult(); } catch (Exception ex) { ; } start += 1011800; start += 1010000; load(start, s, regions, dao2); System.out.println("finished"); } public static void main(String[] args) throws SQLException { CityDAO dao1 = new CityDAO(); City2DAO dao2 = new City2DAO(); // prepare(dao1, dao2); fill(dao1, dao2); } }<file_sep>package org.dyndns.fzoli.mill.client.model; import java.util.List; import org.dyndns.fzoli.mill.common.key.ModelKeys; import org.dyndns.fzoli.mill.common.key.PersonalDataType; import org.dyndns.fzoli.mill.common.key.PlayerKeys; import org.dyndns.fzoli.mill.common.model.entity.BasePlayer; import org.dyndns.fzoli.mill.common.model.entity.OnlineStatus; import org.dyndns.fzoli.mill.common.model.pojo.PlayerData; import org.dyndns.fzoli.mill.common.model.pojo.PlayerEvent; import org.dyndns.fzoli.mvc.client.connection.Connection; import org.dyndns.fzoli.mvc.client.event.ModelActionListener; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; /** * * @author zoli */ public class PlayerModel extends AbstractOnlineModel<PlayerEvent, PlayerData> implements PlayerKeys { public PlayerModel(Connection<Object, Object> connection) { super(connection, ModelKeys.PLAYER, PlayerEvent.class, PlayerData.class); } public void loadCountries(String value, ModelActionListener<PlayerData> callback) { getProperties(new RequestMap().setFirst(KEY_REQUEST, REQ_GET_COUNTRIES).setFirst(KEY_VALUE, value), callback); } public void loadRegions(String value, ModelActionListener<PlayerData> callback) { getProperties(new RequestMap().setFirst(KEY_REQUEST, REQ_GET_REGIONS).setFirst(KEY_VALUE, value), callback); } public void loadCities(String value, ModelActionListener<PlayerData> callback) { getProperties(new RequestMap().setFirst(KEY_REQUEST, REQ_GET_CITIES).setFirst(KEY_VALUE, value), callback); } public PlayerData loadPlayer(String playerName) { return getProperties(new RequestMap() .setFirst(KEY_USER, playerName)); } public int signIn(String user, String password, boolean hash) { return askModel(createSignInRequest(user, password, hash)); } public void signIn(String user, String password, boolean hash, ModelActionListener<Integer> callback) { askModel(createSignInRequest(user, password, hash), callback); } public int signOut() { return askModel(createSignOutRequest()); } public void signOut(ModelActionListener<Integer> callback) { askModel(createSignOutRequest(), callback); } public boolean isEmailFree(String email) { return askModel(new RequestMap() .setFirst(KEY_REQUEST, REQ_IS_EMAIL_FREE) .setFirst(KEY_VALUE, email)) == 1 ? true : false; } public void revalidateEmail(String password, boolean safe, ModelActionListener<Integer> callback) { askModel(new RequestMap() .setFirst(KEY_REQUEST, safe ? REQ_SAFE_REVALIDATE_EMAIL : REQ_REVALIDATE_EMAIL) .setFirst(KEY_PASSWORD, password), callback); } public void suspendAccount(String password, boolean safe, ModelActionListener<Integer> callback) { askModel(new RequestMap() .setFirst(KEY_REQUEST, safe ? REQ_SAFE_SUSPEND_ACCOUNT : REQ_SUSPEND_ACCOUNT) .setFirst(KEY_PASSWORD, password), callback); } public void setActivePermission(int mask, ModelActionListener<Integer> callback) { setProperty(new RequestMap().setFirst(KEY_REQUEST, REQ_SET_ACTIVE_PERMISSION).setFirst(KEY_VALUE, Integer.toString(mask)), callback); } public void setEmail(String password, String email, boolean safe, ModelActionListener<Integer> callback) { setProperty(new RequestMap() .setFirst(KEY_REQUEST, safe ? REQ_SAFE_SET_EMAIL : REQ_SET_EMAIL) .setFirst(KEY_PASSWORD, password) .setFirst(KEY_VALUE, email), callback); } public void setPassword(String oldPassword, String newPassword, boolean safe, ModelActionListener<Integer> callback) { setProperty(new RequestMap() .setFirst(KEY_REQUEST, safe ? REQ_SET_SAFE_PASSWORD : REQ_SET_PASSWORD) .setFirst(KEY_PASSWORD, oldPassword) .setFirst(KEY_VALUE, newPassword), callback); } public void setOnlineStatus(OnlineStatus state, ModelActionListener<Integer> callback) { setProperty(new RequestMap() .setFirst(KEY_REQUEST, REQ_SET_ONLINE_STATUS) .setFirst(KEY_VALUE, state.name()), callback); } public int setPersonalData(PersonalDataType request, String value) { return setProperty(createPersonalDataRequest(request, value)); } public void setPersonalData(PersonalDataType request, String value, ModelActionListener<Integer> callback) { setProperty(createPersonalDataRequest(request, value), callback); } private List<BasePlayer> findPlayerList(PlayerData.PlayerList type) { switch (type) { case BLOCKED_PLAYERS: return getCache().getPlayer().getBlockedUserList(); case WISHED_FRIENDS: return getCache().getPlayer().getFriendWishList(); case POSSIBLE_FRIENDS: return getCache().getPlayer().getPossibleFriends(); default: return getCache().getPlayer().getFriendList(); } } @Override protected void updateCache(List<PlayerEvent> list, PlayerData po) { try { super.updateCache(list, po); if (po.getPlayerName() != null) { BasePlayer p; List<BasePlayer> l = po.getPlayer().createMergedPlayerList(); for (PlayerEvent e : list) { switch (e.getType()) { case SIGNIN: p = findPlayer(l, e.getChangedPlayer()); if (p != null) { p.setOnline(true); } else { PlayerData data = loadPlayer(e.getChangedPlayer()); List<BasePlayer> ls = findPlayerList(data.getAskedPlayerList()); ls.add(data.getAskedPlayer()); BasePlayer.orderList(ls); } break; case SIGNOUT: p = findPlayer(l, e.getChangedPlayer()); if (p != null) p.setOnline(false); break; case VALIDATE: po.getPlayer().setValidated(true); break; case INVALIDATE: po.getPlayer().setEmail(""); po.getPlayer().setValidated(false); break; case SUSPEND: p = findPlayer(l, e.getChangedPlayer()); if (p != null) { po.getPlayer().getFriendList().remove(p); po.getPlayer().getFriendWishList().remove(p); po.getPlayer().getBlockedUserList().remove(p); po.getPlayer().getPossibleFriends().remove(p); } break; case AVATAR_ENABLE: po.getPlayer().setAvatarEnabled(true); break; case AVATAR_DISABLE: po.getPlayer().setAvatarEnabled(false); break; case RELOAD: PlayerData data = loadPlayer(e.getChangedPlayer()); p = findPlayer(l, e.getChangedPlayer()); if (p != null) p.reload(data.getAskedPlayer()); break; case PERSONAL_DATA_CHANGE: data = loadPlayer(e.getChangedPlayer()); p = findPlayer(l, e.getChangedPlayer()); if (p != null) p.setPersonalData(data.getAskedPlayer().getPersonalData()); break; } } } } catch (Exception ex) { ; } } public BasePlayer findPlayer(String playerName) { return findPlayer(getCache().getPlayer().createMergedPlayerList(), playerName); } private BasePlayer findPlayer(List<BasePlayer> l, String name) { for (BasePlayer p : l) { if (p.getPlayerName().equals(name)) return p; } return null; } private RequestMap createPersonalDataRequest(PersonalDataType request, String value) { return new RequestMap() .setFirst(KEY_REQUEST, request.name()) .setFirst(KEY_VALUE, value); } private RequestMap createSignInRequest(String user, String password, boolean hash) { return new RequestMap() .setFirst(KEY_REQUEST, hash ? REQ_SAFE_SIGN_IN : REQ_SIGN_IN) .setFirst(KEY_USER, user) .setFirst(KEY_PASSWORD, <PASSWORD>); } private RequestMap createSignOutRequest() { return new RequestMap() .setFirst(KEY_REQUEST, REQ_SIGN_OUT); } }<file_sep>package org.dyndns.fzoli.mill.common.key; /** * * @author zoli */ public enum PersonalDataType { FIRST_NAME, LAST_NAME, INVERSE_NAME, BIRTH_DATE, SEX, COUNTRY, REGION, CITY, CLEAR }<file_sep>package org.dyndns.fzoli.dao; import java.sql.Connection; import java.sql.DriverManager; import java.util.HashMap; import java.util.Map; /** * * @author zoli */ public abstract class AbstractJdbcDAO { private static final Map<String, Connection> CONNECTIONS = new HashMap<String, Connection>(); // public AbstractJdbcDAO() { // if(getConnection() == null) throw new NullPointerException("JDBC connection is null"); // } protected abstract String getUrl(); protected abstract String getDriver(); protected abstract String getUser(); protected abstract String getPassword(); protected Connection getConnection() { Connection conn = CONNECTIONS.get(getUrl()); if (conn == null) { conn = createConnection(); CONNECTIONS.put(getUrl(), conn); } return conn; } private Connection createConnection() { try { Class.forName(getDriver()).newInstance(); return DriverManager.getConnection(getUrl(), getUser(), getPassword()); } catch (Exception e) { e.printStackTrace(); return null; } } }<file_sep>package org.dyndns.fzoli.mill.client.model; import java.util.List; import org.dyndns.fzoli.mill.common.key.ModelKeys; import org.dyndns.fzoli.mill.common.key.PlayerBuilderKeys; import org.dyndns.fzoli.mill.common.model.pojo.PlayerBuilderData; import org.dyndns.fzoli.mill.common.model.pojo.PlayerBuilderEvent; import org.dyndns.fzoli.mvc.client.connection.Connection; import org.dyndns.fzoli.mvc.client.event.ModelActionListener; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; /** * * @author zoli */ public class PlayerBuilderModel extends AbstractMillModel<PlayerBuilderEvent, PlayerBuilderData> implements PlayerBuilderKeys { public PlayerBuilderModel(Connection<Object, Object> connection) { super(connection, ModelKeys.PLAYER_BUILDER, PlayerBuilderEvent.class, PlayerBuilderData.class); } public void setUser(String user, ModelActionListener<Integer> callback) { setProperty(new RequestMap() .setFirst(KEY_REQUEST, REQ_SET_USER) .setFirst(KEY_VALUE, user), callback); } public void setEmail(String email, ModelActionListener<Integer> callback) { setProperty(new RequestMap() .setFirst(KEY_REQUEST, REQ_SET_EMAIL) .setFirst(KEY_VALUE, email), callback); } public void createUser(String password, boolean hash, ModelActionListener<Integer> callback) { askModel(new RequestMap() .setFirst(KEY_REQUEST, hash ? REQ_SAFE_CREATE : REQ_CREATE) .setFirst(KEY_VALUE, password), callback); } public void validate() { askModel(createValidateMap()); } public void validate(ModelActionListener<Integer> callback) { askModel(createValidateMap(), callback); } @Override protected void updateCache(List<PlayerBuilderEvent> list, PlayerBuilderData cache) { try { for (PlayerBuilderEvent e : list) { if (e.isReset()) cache.reinit(); cache.setUserCount(e.getUserCount()); } } catch (Exception ex) { ; } } private RequestMap createValidateMap() { return new RequestMap() .setFirst(KEY_REQUEST, REQ_VALIDATE); } }<file_sep>package org.dyndns.fzoli.mill.common.model.pojo; /** * * @author zoli */ abstract class PlayerBuilderPojo { private long userCount; PlayerBuilderPojo(long userCount) { this.userCount = userCount; } public long getUserCount() { return userCount; } protected void setUserCount(long userCount) { this.userCount = userCount; } }<file_sep>package org.dyndns.fzoli.mill.common.model.pojo; /** * * @author zoli */ public interface BaseCaptchaPojo { int getCaptchaWidth(); boolean isCaptchaValidated(); void setCaptchaValidated(boolean validated); void setCaptchaWidth(int captchaWidth); }<file_sep>package org.dyndns.fzoli.mill.server.model; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dyndns.fzoli.mill.common.DateUtil; import org.dyndns.fzoli.mill.common.Permission; import org.dyndns.fzoli.mill.common.key.ChatKeys; import org.dyndns.fzoli.mill.common.model.entity.MessageType; import org.dyndns.fzoli.mill.common.model.pojo.ChatData; import org.dyndns.fzoli.mill.common.model.pojo.ChatEvent; import org.dyndns.fzoli.mill.server.model.dao.PlayerDAO; import org.dyndns.fzoli.mill.server.model.entity.ConvertUtil; import org.dyndns.fzoli.mill.server.model.entity.Message; import org.dyndns.fzoli.mill.server.model.entity.Player; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; /** * * @author zoli */ public class ChatModel extends AbstractOnlineModel<ChatEvent, ChatData> implements ChatKeys { private static final PlayerDAO DAO = new PlayerDAO(); public void sendMessage(Message message) { callOnPlayerChanged(ChatModel.class, new ChatEvent(message.getAddress().getPlayerName(), ConvertUtil.createMessage(message))); } @Override protected ChatData getProperties(HttpServletRequest hsr, RequestMap rm) { Player me = getPlayer(); String action = rm.getFirst(KEY_REQUEST); if (me != null && action != null) { if (action.equals(REQ_GET_MESSAGES)) { String player = rm.getFirst(KEY_PLAYER); if (player != null) { Player p = DAO.getPlayer(player); if (p != null) { try { // return every message after the specified date Date d = new Date(Long.parseLong(rm.getFirst(KEY_DATE))); return new ChatData(me.getPlayerName(), ConvertUtil.createMessageList(me.getMessages(p, d))); } catch (Exception ex) { // return only unreaded messages if date is not specified return new ChatData(me.getPlayerName(), ConvertUtil.createMessageList(me.getUnreadedMessages(p))); } } } } } return new ChatData(getPlayerName(), me == null ? null : me.getUnreadedMessagesCount()); } @Override protected int askModel(HttpServletRequest hsr, RequestMap rm) { Player me = getPlayer(); String action = rm.getFirst(KEY_REQUEST); if (action != null && action.equals(REQ_SYNC)) { try { long remote = Long.parseLong(rm.getFirst(KEY_DATE)); long local = DateUtil.getDateInTimeZone(new Date(), "GMT").getTime(); return (int)(local - remote); } catch (Exception ex) { return 0; } } if (me != null && action != null) { String player = rm.getFirst(KEY_PLAYER); if (player != null) { Player p = DAO.getPlayer(player); if (p != null) { if (action.equals(REQ_UPDATE_READ_DATE)) { if (me.updateMessageReadDate(p)) { DAO.save(me); return 1; } else { return 0; } } if (action.equals(REQ_REMOVE_MESSAGES)) { if (DAO.removeMessages(me, p)) { if (me.getFriendList().contains(p) || p.canUsePermission(me, Permission.SEND_PERSON_MESSAGE)) callOnPlayerChanged(ChatModel.class, new ChatEvent(p.getPlayerName(), me.getPlayerName())); return 1; } else { return 0; } } if (p.getFriendList().contains(me) || me.canUsePermission(p, Permission.SEND_PERSON_MESSAGE)) { String value = rm.getFirst(KEY_VALUE); if (value != null) { if (action.equals(REQ_SEND_MESSAGE)) { Message msg = new Message(p, value); DAO.save(msg); me.getPostedMessages().add(msg); DAO.save(me); msg.setSender(me); sendMessage(msg); return 1; } } } else { return me.canUsePermission(p, Permission.DETECT_INVISIBLE_STATUS) ? 0 : 1; } } } } return 0; } @Override protected void onPlayerChanged(ChatEvent evt) { if (evt.isClear() && evt.getPlayerName().equals(getPlayerName())) { addEvent(evt); } if (!evt.isClear() && evt.getMessage().getAddress().equals(getPlayerName())) { addEvent(evt); } } @Override protected int setProperty(HttpServletRequest hsr, RequestMap rm) { return 0; } }<file_sep>package org.dyndns.fzoli.email; import java.io.File; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; public class GMailSender { private static class AuthenticatorData { String user; Authenticator authenticator; AuthenticatorData(String user, Authenticator authenticator) { this.user = user; this.authenticator = authenticator; } } private static Properties createGmailProperties() { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); return props; } private static AuthenticatorData createAuthenticator(File fXmlFile) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); Element e = doc.getDocumentElement(); final String user = e.getAttribute("user"); final String password = e.getAttribute("password"); if (user == null || password == null) throw new Exception("Wrong GMail XML file"); Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }; return new AuthenticatorData(user, authenticator); } catch (Exception ex) { throw new RuntimeException(ex); } } public static void sendEmail(File xml, String address, String subject, String msg) { AuthenticatorData data = createAuthenticator(xml); Session session = Session.getDefaultInstance(createGmailProperties(), data.authenticator); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(data.user)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address)); message.setSubject(subject); message.setContent(msg, "text/html;charset=UTF-8"); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } public static void main(String[] args) { sendEmail(new File("/home/zoli/gmail-authenticator.xml"), "<EMAIL>", "Teszt üzenet", "Kedves e-mail szűrő, kérlek ne töröld az üzenetet.<br />Köszöni a Java.<h1>Öt szép szűz lány őrült írót nyúz.</h1>"); } }<file_sep>package org.dyndns.fzoli.location.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dyndns.fzoli.dao.AbstractJdbcDAO; import org.dyndns.fzoli.location.entity.City; import org.dyndns.fzoli.location.entity.Country; import org.dyndns.fzoli.location.entity.Region; /** * * @author zoli */ public abstract class CityDAO extends AbstractJdbcDAO { private final Log LOG = LogFactory.getLog(CityDAO.class); private static final String ID = "ID", COUNTRY = "COUNTRY", REGION = "REGION", REGION_CODE = "REGION_CODE", NAME = "NAME", ACCENT_NAME = "ACCENT_NAME", POPULATION = "POPULATION", LATITUDE = "LATITUDE", LONGITUDE = "LONGITUDE", CITY = "CITY"; public Country getCountryByName(String name) { if (name == null || name.isEmpty()) return null; return getFirst(getCountries(NAME, name, true)); } public List<Region> getRegionsByCountryId(String countryId) { return getRegions(COUNTRY, countryId, true); } public List<Region> getRegions(String countryName, String regionName) { return getRegionsByCountryAndRegionName(countryName, regionName, true); } public List<Region> getRegionsByCountryName(String countryName) { Country country = getCountryByName(countryName); if (country == null) return new ArrayList<Region>(); return getRegionsByCountryId(country.getID()); } public List<City> getCities(String countryName, String regionName, String cityName) { return getCities(countryName, regionName, cityName, true); } public List<Country> findCountriesByName(String name) { // country auto complette if (name == null || name.isEmpty()) return new ArrayList<Country>(); return getCountries(NAME, name, false); } public List<Region> findRegions(String countryName, String regionName) { // region auto complette return getRegionsByCountryAndRegionName(countryName, regionName, false); } public List<City> findCities(String countryName, String regionName, String cityName) { // city auto complette return getCities(countryName, regionName, cityName, false); } protected abstract String getLocation(); @Override protected String getUrl() { return "jdbc:h2:" + getLocation(); } @Override protected String getDriver() { return "org.h2.Driver"; } @Override protected String getUser() { return "sa"; } @Override protected String getPassword() { return ""; } private List<City> getCities(String countryName, String regionName, String cityName, boolean equals) { cityName = StringEscapeUtils.escapeSql(cityName); List<Region> regions = getRegions(countryName, regionName); if (regions.isEmpty()) return new ArrayList<City>(); String sql = "SELECT * FROM " + CITY + " WHERE REGION IN("; for (int i = 0; i < regions.size(); i++) { sql += regions.get(i).getID(); if (i != regions.size() - 1) sql += ", "; } sql += ") AND (" + (equals ? (/*NAME + " = '" + cityName + "' OR " + */ACCENT_NAME + " = '" + cityName + "'") : ("LOCATE('" + cityName.toUpperCase() + "', UPPER(" + NAME + ")) = 1 OR LOCATE('" + cityName.toUpperCase() + "', UPPER(" + ACCENT_NAME + ")) = 1")) + ");"; LOG.info(sql); return getObjects(sql, City.class); } private List<Region> getRegionsByCountryAndRegionName(String countryName, String regionName, boolean equals) { Country country = getCountryByName(countryName); if (country == null) return new ArrayList<Region>(); return getObjects(new String[]{COUNTRY, NAME}, new boolean[]{true}, new String[]{country.getID(), regionName}, new boolean[]{true, equals}, Region.class, REGION); } private List<Region> getRegions(final String column, final String value, final boolean equals) { return getObjects(column, value, equals, Region.class, REGION); } private List<Country> getCountries(final String column, final String value, final boolean equals) { return getObjects(column, value, equals, Country.class, COUNTRY); } private <T> List<T> getObjects(final String column, String value, final boolean equals, final Class<T> clazz, final String from) { return getObjects(new String[]{column}, new boolean[]{false}, new String[]{value}, new boolean[]{equals}, clazz, from); } private <T> List<T> getObjects(final String[] columns, final boolean[] ands, String[] values, final boolean[] equals, final Class<T> clazz, final String from) { String sql = "SELECT * FROM " + from; if (values != null) { sql += " WHERE "; final int lastIndex = columns.length - 1; for (int i = 0; i <= lastIndex; i++) { String value = StringEscapeUtils.escapeSql(values[i]); sql += equals[i] ? columns[i] + " = '" + value + "'" : "LOCATE('" + value.toUpperCase() + "', UPPER(" + columns[i] + ")) = 1"; if (i != lastIndex) sql += " " + (ands[i] ? "AND" : "OR") + " "; } } sql += ';'; LOG.info(sql); return getObjects(sql, clazz); } private <T> List<T> getObjects(final String sql, final Class<T> clazz) { final List<T> l = new ArrayList<T>(); try { final Statement statement = getConnection().createStatement(); final ResultSet results = statement.executeQuery(sql); while (results.next()) { Object o = null; if (clazz.equals(Country.class)) o = new Country(results.getString(ID), results.getString(NAME)); if (clazz.equals(Region.class)) o = new Region(results.getLong(ID), results.getString(COUNTRY), results.getString(REGION_CODE), results.getString(NAME)); if (clazz.equals(City.class)) o = new City(results.getLong(ID), results.getLong(REGION), results.getString(NAME), results.getString(ACCENT_NAME), results.getInt(POPULATION), results.getDouble(LATITUDE), results.getDouble(LONGITUDE)); if (o != null) l.add((T)o); } results.close(); statement.close(); } catch(SQLException ex) { ex.printStackTrace(); } return l; } private static <T> T getFirst(final List<T> l) { if (l == null || l.isEmpty()) return null; return l.get(0); } }<file_sep>package org.dyndns.fzoli.mill.server.model.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * * @author zoli */ @Entity public class City implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private long id; private Region region; private double latitude, longitude; private String name, accentName; public City() { } public City(Region region, String name, String accentName, double latitude, double longitude) { this.region = region; this.name = name; this.accentName = accentName; this.latitude = latitude; this.longitude = longitude; } public long getId() { return id; } public Region getRegion() { return region; } public String getName() { return name; } public String getAccentName() { return accentName; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } @Override public String toString() { return getName() + '#' + getId(); } } <file_sep>package org.dyndns.fzoli.mill.server.model; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import nl.captcha.Captcha; import nl.captcha.backgrounds.BackgroundProducer; import nl.captcha.backgrounds.FlatColorBackgroundProducer; import nl.captcha.gimpy.GimpyRenderer; import nl.captcha.gimpy.RippleGimpyRenderer; import nl.captcha.noise.CurvedLineNoiseProducer; import nl.captcha.noise.NoiseProducer; import nl.captcha.text.producer.DefaultTextProducer; import nl.captcha.text.producer.TextProducer; import nl.captcha.text.renderer.ColoredEdgesWordRenderer; import nl.captcha.text.renderer.WordRenderer; import org.dyndns.fzoli.mill.common.key.BaseKeys; import org.dyndns.fzoli.mill.common.key.ModelKeys; import org.dyndns.fzoli.mill.server.model.entity.ConvertUtil; import org.dyndns.fzoli.mill.server.model.entity.Player; import org.dyndns.fzoli.mvc.common.request.map.RequestMap; import org.dyndns.fzoli.mvc.server.model.JSONModel; /** * * @author zoli */ abstract class AbstractMillModel<EventObj, PropsObj> extends JSONModel<EventObj, PropsObj> implements BaseKeys { private final static GimpyRenderer GR = new RippleGimpyRenderer(); private final static TextProducer TP = new DefaultTextProducer(6, new char[]{'q', 'w', 'e', 'r', 't', 'z', 'u', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'y', 'x', 'c', 'v', 'b', 'n', 'm'}); private int w = 200, h = 50; private Color fgc = Color.WHITE, bgc = Color.BLACK; private BackgroundProducer bp = new FlatColorBackgroundProducer(bgc); private NoiseProducer np = createProducer(); private WordRenderer wr = createRenderer(); private boolean captchaValidated = false; private Captcha captcha; @Override protected RenderedImage getImage(HttpServletRequest hsr, RequestMap rm) { String action = rm.getFirst(KEY_REQUEST); if (action != null) { if (action.equals(REQ_GET_CAPTCHA)) return getCaptcha(); if (action.equals(REQ_CREATE_CAPTCHA)) return createCaptcha(); } return super.getImage(hsr, rm); } @Override protected int askModel(HttpServletRequest hsr, RequestMap rm) { String action = rm.getFirst(KEY_REQUEST); if (action != null) { String val = rm.getFirst(KEY_VALUE); if (val != null) { if (action.equals(REQ_VALIDATE_CAPTCHA)) { return validate(val) ? 0 : 1; } try { if (action.equals(REQ_SET_CAPTCHA_COLOR)) { setCaptchaBgColor(Boolean.parseBoolean(val)); return 0; } if (action.equals(REQ_SET_CAPTCHA_SIZE)) { setCaptchaSize(Integer.parseInt(val)); return 0; } } catch (Exception ex) {} } } return -1; } public PlayerModel getPlayerModel() { return getPlayerModel(false); } public PlayerModel getPlayerModel(boolean init) { return getModelMap().get(ModelKeys.PLAYER, init, PlayerModel.class); } public int getCaptchaWidth() { return w; } public Player getPlayer() { PlayerModel model = getPlayerModel(); if (model == null) return null; return model.getPlayer(); } public void reinitPlayer() { PlayerModel model = getPlayerModel(); if (model == null) return; model.reinitPlayer(); } public org.dyndns.fzoli.mill.common.model.entity.Player getCommonPlayer() { PlayerModel model = getPlayerModel(); if (model == null) return null; return model.getCommonPlayer(); } public String getPlayerName() { Player player = getPlayer(); if (player == null) return null; return player.getPlayerName(); } protected boolean isCaptchaValidated() { return captchaValidated; } protected boolean validate(String answer) { boolean ok = captcha == null ? false : captcha.isCorrect(answer.toLowerCase()); if (!ok) createCaptcha(); captchaValidated = ok; return ok; } protected void removeCaptcha() { captcha = null; captchaValidated = false; } protected RenderedImage getCaptcha() { if (captcha == null) return createCaptcha(); BufferedImage img = captcha.getImage(); Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(fgc); g.drawRect(0, 0, img.getWidth() - 1, img.getHeight() - 1); return img; } protected void setCaptchaBgColor(boolean white) { bgc = white ? Color.WHITE : Color.BLACK; fgc = white ? Color.BLACK : Color.WHITE; bp = new FlatColorBackgroundProducer(bgc); np = createProducer(); wr = createRenderer(); } protected void setCaptchaSize(int w) { if (w < 200) w = 200; if (w > 1000) w = 1000; this.w = w; this.h = w / 4; wr = createRenderer(); np = createProducer(); removeCaptcha(); } protected NoiseProducer createProducer() { return new CurvedLineNoiseProducer(bgc, w / 100); } protected WordRenderer createRenderer() { return new ColoredEdgesWordRenderer(new ArrayList<Color>() {{add(fgc);}}, new ArrayList<Font>() {{add(new Font("Arial", Font.BOLD, h - (w / 20)));}}, w / 100); } protected RenderedImage createCaptcha() { removeCaptcha(); captcha = new Captcha.Builder(w, h).addText(TP, wr).addBackground(bp).gimp(GR).addBorder().addNoise(np).build(); return getCaptcha(); } }<file_sep>package org.dyndns.fzoli.mill.common.key; /** * * @author zoli */ public enum PlayerAvatarReturn { OK, NOT_OK }<file_sep>package org.dyndns.fzoli.mill.server.test.objectdb; import java.util.List; import javax.persistence.EntityManager; import static org.dyndns.fzoli.mill.server.test.objectdb.Util.*; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; /** * ObjectDB second test. * 1. Create database connection. * 2. Check whether FirstTest finished. * 3. Clear messages. * 4. Try read players. * 5. Create two messages. * 6. Reading back and testing. * @author zoli */ public class SecondTest { private static EntityManager db; public SecondTest() { } @BeforeClass public static void setUpClass() throws Exception { System.out.println("Create database connection."); db = createEntityManager(); assertEquals("There should be exactly 2 players in the database. Please run FirstTest!", 2, getCount(db, Player.class)); } @AfterClass public static void tearDownClass() throws Exception { System.out.println("Close database connection."); db.close(); } @Test(timeout=10000) public void testTwo() { System.out.println("Clear messages."); remove(db, Message.class); System.out.println("Try read players..."); Player p1 = getPlayer(db, PLAYER1); assertNotNull(p1); Player p2 = getPlayer(db, PLAYER2); assertNotNull(p2); System.out.println("Create message 1."); Message m1 = new Message(p2, "message 1"); assertTrue(save(db, m1)); p1.getPostedMessages().add(m1); assertTrue(save(db, p1)); System.out.println("Create message 2."); Message m2 = new Message(p1, "message 2"); assertTrue(save(db, m2)); p2.getPostedMessages().add(m2); assertTrue(save(db, p2)); System.out.println("Testing..."); List<Message> messages = getMessages(db, PLAYER1); assertNotNull(messages); assertEquals(1, messages.size()); assertEquals(1, p1.getReceivedMessages().size()); assertEquals(OnlineStatus.ONLINE, p1.getOnlineStatus()); } }<file_sep>package org.dyndns.fzoli.mill.common; import java.util.ArrayList; import java.util.List; /** Kuka... * Egy adott jog gyakorlásának alap feltétele, hogy a maszk adjon rá jogot. * A három kiegészítő alapelv: * a) Egy adott jog akkor gyakorolható egy másik felhasználón, ha * a másik felhasználó maszkja kisebb (egyenlőség nem megengedett). * (Ebből adódik, hogy fontos a jogok felsorolásának sorrendje.) * b) A felhasználó nem tud olyan jogot adni/elvenni, amivel ő nem rendelkezik * még akkor sem, ha van joga a maszk szerkesztésére. * c) Kitüntetett szerepű maszk a -1. * - Ezen maszkkal az összes jog gyakorolható. * - A legnagyobb maszknak számít. * - A programban soha nem adható senkinek és nem vehető el senkitől. */ /** Alap jogkezelési gondolat. * * Minden jog aktiválható/inaktiválható, ha birtokolja valaki, kivéve a védelem jogát, ami mindig aktív. * * Jogok: * * - statisztika elrejtése: nem láthatják mások, hogy mennyit nyert és veszített a felhasználó a dámában * * - láthatatlan státusz észlelése: annak ellenére, hogy a felhasználó láthatatlan, * ezzel a joggal lehet látni, ha online * * - láthatatlanság nyilvántartásban: a nyilvántartásból elrejtheti magát a felhasználó. * az elrejtés nem érvényes a barátlistára. * * - inaktív felhasználók listázása, adataiknak olvasása * * - chatelés barátlistán kívüliekkel illetve azokkal, akiknél tiltva van a joggal rendelkező -> olyan rendszerüzenet küldése, ami csak 1 embernél, a címzettnél jelenik meg * * - rendszerüzenet küldés: mindenki számára azonnal felugró üzenet küldése * * - felhasználó bannolása: képesség felhasználó bannolására * (bannolás: felhasználó bejelentkezésének tiltása és ha online, azonnali kijelentkeztetése) * * - felhasználó törlése (felfüggesztése): képesség felhasználó törlésére * (törlés: szem. adatok nullázása, felhasználó státusz inaktívvá állítás ami elrejti a nyilvántartásból őt) * * - jogok szerkesztése: képesség jog adására és elvételére * * - védelem: a jogot birtokló felhasználón nem tud senki jogot gyakorolni. * Ez a jog a többivel ellentétben nem aktiválható/inaktiválható. * pl. nem törölheti; láthatatlanságát nem tudja detektálni, * ha rejtve van a nyilvántartásban és van joga észleléshez, akkor sem látja; * nem szerkesztheti jogait; nem tudja elrejteni előtte a statisztikáját; * nem tudja detektálni ha elrejtette magát */ /** Kitüntetett szerepű maszk a -1. * - Ezen maszkkal az összes jog aktív, tehát nem szerkeszthetők a jogai a felhasználónak. * - A védelem joga nem korlátozza és csak ő adhatja illetve veheti el ezt a jogot. * - A programon belül soha nem adható senkinek és nem vehető el senkitől. * - A programon belül nem tudja saját magát kitörölni ellentétben a többiekkel. */ /** * * @author zoli */ public enum Permission { //TODO: ötlet - a 'send person message' jog legyen 'state_inverse' és legyen külön kategória a barátlistánál, ahova az ebben a módban lévő online felhasználók megjelennek ÉS bármelyiküknek lehessen üzenetet küldeni ha nincs a jogot birtokló tiltólistáján HIDDEN_STATISTICS(Group.STATE_INVERSE), DETECT_INVISIBLE_STATUS(Group.STATE_NORMAL), DETECT_SUSPENDED_PLAYER(Group.STATE_NORMAL), // HIDDEN_PLAYER_DETECT(Group.STATE_NORMAL), // SHOW_ALL_PERSONAL_DATA(Group.STATE_NORMAL), HIDDEN_MODE(Group.STATE_INVERSE), // SEE_EVERYONES_AVATAR(Group.STATE_NORMAL), // CHAT_EVERYONE(Group.STATE_NORMAL), SEND_PERSON_MESSAGE(Group.SYSTEM), SEND_SYSTEM_MESSAGE(Group.SYSTEM), PLAYER_BANN(Group.TARGET), PLAYER_SUSPEND(Group.TARGET), PERMISSION_EDIT(Group.TARGET), SHIELD_MODE(Group.STATE_INVERSE); public static final int ROOT = -1; private static final int MIN = 0, MAX = (int) Math.pow(2, Permission.values().length) - 1; private static final List<Integer> MASKS = new ArrayList<Integer>() { { for (int i = MIN; i <= MAX; i++) { add(i); } } }; public static enum Group { TARGET, STATE_NORMAL, STATE_INVERSE, SYSTEM }; private final Group GROUP; private Permission(Group group) { GROUP = group; } public Group getGroup() { return GROUP; } public int getMask() { return getMask(this); } public boolean hasPermission(int mask) { return hasPermission(mask, this); } public boolean hasAllPermission() { return hasAllPermission(getMask()); } public int incPermission(int mask) { return incPermission(mask, this); } public int decPermission(int mask) { return decPermission(mask, this); } public static List<Integer> getMasks() { return MASKS; } public static List<Integer> getMasks(Permission p) { List<Integer> l = new ArrayList<Integer>(); for (int mask : getMasks()) { if (hasPermission(mask, p)) l.add(mask); } return l; } public static int getMask(Permission p) { return (int) Math.pow(2, p.ordinal()); } public static int getMask(List<Permission> permissions) { int i = 0; List<Permission> tmp = new ArrayList<Permission>(); for (Permission p : permissions) { if (tmp.contains(p)) continue; tmp.add(p); i += p.getMask(); } return i; } public static List<Permission> getPermissions(int mask) { List<Permission> ps = new ArrayList<Permission>(); for (Permission p : Permission.values()) { if (p.hasPermission(mask)) ps.add(p); } return ps; } public static boolean hasPermission(int mask, Permission p) { if (mask == ROOT) return true; if (mask < MIN || mask > MAX) return false; return (mask & getMask(p)) != 0; } public static boolean hasAllPermission(int mask) { if (mask == ROOT) return true; return mask == MAX; } public static int incPermission(int mask, Permission p) { if (!hasPermission(mask, p)) return mask + getMask(p); else return mask; } public static int decPermission(int mask, Permission p) { if (hasPermission(mask, p)) return mask - getMask(p); else return mask; } }
dbbbedec88c4af8e317759c64813fbca903a8797
[ "Java" ]
32
Java
fzoli/CheckersServer
c8be0ca8a29040c7a02f894548e15f0cba8896ce
2f87ae431472d5b246c377bf3fe1c84e538d5d1a
refs/heads/master
<repo_name>jcolnago/LibrasProject<file_sep>/librasProject/librasproject/learning/ReviewThread.java package learning; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.scene.paint.Color; /** * Worker thread that implements the behavior of a review and its components * * @author <NAME> */ public class ReviewThread extends Task<Void> { /* Class variables */ private ReviewController controller; public ArrayList<LessonComponent> reviews; public String extraInformation; public List<String> images; public boolean review; /** * Class constructor * @params the reviewController that starts the thread and the review it * should run. */ ReviewThread(ReviewController controller, boolean review) { this.controller = controller; this.review = review; } /** * Implements the logic of the behavior. * @return a string informing that it is done */ @Override protected Void call() throws Exception { boolean result; String recognized; PreparedStatement pStatement; Statement statement; int mistakes = 0; int iterations = controller.lessonComponents.size(); Socket clientSocket = new Socket(controller.application.prop.getProperty("server"), Integer.parseInt(controller.application.prop.getProperty("port"))); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); pStatement = controller.application.getConnection().prepareStatement( "UPDATE review_component SET mistakes=?, last_reviewed='" + controller.getCurrentTimeStamp() + "' WHERE component_id=? AND user_id='" + controller.application.getUserName() + "';"); while (iterations >= 0) { /* Waits for the user to be ready */ controller.setActiveCircle(Color.RED); synchronized(controller.ready) { controller.ready.wait(); } Platform.runLater(new Runnable() { @Override public void run() { controller.setRecognized(""); } }); /* Indicate the user can start */ controller.setActiveCircle(Color.GREEN); out.println("START"); Thread.sleep(3000); // In order to get the predominant value recognized out.println("STOP"); recognized = in.readLine(); result = recognized.equalsIgnoreCase(controller.currentComponent); if (result) { /* Update the review_component with the amout of mistakes made */ pStatement.setInt(1, mistakes); pStatement.setString(2, controller.currentComponent); pStatement.executeUpdate(); Platform.runLater(new Runnable() { @Override public void run() { controller.progress+=1/controller.total; controller.showNextElement(); controller.setActiveCircle(Color.RED); } }); iterations--; mistakes = 0; } else { mistakes++; final String temp = recognized; Platform.runLater(new Runnable() { @Override public void run() { controller.setRecognized(temp); } }); } } if (!review) { statement = controller.application.getConnection().createStatement(); statement.executeUpdate("UPDATE user_lesson SET complete=true" + " WHERE lesson_id='" + controller.lessonName + "' AND user_id='" + controller.application.getUserName() + "';"); } in.close(); out.close(); return null; } }<file_sep>/librasProject/librasproject/login/LoginController.java package login; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import application.LibrasProject; /** * This class is responsible for the control of the login scene. * * @author <NAME> */ public class LoginController extends AnchorPane implements Initializable { /* Class variables */ private LibrasProject application; /* FXML id for the different ui components */ @FXML TextField userId; @FXML PasswordField password; @FXML Label errorMessage; /** * Performs the proper actions for when the close button receives an action. * * @param event the action event information */ @FXML private void handleCloseButtonAction(ActionEvent event) { application.closeConnection(); Platform.exit(); // finishes the application } /** * Sets up the application and any other work that needs to be done on start * up. * * @param application responsible for the scene */ public void setApp(LibrasProject application){ this.application = application; } /** * This function responds to the event of pressing the login button. * It verifies if the user exists and, if so, if the password and login pair * is a valid one * * @param event information about the event */ @FXML public void processLogin(ActionEvent event) { PreparedStatement pStatement; ResultSet rs; try { pStatement = application.getConnection().prepareStatement("SELECT password " + "FROM user_login WHERE user_id='" + userId.getText() + "'"); rs = pStatement.executeQuery(); if (!rs.next()) { errorMessage.setText("Usuario nao cadastrado."); } else { if (!password.getText().equals(rs.getString("password"))){ errorMessage.setText("Usuario ou senha incorreta."); } else { application.setUserName(userId.getText()); application.gotoSelection(); } } } catch (SQLException ex) { Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); } } /** * This function responds to the event of pressing the register button. * It starts the registration scene. * * @param event information about the event */ @FXML public void registerUser(ActionEvent event) { application.gotoRegistration(); } @Override public void initialize(URL location, ResourceBundle resources) { errorMessage.setText(""); userId.setPromptText("learningLibras"); password.setPromptText("<PASSWORD>"); } } <file_sep>/librasProject/librasproject/learning/LearnController.java package learning; import kinect.ViewerPanel; import java.net.URL; import java.sql.SQLException; import java.util.Random; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.layout.Pane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import javafx.util.Duration; import application.LibrasProject; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; /** * This class is responsible for the control of the Lessons scene. * * @author <NAME> */ public class LearnController extends LearningController implements Initializable { /* Class variables */ private LearnThread learn; private MemorizeThread memorize; public final Object waitVideo = new Object(); public final Object waitVerification = new Object(); public boolean isCorrect = false; private ViewerPanel vp; /* FXML id for the different ui components */ @FXML Pane Video; @FXML Button Play; /** * Performs the proper action for when the back button receives an action. * * @param event the action event information */ @FXML private void handleBackButtonAction(ActionEvent event) { learn.cancel(); vp.closeDown(); application.gotoSelection(); // returns to the selection scene } /** * Performs the proper action for when the back button receives an action. * * @param event the action event information */ @FXML private void handlePlayButtonAction(ActionEvent event) { stopVideo(); playVideo(); } /** * Checks if the element clicked is the correct one. * * @param event the action event information */ @FXML private void checkIfCorrect(MouseEvent event) { ImageView image = (ImageView)event.getSource(); isCorrect = image.getId().equals(currentComponent); synchronized(waitVerification) { waitVerification.notify(); } } /** * Sets up the application and any other work that needs to be done on start * up. * * @param application responsible for the scene * @param lessonName lesson's name that needs to be loaded */ public void setApp(LibrasProject application, String lessonName) throws SQLException { this.application = application; this.lessonName = lessonName; progress = 0; /* Get the information from these components*/ lessonComponents = getLessonInformation(); total = lessonComponents.size(); showNextElement(); vp = new ViewerPanel(this); Thread th1 = new Thread(vp); th1.setDaemon(true); th1.start(); // start updating the panel's image learn = new LearnThread(this); Thread th = new Thread(learn); th.setDaemon(true); th.start(); } /** * Sets up the path for the video to be used for the next lesson component. * * @param fileLocation a string containing the video path */ public void setVideo(String fileLocation) { if (!Video.getChildren().isEmpty()) { stopVideo(); Video.getChildren().remove(0); } String video; try { video = (LibrasProject.class.getClassLoader().getResource(fileLocation).toURI().toString()); Media media = new Media(video); // Create the player and set to play automatically. MediaPlayer mediaPlayer = new MediaPlayer(media); //mediaPlayer.setAutoPlay(true); mediaPlayer.setCycleCount(1); // Create the view and add it to the Scene. MediaView mediaView = new MediaView(mediaPlayer); mediaView.setFitHeight(274.0); mediaView.setFitWidth(300.0); mediaView.setPreserveRatio(false); Video.getChildren().add(mediaView); } catch (URISyntaxException ex) { Logger.getLogger(LearnController.class.getName()).log(Level.SEVERE, null, ex); } } /** * Plays the current video. */ public void playVideo() { ((MediaView)Video.getChildren().get(0)).getMediaPlayer().play(); synchronized(waitVideo) { waitVideo.notify(); } } /** * Stops the current video displaying. */ public void stopVideo() { if (((MediaView)Video.getChildren().get(0)).getMediaPlayer().getStatus() == MediaPlayer.Status.PLAYING) { ((MediaView)Video.getChildren().get(0)).getMediaPlayer().stop(); } } /** * Gets the duration in milliseconds of the current video */ public Duration getVideoDuration() { return ((MediaView)Video.getChildren().get(0)).getMediaPlayer().getMedia().getDuration(); } /** * This function sets the value for the new element to be shown and if all * elements have already been shown, display the "done" message. */ public void showNextElement() { int index; Random r = new Random(); Progress.setProgress(progress); if (!lessonComponents.isEmpty()) { /* Defines new random lesson component */ index = r.nextInt(lessonComponents.size()); /* In case of the lessonsController set up the video */ setVideo(lessonComponents.get(index).getVideo()); /* Sets up the first lesson components to be shown */ currentComponent = setUpLessonComponents(index); } else { /* Part one has finished */ application.gotoMemorize(lessonName); } } /** * This function sets the value for the new element to be shown and if all * elements have already been shown, display the "done" message. */ public void showNextElementMemorize() { int index; Random r = new Random(); Progress.setProgress(progress); if (!lessonComponents.isEmpty()) { /* Defines new random lesson component */ index = r.nextInt(lessonComponents.size()); /* In case of the lessonsController set up the video */ setVideo(lessonComponents.get(index).getVideo()); currentComponent = lessonComponents.get(index).getLessonComponentName(); lessonComponents.remove(index); } else { /* Part one has finished */ application.gotoReview(lessonName, false); } } /** * Sets up the memorize part of the lesson. * * @param application responsible for the scene * @param lessonName lesson's name that needs to be loaded */ public void setMemorize(LibrasProject application, String lessonName) throws SQLException { this.application = application; this.lessonName = lessonName; progress = 0; /* Get the information from these components*/ lessonComponents = getLessonInformation(); total = lessonComponents.size(); Image1.setImage(new Image(LibrasProject.class.getClassLoader().getResourceAsStream(lessonComponents.get(0).getImages().get(0)))); Image1.setId(lessonComponents.get(0).getLessonComponentName()); Image2.setImage(new Image(LibrasProject.class.getClassLoader().getResourceAsStream(lessonComponents.get(1).getImages().get(0)))); Image2.setId(lessonComponents.get(1).getLessonComponentName()); Image3.setImage(new Image(LibrasProject.class.getClassLoader().getResourceAsStream(lessonComponents.get(2).getImages().get(0)))); Image3.setId(lessonComponents.get(2).getLessonComponentName()); Image4.setImage(new Image(LibrasProject.class.getClassLoader().getResourceAsStream(lessonComponents.get(3).getImages().get(0)))); Image4.setId(lessonComponents.get(3).getLessonComponentName()); Image5.setImage(new Image(LibrasProject.class.getClassLoader().getResourceAsStream(lessonComponents.get(4).getImages().get(0)))); Image5.setId(lessonComponents.get(4).getLessonComponentName()); showNextElementMemorize(); memorize = new MemorizeThread(this); Thread th = new Thread(memorize); th.setDaemon(true); th.start(); } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } } <file_sep>/librasProject/librasproject/selection/SelectionController.java package selection; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Calendar; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.input.InputEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import application.LibrasProject; import java.util.ArrayList; import learning.LearningController; /** * This class is responsible for the control of the Selection scene * * @author <NAME> */ public class SelectionController extends AnchorPane implements Initializable { /* Class variables */ private LibrasProject application; // relates to the responsible application /* FXML id for the different ui components */ @FXML public AnchorPane anchorPane; /** * Performs the proper actions for when the close button receives an action. * @param event the action event information */ @FXML private void handleCloseButtonAction(ActionEvent event) { application.setUserName(""); application.gotoLogin(); } /** * Performs the proper actions for when the close button receives an action. * @param event the action event information */ @FXML private void handleReview(String lessonName) { boolean inReview = false; try { Statement statement = application.getConnection().createStatement(); ResultSet rs; rs = statement.executeQuery("SELECT c.component_id, mistakes, last_reviewed " + "FROM review_component AS rc, component AS c " + "WHERE user_id='" + application.getUserName() + "'" + "AND lesson_id='" + lessonName + "' " + "AND rc.component_id=c.component_id"); long daysDiff; /* Iterate over every component */ while(rs.next()) { daysDiff = (Calendar.getInstance().getTimeInMillis()-rs.getDate("last_reviewed").getTime())/(1000*60*60*24); if (rs.getInt("mistakes")*2 + daysDiff > 6 && !inReview) { application.gotoReview(lessonName, true); inReview = true; } } if(!inReview) { (new LearningController()).showMessageBox("Parabéns!", "Não há mais nada para ser feito!"); } } catch (SQLException ex) { Logger.getLogger(SelectionController.class.getName()).log(Level.SEVERE, null, ex); } } /** * Performs the proper actions for when the different options of selection * receive mouse events * @param event the action event information */ @FXML private void handleSelectionMouseAction(InputEvent event) { Statement statement; ResultSet rs; boolean complete = false; Group group = (Group)event.getSource(); /* If the mouse pointer clicks the group area */ if (event.getEventType() == MouseEvent.MOUSE_CLICKED) { try { statement = application.getConnection().createStatement(); rs = statement.executeQuery("SELECT complete " + "FROM user_lesson WHERE user_id='" + application.getUserName() + "' AND lesson_id='" + group.getId() + "'"); while(rs.next()) { complete = rs.getBoolean("complete"); } } catch (SQLException ex) { Logger.getLogger(SelectionController.class.getName()).log(Level.SEVERE, null, ex); } if (complete) { handleReview(group.getId()); // initiates the review } else { application.gotoLessons(group.getId()); // initiates the lesson with // the id of the group clicked } } /* If the mouse pointer enters the group area */ if (event.getEventType() == MouseEvent.MOUSE_ENTERED) { group.setOpacity(1.0); // set the group opacity to fully visible } /* If the mouse pointer exits the group area */ else if (event.getEventType() == MouseEvent.MOUSE_EXITED) { group.setOpacity(0.5); // set the group opacity to half visible } } /** * Sets up the application and any other work that needs to be done on start * up. * @param application application that's responsible for the scene */ public void setApp(LibrasProject application){ this.application = application; ResultSet rs; Statement statement; ObservableList<Node> children = anchorPane.getChildren(); ArrayList<String> lessons = new ArrayList<>(); ArrayList<String> complete = new ArrayList<>(); try { statement = application.getConnection().createStatement(); rs = statement.executeQuery("SELECT lesson_id FROM lesson"); while(rs.next()) { lessons.add(rs.getString("lesson_id")); } statement = application.getConnection().createStatement(); rs = statement.executeQuery("SELECT lesson_id FROM user_lesson WHERE " + "complete=true AND user_id='" + this.application.getUserName()+"'"); while(rs.next()) { complete.add(rs.getString("lesson_id")); } for (int i = 0; i < children.size(); i++) { if (children.get(i).getClass() == Group.class) { if (!lessons.contains(children.get(i).getId())) { children.get(i).setDisable(true); } if (complete.contains(children.get(i).getId())) { ObservableList<Node> groupChildren = ((Group)children.get(i)).getChildren(); for (int j = 0; j < groupChildren.size(); j++) { if ("done".equals(groupChildren.get(j).getId())) { groupChildren.get(j).setVisible(true); } } } } } } catch (SQLException ex) { Logger.getLogger(SelectionController.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } } <file_sep>/librasProject/librasproject/registration/RegistrationController.java package registration; import login.LoginController; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.binding.BooleanBinding; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.AnchorPane; import application.LibrasProject; import javafx.scene.control.Label; import validation.InputMaskValidation; /** * This class is responsible for the control of the registration scene. * * @author <NAME> */ public class RegistrationController extends AnchorPane implements Initializable { /* Class variables */ private LibrasProject application; private BooleanBinding binding; private ToggleGroup sex; private ToggleGroup type; /* FXML id for the different ui components */ @FXML TextField userId, age; @FXML PasswordField passw; @FXML RadioButton female, male, deaf, notDeaf; @FXML Button register; @FXML Label message; /** * Sets up the application and any other work that needs to be done on start * up. * * @param application that's responsible for the scene */ public void setApp(LibrasProject application){ this.application = application; final InputMaskValidation listener1 = new InputMaskValidation(InputMaskValidation.TEXTONLY, 15, userId); final InputMaskValidation listener2 = new InputMaskValidation(InputMaskValidation.PASSWORD, 20, passw); final InputMaskValidation listener3 = new InputMaskValidation(InputMaskValidation.NUMBERONLY, 3, age); userId.textProperty().addListener(listener1); passw.textProperty().addListener(listener2); age.textProperty().addListener(listener3); binding = new BooleanBinding() { { super.bind(listener1.erroneous, listener2.erroneous, listener3.erroneous); } @Override protected boolean computeValue() { return (listener1.erroneous.get() || listener2.erroneous.get() || listener3.erroneous.get()); } }; register.disableProperty().bind(binding); sex = new ToggleGroup(); female.setToggleGroup(sex); female.setSelected(true); male.setToggleGroup(sex); type = new ToggleGroup(); notDeaf.setToggleGroup(type); notDeaf.setSelected(true); deaf.setToggleGroup(type); } /** * This function responds to the event of pressing the back button. * It returns to the login scene. * * @param event information about the event */ @FXML public void back2Login(ActionEvent event) { application.gotoLogin(); } /** * This function responds to the event of pressing the register button. * It will add the user to the database as well as insert the values for this * user into other user related tables. * * @param event information about the event */ @FXML public void addUser(ActionEvent event) { Statement statement; char gender; String type; /* Defines which options where selected */ gender = female.isSelected() ? 'F' : 'M'; type = deaf.isSelected() ? "surdo" : "ouvinte"; /* Insert user data into database */ try { statement = application.getConnection().createStatement(); statement.executeUpdate("INSERT INTO user_login" + "(user_id, password, age, gender, type) VALUES ('" + userId.getText() + "','" + passw.getText() + "','" + Integer.parseInt(age.getText()) + "','" + gender + "','" + type + "')"); /* Insert related information into database */ insertUserLesson(userId.getText()); insertReviewComponents(userId.getText()); /* After it is done, return to the login page */ application.gotoLogin(); } catch (SQLException ex) { message.setText("Usuario ja cadastrado."); //Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); } } /** * This function inserts into the user_lesson table the necessary fields. * * @param text contains the user_id */ private void insertUserLesson(String text) { Statement statementSelect; Statement statement; ResultSet rs; try { statementSelect = application.getConnection().createStatement(); statement = application.getConnection().createStatement(); /* Obtain all lessons' ids */ rs = statementSelect.executeQuery("SELECT lesson_id FROM lesson"); while(rs.next()) { /* Insert a pair (lesson_id, user_id) for every lesson */ statement.executeUpdate("INSERT INTO user_lesson" + "(user_id, lesson_id) VALUES ('" + text + "','" + rs.getString("lesson_id") + "')"); } } catch (SQLException ex) { message.setText("Problema na insercao dos dados do usuario. Tente novamente."); //Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); } } /** * This function inserts into the review_component table the necessary fields. * * @param text contains the user_id */ private void insertReviewComponents(String text) { Statement statementSelect; Statement statement; ResultSet rs; try { statementSelect = application.getConnection().createStatement(); statement = application.getConnection().createStatement(); /* Obtain all components' ids */ rs = statementSelect.executeQuery("SELECT component_id FROM component"); while(rs.next()) { /* Insert a pair (component_id, user_id) for every component */ statement.executeUpdate("INSERT INTO review_component" + "(user_id, component_id) VALUES ('" + text + "','" + rs.getString("component_id") + "')"); } } catch (SQLException ex) { message.setText("Problema na insercao dos dados do usuario. Tente novamente."); //Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void initialize(URL location, ResourceBundle resources) { } } <file_sep>/librasProject/librasproject/application/LibrasProject.java package application; import learning.ReviewController; import selection.SelectionController; import registration.RegistrationController; import learning.LearnController; import login.LoginController; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.fxml.JavaFXBuilderFactory; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import lesson2DB.Lesson2DB; /** * Project's main class * * @author <NAME> */ public class LibrasProject extends Application { /* Class variables */ private Stage stage; private String userName; private Connection connection = null; public Properties prop = new Properties(); /** * Function responsible for establishing a connection to the desired * database. */ public void establishConnection() { // If there is a connection already, return. if (connection != null){ return; } // Database url that determines the database to be connected to. try { Class.forName("org.postgresql.Driver"); // Must determine database, user and password connection = DriverManager.getConnection(prop.getProperty("dbURL"), prop.getProperty("dbUser"), prop.getProperty("dbPassword")); if (connection != null) { System.out.println("Connecting to database..."); } } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Function responsible for closing the connection previously established. */ public void closeConnection() { try { connection.close(); } catch(Exception e) { System.out.println("Problem to close the connection to the database"); } } /** * The main entry point for all JavaFX applications. * * @param primaryStage the primary stage */ @Override public void start(Stage primaryStage) throws Exception { /* load the properties file */ prop.load(LibrasProject.class.getClassLoader().getResourceAsStream("lessonResources/config.properties")); establishConnection(); (new Lesson2DB()).insertIntoDB(this); /* Initializes the application state and its properties */ stage = primaryStage; stage.setTitle("Learning Libras"); stage.setResizable(false); stage.centerOnScreen(); gotoLogin(); // starts first Scene primaryStage.show(); // shows the stage } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } /** * Responsible for loading the new scene based on the .fxml file * * @param fxml the fxml related to the scene that should be loaded * @return returns the controller for that scene */ private Initializable replaceSceneContent(String fxml) throws Exception { FXMLLoader loader = new FXMLLoader(); InputStream in = LibrasProject.class.getResourceAsStream(fxml); loader.setBuilderFactory(new JavaFXBuilderFactory()); loader.setLocation(LibrasProject.class.getResource(fxml)); AnchorPane page; try { page = (AnchorPane) loader.load(in); } finally { in.close(); } Scene scene = new Scene(page); stage.setScene(scene); stage.sizeToScene(); return (Initializable) loader.getController(); } /** * Loads the controller for the selection scene based on the .fxml file. */ public void gotoSelection() { try { SelectionController selection = (SelectionController) replaceSceneContent("/selection/Selection.fxml"); selection.setApp(this); } catch (Exception ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Loads the controller for the Lessons scene based on the .fxml file. * * @param lessonName the lesson name of the lesson to be initialized */ public void gotoLessons(String lessonName) { try { LearnController lessons = (LearnController) replaceSceneContent("/learning/Learn.fxml"); lessons.setApp(this, lessonName); } catch (Exception ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Loads the controller for the Lessons scene based on the .fxml file. * * @param lessonName the lesson name of the lesson to be initialized */ public void gotoMemorize(String lessonName) { try { LearnController lessons = (LearnController) replaceSceneContent("/learning/Memorize.fxml"); lessons.setMemorize(this, lessonName); } catch (Exception ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Loads the controller for the review scene based on the .fxml file. */ public void gotoReview(String lessonName, boolean isReview) { try { ReviewController review = (ReviewController) replaceSceneContent("/learning/Review.fxml"); review.setApp(this, lessonName, isReview); } catch (Exception ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Loads the controller for the login scene based on the .fxml file. */ public void gotoLogin() { try { LoginController login = (LoginController) replaceSceneContent("/login/Login.fxml"); login.setApp(this); } catch (Exception ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Loads the controller for the registration scene based on the .fxml file. */ public void gotoRegistration() { try { RegistrationController registration = (RegistrationController) replaceSceneContent("/registration/Registration.fxml"); registration.setApp(this); } catch (Exception ex) { Logger.getLogger(LibrasProject.class.getName()).log(Level.SEVERE, null, ex); } } /** * Gets the current user logged in. * * @return the userName */ public String getUserName() { return userName; } /** * Sets the current user logged in. * * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * Returns the connection to the database * * @return the connection */ public Connection getConnection() { return connection; } }<file_sep>/README.md LibrasProject ============= To use the LibrasProject you need to have the ListeningServer and GestureUI running as well as have created a postgresql database based on the LibrasProject/librasProject/database.backup file. * On installing PostgreSQL on Ubuntu 12.04 and creating the database: sudo apt-get install postgresql // Change the PostgreSQL postgres user paswword sudo -u postgres psql postgres \password postgres // Create DB sudo -u postgres createdb librasProject // restore DB pg_restore -d librasProject -h localhost -p 5432 -U postgres -W database.backup You must also have JavaFX if you plan on developing more uis: * http://www.wikihow.com/Install-JavaFX-on-Ubuntu-Linux You must then set the values on the LibrasProject/librasProject/librasproject/lessonResources/config.properties accordingly. The server and port values are related to the ListeningServer. **These values must be the same for the GestureUI NetworkConfig tab.** ListeningServer ============== To start the ListeningServer you must run the .jar file with the port number you wish to listen to. GestureUI ========= The GestureUI needs a couple of steps to be ready for use: * Pre-requisites - Ubuntu 12.04 LTS amd64 - Synaptic Package Manager (sudo apt-get install synaptic) * Using Synaptic - Search for 'opencv' and select everything except: opecv-doc, python-opencv, libopencv-gpu-dev (this will deselect libopencv-dev) - Search for 'wxwidgets' (2.8) and select: libwxbase, libwxgtk (for both select also the dev option) wx-common, wx2.8-headers - Search for 'boost' and select: libboost-all-dev (1.48) * Download - All the files necessary for this process are inside the GestureUI-Installation folder. * Kinect - After connecting the kinect type on the terminal: lsmod | grep kinect sudo modprobe -r gspca_kinect (in case gspca_kinect was shown with the grep) sudo echo "blacklist gspca_kinect" >> /etc/modprobe.d/blacklist.conf * Openni - Unzip openni tar (create a folder) - Navigate to the folder and execute sudo ./install.sh * Sensor - Unzip sensor tar (create a folder) - Navigate to the folder and execute sudo ./install.sh * Terminal - Execute: sudo apt-get install libusb-1.0.0-dev sudo apt-get install freeglut3 * NITE - Unzip nite tar (create a folder) - Navigate to the folder and execute sudo ./install.sh * Extract the models on your home folder * Extract the gestureUI folder on a folder of choice. ------ Once you start the GestureUI software you should: + Click on the Kinect icon. + Click on the play button. + Fill the server and port values on the NetworkConfig Tab. + With the ListeningServer running click on "Connect to Gesture Interface" icon + Since only two sets of gestures have been trained for the LibrasProject you must select for: - Vogais(Vowels): go to "Gesture Recognition" tab and select "MLP_VivenciaAEIOU_5V_6_MLP" from Configuration>>Trained Model - Consoantes(Consonants): go to "Gesture Recognition" tab and select "MLP_VivenciaBCFLV_2_MLP" from Configuration>>Trained Model + Click on the "Start Gesture Recognition" icon Whenever the user wishes to change lesson (From "vogais" to "consoantes" or vice-versa) it is necessary to stop the gesture recognition and change the Trained Model. Then you must restart the recognition and can start the lesson.
bc8a8434cd27524d54aa78c57391e62d78bd147f
[ "Markdown", "Java" ]
7
Java
jcolnago/LibrasProject
35de19c40b39176ce6be738bb3643c2604dcad27
5f7bf123bc432ceb96803c42862a4d0428b19bf3
refs/heads/master
<file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class Update2ProducerUserInfo : DbMigration { public override void Up() { AlterColumn("dbo.ProducerUserInfo", "FirstName", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerUserInfo", "LastName", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerUserInfo", "Address1", c => c.String(maxLength: 50)); AlterColumn("dbo.ProducerUserInfo", "Address2", c => c.String(maxLength: 50)); AlterColumn("dbo.ProducerUserInfo", "City", c => c.String(maxLength: 50)); AlterColumn("dbo.ProducerUserInfo", "State", c => c.String(maxLength: 2)); AlterColumn("dbo.ProducerUserInfo", "ZipCode", c => c.String(maxLength: 5)); AlterColumn("dbo.ProducerUserInfo", "PrimaryPhoneType", c => c.String()); AlterColumn("dbo.ProducerUserInfo", "PrimaryPhoneNumber", c => c.String(maxLength: 16)); AlterColumn("dbo.ProducerUserInfo", "SecondaryPhoneType", c => c.String()); } public override void Down() { AlterColumn("dbo.ProducerUserInfo", "SecondaryPhoneType", c => c.String(nullable: false)); AlterColumn("dbo.ProducerUserInfo", "PrimaryPhoneNumber", c => c.String(nullable: false, maxLength: 16)); AlterColumn("dbo.ProducerUserInfo", "PrimaryPhoneType", c => c.String(nullable: false)); AlterColumn("dbo.ProducerUserInfo", "ZipCode", c => c.String(nullable: false, maxLength: 5)); AlterColumn("dbo.ProducerUserInfo", "State", c => c.String(nullable: false, maxLength: 2)); AlterColumn("dbo.ProducerUserInfo", "City", c => c.String(nullable: false, maxLength: 50)); AlterColumn("dbo.ProducerUserInfo", "Address2", c => c.String(nullable: false, maxLength: 50)); AlterColumn("dbo.ProducerUserInfo", "Address1", c => c.String(nullable: false, maxLength: 50)); AlterColumn("dbo.ProducerUserInfo", "LastName", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerUserInfo", "FirstName", c => c.String(nullable: false, maxLength: 30)); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using DAL; using Models; using Models.Enums; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<ProducerVerification.Web.DAL.ProducerVerificationDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(ProducerVerificationDbContext context) { // This method will be called after migrating to the latest version. //context.Producers.AddOrUpdate(p => p.AgencyName, new ProducerInfo() //{ // AgencyName = "<NAME>", // BusinessName = "<NAME>", // EmailAddress = "<EMAIL>", // PrimaryPhoneNumber = "123", // PrimaryPhoneType = PhoneType.Business, // PreferredPaymentMethod = CommissionPaymentMethod.ACH //}); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class NonEmptyAddressFields : DbMigration { public override void Up() { AlterColumn("dbo.ProducerInfo", "MailingStreet", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerInfo", "MailingCity", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerInfo", "MailingState", c => c.String(nullable: false, maxLength: 4)); AlterColumn("dbo.ProducerInfo", "MailingZipCode", c => c.String(nullable: false, maxLength: 41)); AlterColumn("dbo.ProducerInfo", "PhysicalStreet", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerInfo", "PhysicalCity", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerInfo", "PhysicalState", c => c.String(nullable: false, maxLength: 4)); AlterColumn("dbo.ProducerInfo", "PhysicalZipCode", c => c.String(nullable: false, maxLength: 41)); AlterColumn("dbo.ProducerInfo", "BillingStreet", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerInfo", "BillingCity", c => c.String(nullable: false, maxLength: 30)); AlterColumn("dbo.ProducerInfo", "BillingState", c => c.String(nullable: false, maxLength: 4)); AlterColumn("dbo.ProducerInfo", "BillingZipCode", c => c.String(nullable: false, maxLength: 41)); } public override void Down() { AlterColumn("dbo.ProducerInfo", "BillingZipCode", c => c.String(maxLength: 41)); AlterColumn("dbo.ProducerInfo", "BillingState", c => c.String(maxLength: 4)); AlterColumn("dbo.ProducerInfo", "BillingCity", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerInfo", "BillingStreet", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerInfo", "PhysicalZipCode", c => c.String(maxLength: 41)); AlterColumn("dbo.ProducerInfo", "PhysicalState", c => c.String(maxLength: 4)); AlterColumn("dbo.ProducerInfo", "PhysicalCity", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerInfo", "PhysicalStreet", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerInfo", "MailingZipCode", c => c.String(maxLength: 41)); AlterColumn("dbo.ProducerInfo", "MailingState", c => c.String(maxLength: 4)); AlterColumn("dbo.ProducerInfo", "MailingCity", c => c.String(maxLength: 30)); AlterColumn("dbo.ProducerInfo", "MailingStreet", c => c.String(maxLength: 30)); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class MoreProducerFields : DbMigration { public override void Up() { CreateTable( "dbo.Address", c => new { Id = c.Int(nullable: false, identity: true), StreetNameHouseNumber = c.String(), City = c.String(), State = c.String(), ZipCode = c.String(), }) .PrimaryKey(t => t.Id); AddColumn("dbo.ProducerInfo", "MailingAddressId", c => c.Int(nullable: false)); AddColumn("dbo.ProducerInfo", "PrimaryPhoneType", c => c.Int(nullable: false)); AddColumn("dbo.ProducerInfo", "SecondaryPhoneType", c => c.Int(nullable: false)); AlterColumn("dbo.ProducerInfo", "Name", c => c.String(nullable: false)); AlterColumn("dbo.ProducerInfo", "BusinessName", c => c.String(nullable: false)); AlterColumn("dbo.ProducerInfo", "PrimaryPhoneNumber", c => c.String(nullable: false)); AlterColumn("dbo.ProducerInfo", "EmailAddress", c => c.String(nullable: false)); CreateIndex("dbo.ProducerInfo", "MailingAddressId"); AddForeignKey("dbo.ProducerInfo", "MailingAddressId", "dbo.Address", "Id", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.ProducerInfo", "MailingAddressId", "dbo.Address"); DropIndex("dbo.ProducerInfo", new[] { "MailingAddressId" }); AlterColumn("dbo.ProducerInfo", "EmailAddress", c => c.String()); AlterColumn("dbo.ProducerInfo", "PrimaryPhoneNumber", c => c.String()); AlterColumn("dbo.ProducerInfo", "BusinessName", c => c.String()); AlterColumn("dbo.ProducerInfo", "Name", c => c.String()); DropColumn("dbo.ProducerInfo", "SecondaryPhoneType"); DropColumn("dbo.ProducerInfo", "PrimaryPhoneType"); DropColumn("dbo.ProducerInfo", "MailingAddressId"); DropTable("dbo.Address"); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class ShortenedStreetColumnName : DbMigration { public override void Up() { AddColumn("dbo.ProducerInfo", "MailingStreet", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "PhysicalStreet", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "BillingStreet", c => c.String(maxLength: 30)); DropColumn("dbo.ProducerInfo", "MailingStreetNameHouseNumber"); DropColumn("dbo.ProducerInfo", "PhysicalStreetNameHouseNumber"); DropColumn("dbo.ProducerInfo", "BillingStreetNameHouseNumber"); } public override void Down() { AddColumn("dbo.ProducerInfo", "BillingStreetNameHouseNumber", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "PhysicalStreetNameHouseNumber", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "MailingStreetNameHouseNumber", c => c.String(maxLength: 30)); DropColumn("dbo.ProducerInfo", "BillingStreet"); DropColumn("dbo.ProducerInfo", "PhysicalStreet"); DropColumn("dbo.ProducerInfo", "MailingStreet"); } } } <file_sep>using ProducerVerification.Web.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Web; namespace ProducerVerification.Web.DAL { public class ProducerVerificationDbContext : DbContext { public ProducerVerificationDbContext() : base("ProducerVerificationDbContext") { } //Tables public DbSet<ProducerInfo> Producers { get; set; } public DbSet<AuthenticationCodes> AuthenticationCodes { get; set; } //public DbSet<Address> Addresses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } public System.Data.Entity.DbSet<ProducerVerification.Web.Models.ProducerUserInfo> ProducerUserInfoes { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProducerVerification.Domain.Models { class ProducerInfo { } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class ConsolidatedAddresses : DbMigration { public override void Up() { DropForeignKey("dbo.ProducerInfo", "MailingAddressId", "dbo.Address"); DropIndex("dbo.ProducerInfo", new[] { "MailingAddressId" }); AddColumn("dbo.ProducerInfo", "ProducerCode", c => c.String(nullable: false, maxLength: 8)); AddColumn("dbo.ProducerInfo", "AgencyName", c => c.String(nullable: false)); AddColumn("dbo.ProducerInfo", "MailingStreetNameHouseNumber", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "MailingCity", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "MailingState", c => c.String(maxLength: 4)); AddColumn("dbo.ProducerInfo", "MailingZipCode", c => c.String(maxLength: 41)); AddColumn("dbo.ProducerInfo", "PhysicalStreetNameHouseNumber", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "PhysicalCity", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "PhysicalState", c => c.String(maxLength: 4)); AddColumn("dbo.ProducerInfo", "PhysicalZipCode", c => c.String(maxLength: 41)); AddColumn("dbo.ProducerInfo", "BillingStreetNameHouseNumber", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "BillingCity", c => c.String(maxLength: 30)); AddColumn("dbo.ProducerInfo", "BillingState", c => c.String(maxLength: 4)); AddColumn("dbo.ProducerInfo", "BillingZipCode", c => c.String(maxLength: 41)); AddColumn("dbo.ProducerInfo", "BankName", c => c.String(nullable: false)); AddColumn("dbo.ProducerInfo", "RoutingNumber", c => c.String(nullable: false)); AddColumn("dbo.ProducerInfo", "LastFourAccountNumber", c => c.String(nullable: false)); AddColumn("dbo.ProducerInfo", "ExpirationYear", c => c.Int(nullable: false)); AlterColumn("dbo.ProducerInfo", "DoingBusinessAs", c => c.String(maxLength: 30)); DropColumn("dbo.ProducerInfo", "Name"); DropColumn("dbo.ProducerInfo", "MailingAddressId"); DropTable("dbo.Address"); } public override void Down() { CreateTable( "dbo.Address", c => new { Id = c.Int(nullable: false, identity: true), StreetNameHouseNumber = c.String(), City = c.String(), State = c.String(), ZipCode = c.String(), }) .PrimaryKey(t => t.Id); AddColumn("dbo.ProducerInfo", "MailingAddressId", c => c.Int(nullable: false)); AddColumn("dbo.ProducerInfo", "Name", c => c.String(nullable: false)); AlterColumn("dbo.ProducerInfo", "DoingBusinessAs", c => c.String()); DropColumn("dbo.ProducerInfo", "ExpirationYear"); DropColumn("dbo.ProducerInfo", "LastFourAccountNumber"); DropColumn("dbo.ProducerInfo", "RoutingNumber"); DropColumn("dbo.ProducerInfo", "BankName"); DropColumn("dbo.ProducerInfo", "BillingZipCode"); DropColumn("dbo.ProducerInfo", "BillingState"); DropColumn("dbo.ProducerInfo", "BillingCity"); DropColumn("dbo.ProducerInfo", "BillingStreetNameHouseNumber"); DropColumn("dbo.ProducerInfo", "PhysicalZipCode"); DropColumn("dbo.ProducerInfo", "PhysicalState"); DropColumn("dbo.ProducerInfo", "PhysicalCity"); DropColumn("dbo.ProducerInfo", "PhysicalStreetNameHouseNumber"); DropColumn("dbo.ProducerInfo", "MailingZipCode"); DropColumn("dbo.ProducerInfo", "MailingState"); DropColumn("dbo.ProducerInfo", "MailingCity"); DropColumn("dbo.ProducerInfo", "MailingStreetNameHouseNumber"); DropColumn("dbo.ProducerInfo", "AgencyName"); DropColumn("dbo.ProducerInfo", "ProducerCode"); CreateIndex("dbo.ProducerInfo", "MailingAddressId"); AddForeignKey("dbo.ProducerInfo", "MailingAddressId", "dbo.Address", "Id", cascadeDelete: true); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class MoreSetupForPaymentMethodEnumToString : DbMigration { public override void Up() { DropColumn("dbo.ProducerInfo", "PreferredPaymentMethod"); } public override void Down() { AddColumn("dbo.ProducerInfo", "PreferredPaymentMethod", c => c.Int(nullable: false)); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitWithProducerInfo : DbMigration { public override void Up() { CreateTable( "dbo.ProducerInfo", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(), BusinessName = c.String(), DoingBusinessAs = c.String(), PrimaryPhoneNumber = c.String(), SecondaryPhoneNumber = c.String(), EmailAddress = c.String(), Fax = c.String(), SeparateAccountEntityName = c.String(), PreferredPaymentMethod = c.Int(nullable: false), IpAddress = c.String(), }) .PrimaryKey(t => t.ID); } public override void Down() { DropTable("dbo.ProducerInfo"); } } } <file_sep>using ProducerVerification.Web.DAL; using ProducerVerification.Web.Models; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Mvc; namespace ProducerVerification.Web.Controllers { public class HomeController : Controller { private ProducerVerificationDbContext db = new ProducerVerificationDbContext(); public ActionResult Index() { return View(); } public ActionResult Home(ProducerUserInfo model) { if (model.ProducerCode == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } model.ProducerCode = model.ProducerCode.Trim(); model.AuthorizationCode = model.AuthorizationCode.Trim(); ProducerInfo producerInfo = db.Producers .Where(p => p.ProducerCode == model.ProducerCode) .FirstOrDefault(); if (producerInfo == null) { return HttpNotFound(); } bool isAuthorized = AuthenticationCodes.VerifyAuthCode(db, model.ProducerCode, model.AuthorizationCode); if (!isAuthorized) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return RedirectToAction("Upload", model); } public ActionResult Upload(ProducerUserInfo model) { return View(); } [HttpPost] public ActionResult Upload(HttpPostedFileBase fileUpload, ProducerUserInfo model) { if( fileUpload != null && fileUpload.ContentLength > 0) { var name = model.ProducerCode + Path.GetFileName(fileUpload.FileName); //var path = Path.Combine(Server.MapPath("~App_Data/uploads"), name); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/uploads/", name); var ext = Path.GetExtension(name); if (ext != ".xlsm") { TempData["error"] = "Please select a valid file."; return View(); } fileUpload.SaveAs(path); TempData["error"] = "Thank you for your time."; return RedirectToAction("Index"); } else { TempData["error"] = "Please select a valid file."; } return View(); } public FilePathResult Download() { var name = ConfigurationManager.AppSettings["ExcelDownload"]; //var path = Path.Combine(Server.MapPath("~App_Data/downloads"), name); //var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), name); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/downloads/", name); return File(path, "application/octet-stream", name); } } }<file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddedAuthCodeTable : DbMigration { public override void Up() { CreateTable( "dbo.AuthenticationCodes", c => new { ProducerCode = c.String(nullable: false, maxLength: 128), AuthenticationCode = c.String(), }) .PrimaryKey(t => t.ProducerCode); } public override void Down() { DropTable("dbo.AuthenticationCodes"); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitProducerUserInfo : DbMigration { public override void Up() { CreateTable( "dbo.ProducerUserInfo", c => new { RecID = c.Int(nullable: false, identity: true), ProducerCode = c.String(nullable: false, maxLength: 8), UserCode = c.String(nullable: false, maxLength: 150), ConfirmUserCode = c.String(nullable: false, maxLength: 150), FirstName = c.String(nullable: false, maxLength: 30), LastName = c.String(nullable: false, maxLength: 30), Address1 = c.String(nullable: false, maxLength: 50), Address2 = c.String(nullable: false, maxLength: 50), City = c.String(nullable: false, maxLength: 50), State = c.String(nullable: false, maxLength: 2), ZipCode = c.String(nullable: false, maxLength: 5), PrimaryPhoneType = c.String(nullable: false), PrimaryPhoneNumber = c.String(nullable: false, maxLength: 16), SecondaryPhoneType = c.String(nullable: false), SecondaryPhoneNumber = c.String(maxLength: 16), FaxNumber = c.String(maxLength: 16), EmailVerified = c.Boolean(nullable: false), }) .PrimaryKey(t => t.RecID); } public override void Down() { DropTable("dbo.ProducerUserInfo"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace ProducerVerification.Web.Models { public class ProducerUserInfo { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int RecID { get; set; } [Required] [MaxLength(8)] [DisplayName("Producer Code")] public string ProducerCode { get; set; } [Required] [MaxLength(150)] [EmailAddress] [DisplayName("Email Address")] public string UserCode { get; set; } [NotMapped] //[MaxLength(150)] //[EmailAddress] //[Compare("UserCode", ErrorMessage = "The email and confirmation email do not match.")] [DisplayName("Confirm Email Address")] public string ConfirmUserCode { get; set; } [NotMapped] [DisplayName("Business Name")] public string BusinessName { get; set; } [NotMapped] [DisplayName("Authorization Code")] public string AuthorizationCode { get; set; } [MaxLength(30)] [DisplayName("First Name")] public string FirstName { get; set; } [MaxLength(30)] [DisplayName("Last Name")] public string LastName { get; set; } [MaxLength(50)] [DisplayName("Business Address")] public string Address1 { get; set; } [MaxLength(50)] [DisplayName("Business Address")] public string Address2 { get; set; } [MaxLength(50)] [DisplayName("City")] public string City { get; set; } [MaxLength(2)] [DisplayName("State")] public string State { get; set; } [MaxLength(5)] [DisplayName("Zip Code")] public string ZipCode { get; set; } public string PrimaryPhoneType { get; set; } [MaxLength(16)] [Phone] [DisplayName("Primary Phone")] public string PrimaryPhoneNumber { get; set; } public string SecondaryPhoneType { get; set; } [MaxLength(16)] [Phone] [DisplayName("Secondary Phone")] public string SecondaryPhoneNumber { get; set; } [MaxLength(16)] [Phone] [DisplayName("Fax Number")] public string FaxNumber { get; set; } public bool EmailVerified { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ProducerVerification.Web.DAL; using ProducerVerification.Web.Models; using System.Web.Mail; using System.Net.Mail; using System.Configuration; using System.Web.Services.Description; using ProducerVerification.Web.Helpers; using System.Text.RegularExpressions; namespace ProducerVerification.Web.Controllers { public class ProducerUserInfoController : Controller { private ProducerVerificationDbContext db = new ProducerVerificationDbContext(); // GET: ProducerUserInfo public ActionResult Index(int? done) { if(done == 1) { TempData["error"] = "Thank you for your time."; } return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(ProducerUserInfo model) { if (model.ProducerCode == null) { TempData["error"] = "The Producer Code you entered is not valid."; return RedirectToAction("Index", "ProducerUserInfo"); } model.ProducerCode = model.ProducerCode.Trim(); model.AuthorizationCode = model.AuthorizationCode.Trim(); ProducerInfo producerInfo = db.Producers .Where(p => p.ProducerCode == model.ProducerCode) .FirstOrDefault(); if (producerInfo == null) { TempData["error"] = "The Producer Code you entered is not valid."; return RedirectToAction("Index", "ProducerUserInfo"); } bool isAuthorized = AuthenticationCodes.VerifyAuthCode(db, model.ProducerCode, model.AuthorizationCode); if (!isAuthorized) { TempData["error"] = "The Authorization Code you entered is not valid."; return RedirectToAction("Index", "ProducerUserInfo"); } //if you want users to have a unique email address //int uniqueEmail = db.ProducerUserInfoes.Count(e => e.UserCode == model.UserCode); //if (uniqueEmail > 0) //{ // TempData["error"] = "The email address you entered already exists. Please use another."; // return RedirectToAction("Index", "ProducerUserInfo"); //} if (model.ConfirmUserCode != model.UserCode) { TempData["error"] = "The Confirm Email Address and Email Address must match."; return RedirectToAction("Index", "ProducerUserInfo"); } var emailUrl = "https://" + Request.Url.Authority.ToString(); if (ModelState.IsValid) { db.ProducerUserInfoes.Add(model); db.SaveChanges(); SendEmail(emailUrl, model.RecID, model.UserCode); TempData["error"] = "A confirmation email has been sent to you. Please refer to it for next steps."; return RedirectToAction("Index", "ProducerUserInfo"); } return View(model); } // GET: ProducerUserInfo/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } byte[] eID = Convert.FromBase64String(id); int rID = BitConverter.ToInt32(eID, 0); var verify = 0; ProducerUserInfo producerUserInfo = db.ProducerUserInfoes.Find(rID); if (producerUserInfo == null) { return RedirectToAction("Edit", "ProducerUserInfo", TempData["error"] = "The Producer Code you entered is not valid."); } else { verify = 1; } ProducerInfo producerInfo = db.Producers .Where(p => p.ProducerCode == producerUserInfo.ProducerCode) .FirstOrDefault(); producerUserInfo.BusinessName = producerInfo.BusinessName; producerUserInfo.Address1 = producerInfo.MailingStreet; producerUserInfo.City = producerInfo.MailingCity; producerUserInfo.State = producerInfo.MailingState; producerUserInfo.ZipCode = producerInfo.MailingZipCode; if (verify == 1) { producerUserInfo.EmailVerified = true; } else { producerUserInfo.EmailVerified = false; } return View(producerUserInfo); } // POST: ProducerUserInfo/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "RecID,ProducerCode,UserCode,FirstName,LastName,Address1,Address2,City,State,ZipCode,PrimaryPhoneType,PrimaryPhoneNumber,SecondaryPhoneType,SecondaryPhoneNumber,FaxNumber,EmailVerified")] ProducerUserInfo producerUserInfo) { byte[] bytes = BitConverter.GetBytes(producerUserInfo.RecID); string s = Convert.ToBase64String(bytes); if (ModelState.IsValid) { db.Entry(producerUserInfo).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Details", new { id = s }); } return View(producerUserInfo); } // GET: ProducerUserInfo/Details/5 public ActionResult Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } byte[] eID = Convert.FromBase64String(id); int rID = BitConverter.ToInt32(eID, 0); ViewBag.id = id; ProducerUserInfo producerUserInfo = db.ProducerUserInfoes.Find(rID); if (producerUserInfo == null) { return HttpNotFound(); } ProducerInfo producerInfo = db.Producers .Where(p => p.ProducerCode == producerUserInfo.ProducerCode) .FirstOrDefault(); producerUserInfo.BusinessName = producerInfo.BusinessName; return View(producerUserInfo); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } public static void SendEmail(string urlFormat, int recID, string userCode) { byte[] bytes = BitConverter.GetBytes(recID); string s = Convert.ToBase64String(bytes); var confirmLink = string.Format(urlFormat + "/ProducerUserInfo/Edit/" + s); var bodyBuilder = new System.Text.StringBuilder(); bodyBuilder.Append("Hello, <br/><br/>"); bodyBuilder.Append("<a href=\""); bodyBuilder.Append(confirmLink); bodyBuilder.Append("\">"); bodyBuilder.Append("Click here "); bodyBuilder.Append("</a>"); bodyBuilder.Append("to verify your email address and continue to next steps. <br/><br/>"); bodyBuilder.Append("NCJUA"); var mail = new System.Net.Mail.MailMessage(); mail.From = new MailAddress(ConfigurationManager.AppSettings["SmtpUser"]); mail.Subject = "NCJUA-NCIUA Producer Data Collection Confirmation Email Address"; mail.Body = bodyBuilder.ToString(); mail.IsBodyHtml = true; mail.To.Add(new MailAddress(userCode)); var client = new SmtpClient() { Host = ConfigurationManager.AppSettings["SmtpHost"], UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network }; client.Send(mail); } } } <file_sep>namespace ProducerVerification.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class Update1ProducerUserInfo : DbMigration { public override void Up() { DropColumn("dbo.ProducerUserInfo", "ConfirmUserCode"); } public override void Down() { AddColumn("dbo.ProducerUserInfo", "ConfirmUserCode", c => c.String(nullable: false, maxLength: 150)); } } }
3c5fa0de1601e3829b8264a8f5bd1ae4ae8949b8
[ "C#" ]
16
C#
coralmorris/Collect-User-Data
43ffde6f3e89ac709c9e8eb299a2ddc17d6d4e50
9b59cf2df2463b3f83b005afddaa32cd785f6890
refs/heads/master
<file_sep># COVID-19-research-paper-analysis Taking massive amounts of research papers and using machine learning &amp; other analytics to help make them consumable. ## Development Information ### How to install: Prerequisites: - Anaconda - Git Run the following commands: `git clone https://github.com/The-Lycaeum/COVID-19-research-paper-analysis.git` `cd COVID-19-research-paper-analysis` `conda env create -f environment.yml -n covid-papers` This creates the environment with the correct dependencies. To access the environment: `conda activate covid-papers` During development, more packages might be required to run. You can use `pip install` to add new packages, but a better way would be to add the package name to the environment.yml file, so everyone will be able to use it. After you add the packages to the environment.yml, you can use `pip install`, or you can also sync your environment to yml file with: `conda env update -f environment.yml -n covid-papers` ## Directory Structure ### Data directory Data is stored in the `src/data` directory. There are 4 sub-directories in `src/data`: `data/raw`, `data/interim`, `data/processed`, and `data/other`. More about these divisions below. Since we don't want to store the data on Github, the data directory & its sub-directories should be empty except for specific .git files, and the `download_data.py` script. Running this script should automatically download the raw data into your `src/data/raw` directory. ### Data sub-directories #### data/raw #### data/interim #### data/processed #### data/other<file_sep>import os import json from pprint import pprint from copy import deepcopy import numpy as np import pandas as pd from tqdm.notebook import tqdm ## formats the author's names in a consistent manner def format_name(author): middle_name = " ".join(author['middle']) if author['middle']: return " ".join([author['first'], middle_name, author['last']]) else: return " ".join([author['first'], author['last']]) ## parses metadata block to extract text of author affiliations, e.g., university def format_affiliation(affiliation): text = [] location = affiliation.get('location') if location: text.extend(list(affiliation['location'].values())) institution = affiliation.get('institution') if institution: text = [institution] + text return ", ".join(text) ## parses metadata block to extract text of the authors def format_authors(authors, with_affiliation=False): name_ls = [] for author in authors: name = format_name(author) if with_affiliation: affiliation = format_affiliation(author['affiliation']) if affiliation: name_ls.append(f"{name} ({affiliation})") else: name_ls.append(name) else: name_ls.append(name) return ", ".join(name_ls) ## formats the body content block of the article text def format_body(body_text): texts = [(di['section'], di['text']) for di in body_text] texts_di = {di['section']: "" for di in body_text} for section, text in texts: texts_di[section] += text body = "" for section, text in texts_di.items(): body += section body += "\n\n" body += text body += "\n\n" return body ## formats the bibliography metadata def format_bib(bibs): if type(bibs) == dict: bibs = list(bibs.values()) bibs = deepcopy(bibs) formatted = [] for bib in bibs: bib['authors'] = format_authors( bib['authors'], with_affiliation=False ) formatted_ls = [str(bib[k]) for k in ['title', 'authors', 'venue', 'year']] formatted.append(", ".join(formatted_ls)) return "; ".join(formatted) def load_files(dirname): filenames = os.listdir(dirname) raw_files = [] for filename in tqdm(filenames): filename = dirname + filename file = json.load(open(filename, 'rb')) raw_files.append(file) return raw_files ## pushes the json loaded files into data frame(s) def generate_clean_df(all_files): cleaned_files = [] for file in tqdm(all_files): features = [ file['paper_id'], file['metadata']['title'], format_authors(file['metadata']['authors']), format_authors(file['metadata']['authors'], with_affiliation=True), format_body(file['abstract']), format_body(file['body_text']), format_bib(file['bib_entries']), file['metadata']['authors'], file['bib_entries'] ] cleaned_files.append(features) col_names = ['paper_id', 'title', 'authors', 'affiliations', 'abstract', 'text', 'bibliography','raw_authors','raw_bibliography'] clean_df = pd.DataFrame(cleaned_files, columns=col_names) clean_df.head() return clean_df all_files = [] for filename in filenames: filename = biorxiv_dir + filename file = json.load(open(filename, 'rb')) all_files.append(file) cleaned_files = [] for file in tqdm(all_files): features = [ file['paper_id'], file['metadata']['title'], format_authors(file['metadata']['authors']), format_authors(file['metadata']['authors'], with_affiliation=True), format_body(file['abstract']), format_body(file['body_text']), format_bib(file['bib_entries']), file['metadata']['authors'], file['bib_entries'] ] cleaned_files.append(features) ## add some column names and throw into pandas dataframe col_names = [ 'paper_id', 'title', 'authors', 'affiliations', 'abstract', 'text', 'bibliography', 'raw_authors', 'raw_bibliography' ] #biorxiv set to CSV clean_df = pd.DataFrame(cleaned_files, columns=col_names) clean_df.to_csv('../data/interim/biorxiv_clean.csv', index=False) #custom license to CSV pdf_dir = '../data/interim/custom_license/pdf_json/' pdf_files = load_files(pdf_dir) pdf_df = generate_clean_df(pdf_files) pdf_df.to_csv('../data/interim/custom_license_pdf.csv', index=False) #commercial license to CSV pdf_dir = '../data/interim/comm_use_subset/pdf_json/' pdf_files = load_files(pdf_dir) pdf_df = generate_clean_df(pdf_files) pdf_df.to_csv('../data/interim/comm_use_subset.csv', index=False) #noncommercial license to CSV pdf_dir = '../data/interim/noncomm_use_subset/pdf_json/' pdf_files = load_files(pdf_dir) pdf_df = generate_clean_df(pdf_files) pdf_df.to_csv('../data/interim/noncomm_use_subset.csv', index=False)<file_sep>from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize, sent_tokenize import re ## Text Cleaning: # Convert everything to lowercase # Remove HTML tags # Contraction mapping (see above) # Remove (‘s) # Remove any text inside the parenthesis ( ) # Eliminate punctuations and special characters # Remove stopwords # Remove short words ## TODO probably need to break this into lots of sub-functions and some way to call ## them together or separately... def text_cleaner(text): newString = text.lower() newString = BeautifulSoup(newString, "lxml").text newString = re.sub(r'\([^)]*\)', '', newString) newString = re.sub("[\(\[].*?[\)\]]", "", newString) newString = re.sub('"','', newString) newString = ' '.join([contraction_mapping[t] if t in contraction_mapping else t for t in newString.split(" ")]) newString = re.sub(r"'s\b","",newString) newString = re.sub("[^a-zA-Z]", " ", newString) tokens = [w for w in newString.split() if not w in stop_words] long_words=[] for i in tokens: if len(i)>=short_word_length: #removing short word long_words.append(i) return (" ".join(long_words)).strip() ## Basic Text Cleaner # just takes lowercase and # filters out non-printable characters def basic_text_cleaner(text): text = text.lower() printable = set(string.printable) text = "".join(list(filter(lambda x: x in printable, text))) return text <file_sep>import re import requests from requests.exceptions import RequestException import os import sys import tarfile import gzip import shutil urls = ['https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/2020-04-10/biorxiv_medrxiv.tar.gz', 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/2020-04-10/custom_license.tar.gz', 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/2020-04-10/comm_use_subset.tar.gz', 'https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/2020-04-10/noncomm_use_subset.tar.gz'] ## functions for unzipping the downloaded tar.gz files def unpack(filename, extractPath): total = untar(filename) if total: args = total, total > 1 and 's were' or ' was' sys.stdout.write('Report: %s file%s untared.' % args) else: filename = os.path.basename(sys.argv[0]) sys.stdout.write('Usage: %s <file_or_dir> ...' % filename) def untar(paths): total = 0 for path in paths: if os.path.isdir(path): try: dir_list = os.listdir(path) except: pass else: total += untar(os.path.join(path, new) for new in dir_list) elif os.path.isfile(path): try: tarfile.open(path).extractall("data/interim/") except: pass else: total += 1 return total # try to load each dataset from source link # if URL header has a title for the data, use that as filename # if not, parse URL for filename for url in urls: print('Attempting to connect to ', url) try: with requests.get(url) as r: print('Connection successful. Downloading content...') fname = '' if "Content-Disposition" in r.headers.keys(): fname = re.findall("filename=(.+)", r.headers["Content-Disposition"])[0] else: fname = url.split("/")[-1] print('Content Accessed: ', fname) path = "data/raw/" + fname extractPath = "data/interim" + fname print('Saving ', fname, " to location: ", path) with open(path, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk) print("File download complete.", "\n") print("Extracting file...", "\n") #fname = fname.split(".")[0] print(fname) unpack(fname, extractPath) print("Extraction for ", fname, " complete.", "\n") except RequestException as e: print('Error: ', e, 'with URL: ', url) print('\n', "All files finished downloading & extracting. Please check /data/raw.") <file_sep>clean: rm -rf data/raw/* touch -f data/raw/.gitkeep rm raw_files.txt raw_files.txt: python src/download_data.py touch raw_files.txt <file_sep>from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize, sent_tokenize import re ## Pre-configured word embedding -- GLOVE (Stanford NLP) def loadEmbeddings(filename): vocab2embd = {} with open(filename) as infile: for line in infile: row = line.strip().split(' ') word = row[0].lower() # print(word) if word not in vocab2embd: vec = np.asarray(row[1:], np.float32) if len(vec) == 100: vocab2embd[word] = vec print('Embedding Loaded.') return vocab2embd
5d0c54f6067a03a03a7af246c8537e667352b86d
[ "Markdown", "Python", "Makefile" ]
6
Markdown
jongfranco/COVID-19-research-paper-analysis
e6c0f0f03d4b2ee0d407b470f87cfda48261ac4c
5534719420f5fa94f570b04e5a3a4635fc413233
refs/heads/master
<repo_name>dervishe-/ambnb<file_sep>/README.md ambnb ===== DESCRIPTION: __ambnb__ is a freeBSD kernel module which allow users to manage the backlight of their screen via the sysctl interface. It was originally written by <NAME> <<EMAIL>> in 2009. It works at least for macbookpro from 1,2 up to 4,2 (not tested for other models. I modifyied it slight a bit in order to make it usable by unpriviledged users and to move it from hw branch to dev branch. INSTALLATION: Retrieve the files: git clone https://github.com/dervishe-/ambnb.git then go to the directory and type: make; make install That's it... Just load the kernel module: kldload ambnb USE: sysctl dev.ambnb.level=value where value is an integer from 0 to 15 <file_sep>/ambnb.c /*- * Copyright (c) 2009 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * Backlight driver for Apple MacbookPro based on a Nvidia or AMD Radeon graphic * chipset * This should work on MacbookPro 1,2 MacBookPro 3,1 MacBookPro 3,2 and MacbookPro 4,2 * * dmidecode: * Handle 0x0011, DMI type 1, 27 bytes * System Information * Manufacturer: Apple Inc. * Product Name: MacBookPro3,1 * * Use the sysctl dev.ambnb.level to set the backlight level (0 <= level <= 15) * * Magic values (not the code) come from the Linux driver (mbp_nvidia_bl.c), thanks! * * ---------------------------------------------------------------------------- * History: * - 12/23/14 : adding possibility to change the backlight for non priviledges user * and changing branch in sysctl tree: hw -> dev (like asmc module) * (<EMAIL>) * - 07/17/09 : fix incorrect use of device_t in ambnb_identify() * (fix build on FreeBSD 8.0) */ #include <sys/cdefs.h> /* __FBSDID("$FreeBSD: $"); */ #include <sys/param.h> #include <sys/systm.h> #include <sys/module.h> #include <sys/sysctl.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/bus.h> #include <machine/pc/bios.h> #define AMBNB_SMI_CTRL 0xb2 #define AMBNB_SMI_DATA 0xb3 /* * Device interface. */ static int ambnb_probe(device_t); static int ambnb_attach(device_t); static int ambnb_detach(device_t); /* * AMBNB functions. */ static void ambnb_identify(driver_t *, device_t); static void ambnb_set_backlight(int); static int ambnb_get_backlight(void); static int ambnb_sysctl_dev_ambnb_level(SYSCTL_HANDLER_ARGS); static device_method_t ambnb_methods[] = { DEVMETHOD(device_identify, ambnb_identify), DEVMETHOD(device_probe, ambnb_probe), DEVMETHOD(device_attach, ambnb_attach), DEVMETHOD(device_detach, ambnb_detach), {0, 0}, }; static driver_t ambnb_driver = { "ambnb", ambnb_methods, 0, /* NB: no softc */ }; static devclass_t ambnb_devclass; DRIVER_MODULE(ambnb, nexus, ambnb_driver, ambnb_devclass, 0, 0); MODULE_VERSION(ambnb, 0); SYSCTL_NODE(_dev, OID_AUTO, ambnb, CTLFLAG_RD, 0, "Apple MacBook Nvidia Backlight"); SYSCTL_PROC(_dev_ambnb, OID_AUTO, level, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY, 0, sizeof(int), ambnb_sysctl_dev_ambnb_level, "I", "backlight level"); /* MacbookPro models */ static struct bios_oem bios_apple = { { 0xe0000, 0xfffff }, { { "MacBookPro1,2", 0, 13 }, { "MacBookPro3,1", 0, 13 }, { "MacBookPro3,2", 0, 13 }, { "MacBookPro4,2", 0, 13 }, { NULL, 0, 0 }, } }; static void ambnb_identify(driver_t *drv, device_t parent) { /* NB: order 10 is so we get attached after h/w devices */ if (device_find_child(parent, "ambnb", -1) == NULL && BUS_ADD_CHILD(parent, 10, "ambnb", -1) == 0) panic("ambnb: could not attach"); } static int ambnb_probe(device_t dev) { #define BIOS_OEM_MAXLEN 80 static u_char bios_oem[BIOS_OEM_MAXLEN] = "\0"; int r; /* Search the bios for suitable Apple MacBookPro */ r = bios_oem_strings(&bios_apple, bios_oem, BIOS_OEM_MAXLEN); if (r > 0) { device_set_desc(dev, "Apple MacBook Nvidia/Radeon Backlight"); return (BUS_PROBE_DEFAULT); } return (ENXIO); } static int ambnb_attach(device_t dev) { return (0); } static int ambnb_detach(device_t dev) { return (0); } static void ambnb_set_backlight(int level) { outb(AMBNB_SMI_DATA, 0x04 | (level << 4)); outb(AMBNB_SMI_CTRL, 0xbf); } static int ambnb_get_backlight(void) { int level; outb(AMBNB_SMI_DATA, 0x03); outb(AMBNB_SMI_CTRL, 0xbf); level = inb(AMBNB_SMI_DATA) >> 4; return (level); } static int ambnb_sysctl_dev_ambnb_level(SYSCTL_HANDLER_ARGS) { int error, level; level = ambnb_get_backlight(); error = sysctl_handle_int(oidp, &level, 0, req); if (error == 0 && req->newptr != NULL) { if (level < 0 || level > 15) return (EINVAL); ambnb_set_backlight(level); } return (error); } <file_sep>/Makefile # ambnb # KMOD = ambnb SRCS = ambnb.c SRCS += device_if.h bus_if.h .include <bsd.kmod.mk>
b33c6ff3b722fb19c333505cba2abb6311a9eab8
[ "Markdown", "C", "Makefile" ]
3
Markdown
dervishe-/ambnb
b7943f39c8e118ebc2d8b9a1a3fb34cff7f30864
69706d78c08dbf2b9ff29403fa5057e99df59dfa
refs/heads/master
<repo_name>dylech30th/sayaka<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/GetBotManagementViewCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.GetBotManagementViewCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetBotManagementViewCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GetBotManagementViewCommandTranslator::class, GetBotManagementViewCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) @WithPrivilege(Privilege.ADMINISTRATOR) class GetBotManagementViewCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GetBotManagementViewCommand> { override val match: String = "/view" override val description: String = "获取Bot当前的管理视图" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SwitchPluginEnabledCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.shared.console.SwitchPluginEnabledCommand import com.github.rinacm.sayaka.common.util.throws import net.mamoe.mirai.message.MessageEvent class SwitchPluginEnabledCommandTranslator : AbstractMessageTranslator<SwitchPluginEnabledCommand>() { override fun translate(rawInput: MessageEvent): SwitchPluginEnabledCommand { val parameters = defaultTrailingParameters(rawInput) return SwitchPluginEnabledCommand( rawInput, parameters[0], when (parameters[1].toLowerCase()) { "enable" -> true "disable" -> false else -> throws<IrrelevantMessageException>() } ) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetGomokuCreditRankingCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GetGomokuCreditRankingCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.gomoku.GomokuCredit import com.github.rinacm.sayaka.gomoku.PlayerCredit import net.mamoe.mirai.contact.Group import net.mamoe.mirai.message.data.MessageChain class GetGomokuCreditRankingCommandHandler : CommandHandler<GetGomokuCreditRankingCommand> { override suspend fun process(command: GetGomokuCreditRankingCommand): List<MessageChain>? { val group = command.messageEvent.subject as Group val sortedList = GomokuCredit.get().filter { group.members.any { m -> m.id.toString() == it.player } }.sortedByDescending(PlayerCredit::credit).take(10) return if (sortedList.isEmpty()) "该群暂时没有任何对局记录".asSingleMessageChainList() else buildString { for (p in sortedList) { appendLine("玩家: ${group[p.player.toLong()].nick} QQ: ${p.player} 点数: ${p.credit}") } }.asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/ShutdownBotCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotFactory import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.ShutdownBotCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class ShutdownBotCommandHandler : CommandHandler<ShutdownBotCommand> { override suspend fun process(command: ShutdownBotCommand): List<MessageChain>? { BotFactory.requestShuttingDown(5000) return "Bot实例将会在5秒钟后关闭".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/ExemptPluginExcludeCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.plugin.ExcludeType import com.github.rinacm.sayaka.common.shared.console.ExemptPluginExcludeCommand import com.github.rinacm.sayaka.common.util.throws import net.mamoe.mirai.message.MessageEvent class ExemptPluginExcludeCommandTranslator : AbstractMessageTranslator<ExemptPluginExcludeCommand>() { override fun translate(rawInput: MessageEvent): ExemptPluginExcludeCommand { val parameters = defaultTrailingParameters(rawInput) return ExemptPluginExcludeCommand(rawInput, parameters[0], parameters[1], ExcludeType.toExcludeType(parameters[2]) ?: throws<IrrelevantMessageException>()) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetRandomRankingCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.pixiv.GetRandomRankingCommand import net.mamoe.mirai.message.MessageEvent class GetRandomRankingCommandTranslator : AbstractMessageTranslator<GetRandomRankingCommand>() { override fun translate(rawInput: MessageEvent): GetRandomRankingCommand { return GetRandomRankingCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/Judgement.kt package com.github.rinacm.sayaka.gomoku import com.github.rinacm.sayaka.common.util.mapAnnotation import kotlin.reflect.KFunction class Judgement(private val chessboard: Array<Array<Piece>>) { private data class Step(val leftX: Int, val leftY: Int, val rightX: Int, val rightY: Int) private fun getStep(attached: KFunction<*>): Step { val (leftX, leftY) = mapAnnotation<StepLeft, Pair<Int, Int>>(attached) { it.stepX to it.stepY } val (rightX, rightY) = mapAnnotation<StepRight, Pair<Int, Int>>(attached) { it.stepX to it.stepY } return Step(leftX, leftY, rightX, rightY) } fun check(piece: Piece): Role { val vertical = checkVertical(piece) val horizontal = checkHorizontal(piece) val leadingDiagonal = checkLeadingDiagonal(piece) val diagonal = checkDiagonal(piece) return when { vertical != Role.NONE -> vertical horizontal != Role.NONE -> horizontal leadingDiagonal != Role.NONE -> leadingDiagonal diagonal != Role.NONE -> diagonal else -> Role.NONE } } private fun check(piece: Piece, step: Step, kind: Role): Boolean { var counter = 0 var check = piece while (check.x <= 14 && check.y <= 14 && check.kind == kind) { if (counter == 5) return true counter++ try { check = chessboard.getPoint(check.x + step.rightX, check.y + step.rightY) } catch (e: IndexOutOfBoundsException) { break } } check = piece while (check.x >= 0 && check.y >= 0 && check.kind == kind) { if (counter == 5) return true counter++ try { check = chessboard.getPoint(check.x + step.leftX, check.y + step.leftY) } catch (e: IndexOutOfBoundsException) { break } } return false } private fun checkBoth(piece: Piece, attached: KFunction<*>): Role { val step = getStep(attached) return when { check(piece, step, Role.WHITE) -> Role.WHITE check(piece, step, Role.BLACK) -> Role.BLACK else -> Role.NONE } } @StepLeft(0, -1) @StepRight(0, 1) private fun checkVertical(piece: Piece): Role = checkBoth(piece, ::checkVertical) @StepLeft(-1, 0) @StepRight(1, 0) private fun checkHorizontal(piece: Piece): Role = checkBoth(piece, ::checkHorizontal) @StepLeft(1, -1) @StepRight(-1, 1) private fun checkLeadingDiagonal(piece: Piece): Role = checkBoth(piece, ::checkLeadingDiagonal) @StepLeft(-1, -1) @StepRight(1, 1) private fun checkDiagonal(piece: Piece): Role = checkBoth(piece, ::checkDiagonal) }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetOrSetCurrentEmittingOptionCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.pixiv.GetOrSetCurrentEmittingOptionCommand import com.github.rinacm.sayaka.common.util.throws import net.mamoe.mirai.message.MessageEvent class GetOrSetCurrentEmittingOptionCommandTranslator : AbstractMessageTranslator<GetOrSetCurrentEmittingOptionCommand>() { override fun translate(rawInput: MessageEvent): GetOrSetCurrentEmittingOptionCommand { val parameters = defaultTrailingParameters(rawInput) if (parameters.isEmpty()) return GetOrSetCurrentEmittingOptionCommand(rawInput, null, null) if (parameters.size != 2) throws<IllegalArgumentException>() return GetOrSetCurrentEmittingOptionCommand(rawInput, parameters[0], parameters[1]) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/Piece.kt package com.github.rinacm.sayaka.gomoku /** * Represents a piece in the chessboard, where [x] and [y] is the * virtual coordinate, e.g. (1, a) (2, b) * @param x the virtual x coordinate * @param y the virtual y coordinate * @param kind role of this piece ([Role.BLACK]/[Role.WHITE]) */ data class Piece(val x: Int, val y: Int, val kind: Role) { companion object { private val invalid = Piece(-1, -1, Role.NONE) fun invalid(): Piece = invalid fun yAxisToNumber(c: Char): Int { val u = c.toUpperCase() if (u in 'A'..'O') { return u - 'A' } throw IndexOutOfBoundsException("$c") } fun numberToYAxis(num: Int): String { if (num in 0 until 15) { return ('A' + num).toString() } throw IndexOutOfBoundsException("$num") } } fun toActualPoint(): Point = Point(x * 40 + 50, y * 40 + 50) } fun Array<Array<Piece>>.getPoint(x: Int, y: Int): Piece { return this[x][y] } enum class Role(val roleName: String) { BLACK("黑"), WHITE("白"), NONE("默认"); fun getNegative(): Role { return when (this) { BLACK -> WHITE WHITE -> BLACK NONE -> NONE } } override fun toString(): String { return roleName } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/SetAdministratorCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.SetAdministratorCommandHandler import com.github.rinacm.sayaka.common.message.translator.SetAdministratorCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(SetAdministratorCommandTranslator::class, SetAdministratorCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = QQ_ID_REGEX) @WithPrivilege(Privilege.SUPERUSER) data class SetAdministratorCommand(val qqId: String, override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<SetAdministratorCommand> { override val match: String = "/op" override val description: String = "将${Placeholder("id")}设置为管理员" override fun canonicalizeName(): String { return "$match ${Placeholder("id")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/ErrorStage.kt package com.github.rinacm.sayaka.common.message.error enum class ErrorStage(val localizedName: String) { VALIDATION("命令验证"), TRANSLATION("命令转译"), PROCESSING("命令处理") }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/AuthorizeException.kt package com.github.rinacm.sayaka.common.message.error import com.github.rinacm.sayaka.common.util.Privilege class AuthorizeException(requiredPrivilege: Privilege) : Exception() { override val message: String = "你没有执行该命令所需要的${requiredPrivilege}权限" }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/AboutSayakaCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.AboutSayakaCommand import net.mamoe.mirai.message.MessageEvent class AboutSayakaCommandTranslator : AbstractMessageTranslator<AboutSayakaCommand>() { override fun translate(rawInput: MessageEvent): AboutSayakaCommand { return AboutSayakaCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/Game.kt package com.github.rinacm.sayaka.gomoku import com.github.rinacm.sayaka.common.init.BotFactory import com.github.rinacm.sayaka.common.util.* import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import net.mamoe.mirai.message.data.At import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.buildMessageChain import java.io.Closeable import kotlin.random.Random import kotlin.random.nextInt enum class PlayerJoinState { SUCCESS, HAS_JOINED, GAME_FULL } /** * Every movement request of current [Game] will trigger an action * which will report a [GameState] to indicate the state of this movement */ enum class GameState { /** Game ended because of chessboard is full */ CHESSBOARD_FULL, /** The movement request is legal */ SUCCESS, /** The movement request is illegal because of the point is out of range or has already been placed by another piece */ ILLEGAL_MOVEMENT, /** The movement request is illegal, which will be considered as an irrelevant request */ IRRELEVANT_MESSAGE } data class DropResult(val gameState: GameState, val dropPoint: Point) class Game(val gameId: String) : Closeable { abstract class Player { abstract val black: String abstract val white: String fun getNegative(p: String): String { return when (p) { black -> white white -> black else -> error("$p is not one of $black or $white") } } fun getByRole(role: Role): String { return when (role) { Role.BLACK -> black Role.WHITE -> white Role.NONE -> error("role must not be ${Role.NONE}") } } fun toRole(id: String): Role { return when (id) { black -> Role.BLACK white -> Role.WHITE else -> Role.NONE } } override fun toString(): String { return "($black, $white)" } } private class MutablePlayer : Player() { override lateinit var black: String override lateinit var white: String fun isBlackInitialized(): Boolean { return ::black.isInitialized } fun isWhiteInitialized(): Boolean { return ::white.isInitialized } fun switchRole() { if (!(isBlackInitialized() && isWhiteInitialized())) error("not initialized") black = white.also { white = black } } } // --- IN-GAME REQUIREMENTS/STATES --- var requestEnding = String.EMPTY to false private val gameRecordDirectory = GameConfiguration.gameRecordDirectory(gameId) private var gameStart = false private var imagePath = String.EMPTY private var chessboard: Array<Array<Piece>> // --- BUNDLED/EXTERNAL UTILITIES --- private val stopWatch = StopWatch() private val judgement: Judgement // --- PLAYERS --- private val player = MutablePlayer() // --- RECORDER FOR LAST 2 STEPS --- private lateinit var previousMove: Piece private lateinit var lastModified: Piece private var step = 0 private var role = Role.BLACK init { gameRecordDirectory.toAbsolutePath().mkdirs() chessboard = Array(15) { Array(15) { Piece.invalid() } } judgement = Judgement(chessboard) for (i in 0 until 15) { for (j in 0 until 15) { chessboard[i][j] = Piece(i, j, Role.NONE) } } } fun join(playerId: String): PlayerJoinState { if (isFull()) return PlayerJoinState.GAME_FULL if (!player.isBlackInitialized()) { player.black = playerId return PlayerJoinState.SUCCESS } if (playerId != player.black) { player.white = playerId return PlayerJoinState.SUCCESS } return PlayerJoinState.HAS_JOINED } fun processGoCommand(command: String): DropResult { val (state, point) = parseCommand(command) if (state == GameState.SUCCESS) { val (success, draw) = go(point.x, point.y) if (success) { drawChessboard() return DropResult(if (draw) GameState.CHESSBOARD_FULL else GameState.SUCCESS, point) } return DropResult(GameState.ILLEGAL_MOVEMENT, point) } return DropResult(state, Point(-1, -1)) } fun startGame() { stopWatch.start() gameStart = true randomizeBlack() drawChessboard() } fun isFull(): Boolean { return player.isBlackInitialized() && player.isWhiteInitialized() } fun isInRole(qq: String): Boolean { return player.black == qq && role == Role.BLACK || player.white == qq && role == Role.WHITE } fun isActivatedAndValid(qq: String): Boolean { return isFull() && isPlayer(qq) } fun isPlayer(qq: String): Boolean { return player.black == qq || player.white == qq } fun getImagePath(): String { return String(imagePath.toCharArray()) } fun getPlayer(): Player { return player } fun getRole(): Role { return role } fun isWin(x: Int, y: Int): Role { return check(chessboard.getPoint(x, y)).apply { if (this != Role.NONE) stopWatch.stop() } } private fun check(piece: Piece): Role { return judgement.check(piece) } private fun randomizeBlack() { val i = Random.nextInt(0..1) if (i == 1) player.switchRole() } private fun switchRole() { role = role.getNegative() } private fun updateImagePath() { imagePath = "$gameRecordDirectory\\chessboard_${step}.jpg".toAbsolutePath().toString() } private fun drawChessboard() { runBlocking { updateImagePath() if (::lastModified.isInitialized) { Painter.save(imagePath, chessboard, lastModified) } else { Painter.save(imagePath) } delay(10) } } private fun parseCommand(command: String): Pair<GameState, Point> { val match = (command match "(?<x>\\d{1,2})(?<y>[a-oA-O])".toRegex())!! val xVal = match.groups["x"]?.value val yVal = match.groups["y"]?.value val illegalPoint = Point(-1, -1) if (xVal.isNullOrEmpty() || yVal.isNullOrEmpty()) { return GameState.IRRELEVANT_MESSAGE to illegalPoint } val x = xVal.toInt() val y = Piece.yAxisToNumber(yVal[0]) if (x > 14) { return GameState.ILLEGAL_MOVEMENT to illegalPoint } return GameState.SUCCESS to Point(x, y) } /** * @return (successMovement, draw) */ private fun go(x: Int, y: Int): Pair<Boolean, Boolean> { if (!validateMovement(x, y)) { return false to false } return when (role) { Role.WHITE -> whiteGo(x, y) Role.BLACK -> blackGo(x, y) Role.NONE -> throw IndexOutOfBoundsException("player role cannot be empty") }.let { if (::lastModified.isInitialized) previousMove = lastModified lastModified = chessboard.getPoint(x, y) true to isChessboardFull() } } private fun whiteGo(x: Int, y: Int) { switchRole() with(Piece(x, y, Role.WHITE)) { chessboard[x][y] = this lastModified = this } step++ } private fun blackGo(x: Int, y: Int) { switchRole() with(Piece(x, y, Role.BLACK)) { chessboard[x][y] = this lastModified = this } step++ } private fun isChessboardFull(): Boolean { return chessboard.flatten().all { it.kind != Role.NONE } } private fun validateMovement(x: Int, y: Int): Boolean { return x <= 14 && y <= 14 && chessboard[x][y].kind == Role.NONE } fun getWinMessageAndDisposeGame(win: Role): MessageChain { val elapsed = stopWatch.elapsed() val winner = player.getByRole(win) val loser = player.getNegative(winner) GomokuCredit.setOrIncreaseCredit(winner, 10000) GomokuCredit.setOrIncreaseCredit(loser, -10000) return buildMessageChain { val w = At(BotFactory.getInstance().getGroup(gameId.toLong())[player.getByRole(win).toLong()]) val l = At(BotFactory.getInstance().getGroup(gameId.toLong())[player.getNegative(player.getByRole(win)).toLong()]) add("${win.roleName}子" followedBy (w + "胜利!游戏结束!\n")) add("胜者" followedBy (w + "获得10000点数,现在一共有${GomokuCredit.getCredit(winner)}点数\n")) add("败者" followedBy (l + "扣去10000点数,现在一共有${GomokuCredit.getCredit(loser)}点数\n")) add("本局游戏共用时${elapsed.toHoursPart()}小时${elapsed.toMinutesPart()}分${elapsed.toSecondsPart()}秒") }.also { close() } } override fun close() { GomokuGameFactory.removeGame(gameId) gameStart = false player.black = String.EMPTY player.white = String.EMPTY stopWatch.stop() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/contextual/WrappedExecutor.kt package com.github.rinacm.sayaka.common.message.contextual /** * Execute another function in the [executeWrapped], inspired by * decorator pattern but more flexible */ interface WrappedExecutor<in T, out R> { suspend fun executeWrapped(parameter: T): R }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/SetGlobalDispatcherImplCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.SetGlobalDispatcherImplCommandHandler import com.github.rinacm.sayaka.common.message.translator.SetGlobalDispatcherImplCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(SetGlobalDispatcherImplCommandTranslator::class, SetGlobalDispatcherImplCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @WithPrivilege(Privilege.ADMINISTRATOR) @Validator(RegexValidator::class, regex = "[a-zA-Z]+") class SetGlobalDispatcherImplCommand(override val messageEvent: MessageEvent, val name: String) : Command { companion object Key : Command.Key<SetGlobalDispatcherImplCommand> { override val match: String = "/dispatchBy" override val description: String = "设置Bot的全局调度器" override fun canonicalizeName(): String { return "$match ${Placeholder("dispatcher_name")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GomokuPlayerMoveCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerMoveCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.common.util.followedBy import com.github.rinacm.sayaka.common.util.uploadAsImage import com.github.rinacm.sayaka.gomoku.GameState import com.github.rinacm.sayaka.gomoku.GomokuGameFactory import com.github.rinacm.sayaka.gomoku.Piece import com.github.rinacm.sayaka.gomoku.Role import net.mamoe.mirai.contact.Group import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.PlainText import net.mamoe.mirai.message.data.at import net.mamoe.mirai.message.data.buildMessageChain class GomokuPlayerMoveCommandHandler : CommandHandler<GomokuPlayerMoveCommand> { override suspend fun process(command: GomokuPlayerMoveCommand): List<MessageChain>? { val game = GomokuGameFactory.tryGetGameOrNull(command.messageEvent.subject.id.toString()) val sender = command.messageEvent.sender.id.toString() if (game != null && game.isActivatedAndValid(sender) && game.isInRole(sender)) { val list = mutableListOf<MessageChain>() val dropResult = game.processGoCommand(command.messageEvent.message[PlainText]!!.content) with(command.messageEvent.subject) { when (dropResult.gameState) { GameState.SUCCESS -> list.add(buildMessageChain { add("${game.getRole()}棋成功落子: [${dropResult.dropPoint.x},${Piece.numberToYAxis(dropResult.dropPoint.y)}]\n") add(game.getImagePath().uploadAsImage(this@with)) }) GameState.ILLEGAL_MOVEMENT -> return "哎呀,您落子的位置好像不太合理,再重新试试吧?".asSingleMessageChainList() GameState.CHESSBOARD_FULL -> { game.close() return "棋盘上已经没有位置了,和棋!\n游戏结束!".asSingleMessageChainList() } GameState.IRRELEVANT_MESSAGE -> return null } } val win = game.isWin(dropResult.dropPoint.x, dropResult.dropPoint.y) with(command.messageEvent.subject as Group) { if (win != Role.NONE) { list.add(game.getWinMessageAndDisposeGame(win)) } else { list.add("请${game.getRole()}方" followedBy (this[game.getPlayer().getByRole(game.getRole()).toLong()].at() + "棋手走子")) } } return list } return null } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetBotManagementViewCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.GetBotManagementViewCommand import net.mamoe.mirai.message.MessageEvent class GetBotManagementViewCommandTranslator : AbstractMessageTranslator<GetBotManagementViewCommand>() { override fun translate(rawInput: MessageEvent): GetBotManagementViewCommand { return GetBotManagementViewCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/RawCommand.kt package com.github.rinacm.sayaka.common.shared data class RawCommand(val name: String, val parameters: String)<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/ShowHelpMessageCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.ShowHelpMessageCommandHandler import com.github.rinacm.sayaka.common.message.translator.ShowHelpMessageCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(ShowHelpMessageCommandTranslator::class, ShowHelpMessageCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "(/?[\\u4e00-\\u9fa5a-zA-Z0-9]+ *)*") class ShowHelpMessageCommand(override val messageEvent: MessageEvent, val names: List<String> = emptyList()) : Command { companion object Key : Command.Key<ShowHelpMessageCommand> { override val match: String = "/help" override val description: String = "查看Sayaka Bot™的使用说明" override fun canonicalizeName(): String { return "$match ${Placeholder("plugin_name_or_command_name(with '/' prefix)", option = PlaceholderOption.OPTIONAL, repeatable = true)}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetOpenSourceMessageCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.GetOpenSourceMessageCommand import net.mamoe.mirai.message.MessageEvent class GetOpenSourceMessageCommandTranslator : AbstractMessageTranslator<GetOpenSourceMessageCommand>() { override fun translate(rawInput: MessageEvent): GetOpenSourceMessageCommand { return GetOpenSourceMessageCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetBotManagementViewCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.console.GetBotManagementViewCommand import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.data.MessageChain import kotlin.reflect.full.companionObjectInstance class GetBotManagementViewCommandHandler : CommandHandler<GetBotManagementViewCommand> { override suspend fun process(command: GetBotManagementViewCommand): List<MessageChain>? { val plugins = Plugin.all() ?: emptyList() return buildString { appendLine("管理员列表: ") appendLineIndent(BotContext.getAdmins().joinToString(" ", "[", "]")) appendLine("黑名单: ") for (p in plugins) { val key = (p.companionObjectInstance as Plugin.Key<*>) if (key.excludes.isNotEmpty()) { appendLineIndent("${key.canonicalizeName()}: ") for ((k, v) in key.excludes) { appendLineIndent("$k -> ${v.joinToString(" ", "[", "]")}", indentLevel = 2) } } } appendLine("插件列表: (使用/help查看所有插件的用法或使用/help ${Placeholder("name")}查看某个具体插件的用法)") appendIndent(plugins.joinToString(",", "[", "]", transform = { with(it.companionObjectInstance) { if (this is Plugin.Key<*>) this.canonicalizeName() else String.EMPTY } })) }.asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GomokuPlayerExitCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GomokuPlayerExitCommandHandler import com.github.rinacm.sayaka.common.message.translator.GomokuPlayerExitCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GomokuPlayerExitCommandTranslator::class, GomokuPlayerExitCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(PurePlainTextValidator::class) class GomokuPlayerExitCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GomokuPlayerExitCommand> { override val match: String = "/ge" override val description: String = "退出当前的五子棋对局" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SetGomokuPlayerCreditCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.SetGomokuPlayerCreditCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.gomoku.GomokuCredit import net.mamoe.mirai.message.data.MessageChain class SetGomokuPlayerCreditCommandHandler : CommandHandler<SetGomokuPlayerCreditCommand> { override suspend fun process(command: SetGomokuPlayerCreditCommand): List<MessageChain>? { val qqId = command.qqId.toLongOrNull() val amount = command.qqId.toLongOrNull() return if (qqId != null && amount != null) { GomokuCredit.setOrRewriteCredit(qqId.toString(), amount) "设置点数成功".asSingleMessageChainList() } else "参数格式错误,请仔细检查后重试".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SwitchPluginEnabledCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.console.SwitchPluginEnabledCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class SwitchPluginEnabledCommandHandler : CommandHandler<SwitchPluginEnabledCommand> { override suspend fun process(command: SwitchPluginEnabledCommand): List<MessageChain>? { val clazz = Plugin.getPluginKeyByName(command.name) if (clazz == ConsolePlugin) { return "不能禁用控制台插件".asSingleMessageChainList() } if (clazz != null) { return (if (clazz.enabled != command.enable) { clazz.enabled = command.enable if (command.enable) "成功启用${clazz.canonicalizeName()}插件" else "成功禁用${clazz.canonicalizeName()}插件" } else { "${clazz.canonicalizeName()}的enabled属性已经是${command.enable}" }).asSingleMessageChainList() } return "未找到${command.name}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/CommandFactory.kt package com.github.rinacm.sayaka.common.shared import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.error.AuthorizeException import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ExcludeType import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.util.* import com.github.rinacm.sayaka.common.util.reflector.TypedSubclassesScanner import net.mamoe.mirai.contact.Friend import net.mamoe.mirai.contact.Group import net.mamoe.mirai.contact.Member import net.mamoe.mirai.contact.User import net.mamoe.mirai.message.MessageEvent import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass import kotlin.reflect.full.companionObject import kotlin.reflect.full.companionObjectInstance import kotlin.reflect.full.primaryConstructor object CommandFactory { private val commandKeywordToCommandClassCache = ConcurrentHashMap<String, KClass<out Command>>() private val commandClassToContextualCache = ConcurrentHashMap<KClass<out Command>, Contextual>() /** * Lookup a [KClass] of [Command] through the [TypedSubclassesScanner.markedMap] * by [cmd] as the match key, if matches found then put them into a [commandKeywordToCommandClassCache] to * improve the query speed */ fun lookup(cmd: String, user: User? = null): KClass<out Command>? { var key = cmd if (user != null) { CommandMapping.findMappingCommandString(user, key)?.let { key = it } } if (key in commandKeywordToCommandClassCache.keys) { return commandKeywordToCommandClassCache[key]!! } val obj = TypedSubclassesScanner.markedMap[Command::class] ?.firstOrNull { tryMatch(key, it.companionObjectInstance as Command.Key<*>?) } ?.companionObject ?: return null @Suppress("UNCHECKED_CAST") return (obj.java.declaringClass.kotlin as KClass<out Command>).apply { commandKeywordToCommandClassCache[key] = this } } /** * Attempting to match a [cmd] string with given [commandKey] and return the * matching result */ private fun tryMatch(cmd: String?, commandKey: Command.Key<*>?): Boolean { if (cmd == null || commandKey == null) return false return when (commandKey.matchOption) { MatchOption.REG_EXP -> cmd matches commandKey.match.toRegex() MatchOption.PLAIN_TEXT -> cmd == commandKey.match } } fun getContextual(cmdClass: KClass<out Command>): Contextual { if (cmdClass in commandClassToContextualCache.keys) { return commandClassToContextualCache[cmdClass]!! } return cmdClass.annotation<Contextual>().apply { commandClassToContextualCache[cmdClass] = this } } fun String.toRawCommand(): RawCommand { return RawCommand(substringBefore(' ').trim(), substringAfter(' ', String.EMPTY).trim().split("\\s+".toRegex()).joinToString(" ")) } fun KClass<out Command>.getAuthority(): Privilege? { return this.annotations.filterIsInstance<WithPrivilege>().firstOrNull()?.privilege } /** * There're totally three checking steps: * 1. check the command is marked as [PermanentlyDisable] * 2. check the command's plugin is enabled and does not block the sender * 3. check the command's [Responding] comfort the sender */ fun checkAccess(cmdClass: KClass<out Command>, messageEvent: MessageEvent): Boolean { val key = Plugin.getPluginKeyByAnnotation(cmdClass.annotations.singleIsInstance()) return !isPermanentlyDisabled(cmdClass) && key != null && key.enabled && checkExcludes(key, messageEvent) && canRespond(cmdClass, messageEvent) } private fun canRespond(cmdClass: KClass<out Command>, messageEvent: MessageEvent): Boolean { return when (cmdClass.annotations.filterIsInstance<Responding>().firstOrNull()?.type) { RespondingType.GROUP -> messageEvent.subject is Group RespondingType.WHISPER -> messageEvent.subject is Friend || messageEvent.subject is Member else -> true } } private fun checkExcludes(key: Plugin.Key<*>, messageEvent: MessageEvent): Boolean { val id = messageEvent.subject.id.toString() if (id !in key.excludes || key.excludes[id] == null) return true return when (messageEvent.subject) { is Group -> ExcludeType.GROUP !in key.excludes[id]!! else -> ExcludeType.WHISPER !in key.excludes[id]!! } } private fun isPermanentlyDisabled(cmdClass: KClass<out Command>): Boolean { return cmdClass.annotations.any { it is PermanentlyDisable } } suspend fun validate(raw: MessageEvent, cmdClass: KClass<out Command>, annotation: Validator) { val clazz = annotation.validatorClass for (c in clazz) { val primaryConstructor = c.primaryConstructor!! when (clazz) { RegexValidator::class -> primaryConstructor.call(annotation.regex, cmdClass).executeWrapped(raw) PurePlainTextValidator::class -> primaryConstructor.call(cmdClass).executeWrapped(raw) } } // validate privilege when (cmdClass.annotations.filterIsInstance<WithPrivilege>().firstOrNull()?.privilege) { Privilege.SUPERUSER -> { if (raw.sender.id.toString() != BotContext.getOwner()) { throw AuthorizeException(Privilege.SUPERUSER) } } Privilege.ADMINISTRATOR -> { if (raw.sender.id.toString() !in BotContext.getAdmins()) { throw AuthorizeException(Privilege.ADMINISTRATOR) } } else -> return } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/ReloadRankingSettingsCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.pixiv.ReloadRankingSettingsCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.pixiv.core.RankingEmitter import net.mamoe.mirai.message.data.MessageChain class ReloadRankingSettingsCommandHandler : CommandHandler<ReloadRankingSettingsCommand> { override suspend fun process(command: ReloadRankingSettingsCommand): List<MessageChain>? { return with(RankingEmitter.getOrCreateByContact(command.messageEvent.subject)) { reload() "成功重置日期为: ${current.second}".asSingleMessageChainList() } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/RaiseExceptionCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.RaiseExceptionCommandHandler import com.github.rinacm.sayaka.common.message.translator.RaiseExceptionCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(RaiseExceptionCommandTranslator::class, RaiseExceptionCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) @WithPrivilege(Privilege.ADMINISTRATOR) class RaiseExceptionCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<RaiseExceptionCommand> { override val match: String = "/traise" override val description: String = "抛出一个被ProcessException所包装的java.lang.IllegalStateException,该命令仅用于测试" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/GetDispatchersMessageCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.GetDispatchersMessageCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetDispatchersMessageCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GetDispatchersMessageCommandTranslator::class, GetDispatchersMessageCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "(global)?") class GetDispatchersMessageCommand(override val messageEvent: MessageEvent, val global: Boolean = false) : Command { companion object Key : Command.Key<GetDispatchersMessageCommand> { override val match: String = "/dispatchers" override val description: String = "查看所有可用调度器/全局调度器" override fun canonicalizeName(): String { return "$match ${Placeholder("global", option = PlaceholderOption.OPTIONAL)}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GomokuPlayerMoveCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerMoveCommand import net.mamoe.mirai.message.MessageEvent class GomokuPlayerMoveCommandTranslator : AbstractMessageTranslator<GomokuPlayerMoveCommand>() { override fun translate(rawInput: MessageEvent): GomokuPlayerMoveCommand { return GomokuPlayerMoveCommand(rawInput) } } <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GomokuPlayerJoinGameCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GomokuPlayerJoinGameCommandHandler import com.github.rinacm.sayaka.common.message.translator.GomokuPlayerJoinGameCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GomokuPlayerJoinGameCommandTranslator::class, GomokuPlayerJoinGameCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(PurePlainTextValidator::class) class GomokuPlayerJoinGameCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GomokuPlayerJoinGameCommand> { override val match: String = "/gj" override val description: String = "发起或加入五子棋对局" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/Annotations.kt package com.github.rinacm.sayaka.common.util import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.message.contextual.MessageTranslator import com.github.rinacm.sayaka.common.message.contextual.MessageValidator import com.github.rinacm.sayaka.common.message.contextual.WrappedExecutor import com.github.rinacm.sayaka.common.plugin.Plugin import org.intellij.lang.annotations.Language import kotlin.reflect.KClass enum class MatchOption { REG_EXP, PLAIN_TEXT } /** * Mark the contextual [MessageTranslator] and [CommandHandler] of the attached class as * its command pipe processor */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class Contextual(val translator: KClass<out WrappedExecutor<*, *>>, val handler: KClass<out WrappedExecutor<*, Unit>>) @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class Validator(vararg val validatorClass: KClass<out MessageValidator>, @Language("RegExp") val regex: String = "") @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class WithPrivilege(val privilege: Privilege) enum class RespondingType { WHISPER, GROUP } @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class Responding(val type: RespondingType) @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class PermanentlyDisable @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class PluginOwnership(val clazz: KClass<out Plugin<*>>) enum class TriggerPoint { STARTUP, BEFORE_CLOSED } @Suppress("unused") enum class TriggerPriority { HIGHEST, HIGH, NORMAL, LOW, LOWEST } /** * This annotation mark a method as dynamically invokable, the marked method will be invoked * at the runtime automatically based on [priority] and [triggerPoint] * * @param triggerPoint indicates the when the method should be invoked * @param priority indicates the invoke priority, the method with higher [priority] * will be executed earlier than others */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION) annotation class TriggerOn(val triggerPoint: TriggerPoint, val priority: TriggerPriority = TriggerPriority.NORMAL)<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/RaiseExceptionCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.RaiseExceptionCommand import com.github.rinacm.sayaka.common.util.throws import net.mamoe.mirai.message.data.MessageChain class RaiseExceptionCommandHandler : CommandHandler<RaiseExceptionCommand> { override suspend fun process(command: RaiseExceptionCommand): List<MessageChain>? { throws<IllegalArgumentException>("THIS IS A TEST-PURPOSE EXCEPTION") } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/Painter.kt package com.github.rinacm.sayaka.gomoku import java.awt.* import java.awt.geom.Rectangle2D import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO object Painter { private const val chessboardImageSize = 650 private const val chessboardSize = 560 private val lines = intArrayOf(50, 90, 130, 170, 210, 250, 290, 330, 370, 410, 450, 490, 530, 570, 610) private val points = arrayOf( Point(170, 170), Point(170, 490), Point(330, 330), Point(490, 170), Point(490, 490), ) fun save(path: String) { val img = drawNew() ImageIO.write(img, "png", File(path)) } fun save(path: String, chessboard: Array<Array<Piece>>, toBeHighlight: Piece) { val img = drawNew() for (piece in chessboard.flatten()) { drawPiece(img, piece, piece == toBeHighlight) } ImageIO.write(img, "png", File(path)) } private fun drawNew(): BufferedImage { val img = BufferedImage(chessboardImageSize, chessboardImageSize, BufferedImage.TYPE_INT_ARGB) val g = getGraphics(img) fillChessboard(g) drawBorder(g) drawCross(g) drawIdentifier(g) drawStars(g) return img } private fun getGraphics(img: BufferedImage): Graphics2D { val graphics = img.createGraphics() graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON) graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON) graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY) return graphics } private fun drawPiece(image: BufferedImage, piece: Piece, highlight: Boolean) { val g = image.createGraphics() val real = piece.toActualPoint() when (piece.kind) { Role.BLACK -> { g.paint = Color.BLACK g.fillOval(real.x - 20, real.y - 20, 40, 40) } Role.WHITE -> { g.paint = Color.WHITE g.fillOval(real.x - 20, real.y - 20, 40, 40) g.paint = Color.BLACK g.stroke = BasicStroke(0.5.toFloat(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER) g.drawOval(real.x - 20, real.y - 20, 40, 40) } Role.NONE -> return } if (highlight) { g.paint = Color(220, 20, 60) g.stroke = BasicStroke(1.5.toFloat(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER) with(real) { g.drawLine(x - 20, y - 20, x - 20, y - 15) g.drawLine(x - 20, y - 20, x - 15, y - 20) g.drawLine(x - 20, y + 20, x - 20, y + 15) g.drawLine(x - 20, y + 20, x - 15, y + 20) g.drawLine(x + 20, y - 20, x + 15, y - 20) g.drawLine(x + 20, y - 20, x + 20, y - 15) g.drawLine(x + 20, y + 20, x + 20, y + 15) g.drawLine(x + 20, y + 20, x + 15, y + 20) } } } private fun fillChessboard(g: Graphics2D) { g.paint = Color(232, 180, 130) g.fillRect(0, 0, chessboardImageSize, chessboardImageSize) } private fun drawBorder(g: Graphics2D) { g.paint = Color.BLACK g.stroke = BasicStroke(1.0.toFloat(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER) g.draw(Rectangle2D.Double(0.5, 0.5, 649.0, 649.0)) } private fun drawCross(g: Graphics2D) { g.paint = Color.BLACK g.stroke = BasicStroke(1.0.toFloat(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER) for (line in lines) { g.drawLine(line, 50, line, chessboardSize + 50) g.drawLine(50, line, chessboardSize + 50, line) } } private fun drawIdentifier(g: Graphics2D) { g.font = Font("consolas", Font.PLAIN, 20) val metrics = g.fontMetrics for (i in lines.indices) { // centered align the string g.drawString(i.toString(), lines[i] - metrics.stringWidth(i.toString()) / 2, 25) g.drawString(Piece.numberToYAxis(i), 20, lines[i] - ((metrics.height / 2) - metrics.ascent - metrics.descent)) } } private fun drawStars(g: Graphics2D) { g.paint = Color.BLACK for ((x, y) in points) { g.fillOval(x - 3, y - 3, 6, 6) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/ExemptPluginExcludeCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.console.ExemptPluginExcludeCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class ExemptPluginExcludeCommandHandler : CommandHandler<ExemptPluginExcludeCommand> { override suspend fun process(command: ExemptPluginExcludeCommand): List<MessageChain>? { val key = Plugin.getPluginKeyByName(command.name) if (key != null) { val set = key.excludes[command.id] if (set == null || command.excludeType !in set) { return "${command.id}不在${command.name}的黑名单中".asSingleMessageChainList() } set.remove(command.excludeType) if (set.isEmpty()) { key.excludes.remove(command.id) } return "成功将${command.id}(${command.excludeType})从${key.canonicalizeName()}的黑名单中移除".asSingleMessageChainList() } return "未找到插件${command.name}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/RemoveCommandMappingCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.CommandMapping import com.github.rinacm.sayaka.common.shared.console.RemoveCommandMappingCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class RemoveCommandMappingCommandHandler : CommandHandler<RemoveCommandMappingCommand> { override suspend fun process(command: RemoveCommandMappingCommand): List<MessageChain>? { if (CommandMapping.removeCommandMapping(command.messageEvent.sender, command.removal)) { return "成功移除对于${command.removal}的命令映射".asSingleMessageChainList() } return "未找到${command.removal}的任何映射".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SetSleepCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.SetSleepCommand import net.mamoe.mirai.message.MessageEvent class SetSleepCommandTranslator : AbstractMessageTranslator<SetSleepCommand>() { override fun translate(rawInput: MessageEvent): SetSleepCommand { return SetSleepCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetDispatchersMessageCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.message.factory.Dispatcher import com.github.rinacm.sayaka.common.shared.console.GetDispatchersMessageCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain import kotlin.reflect.full.companionObjectInstance class GetDispatchersMessageCommandHandler : CommandHandler<GetDispatchersMessageCommand> { override suspend fun process(command: GetDispatchersMessageCommand): List<MessageChain>? { return if (command.global) { (Dispatcher.Global::class.companionObjectInstance as Dispatcher.Key<*>).canonicalizeName().asSingleMessageChainList() } else with(Dispatcher.availableDispatchers()) { this?.joinToString(",", "[", "]", transform = Dispatcher.Key<*>::canonicalizeName)?.asSingleMessageChainList() ?: "未找到任何可用的调度器".asSingleMessageChainList() } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/MandatoryEndGameCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GetGomokuCreditCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.gomoku.GomokuGameFactory import net.mamoe.mirai.message.data.MessageChain class MandatoryEndGameCommandHandler : CommandHandler<GetGomokuCreditCommand> { override suspend fun process(command: GetGomokuCreditCommand): List<MessageChain>? { val group = command.playerQQId.toLongOrNull() if (group != null) { with(GomokuGameFactory.tryGetGameOrNull(group.toString())) { return if (this != null) { close() "成功结束对局: $gameId".asSingleMessageChainList() } else "参数错误或者该群暂时没有对局正在进行".asSingleMessageChainList() } } else return "参数格式错误,必须是一个正确的群聊号码".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/Placeholder.kt @file:Suppress("unused") package com.github.rinacm.sayaka.common.util import java.util.* enum class PlaceholderOption { OPTIONAL, MUTUALLY_EXCLUSIVE, REQUIRED, ARRAY, EMPTY } class Placeholder(private vararg val names: String, private val option: PlaceholderOption = PlaceholderOption.REQUIRED, private val repeatable: Boolean = false) { constructor( vararg placeholders: Placeholder, option: PlaceholderOption = PlaceholderOption.REQUIRED, repeatable: Boolean = false ) : this(*placeholders.map(Placeholder::toString).toTypedArray(), option = option, repeatable = repeatable) companion object { val EMPTY: Placeholder = Placeholder(String.EMPTY, option = PlaceholderOption.EMPTY, repeatable = false) } private var next: LinkedList<Placeholder> = LinkedList(listOf(this)) override fun toString(): String { return buildString { for (n in next) { val curr = when (option) { PlaceholderOption.OPTIONAL -> "[${names[0]}${ellipsisIfRepeatable()}]" PlaceholderOption.REQUIRED -> "<${names[0]}${ellipsisIfRepeatable()}>" PlaceholderOption.MUTUALLY_EXCLUSIVE -> { requires<IllegalArgumentException>(names.size > 1 && !repeatable, "size of placeholder names must be 2 and repeatable must be false when ${PlaceholderOption.MUTUALLY_EXCLUSIVE} is set") names.joinToString("|", "{", "}") } PlaceholderOption.ARRAY -> { requires<java.lang.IllegalArgumentException>(names.size > 1 && !repeatable, "size of placeholder names must be greater than 1 and repeatable must be false when ${PlaceholderOption.ARRAY} is set") names.joinToString(",", "{", "}") } PlaceholderOption.EMPTY -> String.EMPTY } append(curr) if (n != next.last) append(" ") } } } operator fun plusAssign(another: Placeholder) { next.add(another) } private fun ellipsisIfRepeatable(): String { return if (repeatable) "..." else String.EMPTY } } @DslMarker annotation class PlaceholderDsl class PlaceholderBuilder { private var placeHolder: Placeholder = Placeholder.EMPTY fun require(name: String) { placeHolder += Placeholder(name) } fun requireRepeatable(name: String) { placeHolder += Placeholder(name, repeatable = true) } fun optional(name: String) { placeHolder += Placeholder(name, option = PlaceholderOption.OPTIONAL) } fun optionalRepeatable(name: String) { placeHolder += Placeholder(name, option = PlaceholderOption.OPTIONAL, repeatable = true) } fun mutually(first: String, second: String) { placeHolder += Placeholder(first, second, option = PlaceholderOption.MUTUALLY_EXCLUSIVE) } fun array(vararg name: String) { placeHolder += Placeholder(*name, option = PlaceholderOption.ARRAY) } fun build(): Placeholder { return placeHolder } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SetCommandMappingCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.CommandMapping import com.github.rinacm.sayaka.common.shared.console.SetCommandMappingCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class SetCommandMappingCommandHandler : CommandHandler<SetCommandMappingCommand> { override suspend fun process(command: SetCommandMappingCommand): List<MessageChain>? { CommandMapping.addCommandMapping(command.messageEvent.sender, command.target, command.original) return "成功添加映射: ${command.original} -> ${command.target}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/ShutdownBotCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.ShutdownBotCommand import net.mamoe.mirai.message.MessageEvent class ShutdownBotCommandTranslator : AbstractMessageTranslator<ShutdownBotCommand>() { override fun translate(rawInput: MessageEvent): ShutdownBotCommand { return ShutdownBotCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SetCommandMappingCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.SetCommandMappingCommand import net.mamoe.mirai.message.MessageEvent class SetCommandMappingCommandTranslator : AbstractMessageTranslator<SetCommandMappingCommand>() { override fun translate(rawInput: MessageEvent): SetCommandMappingCommand { val p = defaultTrailingParameters(rawInput) return SetCommandMappingCommand(rawInput, p[0], p[1]) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/validation/RegexValidator.kt package com.github.rinacm.sayaka.common.message.validation import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.util.EMPTY import com.github.rinacm.sayaka.common.util.requires import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.PlainText import net.mamoe.mirai.message.data.content import org.intellij.lang.annotations.Language import kotlin.reflect.KClass /** * Validate whether the count of the text command's arguments comfort the [size] * * This validator requires the message must be [PlainText], thus we need to pass * the raw message to [PurePlainTextValidator.validate] first */ open class RegexValidator(@Language("RegExp") private val regex: String, toBeValidated: KClass<*>) : PurePlainTextValidator(toBeValidated) { override fun validate(messageEvent: MessageEvent) { super.validate(messageEvent) requires<IrrelevantMessageException>(messageEvent.message[1].content.replaceBefore(' ', String.EMPTY, String.EMPTY).trim() matches regex.toRegex()) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SetGlobalDispatcherImplCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.SetGlobalDispatcherImplCommand import net.mamoe.mirai.message.MessageEvent class SetGlobalDispatcherImplCommandTranslator : AbstractMessageTranslator<SetGlobalDispatcherImplCommand>() { override fun translate(rawInput: MessageEvent): SetGlobalDispatcherImplCommand { return SetGlobalDispatcherImplCommand(rawInput, defaultOnlyOneParameter(rawInput)!!) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GomokuPlayerJoinGameCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerJoinGameCommand import com.github.rinacm.sayaka.common.util.addLine import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.common.util.uploadAsImage import com.github.rinacm.sayaka.gomoku.Game import com.github.rinacm.sayaka.gomoku.GomokuGameFactory import com.github.rinacm.sayaka.gomoku.PlayerJoinState import net.mamoe.mirai.contact.Group import net.mamoe.mirai.contact.Member import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.at import net.mamoe.mirai.message.data.buildMessageChain class GomokuPlayerJoinGameCommandHandler : CommandHandler<GomokuPlayerJoinGameCommand> { override suspend fun process(command: GomokuPlayerJoinGameCommand): List<MessageChain>? { val game = GomokuGameFactory.getOrCreateGame(command.messageEvent.subject.id.toString()) return when (game.join(command.messageEvent.sender.id.toString())) { PlayerJoinState.SUCCESS -> mutableListOf<MessageChain>().apply { add((command.messageEvent.sender as Member).at() + "成功加入!") if (game.isFull()) { game.startGame() add(getStartMessage(command.messageEvent.subject as Group, game)) } } PlayerJoinState.HAS_JOINED -> "你已经加入过了".asSingleMessageChainList() PlayerJoinState.GAME_FULL -> "当前游戏已满,请等待游戏结束".asSingleMessageChainList() } } private suspend fun getStartMessage(group: Group, game: Game): MessageChain { return buildMessageChain { addLine("开始游戏!") addLine("---------------------------------") addLine(Plugin.help(GomokuPlugin)) val at = group[game.getPlayer().black.toLong()].at() addLine(at + "是黑方先手!请" + (at + "走子")) add(game.getImagePath().uploadAsImage(group)) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/factory/DefaultDispatcherImpl.kt package com.github.rinacm.sayaka.common.message.factory import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.WrappedExecutor import com.github.rinacm.sayaka.common.message.error.AuthorizeException import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.message.error.PipelineException import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.shared.CommandFactory import com.github.rinacm.sayaka.common.shared.CommandFactory.toRawCommand import com.github.rinacm.sayaka.common.shared.RawCommand import com.github.rinacm.sayaka.common.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.mamoe.mirai.contact.Member import net.mamoe.mirai.contact.User import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.PlainText import net.mamoe.mirai.message.data.at import net.mamoe.mirai.message.data.buildMessageChain import net.mamoe.mirai.message.data.content import java.time.Duration import kotlin.reflect.full.createInstance open class DefaultDispatcherImpl : Dispatcher { companion object Key : Dispatcher.Key<DefaultDispatcherImpl> { override val match: String = "Default" override val description: String = "Bot的默认调度器, 将会发送异常信息并将调用栈记录到文件中" override val instance = DefaultDispatcherImpl() } // ======================================================================== // message table to manage the request frequency // ======================================================================== private val messageTable: MutableMap<User, Pair<Int, Long>> = mutableMapOf() // ======================================================================== // blacklist of user's that sending commands too fast // ======================================================================== private val blacklist: MutableSet<User> = mutableSetOf() /** * Command dispatching system cannot work out with any command when [Dispatcher.Sleeping] is on * we simply check if command is /awake or not to decide whether we need to wake the Bot up */ private suspend fun MessageEvent.interceptAwaken(cmd: RawCommand) { if (cmd.name == "/awake" && cmd.parameters.isEmpty()) { Dispatcher.Sleeping = false subject.sendMessage("成功唤醒Bot") } else if (Dispatcher.Sleeping) { throws<IrrelevantMessageException>() } } override suspend fun translateMessage(messageEvent: MessageEvent): Command { // extract the PlainText message in the messageEvent val plainTextMessage = messageEvent.message[PlainText]?.content ?: throws<IrrelevantMessageException>() // attempts to translate the plainTextMessage into raw command val raw = plainTextMessage.toRawCommand() messageEvent.interceptAwaken(raw) val cmdClass = CommandFactory.lookup(raw.name, messageEvent.sender) // if the command is marked as PermanentlyDisable or RespondingType does not comfort MessageEvent // invoke thresholding before the null checking of cmdClass to handle the cases which cannot located // the Command class if (cmdClass == null || !CommandFactory.checkAccess(cmdClass, messageEvent) || !thresholding(messageEvent)) throws<IrrelevantMessageException>() CommandFactory.validate(messageEvent, cmdClass, cmdClass.annotation()) val contextual = CommandFactory.getContextual(cmdClass) @Suppress("UNCHECKED_CAST") return (contextual.translator.createInstance() as WrappedExecutor<MessageEvent, Command>).executeWrapped(messageEvent) } override suspend fun <T : Command> dispatchMessage(messageEvent: MessageEvent, command: T) { @Suppress("UNCHECKED_CAST") val handler = CommandFactory.getContextual(command::class).handler.createInstance() as WrappedExecutor<T, Unit> handler.executeWrapped(command) } override suspend fun dispatchError(messageEvent: MessageEvent, exception: Exception) { when { exception is IrrelevantMessageException || exception is PipelineException && exception.e is IrrelevantMessageException -> return exception is AuthorizeException -> messageEvent.subject.sendMessage(exception.message) else -> { val path = BotContext.getCrashReportPath() @Suppress("DuplicatedCode") File.write(path.toAbsolutePath().toString(), buildString { appendLine("在处理由${messageEvent.senderName}(${messageEvent.sender.id})发来的${messageEvent.message.content}消息时出现了异常") if (exception is PipelineException) { appendLine("异常捕获于: ${exception.errorStage.localizedName}(${exception.errorStage})阶段,日志如下:") } appendLineIndent("异常信息: ${exception.message}") appendLineIndent("异常堆栈: ") appendIndent(exception.stackTraceToString(), indentLevel = 2) }) try { messageEvent.subject.sendMessage(buildString { appendLine("在处理由${messageEvent.senderName}(${messageEvent.sender.id})发来的${messageEvent.message.content}消息时出现了异常,异常信息已经写入${path.toAbsolutePath()}") appendLine("异常信息: $exception") appendLine("由于: ${exception.cause?.toString()}") }) } catch (e: Exception) { /* ignore */ } } } } override suspend fun thresholding(messageEvent: MessageEvent): Boolean { with(messageEvent.sender) { // if the sender is already in the blacklist if (messageEvent.sender in blacklist) return false // if sender is in the table if (this in messageTable.keys) { val (times, startTime) = messageTable[this]!! // increase the successfully match counts (received a message and successfully located the // corresponding Command class will be considered as a successfully match) val newTime = times + 1 messageTable[this] = newTime to startTime // if the match counts is greater than 2 (means it has been successfully matched for 3 times) // and the total in milliseconds is smaller 4 means there're at least 3 successfully matches // in 4 seconds, and that's our frequency control threshold, any requests over this frequency // are treated at potential malicious behavior if (System.currentTimeMillis() - startTime <= 1000 * 4 && newTime >= 2) { // remove the criminal from messageTable and add it to the blacklist messageTable.remove(this) blacklist.add(this).apply { // start a new coroutine and release the criminal after 2 minutes launch(Dispatchers.IO) { delay(Duration.ofMinutes(20).toMillis()) blacklist.remove(this@with) messageEvent.subject.sendMessage(buildMessageChain { if (messageEvent.sender is Member) { add((messageEvent.sender as Member).at()) } add("你已经被移出黑名单") }) } } messageEvent.subject.sendMessage(buildMessageChain { if (messageEvent.sender is Member) { add((messageEvent.sender as Member).at()) } add("你在四秒内发送了超过三条消息,已经被拉入黑名单,2分钟后将会解禁") }) return false } else { // if the match counts is greater than 2 but has normal frequency means it's a legal session if (newTime >= 2) messageTable.remove(this) return true } } else { // add if the sender is not in the messageTable yet return if (this !in messageTable.keys) { messageTable[this] = 0 to System.currentTimeMillis() true } else false } } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GomokuPlayerMoveCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GomokuPlayerMoveCommandHandler import com.github.rinacm.sayaka.common.message.translator.GomokuPlayerMoveCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent import org.intellij.lang.annotations.Language @Contextual(GomokuPlayerMoveCommandTranslator::class, GomokuPlayerMoveCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(PurePlainTextValidator::class) class GomokuPlayerMoveCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GomokuPlayerMoveCommand> { @Language("RegExp") override val match: String = "^\\d{1,2}[a-oA-O]$" override val description: String = "在当前五子棋对局中走一步子" override val matchOption: MatchOption get() = MatchOption.REG_EXP override fun canonicalizeName(): String { return "${Placeholder("x坐标y坐标")} 例: 1a, 3h" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetAdministratorListCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.GetAdministratorListCommand import net.mamoe.mirai.message.MessageEvent class GetAdministratorListCommandTranslator : AbstractMessageTranslator<GetAdministratorListCommand>() { override fun translate(rawInput: MessageEvent): GetAdministratorListCommand { return GetAdministratorListCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/RevokeAdministratorCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.RevokeAdministratorCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class RevokeAdministratorCommandHandler : CommandHandler<RevokeAdministratorCommand> { override suspend fun process(command: RevokeAdministratorCommand): List<MessageChain>? { return if (command.qqId.toLongOrNull() != null) { when { command.qqId == BotContext.getOwner() -> "Bot的持有者(Owner)不可以被移除出管理员列表" BotContext.removeAdmin(command.qqId) -> "成功将${command.qqId}移出管理员列表" else -> "${command.qqId}不在管理员列表中" }.asSingleMessageChainList() } else "参数格式错误,必须是一个正确的QQ号码".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetGomokuCreditCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GetGomokuCreditCommand import com.github.rinacm.sayaka.common.util.toSingleList import com.github.rinacm.sayaka.gomoku.GomokuCredit import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.buildMessageChain class GetGomokuCreditCommandHandler : CommandHandler<GetGomokuCreditCommand> { override suspend fun process(command: GetGomokuCreditCommand): List<MessageChain>? { return buildMessageChain { with(GomokuCredit.getCredit(command.playerQQId)) { if (this != null) { add("${command.playerQQId}的点数为${this}") } else add("${command.playerQQId}尚没有对局记录") } }.toSingleList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/contextual/MessageValidator.kt package com.github.rinacm.sayaka.common.message.contextual import com.github.rinacm.sayaka.common.message.error.ValidationException import net.mamoe.mirai.message.MessageEvent import kotlin.reflect.KClass abstract class MessageValidator(val toBeValidated: KClass<*>) : WrappedExecutor<MessageEvent, Unit> { /** * Perform a validation on [MessageEvent], if the messageEvent is validated * this method should return normally, and if not, it should throw a * [ValidationException] providing the failure messageEvent */ @Throws(ValidationException::class) abstract fun validate(messageEvent: MessageEvent) override suspend fun executeWrapped(parameter: MessageEvent) { try { validate(parameter) } catch (v: ValidationException) { throw v } catch (e: Exception) { throw ValidationException(e) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/Privilege.kt package com.github.rinacm.sayaka.common.util enum class Privilege { SUPERUSER, ADMINISTRATOR }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/PipelineException.kt package com.github.rinacm.sayaka.common.message.error abstract class PipelineException(val e: Exception) : RuntimeException(e) { abstract val errorStage: ErrorStage }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/Command.kt package com.github.rinacm.sayaka.common.shared import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.At import net.mamoe.mirai.message.data.Image import net.mamoe.mirai.message.data.PlainText /** * Base class for all [Command], a command is an abstraction of [MessageEvent] * where messages can be consist of multiple parts such as [Image], [PlainText] * or [At], for [Command] usage there must be at least one [PlainText] message * to match the command name */ interface Command { val messageEvent: MessageEvent interface Key<T : Command> : Descriptor { fun help(key: Key<*>): String { var str = "规范: ${key.canonicalizeName()} 用途: $description" with(key::class.java.declaringClass.annotations) { this.firstOrNull { it is WithPrivilege }?.run { val withAuthorize = this as WithPrivilege str += when (withAuthorize.privilege) { Privilege.SUPERUSER -> " (该命令仅限Bot持有者)" Privilege.ADMINISTRATOR -> " (该命令仅限Bot管理员)" } } this.firstOrNull { it is Responding }?.run { val responding = this as Responding str += when (responding.type) { RespondingType.WHISPER -> " (该命令仅限私聊可用)" RespondingType.GROUP -> " (该命令仅限群聊可用)" } } } return str } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetOrSetCurrentEmittingOptionCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.pixiv.GetOrSetCurrentEmittingOptionCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.pixiv.core.RankOption import com.github.rinacm.sayaka.pixiv.core.RankingEmitter import net.mamoe.mirai.message.data.MessageChain class GetOrSetCurrentEmittingOptionCommandHandler : CommandHandler<GetOrSetCurrentEmittingOptionCommand> { override suspend fun process(command: GetOrSetCurrentEmittingOptionCommand): List<MessageChain>? { val emitter = RankingEmitter.getOrCreateByContact(command.messageEvent.subject) if (command.optionKey == null && command.optionValue == null) { return "榜单项: ${emitter.current.first.alias} 日期: ${emitter.current.second}".asSingleMessageChainList() } else if (command.optionKey != null && command.optionValue == null || command.optionKey == null && command.optionValue != null) { return "参数不全".asSingleMessageChainList() } when (command.optionKey) { "rank" -> emitter.setRank(RankOption.valueOf(command.optionValue!!.toUpperCase())) "date" -> emitter.current = emitter.current.first to command.optionValue!! "shuffle" -> emitter.shuffleMode = RankingEmitter.ShuffleMode.of(command.optionValue!!) ?: return "参数只能是{seq|rnd}".asSingleMessageChainList() } return "成功将${command.optionKey}的值设置为${command.optionValue}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/SetCommandMappingCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.SetCommandMappingCommandHandler import com.github.rinacm.sayaka.common.message.translator.SetCommandMappingCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Contextual import com.github.rinacm.sayaka.common.util.Placeholder import com.github.rinacm.sayaka.common.util.PluginOwnership import com.github.rinacm.sayaka.common.util.Validator import net.mamoe.mirai.message.MessageEvent @Contextual(SetCommandMappingCommandTranslator::class, SetCommandMappingCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "\\w+ \\w+") class SetCommandMappingCommand(override val messageEvent: MessageEvent, val original: String, var target: String) : Command { companion object Key : Command.Key<SetCommandMappingCommand> { override val match: String = "/map" override val description: String = "将给定的参数映射为某个命令" override fun canonicalizeName(): String { return "$match ${Placeholder("original")} ${Placeholder("target")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SetSleepCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.message.factory.Dispatcher import com.github.rinacm.sayaka.common.shared.console.SetSleepCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class SetSleepCommandHandler : CommandHandler<SetSleepCommand> { override suspend fun process(command: SetSleepCommand): List<MessageChain>? { Dispatcher.Sleeping = true return "成功进入休眠状态,请管理员使用/awake指令唤醒".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/contextual/AbstractMessageTranslator.kt package com.github.rinacm.sayaka.common.message.contextual import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.shared.CommandFactory.toRawCommand import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.PlainText abstract class AbstractMessageTranslator<T : Command> : MessageTranslator<T> { abstract override fun translate(rawInput: MessageEvent): T protected fun defaultTrailingParameters(rawInput: MessageEvent): List<String> { return with((rawInput.message[1] as PlainText).content.toRawCommand().parameters) { when { isEmpty() -> emptyList() indexOf(' ') == -1 -> listOf(this) else -> split(' ') } } } protected fun defaultOnlyOneParameter(rawInput: MessageEvent): String? { return defaultTrailingParameters(rawInput).firstOrNull() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GomokuPlayerExitCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerExitCommand import com.github.rinacm.sayaka.common.util.toSingleList import com.github.rinacm.sayaka.gomoku.GomokuCredit import com.github.rinacm.sayaka.gomoku.GomokuGameFactory import net.mamoe.mirai.contact.Member import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.at import net.mamoe.mirai.message.data.buildMessageChain class GomokuPlayerExitCommandHandler : CommandHandler<GomokuPlayerExitCommand> { override suspend fun process(command: GomokuPlayerExitCommand): List<MessageChain>? { val ctx = command.messageEvent val game = GomokuGameFactory.tryGetGameOrNull(ctx.subject.id.toString()) if (game != null && game.isPlayer(ctx.sender.id.toString())) { val message = buildMessageChain { val at = (ctx.sender as Member).at() add(at + "离开游戏, 游戏结束!") if (game.isFull()) { add("\n由于退赛惩罚机制, ") add(at + "将会被扣除20000点数") } } GomokuCredit.setOrIncreaseCredit(ctx.sender.id.toString(), -20000) game.close() return message.toSingleList() } return null } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/contextual/CommandHandler.kt package com.github.rinacm.sayaka.common.message.contextual import com.github.rinacm.sayaka.common.message.error.ProcessException import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.shared.CommandFactory.getAuthority import com.github.rinacm.sayaka.common.util.interceptedAuthority import net.mamoe.mirai.message.data.MessageChain interface CommandHandler<T : Command> : WrappedExecutor<T, Unit> { suspend fun process(command: T): List<MessageChain>? override suspend fun executeWrapped(parameter: T) { try { process(parameter)?.let { for (m in it) { parameter.messageEvent.subject.sendMessage(m.interceptedAuthority(parameter::class.getAuthority())) } } } catch (e: Exception) { throw ProcessException(e) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/RemoveCommandMappingCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.RemoveCommandMappingCommandHandler import com.github.rinacm.sayaka.common.message.translator.RemoveCommandMappingCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Contextual import com.github.rinacm.sayaka.common.util.Placeholder import com.github.rinacm.sayaka.common.util.PluginOwnership import com.github.rinacm.sayaka.common.util.Validator import net.mamoe.mirai.message.MessageEvent @Contextual(RemoveCommandMappingCommandTranslator::class, RemoveCommandMappingCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "\\w+") class RemoveCommandMappingCommand(override val messageEvent: MessageEvent, val removal: String) : Command { companion object Key : Command.Key<RemoveCommandMappingCommand> { override val match: String = "/rmap" override val description: String = "删除对于${Placeholder("alias")}的命令映射" override fun canonicalizeName(): String { return "$match ${Placeholder("alias")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GomokuPlayerSurrenderCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GomokuPlayerSurrenderCommandHandler import com.github.rinacm.sayaka.common.message.translator.GomokuPlayerSurrenderCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GomokuPlayerSurrenderCommandTranslator::class, GomokuPlayerSurrenderCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(PurePlainTextValidator::class) class GomokuPlayerSurrenderCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GomokuPlayerSurrenderCommand> { override val match: String = "/gf" override val description: String = "向当前五子棋对局中的对手投降" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetOwnerCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.GetOwnerCommand import net.mamoe.mirai.message.MessageEvent class GetOwnerCommandTranslator : AbstractMessageTranslator<GetOwnerCommand>() { override fun translate(rawInput: MessageEvent): GetOwnerCommand { return GetOwnerCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetOpenSourceMessageCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.GetOpenSourceMessageCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class GetOpenSourceMessageCommandHandler : CommandHandler<GetOpenSourceMessageCommand> { override suspend fun process(command: GetOpenSourceMessageCommand): List<MessageChain>? { return buildString { appendLine( """ MIT License Copyright (c) 2020 Dylech30th Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """.trimIndent() ) }.asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/init/PreInit.kt package com.github.rinacm.sayaka.common.init import com.github.rinacm.sayaka.common.message.factory.Dispatcher import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import com.github.rinacm.sayaka.common.util.reflector.ScanningTarget import com.github.rinacm.sayaka.common.util.reflector.TypedAnnotationScanner import com.github.rinacm.sayaka.common.util.reflector.TypedSubclassesScanner import java.io.Closeable import java.lang.invoke.MethodHandles import java.lang.reflect.Method import kotlin.Exception import kotlin.reflect.full.companionObjectInstance object PreInit : Closeable { init { registerVariablesGlobal() executeTriggerPointcuts(TriggerPoint.STARTUP) } private fun registerVariablesGlobal() { TypedSubclassesScanner.registerScanner(ScanningTarget.CLASS, Command::class) TypedSubclassesScanner.registerScanner(ScanningTarget.CLASS, Plugin::class) TypedSubclassesScanner.registerScanner(ScanningTarget.CLASS, Dispatcher::class) TypedAnnotationScanner.registerScanner(ScanningTarget.METHOD, TriggerOn::class) TypedAnnotationScanner.registerScanner(ScanningTarget.CLASS, PluginOwnership::class) TypedAnnotationScanner.registerScanner(ScanningTarget.CLASS, Contextual::class) TypedAnnotationScanner.registerScanner(ScanningTarget.CLASS, PermanentlyDisable::class) TypedAnnotationScanner.registerScanner(ScanningTarget.CLASS, Validator::class) TypedAnnotationScanner.registerScanner(ScanningTarget.CLASS, WithPrivilege::class) TypedAnnotationScanner.registerScanner(ScanningTarget.CLASS, Responding::class) } private fun executeTriggerPointcuts(triggerPoint: TriggerPoint) { val ms = TypedAnnotationScanner.markedMap[TriggerOn::class] if (!ms.isNullOrEmpty()) { val methods = ms.cast<Method>() .asSequence() .map { it.annotations.toList().singleIsInstance<TriggerOn>() to it } .sortedBy { it.first.priority } .filter { it.first.triggerPoint == triggerPoint } .map(Pair<TriggerOn, Method>::second) for (m in methods) { m.isAccessible = true val lookup = MethodHandles.lookup() val mh = lookup.unreflect(m) mh.invoke(m.kotlinDeclaringClass.objectInstance) } } } override fun close() { executeTriggerPointcuts(TriggerPoint.BEFORE_CLOSED) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/Helper.kt @file:Suppress("unused") package com.github.rinacm.sayaka.common.util import com.github.rinacm.sayaka.common.message.factory.Dispatcher import com.google.common.collect.Multimap import com.google.gson.Gson import io.ktor.http.* import kotlinx.coroutines.launch import net.mamoe.mirai.Bot import net.mamoe.mirai.contact.Contact import net.mamoe.mirai.event.subscribe import net.mamoe.mirai.event.subscribeMessages import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.* import net.mamoe.mirai.message.uploadAsImage import org.intellij.lang.annotations.Language import java.io.File import java.lang.reflect.Member import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.security.MessageDigest import java.time.Duration import java.util.concurrent.CompletableFuture import kotlin.reflect.KAnnotatedElement import kotlin.reflect.KFunction import kotlin.reflect.full.createInstance @Language("RegExp") const val QQ_ID_REGEX = "(?!0+\\d*)\\d+" fun String.toPath(): Path = Paths.get(this) fun String.toAbsolutePath(): Path = toPath().toAbsolutePath() fun Path.mkdirs() = File(toString()).mkdirs() fun durationNow(): Duration = Duration.ofMillis(System.currentTimeMillis()) val Member.kotlinDeclaringClass get() = declaringClass.kotlin fun <T: R, R> T.runIf(boolean: Boolean, block: T.() -> R): R { return if (boolean) block() else this } fun <T> buildListImmutable(block: MutableList<T>.() -> Unit): List<T> { return mutableListOf<T>().apply { block(this) } } fun <T> buildListMutable(block: MutableList<T>.() -> Unit): MutableList<T> { return mutableListOf<T>().apply { block(this) } } infix fun String.followedBy(content: MessageChain): MessageChain { return PlainText(this) + content } fun StringBuilder.appendIndent(content: String, indentLevel: Int = 1, indent: Int = 4): StringBuilder { append(String(CharArray(indentLevel * indent) { ' ' })) append(content) return this } fun StringBuilder.appendLineIndent(content: String, indentLevel: Int = 1, indent: Int = 4): StringBuilder { append(String(CharArray(indentLevel * indent) { ' ' })) append(content) appendLine() return this } fun indentString(content: String, indentLevel: Int = 1, indent: Int = 4): String { return buildString { appendIndent(content, indentLevel, indent) } } fun MessageChainBuilder.addLine(content: Message): Boolean { return add(content + PlainText("\n")) } fun MessageChainBuilder.addLine(content: String) { return add("$content\n") } inline fun <reified A : Annotation> KAnnotatedElement.annotation(): A { return annotations.singleIsInstance() } suspend fun String.uploadAsImage(c: Contact): Image { return File(this).uploadAsImage(c) } fun MessageChain.interceptedAuthority(privilege: Privilege?): MessageChain { return if (privilege != null) { "[# $privilege PRIVILEGE GRANTED #]\n" followedBy (this + "\n[# $privilege PRIVILEGE REVOKED #]") } else this } fun String.interceptedAuthority(privilege: Privilege?): MessageChain { return asMessageChain().interceptedAuthority(privilege) } fun String.asMessageChain(): MessageChain { return PlainText(this).asMessageChain() } fun String.asSingleMessageChainList(): List<MessageChain> { return asMessageChain().toSingleList() } fun Message.asSingleMessageChainList(): List<MessageChain> { return asMessageChain().toSingleList() } fun Bot.subscribeAlwaysUnderGlobalDispatcherSuspended(block: suspend Dispatcher.(MessageEvent) -> Unit) { subscribeMessages { always { with(Dispatcher.Global) { launch { block(this@always) } } } } } fun <T> T.toSingleList(): List<T> { return listOf(this) } inline fun <reified E : Exception> requires(value: Boolean, message: String? = null) { if (!value) throws<E>(message) } fun <T, R> notEquals(second: T, transform: (T) -> R): (T) -> Boolean { return { transform(it) != transform(second) } } inline fun <reified E : Exception> throws(message: String? = null): Nothing { if (message == null) throw E::class.createInstance() throw (E::class.java.getConstructor(String::class.java)).newInstance(message) } object JsonFactory { val gson: Gson = Gson() } inline fun <reified T> T.toJson(): String { return JsonFactory.gson.toJson(this) } inline fun <reified T> String.fromJson(): T { return JsonFactory.gson.fromJson(this, T::class.java) } infix fun String.match(regex: Regex): MatchResult? = regex.find(this) val String.Companion.EMPTY get() = "" inline fun <reified I> Iterable<*>.singleIsInstance(): I = single { it is I } as I operator fun <K, V> Multimap<K, V>.set(key: K, value: V) { put(key, value) } fun <E> Collection<E>.truncatePair(): Pair<E, E> { return take(2).run { this[0] to this[1] } } @Suppress("UNCHECKED_CAST") fun <R> Iterable<*>.cast(): List<R> { return map { it as R } } @Suppress("UNCHECKED_CAST") fun <R> Sequence<*>.seqCast(): Sequence<R> { return map { it as R } } inline fun <reified T : Annotation, R> mapAnnotation(f: KFunction<*>, mapper: (T) -> R): R { return mapper(f.annotation()) } fun buildPlaceHolder(block: PlaceholderBuilder.() -> Unit): Placeholder { val builder = PlaceholderBuilder() block(builder) return builder.build() } inline fun <reified T> threadLocalOf(noinline supplier: () -> T): ThreadLocal<T> { return ThreadLocal.withInitial(supplier) } inline fun <T, R> ThreadLocal<T>.runAlso(block: T.() -> R): R { return get().block() } inline fun url(builder: URLBuilder.() -> Unit): Url { val b = URLBuilder() b.builder() return b.build() } inline fun urlBuilder(b: URLBuilder = URLBuilder(), builder: URLBuilder.() -> Unit): URLBuilder { b.builder() return b } inline fun parameter(default: ParametersBuilder = ParametersBuilder(), b: ParametersBuilder.() -> Unit): ParametersBuilder { default.b() return default } inline fun parameter(b: ParametersBuilder.() -> Unit): Parameters { return parameter(ParametersBuilder(), b).build() } fun String.md5(): String { val dig = MessageDigest.getInstance("MD5") return dig.digest(toByteArray(StandardCharsets.UTF_8)).joinToString("") { "%02x".format(it) } } object File { fun exists(path: String): Boolean { return Files.exists(path.toPath()) } fun create(path: String) { val p = path.toPath().toAbsolutePath() val directory = p.parent if (!Files.exists(directory)) { Files.createDirectories(directory) } Files.createFile(p) } fun read(path: String): CompletableFuture<String> { return CompletableFuture.supplyAsync { File(path).readText(StandardCharsets.UTF_8) }!! } fun write(path: String, text: String) { if (!exists(path)) create(path) CompletableFuture.runAsync { File(path).writeText(text, StandardCharsets.UTF_8) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GomokuPlayerExitCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerExitCommand import net.mamoe.mirai.message.MessageEvent class GomokuPlayerExitCommandTranslator : AbstractMessageTranslator<GomokuPlayerExitCommand>() { override fun translate(rawInput: MessageEvent): GomokuPlayerExitCommand { return GomokuPlayerExitCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SetAdministratorCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.SetAdministratorCommand import net.mamoe.mirai.message.MessageEvent class SetAdministratorCommandTranslator : AbstractMessageTranslator<SetAdministratorCommand>() { override fun translate(rawInput: MessageEvent): SetAdministratorCommand { return SetAdministratorCommand(defaultOnlyOneParameter(rawInput)!!, rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/factory/DebugDispatcherImpl.kt @file:Suppress("unused") package com.github.rinacm.sayaka.common.message.factory import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.message.error.PipelineException import com.github.rinacm.sayaka.common.util.appendIndent import com.github.rinacm.sayaka.common.util.appendLineIndent import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.content class DebugDispatcherImpl : DefaultDispatcherImpl() { companion object Key : Dispatcher.Key<DebugDispatcherImpl> { override val match: String = "Debug" override val description: String = "调试用调度器: 所有异常堆栈信息将被显式的发送 (对于所有包括来自QQ群或私聊的响应均有效)" override val instance = DebugDispatcherImpl() } override suspend fun dispatchError(messageEvent: MessageEvent, exception: Exception) { when { exception is IrrelevantMessageException || exception is PipelineException && exception.e is IrrelevantMessageException -> return else -> { @Suppress("DuplicatedCode") messageEvent.subject.sendMessage(buildString { appendLine("在处理由${messageEvent.senderName}(${messageEvent.sender.id})发来的${messageEvent.message.content}消息时出现了异常") if (exception is PipelineException) { appendLine("异常捕获于: ${exception.errorStage.localizedName}(${exception.errorStage})阶段,日志如下:") } appendLineIndent("异常信息: ${exception.message}") appendLineIndent("异常堆栈: ") appendIndent(exception.stackTraceToString(), indentLevel = 2) }) } } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/ProcessException.kt package com.github.rinacm.sayaka.common.message.error class ProcessException(cause: Exception) : PipelineException(cause) { override val errorStage: ErrorStage = ErrorStage.PROCESSING }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/Configuration.kt package com.github.rinacm.sayaka.gomoku object GameConfiguration { var gameRootDirectory = "gomoku-data" var gameRecordDirectory: (String) -> String = { "$gameRootDirectory\\data\\image\\$it" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SetPluginExcludeCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.plugin.ExcludeType import com.github.rinacm.sayaka.common.shared.console.SetPluginExcludeCommand import com.github.rinacm.sayaka.common.util.throws import net.mamoe.mirai.message.MessageEvent class SetPluginExcludeCommandTranslator : AbstractMessageTranslator<SetPluginExcludeCommand>() { override fun translate(rawInput: MessageEvent): SetPluginExcludeCommand { val parameters = defaultTrailingParameters(rawInput) return SetPluginExcludeCommand(rawInput, parameters[0], parameters[1], ExcludeType.toExcludeType(parameters[2]) ?: throws<IrrelevantMessageException>()) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/TranslationException.kt package com.github.rinacm.sayaka.common.message.error class TranslationException(cause: Exception) : PipelineException(cause) { override val errorStage: ErrorStage = ErrorStage.TRANSLATION } <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GomokuForceEndGameCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.MandatoryEndGameCommandHandler import com.github.rinacm.sayaka.common.message.translator.MandatoryEndGameCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @WithPrivilege(Privilege.ADMINISTRATOR) @Contextual(MandatoryEndGameCommandTranslator::class, MandatoryEndGameCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(RegexValidator::class, regex = QQ_ID_REGEX) data class GomokuForceEndGameCommand(val groupQQId: String, override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GomokuForceEndGameCommand> { override val match: String = "/ef" override val description: String = "强制结束群${Placeholder("id")}的五子棋对局" override fun canonicalizeName(): String { return "$match ${Placeholder("id")}" } } }<file_sep>/gradle.properties kotlin.code.style=official kotlin.incremental.multiplatform=true kotlin.parallel.tasks.in.project=true miraiVersion=1.0.4 retrofitVersion=2.9.0<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/plugin/PixivPlugin.kt package com.github.rinacm.sayaka.common.plugin class PixivPlugin : Plugin<PixivPlugin>() { companion object Key : Plugin.Key<PixivPlugin> { override var enabled: Boolean = true override var excludes: MutableMap<String, MutableSet<ExcludeType>> = mutableMapOf() override val match: String = "Pixiv" override val description: String = "P站相关的内置插件" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/contextual/MessageTranslator.kt package com.github.rinacm.sayaka.common.message.contextual import com.github.rinacm.sayaka.common.message.error.TranslationException import com.github.rinacm.sayaka.common.shared.Command import net.mamoe.mirai.message.MessageEvent interface MessageTranslator<T : Command> : WrappedExecutor<MessageEvent, T> { fun translate(rawInput: MessageEvent): T override suspend fun executeWrapped(parameter: MessageEvent): T { try { return translate(parameter) } catch (e: Exception) { throw TranslationException(e) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/reflector/TypedAnnotationScanner.kt package com.github.rinacm.sayaka.common.util.reflector import com.github.rinacm.sayaka.common.util.set import java.lang.reflect.GenericDeclaration import kotlin.reflect.KClass object TypedAnnotationScanner : TypedScanner<KClass<out Annotation>, GenericDeclaration>() { override val markedMap: Map<KClass<out Annotation>, List<GenericDeclaration>> by lazy { val map = mutableMapOf<KClass<out Annotation>, List<GenericDeclaration>>() for ((target, classes) in scanMap.asMap()) { for (cls in classes) { map[cls] = when (target!!) { ScanningTarget.METHOD -> reflector.getMethodsAnnotatedWith(cls.java) ScanningTarget.CLASS -> reflector.getTypesAnnotatedWith(cls.java) }.toList() } } return@lazy map } override fun registerScanner(scanningTarget: ScanningTarget, clazz: KClass<out Annotation>) { scanMap[scanningTarget] = clazz } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/SetGomokuPlayerCreditCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.SetGomokuPlayerCreditCommandHandler import com.github.rinacm.sayaka.common.message.translator.SetGomokuPlayerCreditCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @WithPrivilege(Privilege.ADMINISTRATOR) @Contextual(SetGomokuPlayerCreditCommandTranslator::class, SetGomokuPlayerCreditCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Validator(RegexValidator::class, regex = "$QQ_ID_REGEX $QQ_ID_REGEX") data class SetGomokuPlayerCreditCommand(val qqId: String, val amount: String, override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<SetGomokuPlayerCreditCommand> { override val match: String = "/gs" override val description: String = "设置${Placeholder("id")}的Gomoku点数" override fun canonicalizeName(): String { return "$match ${Placeholder("id")} ${Placeholder("amount")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/plugin/ExcludeType.kt package com.github.rinacm.sayaka.common.plugin enum class ExcludeType { GROUP, WHISPER; companion object { fun toExcludeType(str: String): ExcludeType? { return when (str.toLowerCase()) { "group" -> GROUP "whisper" -> WHISPER else -> null } } } }<file_sep>/build.gradle plugins { id 'java' id 'application' id 'org.jetbrains.kotlin.jvm' version '1.4.10' } group 'com.github.rinacm' version '1.0.0' repositories { mavenCentral() jcenter() } sourceCompatibility = targetCompatibility = "11" dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8" implementation "net.mamoe:mirai-core:1.3.1" implementation "net.mamoe:mirai-core-qqandroid:1.3.1" implementation "io.ktor:ktor-client-gson:1.3.2" implementation "io.ktor:ktor-client-okhttp:1.3.2" implementation "com.google.code.gson:gson:2.8.6" implementation "org.reflections:reflections:0.9.12" implementation "com.google.guava:guava:29.0-jre" } compileKotlin { kotlinOptions.jvmTarget = "11" } compileTestKotlin { kotlinOptions.jvmTarget = "11" } jar { manifest { attributes 'Main-Class': 'com.github.rinacm.sayaka.SayakaKt' } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } } exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetGomokuCreditCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GetGomokuCreditCommand import net.mamoe.mirai.message.MessageEvent class GetGomokuCreditCommandTranslator : AbstractMessageTranslator<GetGomokuCreditCommand>() { override fun translate(rawInput: MessageEvent): GetGomokuCreditCommand { return GetGomokuCreditCommand(defaultOnlyOneParameter(rawInput)!!, rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/GetAdministratorListCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.GetAdministratorListCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetAdministratorListCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Contextual import com.github.rinacm.sayaka.common.util.PluginOwnership import com.github.rinacm.sayaka.common.util.Validator import net.mamoe.mirai.message.MessageEvent @Contextual(GetAdministratorListCommandTranslator::class, GetAdministratorListCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) class GetAdministratorListCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GetAdministratorListCommand> { override val match: String = "/ops" override val description: String = "获取在该群的管理员列表 (Bot管理员而非QQ群管理)" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/plugin/ConsolePlugin.kt package com.github.rinacm.sayaka.common.plugin class ConsolePlugin : Plugin<ConsolePlugin>() { companion object Key : Plugin.Key<ConsolePlugin> { override val match: String = "Console" override val description: String = "Sayaka Bot™的控制台插件" override var enabled: Boolean = true override var excludes: MutableMap<String, MutableSet<ExcludeType>> = mutableMapOf() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/ExemptPluginExcludeCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.ExemptPluginExcludeCommandHandler import com.github.rinacm.sayaka.common.message.translator.ExemptPluginExcludeCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.plugin.ExcludeType import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(ExemptPluginExcludeCommandTranslator::class, ExemptPluginExcludeCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "\\w+ $QQ_ID_REGEX (group|whisper)") @WithPrivilege(Privilege.ADMINISTRATOR) class ExemptPluginExcludeCommand(override val messageEvent: MessageEvent, val name: String, val id: String, val excludeType: ExcludeType) : Command { companion object Key : Command.Key<ExemptPluginExcludeCommand> { override val match: String = "/exempt" override val description: String = "将${Placeholder("id")}从${Placeholder("plugin_name")}的黑名单中移除" override fun canonicalizeName(): String { return "$match ${Placeholder("plugin_name")} ${Placeholder("id")} ${Placeholder("group", "whisper", option = PlaceholderOption.MUTUALLY_EXCLUSIVE)}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/init/BotContext.kt package com.github.rinacm.sayaka.common.init import com.github.rinacm.sayaka.common.config.SayakaConfiguration import com.github.rinacm.sayaka.common.util.* import com.github.rinacm.sayaka.pixiv.web.Session import kotlinx.atomicfu.atomic import kotlinx.coroutines.runBlocking import java.nio.file.Paths import java.time.LocalDateTime @Suppress("unused") object BotContext { private var administrators = mutableSetOf<String>() private lateinit var configuration: SayakaConfiguration private lateinit var botOwner: String fun getCrashReportPath(): String { return Paths.get(configuration.crashReportPath, "ExceptionDump-${LocalDateTime.now().toString().replace(":", "-").replace(".", "-")}.txt").toAbsolutePath().toString() } fun addAdmin(qqId: String): Boolean { return administrators.add(qqId) } fun removeAdmin(qqId: String): Boolean { return administrators.remove(qqId) } fun getAdmins(): Set<String> { return administrators } fun getOwner(): String { return String(botOwner.toCharArray()) } @TriggerOn(TriggerPoint.STARTUP, TriggerPriority.HIGHEST) private fun loadConfigurationAndLogin() { if (!File.exists(SayakaConfiguration.SAYAKA_CONFIGURATION_PATH)) throws<IllegalStateException>("config.json must be created") configuration = SayakaConfiguration.read() administrators.addAll(configuration.admins) botOwner = configuration.owner administrators.add(botOwner) BotFactory.login(configuration.account.toLong(), configuration.password) } @TriggerOn(TriggerPoint.STARTUP, TriggerPriority.HIGH) private fun login() { runBlocking { Session.login(configuration.pixivAccount, configuration.pixivPassword) } } @TriggerOn(TriggerPoint.BEFORE_CLOSED) private fun saveConfiguration() { SayakaConfiguration.save(configuration) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/IrrelevantMessageException.kt package com.github.rinacm.sayaka.common.message.error /** * This is the only exception which will be thrown when translation or validation failed **NORMALLY** */ class IrrelevantMessageException : Exception()<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/config/SayakaConfiguration.kt package com.github.rinacm.sayaka.common.config import com.github.rinacm.sayaka.common.util.File import com.github.rinacm.sayaka.common.util.fromJson import com.github.rinacm.sayaka.common.util.toJson import java.nio.file.Files import java.nio.file.OpenOption import java.nio.file.Paths import java.nio.file.StandardOpenOption data class SayakaConfiguration( val account: String, val password: String, val pixivAccount: String, val pixivPassword: String, val owner: String, val crashReportPath: String, val admins: List<String> ) { companion object { const val SAYAKA_CONFIGURATION_PATH = "config.json" fun read(): SayakaConfiguration { return File.read(SAYAKA_CONFIGURATION_PATH).get().fromJson() } fun save(conf: SayakaConfiguration) { Files.writeString(Paths.get(SAYAKA_CONFIGURATION_PATH), conf.toJson()) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetGomokuCreditRankingCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GetGomokuCreditRankingCommand import net.mamoe.mirai.message.MessageEvent class GetGomokuCreditRankingCommandTranslator : AbstractMessageTranslator<GetGomokuCreditRankingCommand>() { override fun translate(rawInput: MessageEvent): GetGomokuCreditRankingCommand { return GetGomokuCreditRankingCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/CommandMapping.kt package com.github.rinacm.sayaka.common.shared import com.google.common.collect.HashBiMap import net.mamoe.mirai.contact.User object CommandMapping { private val mapping = mutableMapOf<User, MutableMap<String, String>>() fun addCommandMapping(user: User, original: String, target: String) { if (mapping[user] == null) { mapping[user] = HashBiMap.create() } mapping[user]!![target] = original } fun removeCommandMapping(user: User, target: String): Boolean { if (mapping[user] == null || target !in mapping[user]!!.keys) return false mapping[user]!!.remove(target) return true } fun findMappingCommandString(user: User, str: String): String? { if (mapping[user] == null || str !in mapping[user]!!.keys) return null return mapping[user]!![str] } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/plugin/GomokuPlugin.kt package com.github.rinacm.sayaka.common.plugin class GomokuPlugin : Plugin<GomokuPlugin>() { companion object Key : Plugin.Key<GomokuPlugin> { override val match: String = "GomokuQQ" override val description: String = "一个能在群里下五子棋的QQ机器人" override var enabled: Boolean = true override var excludes: MutableMap<String, MutableSet<ExcludeType>> = mutableMapOf() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/GetOpenSourceMessageCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.GetOpenSourceMessageCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetOpenSourceMessageCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Contextual import com.github.rinacm.sayaka.common.util.PluginOwnership import com.github.rinacm.sayaka.common.util.Validator import net.mamoe.mirai.message.MessageEvent @Contextual(GetOpenSourceMessageCommandTranslator::class, GetOpenSourceMessageCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) class GetOpenSourceMessageCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GetOpenSourceMessageCommand> { override val match: String = "/opensource" override val description: String = "获取Sayaka Bot™的开源许可证信息" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/AboutSayakaCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.AboutSayakaCommand import com.github.rinacm.sayaka.common.util.appendIndent import com.github.rinacm.sayaka.common.util.appendLineIndent import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class AboutSayakaCommandHandler : CommandHandler<AboutSayakaCommand> { override suspend fun process(command: AboutSayakaCommand): List<MessageChain>? { return buildString { appendLine("Sayaka Bot™ - A powerful qq assistant written in Kotlin and based on Mirai Framework") appendLine("Copyright (C) 2020 Dylech30th, Licensed under MIT(https://en.wikipedia.org/wiki/MIT_License)") appendLine("Project website: https://www.github.com/Rinacm/sayaka") appendLine("Open Source Libraries Usage:") appendLineIndent("org.jetbrains.kotlin:kotlin-stdlib-jdk8") appendLineIndent("net.mamoe:mirai-core:1.3.1") appendLineIndent("net.mamoe:mirai-core-qqandroid:1.3.1") appendLineIndent("io.ktor:ktor-client-gson:1.3.2") appendLineIndent("com.google.code.gson:gson:2.8.6") appendLineIndent("org.reflections:reflections:0.9.12") appendLineIndent("com.google.guava:guava:29.0-jre") appendLine("Acknowledgements: ") appendLineIndent("Jetbrains s.r.o. for providing [Jetbrains Open Source License](https://www.jetbrains.com/community/opensource/)") appendIndent("mamoe/mirai for providing qq bot framework") }.asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GomokuPlayerJoinGameCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerJoinGameCommand import net.mamoe.mirai.message.MessageEvent class GomokuPlayerJoinGameCommandTranslator : AbstractMessageTranslator<GomokuPlayerJoinGameCommand>() { override fun translate(rawInput: MessageEvent): GomokuPlayerJoinGameCommand { return GomokuPlayerJoinGameCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GetGomokuCreditRankingCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GetGomokuCreditRankingCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetGomokuCreditRankingCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GetGomokuCreditRankingCommandTranslator::class, GetGomokuCreditRankingCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(PurePlainTextValidator::class) class GetGomokuCreditRankingCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GetGomokuCreditRankingCommand> { override val match: String = "/gr" override val description: String = "获取当前群的Gomoku点数排名" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetOwnerCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.GetOwnerCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class GetOwnerCommandHandler : CommandHandler<GetOwnerCommand> { override suspend fun process(command: GetOwnerCommand): List<MessageChain>? { return BotContext.getOwner().asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/SetPluginExcludeCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.SetPluginExcludeCommandHandler import com.github.rinacm.sayaka.common.message.translator.SetPluginExcludeCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.plugin.ExcludeType import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(SetPluginExcludeCommandTranslator::class, SetPluginExcludeCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "\\w+ $QQ_ID_REGEX (group|whisper)") @WithPrivilege(Privilege.ADMINISTRATOR) class SetPluginExcludeCommand(override val messageEvent: MessageEvent, val name: String, val id: String, val excludeType: ExcludeType) : Command { companion object Key : Command.Key<SetPluginExcludeCommand> { override val match: String = "/exclude" override val description: String = "将id为${Placeholder("id")}的群/好友添加进${Placeholder("plugin_name")}的黑名单" override fun canonicalizeName(): String { return "$match ${Placeholder("plugin_name")} ${Placeholder("id")} ${Placeholder("group", "whisper", option = PlaceholderOption.MUTUALLY_EXCLUSIVE)}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/Point.kt package com.github.rinacm.sayaka.gomoku data class Point(val x: Int, val y: Int)<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/ShuffleRankOptionCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.pixiv.ShuffleRankOptionCommand import net.mamoe.mirai.message.MessageEvent class ShuffleRankOptionCommandTranslator : AbstractMessageTranslator<ShuffleRankOptionCommand>() { override fun translate(rawInput: MessageEvent): ShuffleRankOptionCommand { return ShuffleRankOptionCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/RaiseExceptionCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.RaiseExceptionCommand import net.mamoe.mirai.message.MessageEvent class RaiseExceptionCommandTranslator : AbstractMessageTranslator<RaiseExceptionCommand>() { override fun translate(rawInput: MessageEvent): RaiseExceptionCommand { return RaiseExceptionCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/MandatoryEndGameCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GomokuForceEndGameCommand import net.mamoe.mirai.message.MessageEvent class MandatoryEndGameCommandTranslator : AbstractMessageTranslator<GomokuForceEndGameCommand>() { override fun translate(rawInput: MessageEvent): GomokuForceEndGameCommand { return GomokuForceEndGameCommand(defaultOnlyOneParameter(rawInput)!!, rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SetPluginExcludeCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.console.SetPluginExcludeCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class SetPluginExcludeCommandHandler : CommandHandler<SetPluginExcludeCommand> { override suspend fun process(command: SetPluginExcludeCommand): List<MessageChain>? { val key = Plugin.getPluginKeyByName(command.name) if (key != null) { val set = key.excludes[command.id] if (command.id == BotContext.getOwner()) { return "Bot的实际持有者不能被加入到黑名单中".asSingleMessageChainList() } if (set == null) { key.excludes[command.id] = mutableSetOf(command.excludeType) } else set.add(command.excludeType) return "成功将${command.id}(${command.excludeType})添加到${key.canonicalizeName()}的黑名单中".asSingleMessageChainList() } return "未找到插件${command.name}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/ShutdownBotCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.ShutdownBotCommandHandler import com.github.rinacm.sayaka.common.message.translator.ShutdownBotCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(ShutdownBotCommandTranslator::class, ShutdownBotCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) @WithPrivilege(Privilege.SUPERUSER) class ShutdownBotCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<ShutdownBotCommand> { override val match: String = "/shutdown" override val description: String = "关闭当前Bot实例,再次使用需要重启进程" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/init/BotFactory.kt package com.github.rinacm.sayaka.common.init import com.github.rinacm.sayaka.common.util.requires import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import net.mamoe.mirai.Bot import net.mamoe.mirai.alsoLogin import net.mamoe.mirai.closeAndJoin import net.mamoe.mirai.join import net.mamoe.mirai.utils.SilentLogger object BotFactory { private lateinit var bot: Bot fun getInstance(): Bot { synchronized(this) { requires<RuntimeException>(BotFactory::bot.isInitialized, "the bot has not been initialized yet") return bot } } suspend fun runAndJoin(block: Bot.() -> Unit) { block(getInstance()) getInstance().join() } fun login(qq: Long, password: String) { synchronized(this) { requires<RuntimeException>(!BotFactory::bot.isInitialized, "the bot has been initialized") runBlocking { bot = Bot(qq, password) { randomDeviceInfo() }.alsoLogin() } } } fun requestShuttingDown(milliseconds: Int) { synchronized(this) { requires<RuntimeException>(BotFactory::bot.isInitialized, "the bot has not been initialized yet") GlobalScope.launch { delay(milliseconds.toLong()) bot.closeAndJoin() } } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GomokuPlayerRequestEndingCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GomokuPlayerRequestEndingCommandHandler import com.github.rinacm.sayaka.common.message.translator.GomokuPlayerRequestEndingCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GomokuPlayerRequestEndingCommandTranslator::class, GomokuPlayerRequestEndingCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Responding(RespondingType.GROUP) @Validator(PurePlainTextValidator::class) class GomokuPlayerRequestEndingCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GomokuPlayerRequestEndingCommand> { override val match: String = "/re" override val description: String = "发起或加入一次结束当前五子棋对局的投票" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/SetSleepCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.SetSleepCommandHandler import com.github.rinacm.sayaka.common.message.translator.SetSleepCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(SetSleepCommandTranslator::class, SetSleepCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) @WithPrivilege(Privilege.ADMINISTRATOR) class SetSleepCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<SetSleepCommand> { override val match: String = "/sleep" override val description: String = "命令bot进入休眠状态" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/SwitchPluginEnabledCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.SwitchPluginEnabledCommandHandler import com.github.rinacm.sayaka.common.message.translator.SwitchPluginEnabledCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(SwitchPluginEnabledCommandTranslator::class, SwitchPluginEnabledCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = "\\w+ (disable|enable)") @WithPrivilege(Privilege.ADMINISTRATOR) class SwitchPluginEnabledCommand(override val messageEvent: MessageEvent, val name: String, val enable: Boolean) : Command { companion object Key : Command.Key<SwitchPluginEnabledCommand> { @Suppress("SpellCheckingInspection") override val match: String = "/setswitch" override val description: String = "关闭或开启一个插件" override fun canonicalizeName(): String { return "$match ${Placeholder("plugin_name")} ${Placeholder("enable", "disable", option = PlaceholderOption.MUTUALLY_EXCLUSIVE)}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/ShowHelpMessageCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.plugin.Plugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.shared.CommandFactory import com.github.rinacm.sayaka.common.shared.console.ShowHelpMessageCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain import kotlin.reflect.full.companionObjectInstance class ShowHelpMessageCommandHandler : CommandHandler<ShowHelpMessageCommand> { override suspend fun process(command: ShowHelpMessageCommand): List<MessageChain>? { val hint = "注: <>为必选参数,[]为可选参数, {1|2}意为从选择1或者2, ...意为可以重复填多个参数(用空格分隔)\n" if (command.names.isNotEmpty()) { return buildString { append(hint) for (n in command.names) { if (n.startsWith('/')) { val cmd = CommandFactory.lookup(n) if (cmd == null) { appendLine("未能找到名称为${n}的命令") } else { val key = cmd.companionObjectInstance as Command.Key<*> appendLine(key.help(key)) } } else { val plg = Plugin.getPluginKeyByName(n) append(if (plg != null) Plugin.help(plg) else "未能找到名称为${n}的插件") } } }.asSingleMessageChainList() } return (hint + Plugin.help()).asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/validation/PurePlainTextValidator.kt package com.github.rinacm.sayaka.common.message.validation import com.github.rinacm.sayaka.common.message.contextual.MessageValidator import com.github.rinacm.sayaka.common.message.error.IrrelevantMessageException import com.github.rinacm.sayaka.common.util.requires import net.mamoe.mirai.message.MessageEvent import net.mamoe.mirai.message.data.PlainText import kotlin.reflect.KClass /** * A validator requires all [MessageEvent.message] except [MessageEvent.source] * must be [PlainText] */ open class PurePlainTextValidator(toBeValidateClass: KClass<*>) : MessageValidator(toBeValidateClass) { override fun validate(messageEvent: MessageEvent) { with(messageEvent) { requires<IrrelevantMessageException>(message.size == 2 && message[1] is PlainText) } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/GomokuCredits.kt @file:Suppress("unused") package com.github.rinacm.sayaka.gomoku import com.github.rinacm.sayaka.common.util.* data class PlayerCredit(val player: String, var credit: Long) object GomokuCredit { private var gomokuPlayerCredits = mutableListOf<PlayerCredit>() private const val fileName = "player_credit.json" fun getCredit(player: String): Long? { return gomokuPlayerCredits.firstOrNull { it.player == player }?.credit } fun setOrIncreaseCredit(id: String, creditIncremental: Long) { if (gomokuPlayerCredits.any { it.player == id }) { with(gomokuPlayerCredits.single { it.player == id }) { credit += creditIncremental } } else gomokuPlayerCredits.add(PlayerCredit(id, creditIncremental)) } fun setOrRewriteCredit(id: String, creditIncremental: Long) { if (gomokuPlayerCredits.any { it.player == id }) { with(gomokuPlayerCredits.single { it.player == id }) { credit = creditIncremental } } else gomokuPlayerCredits.add(PlayerCredit(id, creditIncremental)) } @TriggerOn(TriggerPoint.BEFORE_CLOSED) fun save() { if (!File.exists(fileName)) { File.create(fileName) File.write(fileName, gomokuPlayerCredits.toJson()) } else { val future = File.read(fileName).thenApply<List<PlayerCredit>> { it.fromJson() } future.thenAccept { val added = gomokuPlayerCredits.apply { addAll(it) distinctBy(PlayerCredit::player) } File.write(fileName, added.toJson()) } } } @TriggerOn(TriggerPoint.STARTUP) fun load() { if (File.exists(fileName)) { gomokuPlayerCredits = File.read(fileName).get().fromJson() } } fun get(): List<PlayerCredit> { return gomokuPlayerCredits } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SetGlobalDispatcherImplCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.message.factory.Dispatcher import com.github.rinacm.sayaka.common.shared.console.SetGlobalDispatcherImplCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class SetGlobalDispatcherImplCommandHandler : CommandHandler<SetGlobalDispatcherImplCommand> { override suspend fun process(command: SetGlobalDispatcherImplCommand): List<MessageChain>? { with(Dispatcher.findDispatcherKeyByName(command.name)) { if (this != null) { Dispatcher.Global = this.instance } else { return "未知的调度器${command.name}".asSingleMessageChainList() } } return "调度器成功设置为${command.name}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/AboutSayakaCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.AboutSayakaCommandHandler import com.github.rinacm.sayaka.common.message.translator.AboutSayakaCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Contextual import com.github.rinacm.sayaka.common.util.PluginOwnership import com.github.rinacm.sayaka.common.util.Validator import net.mamoe.mirai.message.MessageEvent @Contextual(AboutSayakaCommandTranslator::class, AboutSayakaCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(PurePlainTextValidator::class) class AboutSayakaCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<AboutSayakaCommand> { override val match: String = "/about" override val description: String = "显示关于Sayaka Bot™的信息" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/RevokeAdministratorCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.RevokeAdministratorCommandHandler import com.github.rinacm.sayaka.common.message.translator.RevokeAdministratorCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(RevokeAdministratorCommandTranslator::class, RevokeAdministratorCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @Validator(RegexValidator::class, regex = QQ_ID_REGEX) @WithPrivilege(Privilege.SUPERUSER) data class RevokeAdministratorCommand(val qqId: String, override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<RevokeAdministratorCommand> { override val match: String = "/revoke" override val description: String = "根据${Placeholder("id")}撤销Bot管理员(非QQ群管理)" override fun canonicalizeName(): String { return "$match ${Placeholder("id")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/RemoveCommandMappingCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.RemoveCommandMappingCommand import net.mamoe.mirai.message.MessageEvent class RemoveCommandMappingCommandTranslator : AbstractMessageTranslator<RemoveCommandMappingCommand>() { override fun translate(rawInput: MessageEvent): RemoveCommandMappingCommand { return RemoveCommandMappingCommand(rawInput, defaultOnlyOneParameter(rawInput)!!) } }<file_sep>/settings.gradle rootProject.name = 'sayaka' <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/StopWatch.kt @file:Suppress("unused") package com.github.rinacm.sayaka.common.util import java.time.Duration class StopWatch { private var startTime = Duration.ZERO private var started = false fun start() { started = true startTime = durationNow() } fun reset() { startTime = durationNow() } fun stop() { startTime = Duration.ZERO started = false } fun elapsed(): Duration { return Duration.ofMillis(System.currentTimeMillis()).minus(startTime) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GomokuPlayerRequestEndingCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerRequestEndingCommand import net.mamoe.mirai.message.MessageEvent class GomokuPlayerRequestEndingCommandTranslator : AbstractMessageTranslator<GomokuPlayerRequestEndingCommand>() { override fun translate(rawInput: MessageEvent): GomokuPlayerRequestEndingCommand { return GomokuPlayerRequestEndingCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetAdministratorListCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.GetAdministratorListCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class GetAdministratorListCommandHandler : CommandHandler<GetAdministratorListCommand> { override suspend fun process(command: GetAdministratorListCommand): List<MessageChain>? { return BotContext.getAdmins().joinToString(" ", "[", "]").asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GetRandomRankingCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.pixiv.GetRandomRankingCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.pixiv.core.RankingEmitter import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.buildMessageChain import net.mamoe.mirai.message.uploadAsImage class GetRandomRankingCommandHandler : CommandHandler<GetRandomRankingCommand> { override suspend fun process(command: GetRandomRankingCommand): List<MessageChain>? { with(RankingEmitter.getOrCreateByContact(command.messageEvent.subject)) { if (coolDown) { return "命令正在冷却过程中,冷却时间为3秒".asSingleMessageChainList() } coolDown = true if (cache.isEmpty()) { command.messageEvent.subject.sendMessage("正在获取新的榜单...") construct() command.messageEvent.subject.sendMessage("榜单获取完成,正在随机...") } val illustration = emit() command.messageEvent.subject.sendMessage("正在下载图片...") val file = illustration.download() return buildMessageChain { add(file.uploadAsImage(command.messageEvent.subject)) add(buildString { appendLine("作品标题: ${illustration.title}") appendLine("作品Pixiv ID: ${illustration.id}") appendLine("作者: ${illustration.userName}") appendLine("作者ID: ${illustration.userId}") appendLine("收藏数: ${illustration.bookmark}") appendLine("上传日期: ${illustration.publishDate}") appendLine("总浏览量: ${illustration.viewCount}") appendLine("下载链接: ${illustration.origin}") append("Tags: ${illustration.tags.joinToString(",", "[", "]")}") }) }.asSingleMessageChainList() } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/SetGomokuPlayerCreditCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.SetGomokuPlayerCreditCommand import net.mamoe.mirai.message.MessageEvent class SetGomokuPlayerCreditCommandTranslator : AbstractMessageTranslator<SetGomokuPlayerCreditCommand>() { override fun translate(rawInput: MessageEvent): SetGomokuPlayerCreditCommand { val args = defaultTrailingParameters(rawInput) return SetGomokuPlayerCreditCommand(args[0], args[1], rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/plugin/Plugin.kt package com.github.rinacm.sayaka.common.plugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import com.github.rinacm.sayaka.common.util.reflector.TypedAnnotationScanner import com.github.rinacm.sayaka.common.util.reflector.TypedSubclassesScanner import kotlin.reflect.KClass import kotlin.reflect.full.companionObjectInstance import kotlin.reflect.full.isSubclassOf abstract class Plugin<T : Plugin<T>> { interface Key<T : Plugin<T>> : Descriptor { var enabled: Boolean var excludes: MutableMap<String, MutableSet<ExcludeType>> } companion object { private val pluginKeyToCommandKeyMapping by lazy { (TypedAnnotationScanner.markedMap[PluginOwnership::class] ?: emptyList()) .asSequence() .seqCast<Class<*>>() .map(Class<*>::kotlin) .filter { it.isSubclassOf(Command::class) } .filter { it.companionObjectInstance is Command.Key<*> } .groupBy({ it.annotations.singleIsInstance<PluginOwnership>().clazz }, KClass<*>::companionObjectInstance) .mapKeys { (plugin, _) -> plugin.companionObjectInstance as Key<*> } .mapValues { (_, commands) -> commands.cast<Command.Key<*>>() } } fun getPluginKeyByName(name: String): Key<*>? { return all()?.firstOrNull { (it.companionObjectInstance as Key<*>).match == name } ?.companionObjectInstance as Key<*>? } fun getPluginKeyByAnnotation(annotation: PluginOwnership): Key<*>? { return annotation.clazz.companionObjectInstance as Key<*>? } fun all(): List<KClass<out Any>>? { return TypedSubclassesScanner.markedMap[Plugin::class] ?.filter { it.companionObjectInstance is Key<*> } } fun help(pluginKey: Key<*>): String { if (pluginKeyToCommandKeyMapping.any { (key, _) -> key == pluginKey }) { val commands = pluginKeyToCommandKeyMapping[pluginKey] return buildString { appendLine("插件 ${pluginKey.canonicalizeName()}: ${pluginKey.description} ") appendLineIndent("命令列表: ") for (cmd in commands!!) { appendLineIndent(cmd.help(cmd), indentLevel = 2) } } } return String.EMPTY } fun help(): String { return buildString { for (plugin in pluginKeyToCommandKeyMapping.keys) { append(help(plugin)) } } } } } <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GomokuPlayerSurrenderCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerSurrenderCommand import net.mamoe.mirai.message.MessageEvent class GomokuPlayerSurrenderCommandTranslator : AbstractMessageTranslator<GomokuPlayerSurrenderCommand>() { override fun translate(rawInput: MessageEvent): GomokuPlayerSurrenderCommand { return GomokuPlayerSurrenderCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/ShuffleRankOptionCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.pixiv.ShuffleRankOptionCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.pixiv.core.RankingEmitter import net.mamoe.mirai.message.data.MessageChain class ShuffleRankOptionCommandHandler : CommandHandler<ShuffleRankOptionCommand> { override suspend fun process(command: ShuffleRankOptionCommand): List<MessageChain>? { RankingEmitter.getOrCreateByContact(command.messageEvent.subject).shuffle() return "成功将榜单选项随机为${RankingEmitter.getOrCreateByContact(command.messageEvent.subject).current.first}".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/SetAdministratorCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.init.BotContext import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.console.SetAdministratorCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import net.mamoe.mirai.message.data.MessageChain class SetAdministratorCommandHandler : CommandHandler<SetAdministratorCommand> { override suspend fun process(command: SetAdministratorCommand): List<MessageChain>? { return if (command.qqId.toLongOrNull() != null) { if (BotContext.addAdmin(command.qqId)) { "成功将${command.qqId}添加到管理员列表成功".asSingleMessageChainList() } else "${command.qqId}已经是一名管理员".asSingleMessageChainList() } else "参数格式错误,必须是一个正确的QQ号码".asSingleMessageChainList() } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GomokuPlayerSurrenderCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerSurrenderCommand import com.github.rinacm.sayaka.gomoku.GomokuGameFactory import net.mamoe.mirai.contact.Member import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.at class GomokuPlayerSurrenderCommandHandler : CommandHandler<GomokuPlayerSurrenderCommand> { override suspend fun process(command: GomokuPlayerSurrenderCommand): List<MessageChain>? { val game = GomokuGameFactory.tryGetGameOrNull(command.messageEvent.subject.id.toString()) val member = command.messageEvent.sender as Member if (game != null && game.isActivatedAndValid(member.id.toString())) { val winner = game.getPlayer().getNegative(member.id.toString()) return mutableListOf<MessageChain>().apply { add(member.at() + "选择了投降!") add(game.getWinMessageAndDisposeGame(game.getPlayer().toRole(winner))) } } return null } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/error/ValidationException.kt package com.github.rinacm.sayaka.common.message.error class ValidationException(cause: Exception) : PipelineException(cause) { override val errorStage: ErrorStage = ErrorStage.VALIDATION }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/handler/GomokuPlayerRequestEndingCommandHandler.kt package com.github.rinacm.sayaka.common.message.handler import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.gomoku.GomokuPlayerRequestEndingCommand import com.github.rinacm.sayaka.common.util.asSingleMessageChainList import com.github.rinacm.sayaka.common.util.toSingleList import com.github.rinacm.sayaka.gomoku.GomokuGameFactory import net.mamoe.mirai.contact.Group import net.mamoe.mirai.message.data.MessageChain import net.mamoe.mirai.message.data.at class GomokuPlayerRequestEndingCommandHandler : CommandHandler<GomokuPlayerRequestEndingCommand> { override suspend fun process(command: GomokuPlayerRequestEndingCommand): List<MessageChain>? { val ctx = command.messageEvent val game = GomokuGameFactory.tryGetGameOrNull(ctx.subject.id.toString()) if (game != null && game.isActivatedAndValid(ctx.sender.id.toString())) { with(ctx.subject as Group) { val (id, requesting) = game.requestEnding if (requesting && id != ctx.sender.id.toString()) { game.close() return "投票通过,结束id为${game.gameId}的对局".asSingleMessageChainList() } else if (!requesting) { game.requestEnding = ctx.sender.id.toString() to true return (this[ctx.sender.id].at() + "发起结束对局投票!同意请输入/re").toSingleList() } } } return null } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/ReloadRankingSettingsCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.pixiv.ReloadRankingSettingsCommand import net.mamoe.mirai.message.MessageEvent class ReloadRankingSettingsCommandTranslator : AbstractMessageTranslator<ReloadRankingSettingsCommand>() { override fun translate(rawInput: MessageEvent): ReloadRankingSettingsCommand { return ReloadRankingSettingsCommand(rawInput) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/GetDispatchersMessageCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.GetDispatchersMessageCommand import net.mamoe.mirai.message.MessageEvent class GetDispatchersMessageCommandTranslator : AbstractMessageTranslator<GetDispatchersMessageCommand>() { override fun translate(rawInput: MessageEvent): GetDispatchersMessageCommand { return GetDispatchersMessageCommand(rawInput, defaultOnlyOneParameter(rawInput) != null) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/StepMarker.kt package com.github.rinacm.sayaka.gomoku @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class StepLeft(val stepX: Int, val stepY: Int) @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class StepRight(val stepX: Int, val stepY: Int) <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/gomoku/GomokuGameFactory.kt package com.github.rinacm.sayaka.gomoku object GomokuGameFactory { private val games = mutableMapOf<String, Game>() @Synchronized fun getOrCreateGame(group: String): Game { if (group in games.keys) { return games[group]!! } return Game(group).apply { games[group] = this } } @Synchronized fun tryGetGameOrNull(group: String): Game? { if (group in games.keys) { return games[group] } return null } @Synchronized fun removeGame(gameId: String) { games.remove(gameId) } }<file_sep>/src/main/java/Test.java import java.util.function.Supplier; public class Test { public static void waitConditional(Supplier<Boolean> condition) { while (!condition.get()) { } } public static void main(String[] args) { waitConditional(() -> false); System.out.println(); } } <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/reflector/TypedSubclassesScanner.kt package com.github.rinacm.sayaka.common.util.reflector import com.github.rinacm.sayaka.common.util.set import kotlin.reflect.KClass object TypedSubclassesScanner : TypedScanner<KClass<*>, KClass<out Any>>() { override val markedMap: Map<KClass<*>, List<KClass<out Any>>> by lazy { val map = mutableMapOf<KClass<*>, List<KClass<out Any>>>() for ((target, classes) in scanMap.asMap()) { for (cls in classes) { if (target == ScanningTarget.CLASS) { map[cls] = reflector.getSubTypesOf(cls.java).map(Class<*>::kotlin) } } } return@lazy map } override fun registerScanner(scanningTarget: ScanningTarget, clazz: KClass<*>) { scanMap[scanningTarget] = clazz } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/RevokeAdministratorCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.RevokeAdministratorCommand import net.mamoe.mirai.message.MessageEvent class RevokeAdministratorCommandTranslator : AbstractMessageTranslator<RevokeAdministratorCommand>() { override fun translate(rawInput: MessageEvent): RevokeAdministratorCommand { return RevokeAdministratorCommand(defaultOnlyOneParameter(rawInput)!!, rawInput) } } <file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/factory/Dispatcher.kt package com.github.rinacm.sayaka.common.message.factory import com.github.rinacm.sayaka.common.message.contextual.CommandHandler import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Descriptor import com.github.rinacm.sayaka.common.util.reflector.TypedSubclassesScanner import net.mamoe.mirai.message.MessageEvent import kotlin.reflect.full.companionObjectInstance /** * Interface to dispatch received messages as a pipe and manage the request flow * 1. use [translateMessage] to translate a [MessageEvent] to an Command Object * 2. check if the [MessageEvent] comfort [thresholding] * 3. validation stage happens in translation stage, it will intercept all illegal * messages(.i.e a message with correct command match but has no parameters), a * [ValidationException] will be thrown when the illegal messages being captured * 4. use [dispatchMessage] to dispatch the message to the corresponds [CommandHandler] * and if [translateMessage] throws means there's an exception occurred during * the the translation stage therefore you should call the [dispatchError] to handle the * error message */ interface Dispatcher { interface Key<T : Dispatcher> : Descriptor { val instance: T } companion object { var Global: Dispatcher = DefaultDispatcherImpl.instance var Sleeping: Boolean = false fun availableDispatchers(): List<Key<*>>? { return TypedSubclassesScanner.markedMap[Dispatcher::class] ?.filter { it.companionObjectInstance is Key<*> } ?.map { it.companionObjectInstance as Key<*> } } fun findDispatcherKeyByName(name: String): Key<*>? { return TypedSubclassesScanner.markedMap[Dispatcher::class] ?.filter { it.companionObjectInstance is Key<*> } ?.map { it.companionObjectInstance as Key<*> } ?.firstOrNull { it.match == name } } } suspend fun translateMessage(messageEvent: MessageEvent): Command suspend fun <T : Command> dispatchMessage(messageEvent: MessageEvent, command: T) suspend fun dispatchError(messageEvent: MessageEvent, exception: Exception) suspend fun thresholding(messageEvent: MessageEvent): Boolean }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/gomoku/GetGomokuCreditCommand.kt package com.github.rinacm.sayaka.common.shared.gomoku import com.github.rinacm.sayaka.common.message.handler.GetGomokuCreditCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetGomokuCreditCommandTranslator import com.github.rinacm.sayaka.common.message.validation.RegexValidator import com.github.rinacm.sayaka.common.plugin.GomokuPlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.* import net.mamoe.mirai.message.MessageEvent @Contextual(GetGomokuCreditCommandTranslator::class, GetGomokuCreditCommandHandler::class) @PluginOwnership(GomokuPlugin::class) @Validator(RegexValidator::class, regex = QQ_ID_REGEX) data class GetGomokuCreditCommand(val playerQQId: String, override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GetGomokuCreditCommand> { override val match: String = "/gc" override val description: String = "获取${Placeholder("id")}对应的Gomoku点数" override fun canonicalizeName(): String { return "$match ${Placeholder("id")}" } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/shared/console/GetOwnerCommand.kt package com.github.rinacm.sayaka.common.shared.console import com.github.rinacm.sayaka.common.message.handler.GetOwnerCommandHandler import com.github.rinacm.sayaka.common.message.translator.GetOwnerCommandTranslator import com.github.rinacm.sayaka.common.message.validation.PurePlainTextValidator import com.github.rinacm.sayaka.common.plugin.ConsolePlugin import com.github.rinacm.sayaka.common.shared.Command import com.github.rinacm.sayaka.common.util.Contextual import com.github.rinacm.sayaka.common.util.PermanentlyDisable import com.github.rinacm.sayaka.common.util.PluginOwnership import com.github.rinacm.sayaka.common.util.Validator import net.mamoe.mirai.message.MessageEvent @Contextual(GetOwnerCommandTranslator::class, GetOwnerCommandHandler::class) @PluginOwnership(ConsolePlugin::class) @PermanentlyDisable @Validator(PurePlainTextValidator::class) class GetOwnerCommand(override val messageEvent: MessageEvent) : Command { companion object Key : Command.Key<GetOwnerCommand> { override val match: String = "/owner" override val description: String = "获取该Bot的实际持有者" } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/message/translator/ShowHelpMessageCommandTranslator.kt package com.github.rinacm.sayaka.common.message.translator import com.github.rinacm.sayaka.common.message.contextual.AbstractMessageTranslator import com.github.rinacm.sayaka.common.shared.console.ShowHelpMessageCommand import net.mamoe.mirai.message.MessageEvent class ShowHelpMessageCommandTranslator : AbstractMessageTranslator<ShowHelpMessageCommand>() { override fun translate(rawInput: MessageEvent): ShowHelpMessageCommand { return ShowHelpMessageCommand(rawInput, defaultTrailingParameters(rawInput)) } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/Sayaka.kt package com.github.rinacm.sayaka import com.github.rinacm.sayaka.common.init.BotFactory import com.github.rinacm.sayaka.common.init.PreInit import com.github.rinacm.sayaka.common.util.subscribeAlwaysUnderGlobalDispatcherSuspended import kotlinx.coroutines.runBlocking fun main() = runBlocking { PreInit.use { BotFactory.runAndJoin { subscribeAlwaysUnderGlobalDispatcherSuspended { try { val msg = translateMessage(it) dispatchMessage(it, msg) } catch (e: Exception) { dispatchError(it, e) } } } } }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/Descriptor.kt package com.github.rinacm.sayaka.common.util interface Descriptor { val match: String val matchOption: MatchOption get() = MatchOption.PLAIN_TEXT val description: String /** * canonicalize string of [match], default value is [match] itself */ fun canonicalizeName() = match }<file_sep>/src/main/kotlin/com/github/rinacm/sayaka/common/util/reflector/TypedScanner.kt package com.github.rinacm.sayaka.common.util.reflector import com.github.rinacm.sayaka.common.util.reflector.TypedAnnotationScanner.markedMap import com.google.common.collect.Multimap import com.google.common.collect.MultimapBuilder import org.reflections.Reflections import org.reflections.scanners.MethodAnnotationsScanner import org.reflections.scanners.SubTypesScanner import org.reflections.scanners.TypeAnnotationsScanner enum class ScanningTarget { METHOD, CLASS } /** * Provide a set of functionalities to scan through the project and get * a list which denotes for every condition [T] there's such a set of [R] exists */ abstract class TypedScanner<T : Any, R : Any> { companion object { @JvmStatic protected val reflector by lazy { Reflections("com.github.rinacm.sayaka" /* root package */, TypeAnnotationsScanner(), MethodAnnotationsScanner(), SubTypesScanner()) } } protected val scanMap: Multimap<ScanningTarget, T> = MultimapBuilder.hashKeys().arrayListValues().build() abstract val markedMap: Map<T, List<R>> /** * [registerScanner] is not dynamically invokable, you must register every class before you use [markedMap] * this method will be invalid once you use [markedMap] */ abstract fun registerScanner(scanningTarget: ScanningTarget, clazz: T) }
0a1014c5400e45c2880d2647e5c39495dec304d8
[ "Java", "Kotlin", "INI", "Gradle" ]
142
Kotlin
dylech30th/sayaka
f27998445fafc1cf0ee66fef2b8abc7a95efecca
3bbda7b511721534e239926d69b01d9808b6a628
refs/heads/master
<file_sep><?php /** * 引数の配列をvar_dump()する。 * * @author <NAME> */ function smarty_function_dump($params, &$smarty){ //引数は連想配列「$params」で受け取っている $target_array = $params["target_array"]; var_dump($target_array); }//function /* //tpl側の書き方の想定 <!--{dump target_array=$array}--> //このファイルの置き場所 //\data\module\Smarty\libs\plugins */ <file_sep><?php /** * ログイン状態を取得するクラス。 * * @author <NAME> */ function smarty_function_getter_login_condition($params, &$smarty){ // transactionid取得 $transactionId = SC_Helper_Session_Ex::getToken(); // ログイン判定 $objCustomer = new SC_Customer(); if($objCustomer->isLoginSuccess()){ //ログイン済み //テンプレート側で使える変数作成 $smarty->assign("is_logged_in", true); }else{ //非ログイン //テンプレート側で使える変数作成 $smarty->assign("is_logged_in", false); }//if }//function /* //tpl側の書き方の想定 //まず、ログイン状態を示す変数 $is_logged_in の作成のために一行の命令が必要。 <!--ログイン状態の取得($is_logged_inの作成)--> <!--{getter_login_condition}--> //しかるのち、$is_logged_in がif文判定で使える <!--{if $is_logged_in}--> <!--ログイン時の処理--> <!--{else}--> <!--非ログイン時の処理--> <!--{/if}--> */
a58ba41014e19bbf3947ab3059423ada00a57ba7
[ "PHP" ]
2
PHP
ishiitakeru/Eccube_plugins
2d2f0e9b2ceb539b7df23d50c7a10f1844e352f8
ff2414d954f24bceca9cfba98e1e22b343838f76
refs/heads/master
<repo_name>CS2103-AY1819S1-T16-1/main<file_sep>/docs/UserGuide.adoc = WishBook - User Guide :site-section: UserGuide :toc: :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full :experimental: ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: endif::[] :repoURL: https://github.com/CS2103-AY1819S1-T16-1/main By: `Team SE-EDU` Since: `Jun 2016` Licence: `MIT` == Introduction **WishBook** (WB) is a piggy bank in a digital app form, made for people who need a user-friendly solution for keeping track of their disposable income. Not only does WB keep records of your savings, it also allows you to set items as goals for users to work towards, serving as a way to cultivate the habit of saving. WB is made for people who have material wants in life, but are uncertain of purchasing said wants, by helping them to reserve disposable income so that they know they can spend on their wants. So what are you waiting for? Go to Section 2, <<Quick Start>> and start saving! == Quick Start . Ensure you have Java version `9` or later installed in your Computer. . Download the latest `wishbook.jar` link:{repoURL}/releases[here]. . Copy the file to the folder you want to use as the home folder for your WishBook app. . Double-click the file to start the app. The GUI should appear in a few seconds. + image::Ui.png[width="790"] + . Type the command in the command box and press kbd:[Enter] to execute it. + e.g. typing *`help`* and pressing kbd:[Enter] will open the help window. . Some example commands you can try: * *`list`* : Lists all the items you have set as wishes (sorted by due date). * **`add`**`n/uPhoneXX p/1000 a/5m` : adds an item “uPhoneXX” as a goal to be completed in 5 months. * *`help`*: displays list of command with usage. * *`clear`*: clears view * *`exit`* : exits the app . Refer to <<Features>> for details of each command. [[Features]] == Features ==== *Command Format* * Words in `UPPER_CASE` are the parameters to be supplied by the user e.g. in `add WISH`, `WISH` is a parameter which can be used as add iPhone. * Items in square brackets are optional e.g. in `list [FILTER]`, `FILTER` is an optional parameter, since the list command can be used as `list` to display all wishes in WishBook. ** An exception to this is `TIME_GIVEN` and `END_DATE`, whereby only one of the two can be used in any command. ** The `add` command requires either `TIME_GIVEN` and `END_DATE`. ** The `edit` command can take either or none of them. * Items with `…`​ after them can be used multiple times including zero times e.g. `[t/TAG]...` can be used as `{nbsp}` (i.e. 0 times), `t/broke`, `t/needs` etc. * The `/` symbol between parameters means that you can use either of the parameters types in the command e.g. in `add WISH PRICE [TIME_GIVEN]/[START_DATE to END_DATE]`, you provide either the `TIME_GIVEN` parameter or `START_DATE` and `END_DATE` parameters. ==== === Viewing help : `help` Displays a popup window showing all the commands a user can use in `WishBook`. + Format: `help` === Add a new wish: `add` Add a new wish to the wish list. + Format: `add n/WISH_NAME p/PRICE [a/PERIOD_GIVEN]/[d/END_DATE] [u/URL] [t/TAG]...` [TIP] * `[END_DATE]`: Specified in _dd/mm/yyyy_ format. * `[TIME_GIVEN]`: Specified in terms of years, months, weeks, and days, suffixes (coming after the value) marking such time periods are _‘y’_, _‘m’_, _‘w’_, and _‘d’_ respectively. The order of `[TIME_GIVEN]` must be from the biggest unit of time to the smallest unit of time, meaning that the suffix _`y`_ cannot come after any of the other three suffixes, and _'w'_ cannot come after _'d'_, but can come after _'y'_ and _'m'_. [NOTE] ==== If you enter an invalid date, a warning message will be displayed to prompt the user to reenter a valid date. Until all fields provided are valid, the wish will not be added to `WishBook`. ==== [NOTE] ==== The expiry date you enter must be after current date. ==== Examples: * `add n/XBoxTwo p/999 a/1y` * `add n/kfcBook 13inch p/2300 a/6m3w r/For dad t/family t/computing` * `add n/prinkles p/1.95 d/24/04/2020` * `add n/prinkles p/1.95 d/24/04/2020 u/www.amazon.com/prinkles t/high` === Edit a wish : `edit` Edits an existing wish in the wish list. + Format: `edit INDEX [n/WISH_NAME] [p/PRICE] [a/TIME_GIVEN]/[d/END_DATE] [u/URL] [t/TAG]` **** * Edits the wish at the specified `INDEX`. `INDEX` refers to the index number shown in the displayed list of goals. `INDEX` must be a positive integer 1, 2, 3, … * `INDEX` is labelled at the side of each wish. * At least one of the optional fields must be provided. * Existing values will be updated to the input values. * When editing tags, the existing tags of the wish will be removed i.e. adding of tags is not cumulative. * You can remove all tags by typing `t/` without specifying any tags after it. **** Examples: * `edit 1 n/Macbook Pro t/Broke wishes` + Edits the name of the wish and the tag of the 1st wish to be Macbook Pro and Broke wishes respectively * `edit 2 p/22 a/22w` + Edits the price and time given to accomplish the 2nd wish to 22 (in the chosen currency) and 22 weeks respectively. === List wishes : `list` Shows a list of all the wishes you have set, sorted by date by default, based on the given filter. If no filter is specified, all wishes in the WishBook will be listed. + Format: `list [FILTER]` * `list` + Lists all the wishes in the WishBook. * `list -c` + Lists all the completed wishes in the WishBook. * `list -u` + Lists all the uncompleted wishes in the WishBook. **** * Only wishes in the current state of the wishbook will be listed. * Deleted wishes will not be displayed. **** === List history of entered commands : `history -c` Lists all the commands that you have entered in reverse chronological order. + Format: `history -c` [NOTE] ==== Pressing the kbd:[&uarr;] and kbd:[&darr;] arrows will display the previous and next input respectively in the command box. ==== // tag::savingsHistory[] === View your saving history: `history -s` Shows a history of savings you have allocated, from newest to oldest. + Format: `history -s` [NOTE] ==== Only history of wishes which currently exist in the `WishBook` will be stored. (i.e. wishes that have been deleted will no longer be tracked.) ==== // end::savingsHistory[] // tag::find[] === Locate your wish with speed and precision: `find` Find wishes which match the given search keywords. + Format: `find [-e] [n/NAME_KEYWORD]... [t/TAG_KEYWORD]... [r/REMARK_KEYWORD]...` **** * At least one keyword must be provided. * Searching multiple keywords of the *same prefix* will return wishes whose attribute corresponding to the prefix contain *any* one of the keywords. * Searching with keywords of *different prefixes* will return only wishes that match will *all* the keywords of the different prefixes. * Using the exact match flag, `-e` returns wishes whose corresponding attributes contain *all* the keywords. * The search is case insensitive. e.g. watch will match Watch. **** Examples: * `find n/wat` + Returns any wish whose name contains the _wat_. * `find n/wat n/balloon n/appl` + Returns wishes whose names which contain at least any one of _wat_, _balloon_ or _appl_. * `find -e n/wat n/balloon n/appl` + Returns only wishes whose names that contain all of _wat_, _balloon_ and _appl_. * `find n/watch t/important` + Returns any wish whose name contains _watch_, and whose tags contains _broke wishes_. * `find n/wat n/balloon t/important` + Returns any wish whose name contains _wat_ or _balloon_, and whose tags contains _important_. // end::find[] === Delete a wish : `delete` Deletes the specified wish from the list and moves any funds in that wish to `unusedFunds`. + Format: `delete INDEX` **** * `INDEX` refers to the index number shown in the displayed list. * `INDEX` must be a positive integer 1, 2, 3... * If the wish at `INDEX` is not yet fulfilled, the saved amount in that wish will be channelled to `unusedFunds`. **** Examples: * `list` + `delete 2` + Deletes the 2nd wish in the list. * `find watch` + `delete 1` + Deletes the 1st wish in the results of the find command (if any). === Select a wish : `select` Selects the wish identified by the index number used in the displayed wish list. + Format: `select INDEX` **** * Selects the wish and displays content relevant to that wish in the view. * Webpage at the `url` specific to that wish at the specified `INDEX` will be loaded in the view. * If there is no internet connection, the webpage will not be loaded. * Savings history view will also reflect the savings history for the selected wish, if the selected wish is valid. * `INDEX` refers to the index number shown in the displayed wish list. * `INDEX` *must be a positive integer* `1, 2, 3, ...` **** Examples: * `list` + `select 2` + Selects the 2nd wish in the wish list. * `find price` + `select 1` + Selects the 1st wish in the results of the `find` command. // tag::save[] === Save money for a particular wish: `save` Channel a specified amount of money to savings for a specified wish. + Format: `save INDEX AMOUNT` **** * `INDEX` should be a positive integer 1, 2, 3… no larger than the number of wishes. * If `INDEX` is 0, `AMOUNT` will be channelled directly to `unusedFunds`. * If `AMOUNT` saved to `INDEX` is greater than the amount needed to fulfil that wish, excess funds will be channelled to `unusedFunds`. * If `AMOUNT` is negative, money will be removed from amount saved for that wish. + * `AMOUNT` will not be accepted if: ** `AMOUNT` brings the savings value for that wish to below 0. ** The wish at `INDEX` is already fulfilled. **** Examples: + * `save 1 1000` + Attempt to save $1000 for the wish at index 1. * `save 1 -100.50` + Attempt to remove $100.50 from the savings for the wish at index 1. * `save 0 100.50` + Attempt save $100.50 to `unusedFunds`. // end::save[] // tag::move[] === Move money between wishes: `move` Moves funds from one wish to another. + Format: `move FROM_WISH_INDEX TO_WISH_INDEX AMOUNT` **** * `FROM_WISH_INDEX` and `TO_WISH_INDEX` should be a positive integer 1, 2, 3… no larger than the number of wishes * If `FROM_WISH_INDEX` is 0, `AMOUNT` will be channelled from `unusedFunds` to `TO_WISH_INDEX`. * If `TO_WISH_INDEX` is 0, `AMOUNT` will be channelled from `FROM_WISH_INDEX` to `unusedFunds`. * `AMOUNT` from `unusedFunds` will only be successfully channelled if the exact amount requested is present in `unusedFunds`. * If `FROM_WISH_INDEX` equals `TO_WISH_INDEX`, both indexes will not be accepted. * If `AMOUNT` saved to `TO_WISH_INDEX` is greater than the amount needed to fulfil that wish, excess funds will be channelled to `unusedFunds`. * `AMOUNT` will not be accepted if: ** `AMOUNT` is negative. ** `AMOUNT` brings the savings amount of wish at `FROM_WISH_INDEX` to below 0. ** Either wish at `FROM_WISH_INDEX` or `TO_WISH_INDEX` is already fulfilled. **** [NOTE] ==== Index 0 is specially allocated for `unused funds`. Excess funds when user attempts to save to a wish will be automatically allocated to `unusedFunds`. The user can also choose to channel funds from `unusedFunds` to a valid wish. ==== Examples: + * `move 1 2 10` + Attempt to move $10 from the wish at index 1 to the wish at index 2. * `move 0 1 10` + Attempt to move $10 from `unusedFunds` to the wish at index 1. * `move 1 0 10` + Attempt to move $10 from the wish at index 1 to `unusedFunds`. // end::move[] === Edit a remark for a wish : `remark` Edits the remark for a wish specified in the index. + Format: `remark INDEX r/[REMARK]` **** * `INDEX` refers to the index number shown in the displayed list. * `INDEX` must be a positive integer 1, 2, 3... **** Examples: * `list` + `remark 1 r/Buying this for dad.` + Edits the remark for the first wish to `Buying this for dad.` * `list` + `remark 1 r/` + Removes the remark for the first wish (if any). // tag::undoredo[] === Undo previous command : `undo` Restores WishBook to the state before the previous undoable command was executed. + Format: `undo` **** * If no undoable commands exist or the state of the wishbook is already in its original state, the undo command will fail and the state of the wishbook will remain unchanged. **** [NOTE] ==== Undoable commands: commands that modify WishBook content (`add, delete, edit, save`). ==== Examples: * `delete 1` + `list` + `undo` (reverses the `delete 1` command) + * `select 1` + `list` + `undo` + The `undo` command fails as there are no undoable commands executed previously. * `delete 1` + `clear` + `undo` (reverses the `clear` command) + `undo` (reverses the `delete 1` command) + === Redo the previously undone command : `redo` Reverses the most recent `undo` command. + Format: `redo` Examples: * `delete 1` + `undo` (reverses the `delete 1` command) + `redo` (reapplies the `delete 1` command) + * `delete 1` + `redo` + The `redo` command fails as there are no `undo` commands executed previously. * `delete 1` + `clear` + `undo` (reverses the `clear` command) + `undo` (reverses the `delete 1` command) + `redo` (reapplies the `delete 1` command) + `redo` (reapplies the `clear` command) + // end::undoredo[] === Clearing all entries : `clear` Clears all entries from WishBook. + Format: `clear` === Exiting the program : `exit` Exits the program. + Format: `exit` === Saving the data WishBook data are saved in the hard disk automatically after any command that changes the data. + There is no need to save manually. == FAQ *Q*: How do I transfer my data to another Computer? + *A*: Install the app in the other computer and overwrite the empty data file it creates with the file that contains the data of your previous WishBook folder. == Command Summary * *Add* `add n/WISH_NAME p/PRICE t/[a/TIME_GIVEN]/[d/END_DATE] [u/URL] [t/TAG]...` + e.g. `add n/Sega Genesis p/2300 a/6m3w` * *Clear* : `clear` * *Delete* : `delete INDEX` + e.g. `delete 3` * *Edit* : `edit INDEX [n/WISH_NAME] [p/PRICE] [a/TIME_GIVEN]/[d/END_DATE] [t/TAG]` + e.g. `edit 1 n/Macbook Pro t/technology` * *Find* : `find [-e] [n/NAME_KEYWORD]... [t/TAG_KEYWORD]... [r/REMARK_KEYWORD]...` + e.g. `find n/Vacuum Cleaner t/family` * *List* : `list` * *List completed* : `list -c` * *List uncompleted* : `list -u` * *Help* : `help` * *Select* : `select INDEX` + e.g.`select 2` * *Save* : `save INDEX AMOUNT` + e.g. `save 1 1000` * *Move* : `move FROM_WISH_INDEX TO_WISH_INDEX AMOUNT` + e.g. `move 1 2 10` * *Command History* : `history -c` * *Savings History* : `history -s` * *Remark* : `remark INDEX r/[REMARK]` * *Undo* : `undo` * *Redo* : `redo` * *Exit* : `exit` <file_sep>/src/main/java/seedu/address/model/wish/WishContainsKeywordsPredicate.java package seedu.address.model.wish; import java.util.List; import java.util.function.Predicate; /** * Tests that a {@code Wish}'s {@code Name}, {@code Tags} and {@code Remark} match any or all of the keywords given. */ public class WishContainsKeywordsPredicate implements Predicate<Wish> { private final boolean isExactMatch; private final List<String> nameKeywords; private final List<String> tagKeywords; private final List<String> remarkKeywords; /** * Constructs a {@link WishContainsKeywordsPredicate} using the specified keywords. * @param nameKeywords Keywords to test against {@code Wish} name. * @param tagKeywords Keywords to test against {@code Wish} tags. * @param remarkKeywords Keywords to test against {@code Wish} remark. * @param isExactMatch Indicate whether to test for a match with a single keyword or a match with all the keywords * for each {@code Wish} field. */ public WishContainsKeywordsPredicate(List<String> nameKeywords, List<String> tagKeywords, List<String> remarkKeywords, boolean isExactMatch) { this.isExactMatch = isExactMatch; this.nameKeywords = nameKeywords; this.tagKeywords = tagKeywords; this.remarkKeywords = remarkKeywords; } @Override public boolean test(Wish wish) { if (isExactMatch) { return testAllMatch(wish.getName().toString(), nameKeywords) && testAllMatch(wish.getTags().toString(), tagKeywords) && testAllMatch(wish.getRemark().toString(), remarkKeywords); } return testAnyMatch(wish.getName().toString(), nameKeywords) && testAnyMatch(wish.getTags().toString(), tagKeywords) && testAnyMatch(wish.getRemark().toString(), remarkKeywords); } @Override public boolean equals(Object other) { return other == this //short circuit if same object || ((other instanceof WishContainsKeywordsPredicate) && isExactMatch == ((WishContainsKeywordsPredicate) other).isExactMatch && nameKeywords.equals(((WishContainsKeywordsPredicate) other).nameKeywords) && tagKeywords.equals(((WishContainsKeywordsPredicate) other).tagKeywords) && remarkKeywords.equals(((WishContainsKeywordsPredicate) other).remarkKeywords)); } /** Returns true if all keyword is found in the sentence, case insensitive. */ private boolean testAllMatch(String sentence, List<String> keywords) { String processedSentence = sentence.toLowerCase(); return keywords.stream().allMatch(keyword -> processedSentence.contains(keyword.toLowerCase())); } /** Returns true if any keyword is found in the sentence, case insensitive. */ private boolean testAnyMatch(String sentence, List<String> keywords) { if (keywords.isEmpty()) { return true; } String processedSentence = sentence.toLowerCase(); return keywords.stream().anyMatch(keyword -> processedSentence.contains(keyword.toLowerCase())); } } <file_sep>/docs/team/jiholim.adoc = <NAME> (jiholim) - Project Portfolio :site-section: AboutUs :imagesDir: ../images :stylesDir: ../stylesheets ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :experimental: endif::[] == PROJECT: WishBook --- == Overview WishBook is a desktop saving assistant application built for people who want to set saving goals and keep track of their progress. WishBook makes saving money easy, motivating, & fun and aims to help users to complete their saving goals by making sure they stick to the target and maintain progress regularly. WishBook boasts a beautifully designed Graphical User Interface (GUI) and makes use of a Command Line Interface (CLI) for most of the user interaction. The application is written in Java and contains about 10 kLoC. Below is a high definition product preview photo. image::Ui2.png[width="800"] == Summary of contributions * *Major enhancement*: A complete redesign of GUI (UI & UX) and front-end development ** What it does: Displays an intuitive and data-rich graphical user interface that achieves the product’s goal and delivers smooth user experience when the features are being used. ** Justification: The redesign of the application is necessary as it unifies the different set of features that are built into a well-integrated product. It improves the product significantly because user can reap the maximum intended benefits of the features.
 ** Highlights: This enhancement affects existing ui components and elements to be added in future. It required an in-depth analysis of design alternatives. The implementation too was challenging as it required changes to existing ui-related codebase * *Minor enhancements*: ** Devised and built appropriate event handlers to present changes in model on ui ** Various Bug Fixes ** Update HelpWindow display * *Code contributed*: https://nus-cs2103-ay1819s1.github.io/cs2103-dashboard/#=undefined&search=jiholim[Project Code Dashboard link] * *Other contributions*: ** Project management: *** Managed milestones `v1.1` - `v1.4` and one `v1.5` (release) on GitHub *** Helped with the issue tracking using labels and assignees on Github ** Documentation: *** Updated README file to add descriptions of the application with relevant mockup picture (Pull requests https://github.com/CS2103-AY1819S1-T16-1/main/pull/7[#7]) *** Updated User Guide and Developer Guide for the features I added. ** Community: *** Review pull requests weekly (https://github.com/CS2103-AY1819S1-T16-1/main/pulls?q=is%3Apr+is%3Aclosed[see here]) *** Reported bugs and gave suggestions for other group’s project. == Contributions to the User Guide |=== |_Given below are sections I contributed to the User Guide. They showcase my ability to write documentation targeting end-users._ |=== === List wishes : `list` Shows a list of all the wishes you have set, sorted by date by default, based on the given filter. If no filter is specified, all wishes in the WishBook will be listed. + Format: `list [FILTER]` * `list` + Lists all the wishes in the WishBook. * `list -c` + Lists all the completed wishes in the WishBook. * `list -u` + Lists all the uncompleted wishes in the WishBook. **** * Only wishes in the current state of the wishbook will be listed. * Deleted wishes will not be displayed. **** == Contributions to the Developer Guide |=== |_Given below are sections I contributed to the Developer Guide. They showcase my ability to write technical documentation and the technical depth of my contributions to the project._ |=== === List feature The `list -c and list -u` command allows the user to view the list of all wishes, completed and ongoing, respectively. A wish is completed if the savedAmount is greater or equal to the price of the wish. ==== Current Implementation Given below is an example usage scenario and how the list overdue mechanism behaves at each step: . The user executes the command `list -c`. . `model.updateFilteredWishList()` will update the wish list with `WishCompletedPredicate` as the parameter (boolean). `wish.isFulfilled()` is called to check whether the wish is completed or not. . The updated wish list would be reflected on the UI to be displayed to the user. The following sequence diagram shows how the Wish Detail Panel displays its updated content: image::ListCompletedSequenceDiagram.png[width="800"] === Redesign of User Interface The UI has been redesigned to implement the following UI components required for WishBook: * Command Box * Wish List Panel * Wish Detail Panel ==== Wish List Panel The Wish List Panel consists of a list of Wish Card which contains 4 UI elements: * `WishCard#nameLabel` - A `Text` element that displays the wish’s name. * `WishCard#progressLabel` - A `Text` element that displays the wish’s saving progress in percentage format. * `WishCard#tags` - A `FlowPane` element that contains a `Text` element which displays the wish’s assigned tags. * `WishCard#progressBar` - A `progressBar` element that visually presents the percentage of the wish’s current saving progress. Whenever the user adds a new wish or edits an existing wish, a new WishCard containing the wish will be added to the Wish List Panel or the content in the existing WishCard will be updated respectively. The user will be able to view the wish’s current saving progress both in terms of text on the progressLabel (e.g. ’80%’) and the progressBar. Also, the user will be able to see all the tags he/she assigned to categorize the wish. ===== Problem with the old design The UI (MainWindow) constructs the `WishListPanel` by obtaining an `ObservableList` of wish cards from `Model`, this list is assigned when UI starts, and will never be re-assigned. The UI "observes" the list and updates when it is modified. This approach works well for the `WishListPanel` because WishBook contains only 1 list of wish cards. However, the saving history list in the `WishDetailPanel` can not be updated in the same manner because Model component will change its card list’s reference when a user adds a new wish or updates the content of the wish. In this case, the `WishDetailPanel` in UI will not be updated because the card list of which UI has reference to is actually not changed. ===== Design considerations * **Alternative 1 (current choice)**: Have a wishList in `Model` and keep it updated with the current list of cards ** Explanation: The UI needs only 1 reference to this `wishList`, each time user executes any changes, `wishList` is cleared and the new list of cards is copy to the `wishList`. ** Pros: The structure of `Model` and UI component needs not be changed ** Cons: Need to keep a copy of the current card list, copying the whole list of cards for each command operation has bad effect on performance
. * **Alternative 2**: Model component raises an event when its current card list’s reference is changed ** Explanation: When user adds a new wish or executes save, `Model` will raise an event (`WishPanelUpdatedEvent`), which is subscribed by UI, then UI can re-assign its list of cards and update the cards panel accordingly. ** Pros: Better performance ** Cons: Need to re-design `Model` and UI components
 ==== Wish Detail Panel The Wish Detail Panel consists of 3 UI sub-components: * `WishDetailSavingAmount` that contains `Text` elements to display price and the saving progress of the wish * `WishDetailSavingHistory` that contains a `List` of history of saving inputs of the wish * `WishBrowserPanel` that displays `WebView` of the URL of the wish. Whenever the user adds a new wish or edits an existing wish, the content of the wish in Wish Detail Panel will be updated. The user will be able to view the wish’s current saving progress and the history of his/her saving inputs of the wish in the list format. Also, the user will be able to browse through the wish’s product page via its assigned URL. ===== Current Implementation Every time a new Wish is added or an existing wish is updated by the commands such as save, it raises a `WishDataUpdatedEvent`. The UI will then handle that event and update the `WishDetailPanel` with the new version of wish. Given below is an example usage scenario and how the WishBook behaves and `WishDetailPanel` is updated at each step: . The user executes the command `save 1 1000`. [NOTE] If a command fails its execution, WishDataUpdatedEvent will not be posted. . The save command updates the model with the new wish and raises a new `WishDataUpdatedEvent`. . `WishDetailSavingAmount` and `WishDetailSavingHistory` responds to the `WishDataUpdatedEvent` with `WishListPanel#handleWishUpdatedEvent()`. . The `WishDetailSavingAmount` updates the wish’s current saving progress when `WishDetailSavingAmount#loadWishDetails` is called. . The progress is calculated from when `Wish#getProgress` is called. The value is saveAmount / price. Then the progress label for the wish is set to that fraction. . The `WishDetailSavingHistory` updates the wish’s saving history list when `WishDetailSavingHistory#loadWishDetails` is called. . The saving history list is cleared. . The new set of history entry is retrieved from `wishTransaction#getWishMap` and the saved amount is calculated from subtracting previous saving amount from the next one. . The saving history list is now filled with the new list of updated saving history. The following sequence diagram shows how the Wish Detail Panel displays its updated content: image::WishDetailPanelSequenceDiagram.png[width="800"] ===== Design Considerations **Aspect: How to update the progress and saving history on UI** * **Alternative 1 (current choice)**: Clear all the sub components and add new sub components accordingly ** Pros: No matter which progress or history is changed, or what type of change (ie. delete, add, or edit), this change can be handled by the same method each time. ** Cons: It is redundant to clear everything and replace them with new sub components. * **Alternative 2**: Handle different kinds of changes to the progress or history lists. ** Pros: It is a lot faster to only change the sub component that is affected. ** Cons: There are too many cases for how the lists can be changed. (ie. a different change is needed for each of these cases: wish is deleted/edited/created/cleared, or a `wishTransaction` is deleted/added) <file_sep>/src/test/java/seedu/address/model/ModelManagerTest.java package seedu.address.model; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_FRIEND; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_WISHES; import static seedu.address.testutil.TypicalWishes.ALICE; import static seedu.address.testutil.TypicalWishes.BENSON; import java.nio.file.Paths; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.address.model.tag.Tag; import seedu.address.model.wish.WishContainsKeywordsPredicate; import seedu.address.testutil.WishBookBuilder; public class ModelManagerTest { @Rule public ExpectedException thrown = ExpectedException.none(); private ModelManager modelManager = new ModelManager(); @Test public void hasWish_nullWish_throwsNullPointerException() { thrown.expect(NullPointerException.class); modelManager.hasWish(null); } @Test public void hasWish_wishNotInWishBook_returnsFalse() { assertFalse(modelManager.hasWish(ALICE)); } @Test public void hasWish_wishInWishBook_returnsTrue() { modelManager.addWish(ALICE); assertTrue(modelManager.hasWish(ALICE)); } @Test public void hasTagAfterRemoveTag() { Tag tag = new Tag(VALID_TAG_FRIEND); modelManager.addWish(BENSON); modelManager.deleteTag(tag); assertFalse(modelManager .getWishBook() .getWishList() .filtered(wish -> wish.getTags().contains(tag)).size() > 0); } @Test public void getFilteredWishList_modifyList_throwsUnsupportedOperationException() { thrown.expect(UnsupportedOperationException.class); modelManager.getFilteredSortedWishList().remove(0); } @Test public void equals() { WishBook wishBook = new WishBookBuilder().withWish(ALICE).withWish(BENSON).build(); WishTransaction wishTransaction = new WishTransaction(wishBook); WishBook differentWishBook = new WishBook(); WishTransaction differentWishTransaction = new WishTransaction(); UserPrefs userPrefs = new UserPrefs(); // same values -> returns true modelManager = new ModelManager(wishBook, wishTransaction, userPrefs); ModelManager modelManagerCopy = new ModelManager(wishBook, wishTransaction, userPrefs); assertTrue(modelManager.equals(modelManagerCopy)); // same object -> returns true assertTrue(modelManager.equals(modelManager)); // null -> returns false assertFalse(modelManager.equals(null)); // different types -> returns false assertFalse(modelManager.equals(5)); // different wishBook -> returns false assertFalse(modelManager.equals(new ModelManager(differentWishBook, differentWishTransaction, userPrefs))); // different filteredList -> returns false String[] nameKeywords = ALICE.getName().fullName.split("\\s+"); modelManager.updateFilteredWishList(new WishContainsKeywordsPredicate(Arrays.asList(nameKeywords), Arrays.asList(), Arrays.asList(), true)); assertFalse(modelManager.equals(new ModelManager(wishBook, wishTransaction, userPrefs))); // resets modelManager to initial state for upcoming tests modelManager.updateFilteredWishList(PREDICATE_SHOW_ALL_WISHES); // different userPrefs -> returns true UserPrefs differentUserPrefs = new UserPrefs(); differentUserPrefs.setWishBookFilePath(Paths.get("differentFilePath")); assertTrue(modelManager.equals(new ModelManager(wishBook, wishTransaction, differentUserPrefs))); } } <file_sep>/src/test/java/seedu/address/logic/parser/RemarkCommandParserTest.java package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.commands.CommandTestUtil.REMARK_DESC_EMPTY; import static seedu.address.logic.commands.CommandTestUtil.REMARK_DESC_SAMPLE_1; import static seedu.address.logic.commands.CommandTestUtil.REMARK_DESC_SAMPLE_2; import static seedu.address.logic.commands.CommandTestUtil.SAMPLE_REMARK_1; import static seedu.address.logic.commands.CommandTestUtil.SAMPLE_REMARK_EMPTY; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_WISH; import org.junit.Test; import seedu.address.logic.commands.RemarkCommand; public class RemarkCommandParserTest { private static final String MESSAGE_INVALID_FORMAT = String.format( MESSAGE_INVALID_COMMAND_FORMAT, RemarkCommand.MESSAGE_USAGE); private RemarkCommand expectedCommand = new RemarkCommand(INDEX_FIRST_WISH, SAMPLE_REMARK_1); private RemarkCommandParser parser = new RemarkCommandParser(); @Test public void parse_allFieldsPresent_success() { // empty remark assertParseSuccess(parser, INDEX_FIRST_WISH.getOneBased() + REMARK_DESC_EMPTY, new RemarkCommand(INDEX_FIRST_WISH, SAMPLE_REMARK_EMPTY)); // no empty fields assertParseSuccess(parser, INDEX_FIRST_WISH.getOneBased() + REMARK_DESC_SAMPLE_1, expectedCommand); } @Test public void parse_invalidPreamble_failure() { // empty index assertParseFailure(parser, "", MESSAGE_INVALID_FORMAT); // negative index assertParseFailure(parser, "-5" + REMARK_DESC_SAMPLE_1, MESSAGE_INVALID_FORMAT); //zero index assertParseFailure(parser, "0" + REMARK_DESC_SAMPLE_1, MESSAGE_INVALID_FORMAT); // invalid arguments being parsed as preamble assertParseFailure(parser, "5 random string" + REMARK_DESC_SAMPLE_1, MESSAGE_INVALID_FORMAT); } @Test public void parse_multipleRepeatedFields_acceptsLast() { // remark is repeated twice -> second remark is taken assertParseSuccess(parser, INDEX_FIRST_WISH.getOneBased() + REMARK_DESC_SAMPLE_2 + REMARK_DESC_SAMPLE_1, expectedCommand); } @Test public void parse_missingParts_failure() { // missing index assertParseFailure(parser, REMARK_DESC_SAMPLE_1, MESSAGE_INVALID_FORMAT); // missing remark assertParseFailure(parser, "" + INDEX_FIRST_WISH.getOneBased(), MESSAGE_INVALID_FORMAT); } } <file_sep>/src/main/java/seedu/address/model/Model.java package seedu.address.model; import java.util.function.Predicate; import javafx.collections.ObservableList; import seedu.address.commons.core.amount.Amount; import seedu.address.model.wish.Wish; /** * The API of the Model component. */ public interface Model { /** {@code Predicate} that always evaluate to true */ Predicate<Wish> PREDICATE_SHOW_ALL_WISHES = unused -> true; /** Returns the WishTransaction */ WishTransaction getWishTransaction(); /** Clears existing backing model and replaces with the provided new data. */ void resetData(ReadOnlyWishBook newData); /** Returns the unusedFunds of the WishBook. */ String getUnusedFunds(); /** Returns the WishBook. */ ReadOnlyWishBook getWishBook(); /** * Returns true if a wish with the same identity as {@code wish} exists in the wish book. */ boolean hasWish(Wish wish); /** * Deletes the given wish. * The wish must exist in the wish book. */ void deleteWish(Wish target); /** * Adds the given wish. * {@code wish} must not already exist in the wish book. */ void addWish(Wish wish); /** * Replaces the given wish {@code target} with {@code editedWish}. * {@code target} must exist in the wish book. * The wish identity of {@code editedWish} must not be the same as another existing wish in the wish book. */ void updateWish(Wish target, Wish editedWish); /** * Updates the unusedFunds amount by the given {@code change} * @code change The amount to update unusedFunds by. */ void updateUnusedFunds(Amount change); /** Returns an unmodifiable view of the filtered wish list */ ObservableList<Wish> getFilteredSortedWishList(); /** * Updates the filter of the filtered wish list to filter by the given {@code predicate}. * @throws NullPointerException if {@code predicate} is null. */ void updateFilteredWishList(Predicate<Wish> predicate); /** * Returns true if the model has previous wish book states to restore. */ boolean canUndoWishBook(); /** * Returns true if the model has undone wish book states to restore. */ boolean canRedoWishBook(); /** * Restores the model's wish book to its previous state. */ void undoWishBook(); /** * Restores the model's wish book to its previously undone state. */ void redoWishBook(); /** * Saves the current wish book state for undo/redo. */ void commitWishBook(); } <file_sep>/docs/DeveloperGuide.adoc = WishBook - Developer Guide :site-section: DeveloperGuide :toc: :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :experimental: endif::[] :repoURL: https://github.com/CS2103-AY1819S1-T16-1/main By: `Team SE-EDU`      Since: `Jun 2016`      Licence: `MIT` == Setting up === Prerequisites . *JDK `9`* or later + [WARNING] JDK `10` on Windows will fail to run tests in <<UsingGradle#Running-Tests, headless mode>> due to a https://github.com/javafxports/openjdk-jfx/issues/66[JavaFX bug]. Windows developers are highly recommended to use JDK `9`. . *IntelliJ* IDE + [NOTE] IntelliJ by default has Gradle and JavaFx plugins installed. + Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them. === Setting up the project in your computer . Fork this repo, and clone the fork to your computer . Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first) . Set up the correct JDK version for Gradle .. Click `Configure` > `Project Defaults` > `Project Structure` .. Click `New...` and find the directory of the JDK . Click `Import Project` . Locate the `build.gradle` file and select it. Click `OK` . Click `Open as Project` . Click `OK` to accept the default settings . Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. + This will generate all resources required by the application and tests. . Open link:{repoURL}/src/main/java/seedu/url/storage/XmlAdaptedWish.java[`XmlAdaptedWish.java`] and link:{repoURL}/src/main/java/seedu/url/ui/MainWindow.java[`MainWindow.java`] and check for any code errors .. Due to an ongoing https://youtrack.jetbrains.com/issue/IDEA-189060[issue] with some of the newer versions of IntelliJ, code errors may be detected even if the project can be built and run successfully .. To resolve this, place your cursor over any of the code section highlighted in red. Press kbd:[ALT + ENTER], and select `Add '--add-modules=...' to module compiler options` for each error . Repeat this for the test folder as well (e.g. check link:{repoURL}/src/test/java/seedu/url/commons/util/XmlUtilTest.java[`XmlUtilTest.java`] and link:{repoURL}/src/test/java/seedu/url/ui/HelpWindowTest.java[`HelpWindowTest.java`] for code errors, and if so, resolve it the same way) === Verifying the setup . Run the `seedu.url.MainApp` and try a few commands . <<Testing,Run the tests>> to ensure they all pass. === Configurations to do before writing code ==== Configuring the coding style This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify, . Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS) . Select `Editor` > `Code Style` > `Java` . Click on the `Imports` tab to set the order * For `Class count to use import with '\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements * For `Import Layout`: The order is `import static all other imports`, `import java.\*`, `import javax.*`, `import org.\*`, `import com.*`, `import all other imports`. Add a `<blank line>` between each `import` Optionally, you can follow the <<UsingCheckstyle#, UsingCheckstyle.adoc>> document to configure Intellij to check style-compliance as you write code. ==== Updating documentation to match your fork After forking the repo, the documentation will still have the SE-EDU branding and refer to the `CS2103-AY1819S1-T16-1/main` repo. If you plan to develop this fork as a separate product (i.e. instead of contributing to `CS2103-AY1819S1-T16-1/main`), you should do the following: . Configure the <<Docs-SiteWideDocSettings, site-wide documentation settings>> in link:{repoURL}/build.gradle[`build.gradle`], such as the `site-name`, to suit your own project. . Replace the URL in the attribute `repoURL` in link:{repoURL}/docs/DeveloperGuide.adoc[`DeveloperGuide.adoc`] and link:{repoURL}/docs/UserGuide.adoc[`UserGuide.adoc`] with the URL of your fork. ==== Setting up CI Set up Travis to perform Continuous Integration (CI) for your fork. See <<UsingTravis#, UsingTravis.adoc>> to learn how to set it up. After setting up Travis, you can optionally set up coverage reporting for your team fork (see <<UsingCoveralls#, UsingCoveralls.adoc>>). [NOTE] Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork. Optionally, you can set up AppVeyor as a second CI (see <<UsingAppVeyor#, UsingAppVeyor.adoc>>). [NOTE] Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) ==== Getting started with coding When you are ready to start coding, 1. Get some sense of the overall design by reading <<Design-Architecture>>. 2. Take a look at <<GetStartedProgramming>>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::Architecture.png[width="600"] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. [TIP] The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`. `Main` has only one class called link:{repoURL}/src/main/java/seedu/url/MainApp.java[`MainApp`]. It is responsible for, * At app launch: Initializes the components in the correct sequence, and connects them up with each other. * At shut down: Shuts down the components and invokes cleanup method where necessary. <<Design-Commons,*`Commons`*>> represents a collection of classes used by multiple other components. Two of those classes play important roles at the architecture level. * `EventsCenter` : This class (written using https://github.com/google/guava/wiki/EventBusExplained[Google's Event Bus library]) is used by components to communicate with other components using events (i.e. a form of _Event Driven_ design) * `LogsCenter` : Used by many classes to write log messages to the App's log file. The rest of the App consists of four components. * <<Design-Ui,*`UI`*>>: The UI of the App. * <<Design-Logic,*`Logic`*>>: The command executor. * <<Design-Model,*`Model`*>>: Holds the data of the App in-memory. * <<Design-Storage,*`Storage`*>>: Reads data from, and writes data to, the hard disk. Each of the four components * Defines its _API_ in an `interface` with the same name as the Component. * Exposes its functionality using a `{Component Name}Manager` class. For example, the `Logic` component (see the class diagram given below) defines it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. .Class Diagram of the Logic Component image::LogicClassDiagram.png[width="800"] [discrete] ==== Events-Driven nature of the design The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `delete 1`. .Component interactions for `delete 1` command (part 1) image::SDforDeleteWish.png[width="800"] [NOTE] Note how the `Model` simply raises a `WishBookChangedEvent` when the Wish Book data is changed, instead of asking the `Storage` to save the updates to the hard disk. This event also triggers the save of wish histories to disk. The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time. .Component interactions for `delete 1` command (part 2) image::SDforDeleteWishEventHandling.png[width="800"] [NOTE] Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components. The sections below give more details of each component. [[Design-Ui]] === UI component .Structure of the UI Component image::UiClassDiagram.png[width="800"] *API* : link:{repoURL}/src/main/java/seedu/url/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `WishListPanel`, `StatusBarFooter`, `BrowserPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/seedu/url/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`] The `UI` component, * Executes user commands using the `Logic` component. * Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change. * Responds to events raised from various parts of the App and updates the UI accordingly. [[Design-Logic]] === Logic component [[fig-LogicClassDiagram]] .Structure of the Logic Component image::LogicClassDiagram.png[width="800"] *API* : link:{repoURL}/src/main/java/seedu/url/logic/Logic.java[`Logic.java`] . `Logic` uses the `WishBookParser` class to parse the user command. . This results in a `Command` object which is executed by the `LogicManager`. . The command execution can affect the `Model` (e.g. adding a wish) and/or raise events. . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute("delete 1")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeletePersonSdForLogic.png[width="800"] [[Design-Model]] === Model component .Structure of the Model Component image::ModelClassDiagram.png[width="800"] *API* : link:{repoURL}/src/main/java/seedu/url/model/Model.java[`Model.java`] The `Model`, * stores a `UserPref` object that represents the user's preferences. * stores the Wish Book data. * stores the data of wish histories. * exposes an unmodifiable `ObservableList<Wish>` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. The elements of the `ObservableList<Wish>` can also be filtered and sorted to suit the needs of specific commands. * does not depend on any of the other three components. [NOTE] As a more OOP model, we can store a `Tag` list in `Wish Book`, which `Wish` can reference. This would allow `Wish Book` to only require one `Tag` object per unique `Tag`, instead of each `Wish` needing their own `Tag` object. An example of how such a model may look like is given below. + + image:ModelClassBetterOopDiagram.png[width="800"] [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[width="800"] *API* : link:{repoURL}/src/main/java/seedu/url/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the Wish Book data in xml format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.WishBook.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. // tag::implementationmodel[] === Model ==== Wish Model A wish is uniquely identified by its Universal Unique Identifier (UUID) which is generated randomly only once for a particular wish, upon its creation through the `AddCommand`. A wish stores the following primary attributes: * Name * Price * Date * Saved Amount * Url * Remark * Tags * UUID [NOTE] It is impossible for the user to create a duplicate wish as it is impossible to modify a wish's UUID. ==== Wish Priority A wish needs to be prioritised in a specific order such that the wishes with the highest priority will be visible on the top of the list. In WishBook, the priority is determined primarily by the due date of the wish which is stored in every wish's `Date` attribute. Ties are broken by `Name`. Further ties are broken by `UUID` as it is possible for the `Date` and `Name` of two wishes to be identical. The sorting of the displayed results is done by the `filteredSortedWishes` list. The sorting order is specified by `WishComparator`. ==== Design Considerations ===== Aspect: Uniqueness of a Wish * **Alternative 1(current choice):** Identify a `Wish` by a randomly generated UUID. ** Pros: Extremely low probability of collision. ** Pros: No extra maintenance required upon generation as every `Wish` is unique. ** Cons: UUID does not map to any real world entity and it is used strictly for identification. ** Cons: It is more difficult to system test the `AddCommand` with the current group of methods for system tests as UUID is randomly generated each time. * **Alternative 2:** Identify a wish by `Name`, `Price`, `Date`, `Url`, `Tags`. Wishes with identical values for these attributes will be represented by a single `WishCard`. The `WishCard` will be augmented with a `Multiplicity` to indicate the number of identical wishes. ** Pros: WishBook will be more compact and every attribute stored in a `Wish` maps to a real entity. ** Cons: Additional attribute `Multiplicity` may have to be frequently edited as it is another attribute that is affected by multiple commands. * **Alternative 3:** Identify a wish by a new attribute `CreatedTime`, which is derived from the system time when the wish is created. ** Pros: The attribute maps to a real entity. It can be an additional information presented to the user about a wish. ** Cons: There might be collisions in `CreatedTime` if the the system time is incorrect. // end::implementationmodel[] // tag::undoredo[] === Undo/Redo feature ==== Current Implementation The undo/redo mechanism is facilitated by `VersionedWishBook`. It extends `WishBook` with an undo/redo history, stored internally as an `WishBookStateList` and `currentStatePointer`. Additionally, it implements the following operations: * `VersionedWishBook#commit()` -- Saves the current wish book state in its history. * `VersionedWishBook#undo()` -- Restores the previous wish book state from its history. * `VersionedWishBook#redo()` -- Restores a previously undone wish book state from its history. These operations are exposed in the `Model` interface as `Model#commitWishBook()`, `Model#undoWishBook()` and `Model#redoWishBook()` respectively. Given below is an example usage scenario and how the undo/redo mechanism behaves at each step. Step 1. The user launches the application for the first time. The `VersionedWishBook` will be initialized with the initial wish book state, and the `currentStatePointer` pointing to that single url book state. image::UndoRedoStartingStateListDiagram.png[width="800"] Step 2. The user executes `delete 5` command to delete the 5th wish in the wish book. The `delete` command calls `Model#commitWishBook()`, causing the modified state of the url book after the `delete 5` command executes to be saved in the `WishBookStateList`, and the `currentStatePointer` is shifted to the newly inserted url book state. image::UndoRedoNewCommand1StateListDiagram.png[width="800"] Step 3. The user executes `add n/David ...` to add a new wish. The `add` command also calls `Model#commitWishBook()`, causing another modified wish book state to be saved into the `WishBookStateList`. image::UndoRedoNewCommand2StateListDiagram.png[width="800"] [NOTE] If a command fails its execution, it will not call `Model#commitWishBook()`, so the wish book state will not be saved into the `WishBookStateList`. Step 4. The user now decides that adding the wish was a mistake, and decides to undo that action by executing the `undo` command. The `undo` command will call `Model#undoWishBook()`, which will shift the `currentStatePointer` once to the left, pointing it to the previous wish book state, and restores the url book to that state. image::UndoRedoExecuteUndoStateListDiagram.png[width="800"] [NOTE] If the `currentStatePointer` is at index 0, pointing to the initial wish book state, then there are no previous url book states to restore. The `undo` command uses `Model#canUndoWishBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the undo. The following sequence diagram shows how the undo operation works: image::UndoRedoSequenceDiagram.png[width="800"] The `redo` command does the opposite -- it calls `Model#redoWishBook()`, which shifts the `currentStatePointer` once to the right, pointing to the previously undone state, and restores the wish book to that state. [NOTE] If the `currentStatePointer` is at index `WishBookStateList.size() - 1`, pointing to the latest wish book state, then there are no undone url book states to restore. The `redo` command uses `Model#canRedoWishBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the redo. Step 5. The user then decides to execute the command `list`. Commands that do not modify the wish book, such as `list`, will usually not call `Model#commitWishBook()`, `Model#undoWishBook()` or `Model#redoWishBook()`. Thus, the `WishBookStateList` remains unchanged. image::UndoRedoNewCommand3StateListDiagram.png[width="800"] Step 6. The user executes `clear`, which calls `Model#commitWishBook()`. Since the `currentStatePointer` is not pointing at the end of the `WishBookStateList`, all wish book states after the `currentStatePointer` will be purged. We designed it this way because it no longer makes sense to redo the `add n/David ...` command. This is the behavior that most modern desktop applications follow. image::UndoRedoNewCommand4StateListDiagram.png[width="800"] The following activity diagram summarizes what happens when a user executes a new command: image::UndoRedoActivityDiagram.png[width="650"] ==== Design Considerations ===== Aspect: How undo & redo executes * **Alternative 1 (current choice):** Saves the entire wish book. ** Pros: Easy to implement. ** Cons: May have performance issues in terms of memory usage. * **Alternative 2:** Individual command knows how to undo/redo by itself. ** Pros: Will use less memory (e.g. for `delete`, just save the wish being deleted). ** Cons: We must ensure that the implementation of each individual command are correct. ===== Aspect: Data structure to support the undo/redo commands * **Alternative 1 (current choice):** Use a list to store the history of wish book states. ** Pros: Easy for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project. ** Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both `HistoryManager` and `VersionedWishBook`. * **Alternative 2:** Use `HistoryManager` for undo/redo ** Pros: We do not need to maintain a separate list, and just reuse what is already in the codebase. ** Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as `HistoryManager` now needs to do two different things. // end::undoredo[] // tag::savingsHistory[] === Savings History feature ==== Capturing the state of `WishTransaction` The current state of the savings history of the `WishBook` is captured by `VersionedWishTransaction`. `VersionedWishTransaction` extends `WishTransaction` and has an undo/redo history, similar to the implementation of the Undo/Redo feature, and is stored internally as a `wishStateList` and `currentStatePointer`. Additionally, it implements `VersionedModel` and so contains the implementation of the following operations: * `VersionedWishTransaction#commit()` -- Saves the current wish transaction state in its history. * `VersionedWishTransaction#undo()` -- Restores the previous wish transaction state from its history. * `VersionedWishTransaction#redo()` -- Restores a previously undone wish transaction state from its history. These operations are exposed in the `Model` interface as `Model#commitWishBook()`, `Model#undoWishBook()` and `Model#redoWishBook()` respectively. ==== Capturing the state of each `Wish` `WishTransaction` keeps track of the state of all wishes in `WishBook` via a `wishMap` which maps the unique ID of a `Wish` to a list of `Wish` states. `WishTransaction` implements `ActionCommandListener` such that any state changing command performed to a `Wish` or the `WishBook` such as `AddCommand()`, `EditCommand()`, `SaveCommand()`, etc will result in the `WishMap` being updated accordingly in `WishTransaction`. ==== Persistent storage `VersionedWishTransaction`, `WishTransaction` can be easily converted to and from xml using `XmlWishTransactions`. `XmlWishTransactions` is saved as an xml file when the user explicitly closes the window, thereby invoking `MainApp#stop()` which saves the current state of `VersionedWishTransaction` in the `wishStateList` to hard disk. If the user's command triggers a change in the state of the `WishBook`, a `WishBookChangedEvent` will be raised, causing the subscribed `StorageManager` to respond by saving both the current state of the `WishBook` and `WishTransaction` to disk. Given below is an example usage scenario and how the savings history mechanism behaves at each step. Step 1. The user launches the application. The default file path storing the previous state of the `WishTransaction` will be retrieved, unless otherwise specified by the user, and the contents from the xml file will be parsed and converted into a `WishTransaction` object via the `XmlWishTransactions` object. If the file at the specified location is behind the current state of the `WishBook`, content of the `WishTransaction` will be overwritten by the `WishBook`. [NOTE] The `wishStateList` starts off with the initial state of the `WishTransaction` as the first item in the list. Step 2. The user executes `add n/iPhone ...` to add a new wish. The `add` command calls `Model#commitWishBook()`, causing the current state of the modified wish transaction state to be saved into `wishStateList`. As this is a command that changes the state of the `WishBook`, `Model#addWish()` will call `VersionedWishTransaction#addWish()` to add a new wish to the `WishMap`. [NOTE] * If a command fails its execution, it will not call `Model#commitWishBook()`, so the wish transaction state will not be saved into the `wishStateList`. * If the `WishMap` contains an identical wish (such is identified by `Wish#isSameWish()`), then the call to add this wish will fail. As such, the wish will not be added to the `WishMap` or the `WishBook`. Step 3. The user now decides that adding the wish was a mistake, and decides to undo that action by executing the `undo` command. The `undo` command will call `Model#undoWishBook()`, which will shift the `currentStatePointer` once to the left, pointing it to the previous wish transaction state, and restores the wish transaction to that state. [NOTE] If the `currentStatePointer` is at index 0, pointing to the initial wish transaction state, then there are no previous wish transaction states to restore. The `undo` command uses `Model#canUndoWishBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the undo. The `redo` command does the opposite -- it calls `Model#redoWishBook()`, which shifts the `currentStatePointer` once to the right, pointing to the previously undone state, and restores the wish transaction to that state. [NOTE] If the `currentStatePointer` is at index `wishStateList.size() - 1`, pointing to the latest wish transaction state, then there are no undone wish transaction states to restore. The `redo` command uses `Model#canRedoWishBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the redo. Step 4. The user then decides to execute the command `list`. Commands that do not modify the state of the `WishBook`, such as `list`, will usually not call `Model#commitWishBook()`, `Model#undoWishBook()` or `Model#redoWishBook()`. Thus, the `WishBookStateList` remains unchanged. Step 5. The user finally exits the app by clicking on the close button. The most recent state of the `WishTransaction` will be converted into xml format via the the `XmlWishTransactions` object and be saved into the same file path it was first retrieved from. [NOTE] If there was some error saving the current state of the `WishTransaction` to the specified file path in hard disk, an exception will be thrown and a warning will be shown to the user. The current state of the `WishTransaction` object will not be saved to hard disk. // end::savingsHistory[] // tag::wish[] === Add Wish feature ==== Current Implementation The Add Wish feature is executed through an `AddCommand` by the user, which after parsing, is facilitated mainly by the `ModelManager` which implements `Model`. It also affects `versionedWishBook` and `versionedWishTransaction` by adding the resultant wish to both of their respective data structures. After adding a `Wish`, the `filteredSortedWishes` is also updated to reflect the latest version of WishBook. The UI is also prompted to refresh through a `WishBookChangedEvent`. `AddCommandParser` parses the user's input for parameters using prefixes, and checks them against their respective regular expressions (regex), specified in their respective classes. ==== The following prefix/parameter pairs are **compulsory**, where a user's input will be rejected if they are not provided: * `n/`: Name * `p/`: Price * One of the following Date parameters: ** `d/`: Exact expiry date ** `a/`: duration (or lifetime) from time when command is entered The following prefix/parameter pairs are **optional**, where a user's input will be successful even if they are not provided: * `t/`: tags (more than one allowed) * `u/`: product's URL (product page) ==== [NOTE] ==== **Regarding Duration (`a/`) vs Date (`d/`)** * If `d/` is used, a valid Date should be used. ** Date comes in the format of `dd/mm/yyyy`, `dd` being days, `mm` being months, `yyyy` being the year, and the ** Specified date should also be a valid date in the future. * If `a/` is used, a valid Duration should be used. ** length instead of `dd/mm/yyyy` format, the format should be `<years>y<months>m<days>d`. * In any command, only `Duration` or `Date` can be used. Never both. * If an invalid string for date or duration is provided, a warning will be displayed to prompt the user to enter a valid date or duration. ==== Given below is an example usage scenario and how an AddCommand is carried out. Step 1. The user types in a valid `AddCommand`, `add n/1 TB Toshiba SSD p/158 a/200d`, and the current date is 2nd October 2017 (2/10/2017). The `AddCommandParser` will employ `ParserUtil` to parse the attributes specified after each prefix. The parsing of the `Duration` attribute which follows `a/` in the command will be discussed below. Since `Duration` prefix is used, the computation of a wish's expiry date is handled internally in the `ParserUtil` class, which `ParserUtil#parseDate()` parses and converts the input string into a `Period` object (if input is valid), and adds the resultant `Period` to the current `Date` to get the desired `Date` of the `Wish`. The resultant `Wish` will have the following properties: * id: `a randomly-generated UUID` * Name: _1TB Toshiba SSD_ * SavedAmount: 0.00 * Price: 158.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `false` * Expired: `false` The resultant wish is pass into `VersionedWishBook#addWish` and `VersionedWishTransaction#addWish`, which tracks the history of the `WishBook` and `Wish` respectively. The list of wishes shown on the UI is also updated to show all wishes again, as `filteredSortedWishes` is updated to have all wishes in `WishBook` and a `WishBookChangedEvent` is fired. The following sequence diagram shows how an `AddCommand` is processed in WB: image::AddWishSequenceDiagram.png[width="800"] Step 2. Some time later, the user decides that she wants the exact same wish, but duplicated, and enters the exact same command, but with an exact `Date` instead of `Duration`, so the command entered is `add n/1 TB Toshiba SSD p/158 d/20/4/2018`. Since `Date` prefix is used, the `ParserUtil` parses the string into a `Date` object, and the resultant object is used directly for the resultant `Wish`. Similar to in Step 1, the command will be parsed successfully and a second `Wish` will be added, albeit with a different (hidden) id generated. The resultant `Wish` will have the following properties: * id: `another randomly-generated UUID` * Name: _1TB Toshiba SSD_ * SavedAmount: 0.00 * Price: 158.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `false` * Expired: `false` ==== Design Considerations * **Alternative 1 (current choice)**: Different prefixes for `Duration` and `Date`. ** Pros: More focused user experience. User get more specific feedback depending on their preferred way of inputting date if a wrong input was made. If user uses `a/` and enters an incorrect `Duration`, the user will not receive an error message about the correct format for an exact `Date`, and will only be notified of the correct format of a `Duration`. ** Pros: Easier to implement and handle isolate errors related to respective input parameters. ** Cons: More prefixes for user to remember. * **Alternative 2**: Have `Duration` and `Date` use the same prefix. ** Pros: More natural usage of one prefix to determine `Wish` 's desired expiry date. ** Cons: Conflating implementation of `Duration` and `Date`, hence harder to debug. ** Cons: Tricky to implement, as we are parsing one input for two different desired formats. // end::wish[] // tag::save[] === Save Amount feature ==== Current Implementation The Save Amount feature is executed through a `SaveCommand` by the user, which after parsing, is facilitated mainly by the `ModelManager` which implements `Model`. Wish stores the `price` and `savedAmount` of `Wish`, helping to track the progress of the savings towards the `price`. Meanwhile, WishBook stores an `unusedFunds`, which is an unallocated pool of funds that can be used in the future. After adding a saving, the `filteredSortedWishes` in `ModelManager` is updated to reflect the latest observable WishBook. Given below is an example usage scenario and how the SaveCommand behaves at each step: Step 1. The user executes `save 1 10`, to save $10 into an existing wish with `Index` 1 and `Price` $15. The $10 is wrapped in an `Amount` and a `SaveCommand` instance is created with the `Amount`. `Amount` is then used to make an updated instance of the `Wish` at index 1 whose `SavedAmount` will be updated. `Model#updateWish` is then called to update this wish with the old one in `WishBook`. [NOTE] The `Index` of each `Wish` is labelled at the side of the app. The resultant wish will have the following properties: * Name: _1TB Toshiba SSD_ * SavedAmount: 10.00 * Price: 15.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `false` * Expired: `false` [NOTE] `Amount` to be saved can be a negative value where it would mean a withdrawal of money from a particular wish. [NOTE] `SavedAmount` of a wish cannot be negative. This means that an `Amount` cannot be negative enough to cause `SavedAmount` to be negative. Step 2. The user decides to execute `save 1 10` again. However, SaveCommand checks that `savedAmount` > `price`. SaveCommand#execute creates a new updated `Wish` with `savedAmount = wish.getPrice()`. The resultant wish will have the following properties: * Name: _1TB Toshiba SSD_ * SavedAmount: 15.00 * Price: 15.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `true` * Expired: `false` Step 3. The excess amount of $5 is stored in a new `Amount` variable `excess`. SaveCommand#execute then calls Model#updateUnusedFunds(excess) to update the `unusedFunds` in WishBook. In WishBook, the result would be: * unusedFunds: 5.00 Step 4. The user tries to execute `save 1 10` again. However, since the value for Wish#isFulfilled is true, the amount will not be saved. SaveCommand#execute will throw a CommandException, with the message "Wish has already been fulfilled!". The following sequence diagram shows how the save operation works: image::SaveCommandSequenceDiagram.png[width="800"] ==== Design Considerations ===== Aspect: Data structure to support the unusedFunds feature * **Alternative 1 (current choice):** Store it in a `SavedAmount` variable in `WishBook`. ** Pros: Easy to implement. ** Cons: More methods needed when needing to move funds from `unusedFunds` to other wishes. * **Alternative 2:** Store it as a pseudo wish with index 0. ** Pros: It can be treated as another `wish`, hence existing methods can be used without needing to create much more new ones. ** Cons: Requires dealing with an extra wish that has to be hidden on the `WishListPanel` and displayed separately on the UI. We must remember to skip this wish in methods that involve displaying the WishList. // end::save[] // tag::find[] === Find Wish Feature ==== Current Implementation The find mechanism is supported by `FindCommandParser`. It implements `Parser` that implements the following operation: * `FindCommandParser#parse()` -- Checks the arguments for empty strings and throws a `ParseException` if empty string is found. It then splits the arguments using `ArgumentTokenizer#tokenize()` and returns an `ArgumentMultimap`. Keywords of the same prefix are then grouped using `ArgumentMultimap#getAllValues()`. The find mechanism is also facilitated by `FindCommand`. It extends `Command` and implements the following operation: * `FindCommand#execute()` -- Executes the command by updating the current `FilteredSortedWishList` with the `WishContainsKeywordPredicate`. The predicate `WishContainsKeywordsPredicate`, takes in three lists of the keywords for the following attributes: * Name * Tags * Remark and also the `isExactMatch` argument. The result of the predicate is determined by checking whether a `Wish` contains the given keywords at their corresponding attributes. The match threshold is dictated by the value of `isExactMatch`. ==== Example Given below is an example usage scenario and how the Find mechanism behaves at each step. Step 1. The user launches the application for the first time. Step 2. The user executes `find n/wat n/apple t/impor` command to get all wishes whose name contains the keywords 'iphone' or 'tablet'. Step 3. The `FindCommandParser#parse()` is called and the `WishContainsKeywordPredicate` is constructed with the arguments of the find command. Step 4. `FindCommand#execute()` is then called. Step 5. The entire list of wishes is filtered by the predicate `WishContainsKeywordsPredicate`. Step 6. The filtered list of wishes is returned to the GUI. image::FindCommandSequenceDiagram.png[width="800"] ==== Design Considerations ===== Aspect: Argument format * **Alternative 1 (Current choice):** Require the user to prepend every keyword argument with the appropriate Wish attribute prefix. ** Pros: Easier to implement as it easier to match keyword against a Wish if the attribute to match against is known. ** Pros: User has more control over the results returned. ** Cons: User is required to type slightly more. * **Alternative 2:** No prefixes are required in the arguments. Keywords can match with any one of the following chosen wish attributes: `Name`, `Tags` or `Remark`. ** Pros: Less typing required from user. ** Cons: Command might be slightly slower as every keyword has to be checked against all chosen attributes of the wish. ** Cons: User has less control over the results returned. ==== Aspect: Default threshold for match without the exact match flag * **Alternative 1 (Current choice):** Keywords appended to different prefixes are grouped with a logical AND and keywords appended to the same prefixes are grouped with a logical OR when being matched against a `Wish`. ** Pros: A more intuitive way to find wishes. ** Cons: Can be restrictive in some situations. * **Alternative 2:** Keywords appended to different prefixes are grouped with a logical OR and keywords appended to the same prefixes are grouped with a logical OR when being matched against a `Wish`. ** Pros: Search results will be more inclusive. ** Cons: Very slim chance for such a use case. // end::find[] // tag::list[] === List feature The `list -c and list -u` command allows the user to view the list of all wishes, completed and ongoing, respectively. A wish is completed if the savedAmount is greater or equal to the price of the wish. ==== Current Implementation Given below is an example usage scenario and how the list overdue mechanism behaves at each step: . The user executes the command `list -c`. . `model.updateFilteredWishList()` will update the wish list with `WishCompletedPredicate` as the parameter (boolean). `wish.isFulfilled()` is called to check whether the wish is completed or not. . The updated wish list would be reflected on the UI to be displayed to the user. The following sequence diagram shows how the Wish Detail Panel displays its updated content: image::ListCompletedSequenceDiagram.png[width="790"] // end::list[] // tag::redesign[] === Redesign of User Interface The UI has been redesigned to implement the following UI components required for WishBook: * Command Box * Wish List Panel * Wish Detail Panel ==== Wish List Panel The Wish List Panel consists of a list of Wish Card which contains 4 UI elements: * `WishCard#nameLabel` - A `Text` element that displays the wish’s name. * `WishCard#progressLabel` - A `Text` element that displays the wish’s saving progress in percentage format. * `WishCard#tags` - A `FlowPane` element that contains a `Text` element which displays the wish’s assigned tags. * `WishCard#progressBar` - A `progressBar` element that visually presents the percentage of the wish’s current saving progress. Whenever the user adds a new wish or edits an existing wish, a new WishCard containing the wish will be added to the Wish List Panel or the content in the existing WishCard will be updated respectively. The user will be able to view the wish’s current saving progress both in terms of text on the progressLabel (e.g. ’80%’) and the progressBar. Also, the user will be able to see all the tags he/she assigned to categorize the wish. ===== Problem with the old design The UI (MainWindow) constructs the `WishListPanel` by obtaining an `ObservableList` of wish cards from `Model`, this list is assigned when UI starts, and will never be re-assigned. The UI "observes" the list and updates when it is modified. This approach works well for the `WishListPanel` because WishBook contains only 1 list of wish cards. However, the saving history list in the `WishDetailPanel` can not be updated in the same manner because Model component will change its card list’s reference when a user adds a new wish or updates the content of the wish. In this case, the `WishDetailPanel` in UI will not be updated because the card list of which UI has reference to is actually not changed. ===== Design considerations * **Alternative 1 (current choice)**: Have a wishList in `Model` and keep it updated with the current list of cards ** Explanation: The UI needs only 1 reference to this `wishList`, each time user executes any changes, `wishList` is cleared and the new list of cards is copy to the `wishList`. ** Pros: The structure of `Model` and UI component needs not be changed ** Cons: Need to keep a copy of the current card list, copying the whole list of cards for each command operation has bad effect on performance
. * **Alternative 2**: Model component raises an event when its current card list’s reference is changed ** Explanation: When user adds a new wish or executes save, `Model` will raise an event (`WishPanelUpdatedEvent`), which is subscribed by UI, then UI can re-assign its list of cards and update the cards panel accordingly. ** Pros: Better performance ** Cons: Need to re-design `Model` and UI components
 ==== Wish Detail Panel The Wish Detail Panel consists of 3 UI sub-components: * `WishDetailSavingAmount` that contains `Text` elements to display price and the saving progress of the wish * `WishDetailSavingHistory` that contains a `List` of history of saving inputs of the wish * `WishBrowserPanel` that displays `WebView` of the URL of the wish. Whenever the user adds a new wish or edits an existing wish, the content of the wish in Wish Detail Panel will be updated. The user will be able to view the wish’s current saving progress and the history of his/her saving inputs of the wish in the list format. Also, the user will be able to browse through the wish’s product page via its assigned URL. ===== Current Implementation Every time a new Wish is added or an existing wish is updated by the commands such as save, it raises a `WishDataUpdatedEvent`. The UI will then handle that event and update the `WishDetailPanel` with the new version of wish. Given below is an example usage scenario and how the WishBook behaves and `WishDetailPanel` is updated at each step: . The user executes the command `save 1 1000`. [NOTE] If a command fails its execution, WishDataUpdatedEvent will not be posted. . The save command updates the model with the new wish and raises a new `WishDataUpdatedEvent`. . `WishDetailSavingAmount` and `WishDetailSavingHistory` responds to the `WishDataUpdatedEvent` with `WishListPanel#handleWishUpdatedEvent()`. . The `WishDetailSavingAmount` updates the wish’s current saving progress when `WishDetailSavingAmount#loadWishDetails` is called. . The progress is calculated from when `Wish#getProgress` is called. The value is saveAmount / price. Then the progress label for the wish is set to that fraction. . The `WishDetailSavingHistory` updates the wish’s saving history list when `WishDetailSavingHistory#loadWishDetails` is called. . The saving history list is cleared. . The new set of history entry is retrieved from `wishTransaction#getWishMap` and the saved amount is calculated from subtracting previous saving amount from the next one. . The saving history list is now filled with the new list of updated saving history. The following sequence diagram shows how the Wish Detail Panel displays its updated content: image::WishDetailPanelSequenceDiagram.png[width="790"] ===== Design Considerations **Aspect: How to update the progress and saving history on UI** * **Alternative 1 (current choice)**: Clear all the sub components and add new sub components accordingly ** Pros: No matter which progress or history is changed, or what type of change (ie. delete, add, or edit), this change can be handled by the same method each time. ** Cons: It is redundant to clear everything and replace them with new sub components. * **Alternative 2**: Handle different kinds of changes to the progress or history lists. ** Pros: It is a lot faster to only change the sub component that is affected. ** Cons: There are too many cases for how the lists can be changed. (ie. a different change is needed for each of these cases: wish is deleted/edited/created/cleared, or a `wishTransaction` is deleted/added) // end::redesign[] // tag::savingsNotifications[] === [Proposed] Savings Notifications ==== Justification Some users may have many wishes, all of which have a different targeted date of completion and different price. It may thus be difficult for users to keep track of how much they need to consistently save to fulfil their various wishes on time. This Savings Notification feature will allow users to opt for daily/weekly/monthly notifications for each specific wish, reminding them of the amount that they need to save at the beginning of the chosen time period. This will help users to consistently save towards their wishes. // end::savingsNotifications[] === Logging We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations. * The logging level can be controlled using the `logLevel` setting in the configuration file (See <<Implementation-Configuration>>) * The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level * Currently log messages are output through: `Console` and to a `.log` file. *Logging Levels* * `SEVERE` : Critical problem detected which may possibly cause the termination of the application * `WARNING` : Can continue, but with caution * `INFO` : Information showing the noteworthy actions by the App * `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size [[Implementation-Configuration]] === Configuration Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: `config.json`). == Documentation We use asciidoc for writing documentation. [NOTE] We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. === Editing Documentation See <<UsingGradle#rendering-asciidoc-files, UsingGradle.adoc>> to learn how to render `.adoc` files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time. === Publishing Documentation See <<UsingTravis#deploying-github-pages, UsingTravis.adoc>> to learn how to deploy GitHub Pages using Travis. === Converting Documentation to PDF format We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages. Here are the steps to convert the project documentation files to PDF format. . Follow the instructions in <<UsingGradle#rendering-asciidoc-files, UsingGradle.adoc>> to convert the AsciiDoc files in the `docs/` directory to HTML format. . Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`. . Within Chrome, click on the `Print` option in Chrome's menu. . Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below. .Saving documentation as PDF files in Chrome image::chrome_save_as_pdf.png[width="300"] [[Docs-SiteWideDocSettings]] === Site-wide Documentation Settings The link:{repoURL}/build.gradle[`build.gradle`] file specifies some project-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how all documentation files within this project are rendered. [TIP] Attributes left unset in the `build.gradle` file will use their *default value*, if any. [cols="1,2a,1", options="header"] .List of site-wide attributes |=== |Attribute name |Description |Default value |`site-name` |The name of the website. If set, the name will be displayed near the top of the page. |_not set_ |`site-githuburl` |URL to the site's repository on https://github.com[GitHub]. Setting this will add a "View on GitHub" link in the navigation bar. |_not set_ |`site-seedu` |Define this attribute if the project is an official SE-EDU project. This will render the SE-EDU navigation bar at the top of the page, and add some SE-EDU-specific navigation items. |_not set_ |=== [[Docs-PerFileDocSettings]] === Per-file Documentation Settings Each `.adoc` file may also specify some file-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how the file is rendered. Asciidoctor's https://asciidoctor.org/docs/user-manual/#builtin-attributes[built-in attributes] may be specified and used as well. [TIP] Attributes left unset in `.adoc` files will use their *default value*, if any. [cols="1,2a,1", options="header"] .List of per-file attributes, excluding Asciidoctor's built-in attributes |=== |Attribute name |Description |Default value |`site-section` |Site section that the document belongs to. This will cause the associated item in the navigation bar to be highlighted. One of: `UserGuide`, `DeveloperGuide`, ``LearningOutcomes``{asterisk}, `AboutUs`, `ContactUs` _{asterisk} Official SE-EDU projects only_ |_not set_ |`no-site-header` |Set this attribute to remove the site navigation bar. |_not set_ |=== === Site Template The files in link:{repoURL}/docs/stylesheets[`docs/stylesheets`] are the https://developer.mozilla.org/en-US/docs/Web/CSS[CSS stylesheets] of the site. You can modify them to change some properties of the site's design. The files in link:{repoURL}/docs/templates[`docs/templates`] controls the rendering of `.adoc` files into HTML5. These template files are written in a mixture of https://www.ruby-lang.org[Ruby] and http://slim-lang.com[Slim]. [WARNING] ==== Modifying the template files in link:{repoURL}/docs/templates[`docs/templates`] requires some knowledge and experience with Ruby and Asciidoctor's API. You should only modify them if you need greater control over the site's layout than what stylesheets can provide. The SE-EDU team does not provide support for modified template files. ==== [[Testing]] == Testing === Running Tests There are three ways to run tests. [TIP] The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. *Method 1: Using IntelliJ JUnit test runner* * To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'` * To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'` *Method 2: Using Gradle* * Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`) [NOTE] See <<UsingGradle#, UsingGradle.adoc>> for more info on how to run tests using Gradle. *Method 3: Using Gradle (headless)* Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running. To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`) === Types of tests We have two types of tests: . *GUI Tests* - These are tests involving the GUI. They include, .. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package. .. _Unit tests_ that test the individual components. These are in `seedu.url.ui` package. . *Non-GUI Tests* - These are tests not involving the GUI. They include, .. _Unit tests_ targeting the lowest level methods/classes. + e.g. `seedu.url.commons.StringUtilTest` .. _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). + e.g. `seedu.url.storage.StorageManagerTest` .. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. + e.g. `seedu.url.logic.LogicManagerTest` === Troubleshooting Testing **Problem: `HelpWindowTest` fails with a `NullPointerException`.** * Reason: One of its dependencies, `HelpWindow.html` in `src/main/resources/docs` is missing. * Solution: Execute Gradle task `processResources`. == Dev Ops === Build Automation See <<UsingGradle#, UsingGradle.adoc>> to learn how to use Gradle for build automation. === Continuous Integration We use https://travis-ci.org/[Travis CI] and https://www.appveyor.com/[AppVeyor] to perform _Continuous Integration_ on our projects. See <<UsingTravis#, UsingTravis.adoc>> and <<UsingAppVeyor#, UsingAppVeyor.adoc>> for more details. === Coverage Reporting We use https://coveralls.io/[Coveralls] to track the code coverage of our projects. See <<UsingCoveralls#, UsingCoveralls.adoc>> for more details. === Documentation Previews When a pull request has changes to asciidoc files, you can use https://www.netlify.com/[Netlify] to see a preview of how the HTML version of those asciidoc files will look like when the pull request is merged. See <<UsingNetlify#, UsingNetlify.adoc>> for more details. === Making a Release Here are the steps to create a new release. . Update the version number in link:{repoURL}/src/main/java/seedu/url/MainApp.java[`MainApp.java`]. . Generate a JAR file <<UsingGradle#creating-the-jar-file, using Gradle>>. . Tag the repo with the version number. e.g. `v0.1` . https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created. === Managing Dependencies A project often depends on third-party libraries. For example, Wish Book depends on the http://wiki.fasterxml.com/JacksonHome[Jackson library] for XML parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives. + a. Include those libraries in the repo (this bloats the repo size) + b. Require developers to download those libraries manually (this creates extra work for developers) [appendix] == Product Scope *Target user profile*: * has a need to manage savings for a significant number of items to buy * prefer desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps *Value proposition*: manage savings faster than a typical mouse/GUI driven app [appendix] == User Stories Priorities: High (must have) - `* * \*`, Medium (nice to have) - `* \*`, Low (unlikely to have) - `*` [width="59%",cols="22%,<23%,<25%,<30%",options="header",] |======================================================================= |Priority |As a ... |I want to ... |So that I can... |`* * *` |new user |see usage instructions |refer to instructions when I forget how to use the App |`* * *` |user |add a new wish |keep track of the things I want to purchase |`* * *` |user |add savings to selected wishes | make faster progress towards certain wishes |`* * *` |user |delete a wish |remove items that I no longer need |`* * *` |user |find a wish by name |locate details of a wish without having to go through the entire list |`* * *` |user |view all fulfilled wishes | so I can keep track of items I have bought |`* * *` |user |view all past savings for my wishes | have a better idea of my saving habits in general |`* * *` |user |view all my wishes | monitor the progress I have made in all my wishes |`* * *` |user |undo past commands | reverse wrong commands |`* *` |user |distribute a saving to a few wishes | make equal progress to a few of my wishes |`* *` |user |rank my wishes | prioritise certain wishes over others so that money can be allocated accordingly |`* *` |user |transfer money from one wish to another | progress towards other wishes faster |`* *` |user |withdraw from savings | spend the money if need be |`* *` |user |reorder the priority of a wish | fulfil the specified wish faster |`* *` |user |save money without a wish | allocate my savings to a wish later |`*` |user |receive email reminders about wishes that are due |be more mindful of my savings to fulfil wishes |`*` |user |view all past savings for a particular wish |have a better idea of my saving habits for a wish |======================================================================= [appendix] == Use Cases (For all use cases below, the *System* is the `WishBook` and the *Actor* is the `user`, unless specified otherwise) [discrete] === Use case: Add wish *MSS* 1. *Actor* enters a wish with Name, Date, Price. 2. *System* adds wish to the wish list. + Use case ends. *Extensions* [none] * 2a. *Actor* fails to specify any of the compulsory fields (Name, Price, and Date/Duration). + [none] ** 2a1. *System* shows a correct Add command usage with example. + Use case ends. * 2b. *Actor* enters incorrectly formatted arguments. + [none] ** 2b1. *System* shows Add command usage. ** 2b2. *Actor* is prompted to enter a valid argument in a specific format shown. + Use case ends. [discrete] === Use case: Delete wish *MSS* 1. *Actor* requests to list wishes. 2. *System* shows a list of wishes. 3. *Actor* requests to delete a specific wish in the list. 4. *System* deletes the wish. + Use case ends. *Extensions* [none] * 2a. The list is empty. + Use case ends. * 3a. The given index is invalid. + [none] ** 3a1. *System* shows an error message. + Use case resumes at step 2. ** 3b1. Wish requested to be deleted has a non-zero savings amount. ** 3b2. *System* displays warning to user that wish to be deleted has a non-zero savings amount. + Use case resumes at step 2. [discrete] === Use case: Edit wish *MSS* 1. *Actor* requests to edit wish. 2. *System* updates wish and shows updated wish to *Actor*. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded wishes. + [none] ** 1a1. *Actor* is prompted to add a wish. + Use case ends. * 1b. *Actor* enters invalid arguments + [none] ** 1b1. *System* shows Edit command usage. ** 1b2. *Actor* is prompted to enter a valid argument. + Use case ends. [discrete] === Use case: Find wishes *MSS* 1. *Actor* specifies the search predicate. 2. *System* shows all wishes matching the given search predicate. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded wishes. + [none] ** 1a1. *System* shows dialog notifying *Actor* that no relevant results can be found. + Use case ends. * 1b. *Actor* enters invalid arguments + [none] ** 1b1. *System* shows Find command usage. ** 1b2. *Actor* is prompted to enter a valid argument. + Use case ends. * 1c. *System* unable to find any matching wishes. + [none] ** 1c1. *System* shows dialog notifying *Actor* that no relevant results can be found. + Use case ends. * 1d. *Actor* enters empty prefixes for arguments. + [none] ** 1c1. *System* shows all wishes in the WishBook. + Use case ends. [discrete] === Use case: Move amount between wishes *MSS* 1. *Actor* specifies the origin wish index, the destination wish index, and amount to move. 2. *System* moves specified amount from origin wish to destination wish. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded wishes. + [none] ** 1a1. *Actor* is prompted to add a wish. + Use case ends. * 1b. *Actor* enters invalid arguments. + [none] ** 1b1. *System* shows Move command usage. ** 1b2. *Actor* is prompted to enter a valid argument. + Use case ends. * 1c. *Actor* enters the same index for origin wish and destination wish. + [none] ** 1c1. *System* shows Move command usage. ** 1c2. *Actor* is prompted to enter a valid argument. + Use case ends. * 1d. The amount to move is greater than the existing saved amount in the origin wish. + [none] ** 1d1. *System* reports that saved amount of wish cannot become negative. + Use case ends. * 1e. The amount moved to destination wish exceeds the amount needed to fulfil the wish. + [none] ** 1e1. *System* moves to destination wish the required amount needed to fulfil it. ** 1e2. *System* moves the excess amount to unused funds. + Use case ends. * 1f. *Actor* specifies unused funds as the origin wish. + [none] ** 1f1. *System* moves amount from unused funds to the destination wish. + Use case ends. * 1g. *Actor* specifies unused funds as the destination wish. + [none] ** 1g1. *System* moves amount from origin wish to unused funds. + Use case ends. [discrete] === Use case: Save money for a wish *MSS* 1. *Actor* enters [underline]#X# amount of money to be saved. 2. *System* transfers [underline]#X# to the wish with the specified index. + Use case ends. *Extensions* [none] * 1a. *Actor* specifies to allocate the money to unused funds. + [none] ** 1a1. *System* adds [underline]#X# to unused funds. + Use case ends. * 1b. *System* has no recorded wishes. + [none] ** 1b1. *Actor* is prompted to add a wish. + Use case ends. * 1c. *Actor* enters an invalid value of money to be saved. + [none] ** 1c1. *Actor* is prompted to enter a valid value. + Use case ends. * 1d. *Actor* enters an amount of money that causes the wish's saved amount to exceed the amount needed to fulfil the wish. + [none] ** 1d1. *System* adds the required amount to fulfil the saved amount of the wish at the specified index. ** 1d2. *System* adds the excess amount to unused funds. + Use case ends. * 1e. *Actor* enters an amount that causes the wish's resulting saved amount to become negative. + [none] ** 1e1. *Actor* is prompted to enter a valid value. + Use case ends. [discrete] === Use case: View all wishes *MSS* 1. *Actor* requests to view all wishes. 2. *System* shows all wishes. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded wishes. + [none] ** 1a1. User is prompted to add a wish. + Use case ends. * 1b. *System* has no recorded wishes. + [none] ** 1b1. *System* shows dialog notifying *Actor* that there are no such wishes. + Use case ends. [discrete] === Use case: View uncompleted wishes *MSS* 1. *Actor* requests to view uncompleted wishes. 2. *System* shows all uncompleted wishes. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded uncompleted wishes. + [none] ** 1a1. User is prompted to add a wish. + Use case ends. * 1b. *System* has no recorded uncompleted wishes. + [none] ** 1b1. *System* shows dialog notifying *Actor* that there are no such wishes. + Use case ends. [discrete] === Use case: View completed wish list *MSS* 1. *Actor* requests to list completed wishes. 2. *System* shows a list of completed wishes. + Use case ends. *Extensions* [none] * 2a. List is empty. + Use case ends. [discrete] === Use case: View command history *MSS* 1. *Actor* requests to view history of commands entered. 2. *System* shows all commands entered. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded commands. + [none] ** 1a1. User is prompted to enter a command. + Use case ends. [discrete] === Use case: View savings history *MSS* 1. *Actor* requests to view history of savings entered. 2. *System* shows all savings entered, from newest to oldest. + Use case ends. *Extensions* [none] * 1a. *System* has no recorded savings. + [none] ** 1a1. User is prompted to enter a saving. + Use case ends. [appendix] == Non Functional Requirements . Should work on any <<mainstream-os,mainstream OS>> as long as it has Java `9` or higher installed. . Should be able to hold up to 1000 wishes without user experiencing a drop in application performance. . A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse. . User data can be transferred across different machines (of different platforms). . The software should not use a DBMS (Database Management System) to store data. . User data is stored locally. . User data is human readable and can be edited. . Friendly towards color-blind users. . Command Line Interface (CLI) is the primary mode of input. GUI is used mainly for visual feedback rather than to collect input. Usage of mouse should be minimized. . The software should follow the Object-Oriented Paradigm. . The software should work without requiring an installer. [appendix] == Glossary [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X. [[index]] Index:: Order of priority of a wish. [[wish]] Wish:: Something the user wants to save up money for. [[wishlist]] Wishlist:: A record of all wishes added by the user. [appendix] == Instructions for Manual Testing Given below are instructions to test the app manually. [NOTE] These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing. === Launch and Shutdown . Initial launch .. Download the jar file and copy into an empty folder .. Double-click the jar file + Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum. . Saving window preferences .. Resize the window to an optimum size. Move the window to a different location. Close the window. .. Re-launch the app by double-clicking the jar file. + Expected: The most recent window size and location is retained. === Deleting a wish . Deleting a wish while all wishes are listed .. Prerequisites: List all wishes using the list command. Multiple wishes in the list. Wish at index 1 should be fulfilled. .. Test case: `delete 1` + Expected: First wish is deleted from the list. Details of the deleted wish shown in the status message. Unused funds will not be updated as the product has already been bought. Deleted wish details and amount in unused funds shown in status message. Timestamp in the status bar is updated. .. Test case: `delete 2` + Expected: Second wish is deleted. Money in the wish will be transferred to unused funds. Deleted wish details and amount in unused funds shown in status message. Timestamp in the status bar is updated. .. Test Case: `delete` + Expected: Error. Invalid command format message shown in unused funds. .. Test Case: `delete -1` + Expected: Error. Invalid command format message shown in unused funds. .. Other incorrect delete commands to try: `delete x` (where x is larger than the list size) + Expected: Error. Invalid wish provided message in message status. === Saving to a wish . Saving to a wish .. Prerequisites: Add a new wish with the add command with a date earlier than the earliest wish in the WishBook. If the current date is past the earliest wish’s date, delete the first wish until this is no longer true and then add a new wish earlier than the earliest wish in the WishBook. .. Test case: `save 1 0` + Expected: 0.00 saved to first wish. Details of saved amount and the remaining amount left for completion shown in the status message. Timestamp in the status bar is updated. .. Test case: `save 1 0.01` + Expected: 0.01 saved to first wish. Details of saved amount and the remaining amount left for completion shown in the status message. Timestamp in the status bar is updated. .. Test case: `save 1 -0.01` + Expected: 0.01 removed from first wish. Details of removed amount and the remaining amount left for completion shown in the status message. Timestamp in the status bar is updated. .. Test case: `save 1 [VALUE LARGER THAN WISH PRICE]` + Expected: Wish will be 100% and fulfilled. Details of the excess amount saved and the unused funds value shown in status message. .. Test case: `save 1 5` + Expected: Unable to save to wish. Wish already fulfilled message shown in status message. Timestamp in status bar is updated. .. Other incorrect delete commands to try: `save 2 0.001`, `save 2 12.`, `save 2 12@` + Expected: Similar to previous. === Moving funds between wishes . Moving funds between 2 wishes: .. Prerequisites: Wish at index 1 should be fulfilled. If it is not, `save` until it is. The other wishes used in the subsequent commands should not be fulfilled. .. Test case: `move 1 2 50` + Expected: No money moved from wish 1 to 2. Wish already fulfilled status message shown. .. Test case: `move 2 3 [AMOUNT SMALLER THAN SAVED AMOUNT AT FROM_INDEX]` + Expected: Specified amount moved from wish 2 to wish 3. Moved message shown in status message. Timestamp in status bar is updated. .. Test case: `move 2 3 [AMOUNT LARGER THAN SAVED AMOUNT AT FROM_INDEX]` + Expected: No money moved from wish 1 to 2. `FROM_INDEX` does not contain the specified amount shown in status message. .. Test case: `move 2 3 [AMOUNT LARGER THAN SAVED AMOUNT AT TO_INDEX]` + Expected: Money moved from wish 2 to 3. Wish 3 is fulfilled. Excess money goes to unused funds(index 0). Moved amount, excess and updated unused funds shown in status message. Timestamp in status bar is updated. ed. Incorrect move commands to try: `move 2 3 -50`, `move 2 3 0.0001` Expected: No money will be moved. Appropriate error message shown in status message. === Adding a wish . Adding to a wish . Positive test cases .. Prerequisites: None. Duplicate Wishes can exist and have the same user-defined properties. .. Test case: `add n/PS4 Golden Pro d/25/12/2018 p/499.99` + Expected: A new Wish named “PS4 Golden Pro”, priced at $499.99, and expiry date set to 25th December 2018, default URL of “www.amazon.com” will be added to the list of Wishes. Status message shows the details of the newly added Wish. .. Test case: `add n/PS4 Golden Pro d/25/12/2018 p/499.99 t/technology` + Expected: A new Wish named “PS4 Golden Pro”, priced at $499.99, and expiry date set to 25th December 2018, default URL of “www.amazon.com”, with a tag named “technology”, will be added to the list of Wishes. Status message shows the details of the newly added Wish. Selecting on the newly added Wish will also bring up the Amazon’s homepage on the right side of the Detail Panel. .. Test case: `add n/PS4 Golden Pro a/60d p/499.99` + Expected: A new Wish named “PS4 Golden Pro”, priced at $499.99, and expiry date set to your current date plus 60 days, default URL of “www.amazon.com” will be added to the list of Wishes. Status message shows the details of the newly added Wish. Selecting on the newly added Wish will also bring up the Amazon’s homepage on the right side of the Detail Panel. .. Test case: `add n/PS4 Golden Pro a/2y p/499.99 u/www.google.com` + Expected: A new Wish named “PS4 Golden Pro”, priced at $499.99, and expiry date set to your current date plus 2 years, default URL of “www.amazon.com” will be added to the list of Wishes. Status message shows the details of the newly added Wish. Selecting on the newly added Wish will also bring up the Google search engine webpage on the right side of the Detail Panel. . Negative test cases .. Prerequisites: None. .. Test case: `add n/PS’4 Golden Pro a/30d p/499.99` + Expected: Status message shows that a Wish’s name can only contain alphanumeric numbers and spaces, and should not be blank. .. Test case: `add n/ a/30d p/499.99` + Expected: Status message shows that a Wish’s name can only contain alphanumeric numbers and spaces, and should not be blank. .. Test case: `add n/PS4 Golden Pro a/30d3y p/499.99` + Expected: Status message shows the given time format is invalid, and also shows the user’s time input. .. Test case: `add n/PS4 Golden Pro d/30.30.9999 p/499.99` + Expected: Status message shows that the time should be of format: dd/mm/yy. .. Test case: `add n/PS4 Golden Pro a/3d p/499.9999999` + Expected: Status message states that price value should only contain numbers, and at most two numbers after the decimal point. .. Test case: `add n/PS4 Golden Pro a/3d p/abc.de` + Expected: Status message states that price value should only contain numbers, and at most two numbers after the decimal point. .. Test case: `add n/PS4 Golden Pro a/-1d p/22.22` + Expected: Status message states that the given expiry date should be after the current date. .. Test case: `add n/PS4 Golden Pro d/25/12/1111 p/22.22` + Expected: Status message states that the given expiry date should be after the current date. .. Test case: `add n/PS4 Golden Pro a/1d` + Expected: Status message states that this is an invalid command format, and shows the correct usage of add command. .. Test case: `add n/PS4 Golden Pro d/25/12/2018 p/22.22 u/abc def.com` + Expected: Status message states that URLs cannot have whitespaces. === Listing out wishes . Listing out wishes in the list . Prerequisites: Have both completed (amount saved more than price) and uncompleted wishes. .. Test case: `list` + Expected: All wishes in WishBook is listed. .. Test case: `list -c` + Expected: Only wishes that are completed will be shown on the list. .. Test case: `list -u` + Expected: Only wishes that are uncompleted will be shown on the list. === Finding wishes . Finding a wish by name, tags or remark: . Prerequisites: None .. Test case: `find r/Alice` + Expected: Returns all the wishes whose remark contains “Alice” case insensitive. Number of wishes found is listed in status message. Only matched wishes visible in WishList. .. Test case: `find t/neigh t/paren` + Expected: Returns all the wishes whose tags contain the keywords “neigh” or “paren”. Number of wishes found is listed in status message. Only matched wishes visible in WishList. .. Test case: `find n/EVG t/PS` + Expected: Returns all wishes whose name contains “EVG” and whose tag contains “PS” case insensitve. Number of wishes found is listed in status message. Only matched wishes visible in WishList. .. Test case: `find n/EVG n/PS t/neigh t/paren` + Expected: Returns all wishes whose name contains (“EVG” or “PS”) and (“neigh” or “paren”). Number of wishes found is listed in status message. Only matched wishes visible in WishList. .. Test case: `find` + Expected: Invalid command. Invalid command format message shown in status message. .. Other incorrect delete commands to try: `find test`, `find d/22/10/1996`. + Expected: Similar to previous. === Saving data . Dealing with missing/corrupted data files .. Prerequisites: content of WishBook.xml and wishTransaction.xml files will be used to load data for a new session of WishBook. If data is missing from any of these files, data will be lost from subsequent sessions of WishBook unless the xml file data is restored and in proper format. .. Test case (gracefully exiting app assuming that WishBook contains more than 1 wish): `save 1 10` and then `exit` + Expected: when a new session is started, WishBook should contain all wishes from the previous session. Wish in which the save command is performed for should have its saving history and save amount updated. .. Test case (WishBook data and wishTransaction data should be backed up everytime the state of WishBook changes): `save 1 10` + Expected: assuming WishBook contains more than 1 wish, the execution of the save command should cause the WishBook.xml and wishTransaction.xml files to be updated with a new save amount. .. Test case (empty WishBook to simulate missing data) Copy the contents of the empty xml file after executing the clear command to simulate missing file data into WishBook.xml at the file path specified in the save location (which is specified in the preferences.json file) + Expected: When the WishBook is loaded, all wish data should be absent. .. Test case (corrupted data): delete data for 1 wish currently in WishBook by editing the WishBook.xml file. + Expected: assuming that the data format of the xml file is valid, WishBook should load the content of the WishBook based on the data present in WishBook.xml file (without the deleted wish data). If the data format of the xml file is invalid the WishBook will not load properly and an error message should appear. <file_sep>/src/test/java/seedu/address/testutil/TypicalWishes.java package seedu.address.testutil; import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_1; import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_2; import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_CHARLES; import static seedu.address.logic.commands.CommandTestUtil.VALID_ID_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_ID_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_ID_CHARLES; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_CHARLES; import static seedu.address.logic.commands.CommandTestUtil.VALID_PRICE_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_PRICE_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_PRICE_CHARLES; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_FRIEND; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND; import static seedu.address.logic.commands.CommandTestUtil.VALID_URL_AMY; import static seedu.address.logic.commands.CommandTestUtil.VALID_URL_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_URL_CHARLES; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.address.model.WishBook; import seedu.address.model.WishTransaction; import seedu.address.model.wish.Wish; /** * A utility class containing a list of {@code Wish} objects to be used in tests. */ public class TypicalWishes { /* Following wishes must have unique names and must be in ascending dates. Or else the * following tests will fail: * EditCommandTest#execute_duplicateWishFilteredList_failure * CommandTestUtil#showWishAtIndex */ public static final Wish ALICE = new WishBuilder().withName("<NAME>") .withUrl("https://www.lazada.sg/products/" + "ps4-092-hori-real-arcade-pron-hayabusaps4ps3pc-i223784444-s340908955.html") .withDate("4/09/2020") .withPrice("94.35") .withTags("friends") .withSavedAmountIncrement("0.00") .withId("bf557b11-6b8d-4aa0-83cb-b730253bb6e2") .build(); public static final Wish BENSON = new WishBuilder().withName("<NAME>") .withUrl("https://www.amazon.com/Apple-iPhone-Fully-Unlocked-32GB/dp/B0731HBTZ7") .withDate("21/09/2020") .withPrice("98.76") .withTags("owesMoney", "friends") .withSavedAmountIncrement("0.00") .withId("b38ceb7a-2cd3-48c9-860c-3918155e4fd6") .build(); public static final Wish CARL = new WishBuilder().withName("<NAME>") .withPrice("98.76") .withDate("21/09/2020") .withUrl("https://www.amazon.com/EVGA-GeForce-Gaming-GDDR5X-Technology/dp/B0762Q49NV") .withSavedAmountIncrement("0.00") .withId("a758eec0-6056-4737-9c05-d3bf60f6f67d") .build(); public static final Wish DANIEL = new WishBuilder().withName("<NAME>") .withPrice("87.65") .withDate("21/11/2023") .withUrl("https://www.amazon.com/Logitech-Mechanical-Keyboard-Romer-Switches/dp/B071VHYZ62") .withTags("friends") .withSavedAmountIncrement("0.00") .withId("a2dde843-9cde-4417-946d-40bc465462cf") .build(); public static final Wish ELLE = new WishBuilder().withName("<NAME>") .withPrice("94.82") .withDate("19/07/2020") .withUrl("https://www.amazon.com/EVGA-GeForce-Gaming-GDDR5X-Technology/dp/B0762Q49NV") .withSavedAmountIncrement("0.00") .withId("6387ec7d-da35-4569-a549-a8332e650429") .build(); public static final Wish FIONA = new WishBuilder().withName("<NAME>") .withPrice("94.82") .withDate("24/09/2010") .withUrl("https://www.lazada.sg/products/" + "nintendo-switch-neon-console-1-year-local-warranty-best-seller-i180040203-s230048296.html") .withSavedAmountIncrement("0.00") .withId("dcb605d6-af12-444d-a2ee-44b5fccfe137") .build(); public static final Wish GEORGE = new WishBuilder().withName("<NAME>") .withPrice("94.82") .withDate("24/09/2019") .withUrl("https://www.amazon.com/EVGA-GeForce-Gaming-GDDR5X-Technology/dp/B0762Q49NV") .withSavedAmountIncrement("0.00") .withId("32ea1ae8-f1da-435c-a6a8-ca501a9650c1") .build(); // Manually added public static final Wish HOON = new WishBuilder().withName("<NAME>") .withPrice("84.82") .withDate("28/08/2019") .withUrl("https://www.amazon.com/EVGA-GeForce-Gaming-GDDR5X-Technology/dp/B0762Q49NV") .withSavedAmountIncrement("0.00") .withId("ace52214-c1d5-4dff-a05c-b0e6ac1c5fa9") .build(); public static final Wish IDA = new WishBuilder().withName("<NAME>") .withPrice("84.82") .withDate("02/09/2019") .withUrl("https://www.amazon.com/EVGA-GeForce-Gaming-GDDR5X-Technology/dp/B0762Q49NV") .withSavedAmountIncrement("0.00") .withId("c8e1624c-9d91-4c3d-85e1-dee255126944") .build(); // Manually added - Wish's details found in {@code CommandTestUtil} public static final Wish AMY = new WishBuilder().withName(VALID_NAME_AMY).withPrice(VALID_PRICE_AMY) .withDate(VALID_DATE_1).withUrl(VALID_URL_AMY).withTags(VALID_TAG_FRIEND) .withSavedAmountIncrement("0.00") .withId(VALID_ID_AMY) .build(); public static final Wish BOB = new WishBuilder().withName(VALID_NAME_BOB).withPrice(VALID_PRICE_BOB) .withDate(VALID_DATE_2).withUrl(VALID_URL_BOB) .withTags(VALID_TAG_HUSBAND, VALID_TAG_FRIEND).withSavedAmountIncrement("0.00") .withId(VALID_ID_BOB) .build(); public static final Wish CHARLES = new WishBuilder().withName(VALID_NAME_CHARLES).withPrice(VALID_PRICE_CHARLES) .withDate(VALID_DATE_CHARLES).withUrl(VALID_URL_CHARLES) .withId(VALID_ID_CHARLES) .build(); public static final String KEYWORD_MATCHING_MEIER = "Meier"; // A keyword that matches MEIER private TypicalWishes() {} // prevents instantiation1 /** * Returns an {@code WishBook} with all the typical wishes. */ public static WishBook getTypicalWishBook() { WishBook ab = new WishBook(); for (Wish wish : getTypicalWishes()) { ab.addWish(wish); } return ab; } /** * Returns a {@code WishTransaction} with all the typical wish transactions. * Assumption: no previous wish transaction available other than current state of {@code WishBook}. */ public static WishTransaction getTypicalWishTransaction() { return new WishTransaction(getTypicalWishBook()); } public static List<Wish> getTypicalWishes() { return new ArrayList<>(Arrays.asList(ALICE, BENSON, CARL, DANIEL, ELLE, FIONA, GEORGE)); } } <file_sep>/src/main/java/seedu/address/model/wish/WishCompletedPredicate.java package seedu.address.model.wish; import java.util.function.Predicate; /** * Tests if a {@code Wish} is completed. */ public class WishCompletedPredicate implements Predicate<Wish> { private final boolean isCompletedList; public WishCompletedPredicate(boolean isCompleted) { this.isCompletedList = isCompleted; } @Override public boolean test(Wish wish) { return wish.isFulfilled() == this.isCompletedList; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof WishCompletedPredicate // instanceof handles nulls && isCompletedList == (((WishCompletedPredicate) other).isCompletedList)); // state check } } <file_sep>/docs/team/lionelat.adoc = <NAME> - Project Portfolio :site-section: AboutUs :imagesDir: ../images :stylesDir: ../stylesheets == PROJECT: WishBook --- == Overview WishBook is a desktop savings assistant application written in Java, built for people who want to set savings goals (Wishes) and keep track of their progress in saving toward those wishes. It is created by Team T16-1 for CS2103T: Software Engineering module offered by School of Computing, National University of Singapore, in AY2018/2019 Semester 1. The image below shows the main layout of our application: image::Ui.png[width="800"] WishBook aims to promote responsible saving and spending among users, by helping them be more prudent with their income and encouraging regular, incremental savings to attain their wishes. The source code of WishBook can be found https://github.com/CS2103-AY1819S1-T16-1/main[here]. Being in charge of the Logic Component and documentation, I was tasked with implementing new commands, while also making sure that all changes made by our team were consistently documented in our User Guide and Developer Guide. This project portfolio consists of the contributions I have made to WishBook over the semester. == Summary of contributions |=== |_Given below are the contributions I have made to WishBook's development. Major components were delegated to each member of the team, and I was tasked with the Logic component._ |=== === Major Enhancements * *Move Command*: added Move Command ** *What it does*: Allows users to move funds between wishes, or to transfer between wishes and the unused funds. ** *Justification*: Previously, to reallocate funds from one wish to another, the user had to save a negated amount from one of their wishes, and then save that positive amount into the targeted wish. It can be quite troublesome to shift funds between wishes, as the user would have to type two separate commands. As such, I developed the move command that allows the user to transfer funds between wishes directly in a single command. * *Save to unused funds*: ** *What it does*: Allow users to save toward unused funds directly. Also, any excess saved amount will be channelled automatically to unused funds. ** *Justification*: Previously, if the input amount causes the wish’s saved amount to exceed its price, the excess amount would be stored inside that wish. However, this excess amount cannot be reallocated, since the wish has already been fulfilled. Thus, I modified the Save command to channel any excess saved amount to an UnusedFunds within WishBook. The money inside the UnusedFunds can later be redistributed to other wishes, via the Move Command. === Minor Enhancements * *Savings History*: add option to show savings history for History Command. * *List*: add option to display only completed or uncompleted wishes. === Other Contributions ** Shorthand alias: Add shorthand equivalent alias for commands. *** Useful to increase speed and efficiency while using WishBook *** users would now be able to type a command with only 1 or 2 characters, instead of typing the whole word. (Pull Request https://github.com/CS2103-AY1819S1-T16-1/main/pull/3[#3]) ** Documentation: *** Documented new functions added to User Guide. *** Consistently updated the User Guide to reflect the current function usage in our application. *** Refactored Developer Guide to make it specific to our WishBook implementation. ** Refactored code and documentation: *** Contributed regularly to refactoring the code from the previous AddressBook-Level 4 application. *** Refactor terms specific to AddressBook-Level 4, to suit our current WishBook application ** Reported bugs and issues: https://github.com/CS2103-AY1819S1-T16-1/main/issues/61[#61] https://github.com/CS2103-AY1819S1-T16-1/main/issues/created_by/lionelat[#90] *Code contributed*: https://nus-cs2103-ay1819s1.github.io/cs2103-dashboard/#=undefined&search=lionelat[Project Code DashBoard Link] == Contributions to the User Guide |=== |_Given below are sections I contributed to the User Guide. They showcase my ability to write documentation targeting end-users._ |=== === Save money for a particular wish: `save` Channel a specified amount of money to savings for a specified wish. + Format: `save INDEX AMOUNT` **** * `INDEX` should be a positive integer 1, 2, 3… no larger than the number of wishes. * If `INDEX` is 0, `AMOUNT` will be channelled directly to `unusedFunds`. * If `AMOUNT` saved to `INDEX` is greater than the amount needed to fulfil that wish, excess funds will be channelled to `unusedFunds`. * If `AMOUNT` is negative, money will be removed from amount saved for that wish. + * `AMOUNT` will not be accepted if: ** `AMOUNT` brings the savings value for that wish to below 0. ** The wish at `INDEX` is already fulfilled. **** Examples: + * `save 1 1000` + Attempt to save $1000 for the wish at index 1. * `save 1 -100.50` + Attempt to remove $100.50 from the savings for the wish at index 1. * `save 0 100.50` + Attempt save $100.50 to `unusedFunds`. === Move money between wishes: `move` Moves funds from one wish to another. + Format: `move FROM_WISH_INDEX TO_WISH_INDEX AMOUNT` **** * `FROM_WISH_INDEX` and `TO_WISH_INDEX` should be a positive integer 1, 2, 3… no larger than the number of wishes * If `FROM_WISH_INDEX` is 0, `AMOUNT` will be channelled from `unusedFunds` to `TO_WISH_INDEX`. * If `TO_WISH_INDEX` is 0, `AMOUNT` will be channelled from `FROM_WISH_INDEX` to `unusedFunds`. * `AMOUNT` from `unusedFunds` will only be successfully channelled if the exact amount requested is present in `unusedFunds`. * If `FROM_WISH_INDEX` equals `TO_WISH_INDEX`, both indexes will not be accepted. * If `AMOUNT` saved to `TO_WISH_INDEX` is greater than the amount needed to fulfil that wish, excess funds will be channelled to `unusedFunds`. * `AMOUNT` will not be accepted if: ** `AMOUNT` is negative. ** `AMOUNT` brings the savings amount of wish at `FROM_WISH_INDEX` to below 0. ** Either wish at `FROM_WISH_INDEX` or `TO_WISH_INDEX` is already fulfilled. **** [NOTE] ==== Index 0 is specially allocated for `unused funds`. Excess funds when user attempts to save to a wish will be automatically allocated to `unusedFunds`. The user can also choose to channel funds from `unusedFunds` to a valid wish. ==== Examples: + * `move 1 2 10` + Attempt to move $10 from the wish at index 1 to the wish at index 2. * `move 0 1 10` + Attempt to move $10 from `unusedFunds` to the wish at index 1. * `move 1 0 10` + Attempt to move $10 from the wish at index 1 to `unusedFunds`. //include::../UserGuide.adoc[tag=save] //include::../UserGuide.adoc[tag=move] == Contributions to the Developer Guide |=== |_Given below are sections I contributed to the Developer Guide. They showcase my ability to write technical documentation and the technical depth of my contributions to the project._ |=== === Save Amount feature ==== Current Implementation The Save Amount feature is executed through a `SaveCommand` by the user, which after parsing, is facilitated mainly by the `ModelManager` which implements `Model`. Wish stores the `price` and `savedAmount` of `Wish`, helping to track the progress of the savings towards the `price`. Meanwhile, WishBook stores an `unusedFunds`, which is an unallocated pool of funds that can be used in the future. After adding a saving, the `filteredSortedWishes` in `ModelManager` is updated to reflect the latest observable WishBook. Given below is an example usage scenario and how the SaveCommand behaves at each step: Step 1. The user executes `save 1 10`, to save $10 into an existing wish with `Index` 1 and `Price` $15. The $10 is wrapped in an `Amount` and a `SaveCommand` instance is created with the `Amount`. `Amount` is then used to make an updated instance of the `Wish` at index 1 whose `SavedAmount` will be updated. `Model#updateWish` is then called to update this wish with the old one in `WishBook`. [NOTE] The `Index` of each `Wish` is labelled at the side of the app. The resultant wish will have the following properties: * Name: _1TB Toshiba SSD_ * SavedAmount: 10.00 * Price: 15.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `false` * Expired: `false` [NOTE] `Amount` to be saved can be a negative value where it would mean a withdrawal of money from a particular wish. [NOTE] `SavedAmount` of a wish cannot be negative. This means that an `Amount` cannot be negative enough to cause `SavedAmount` to be negative. Step 2. The user decides to execute `save 1 10` again. However, SaveCommand checks that `savedAmount` > `price`. SaveCommand#execute creates a new updated `Wish` with `savedAmount = wish.getPrice()`. The resultant wish will have the following properties: * Name: _1TB Toshiba SSD_ * SavedAmount: 15.00 * Price: 15.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `true` * Expired: `false` Step 3. The excess amount of $5 is stored in a new `Amount` variable `excess`. SaveCommand#execute then calls Model#updateUnusedFunds(excess) to update the `unusedFunds` in WishBook. In WishBook, the result would be: * unusedFunds: 5.00 Step 4. The user tries to execute `save 1 10` again. However, since the value for Wish#isFulfilled is true, the amount will not be saved. SaveCommand#execute will throw a CommandException, with the message "Wish has already been fulfilled!". The following sequence diagram shows how the save operation works: image::SaveCommandSequenceDiagram.png[width="800"] ==== Design Considerations ===== Aspect: Data structure to support the unusedFunds feature * **Alternative 1 (current choice):** Store it in a `SavedAmount` variable in `WishBook`. ** Pros: Easy to implement. ** Cons: More methods needed when needing to move funds from `unusedFunds` to other wishes. * **Alternative 2:** Store it as a pseudo wish with index 0. ** Pros: It can be treated as another `wish`, hence existing methods can be used without needing to create much more new ones. ** Cons: Requires dealing with an extra wish that has to be hidden on the `WishListPanel` and displayed separately on the UI. We must remember to skip this wish in methods that involve displaying the WishList. === [Proposed] Savings Notifications ==== Justification Some users may have many wishes, all of which have a different targeted date of completion and different price. It may thus be difficult for users to keep track of how much they need to consistently save to fulfil their various wishes on time. This Savings Notification feature will allow users to opt for daily/weekly/monthly notifications for each specific wish, reminding them of the amount that they need to save at the beginning of the chosen time period. This will help users to consistently save towards their wishes. //include::../DeveloperGuide.adoc[tag=save] //include::../DeveloperGuide.adoc[tag=savingsNotifications] --- <file_sep>/docs/team/leongshengmin.adoc = <NAME> - Project Portfolio :site-section: AboutUs :imagesDir: ../images :stylesDir: ../stylesheets == PROJECT: WishBook By: `CS2103T Team T16-1` --- == Overview WishBook (WB) is a piggy bank in a digital app form, made for people who need a user-friendly solution for keeping track of their disposable income. Not only does WB keep records of your savings, it also allows users to set items as goals for users to work towards, serving as a way to cultivate the habit of saving. WB is made for people who have material wants in life, but are uncertain of purchasing said wants, by helping them to reserve disposable income so that they know they can spend on their wants. This project portfolio consists of the contributions I have made to WishBook over the semester. **** Below is a mockup of `WishBook` image::Ui.png[width="790", caption="Fig 1: Mockup of `WishBook`", align="center"] _Fig 1: Mockup of WishBook_ **** <<< == Summary of contributions === *Major enhancement*: added the ability to view savings history **** Below is a screenshot of the savings history for a `Wish` image::savingsHistoryUI.png[caption="Fig 2: Savings History of a Wish", align="center", width="300"] _Fig 2: Savings History of a Wish_ **** * What it does: Shows a history of savings you have allocated for any particular wish in the wishbook, from newest to oldest. * Justification: This feature improves the product significantly because the automatic book-keeping of savings for each Wish allows the user to easily and clearly keep track of his or her savings over a length of time. + This feature also allows for extensions since the data collected in terms of amount saved as well as frequency of saving allows for precious insights to be drawn about the saving habits as well as saving priorities of the user. * Highlights: This enhancement affects existing commands and commands to be added in future. + The implementation of this feature involves many different components and is intrinsically tied to the state of the `WishBook`, which changes when the user executes an action-based command such as the `Add`, `Save`, `Edit` command. <<< ==== Areas involved: * Persistent Storage ** Facilitate reading and writing of savings histories of all wishes to hard disk. This data will also be saved to the hard disk when triggered by a change in the state of the wishbook. * Dynamic updating of savings history ** In order for savings histories of each `Wish` to be updated dynamically, the implementation follows an event-driven model. When an action-based command is executed, subscribed classes will be notified of the change in state of the `WishBook`. ** The implementation of tracking the savings history of each `Wish` also needs to follow a `VersionedModel` that responds when notified by the change in `WishBook` state. * Testing ** Unit and Integrated testing for the code contributed. ==== * Credits: ** Persistent storage *** Savings history saved as `xml` format using the `JAXB` framework. ** Dynamic updating of savings history *** Follows event-driven model of `AddressBook-L4` *** `VersionedModel` implementation inspired by `undo`, `redo` functionality in `AddressBook-L4`. ** Testing *** `JUnit` testing framework adopted. <<< === *Minor enhancement*: updated the `Help Window` display. The `Help Window` is a pop-up window that appears when the `Help` command is executed. It is a guide to aid the user navigate the `WishBook`. **** The image below shows a screenshot of the `Help Window`. image::helpWindow.png[width="790", caption="Fig 3: Help Window", align="center"] _Fig 3: Help Window_ **** === *Code contributed*: _The following links contain code snippets of code contributed_ [https://github.com/CS2103-AY1819S1-T16-1/main/commit/6fb424a707d9bee9bd5b2441c741c5051bed3b18#diff-7b7c12031dc90ab5f6a8ec163dc2e541[Functional code]] [https://github.com/CS2103-AY1819S1-T16-1/main/commit/6fb424a707d9bee9bd5b2441c741c5051bed3b18#diff-b84c42f13e31e9508d50fbccaca0ac08[Test code]] === *Other contributions*: * Documentation: ** User Guide: *** Wrote the first version of the user guide containing all features in the first version of `WishBook`.[https://github.com/CS2103-AY1819S1-T16-1/main/blob/master/docs/old_userguide.md[link]] *** Added content for `History -s` command. [https://github.com/CS2103-AY1819S1-T16-1/main/blob/master/docs/UserGuide.adoc#viewing-your-saving-history-code-history-s-code[link]] ** Developer Guide: *** Added content for `History -s` command. [https://github.com/CS2103-AY1819S1-T16-1/main/blob/master/docs/DeveloperGuide.adoc#savings-history-feature[link]] *** Refactored undo, redo UML diagrams to reflect current version of WishBook. **** The following images show the undo, redo UML diagrams: image::UndoRedoSequenceDiagram.png[caption="Fig 5.1: Undo Redo Sequence Diagram", align="center"] _Fig 5.1: Undo Redo Sequence Diagram_ image::UndoRedoExecuteUndoStateListDiagram.png[caption="Fig 5.2.2 Undo Redo State Diagram after `Undo` command executed", align="center"] _Fig 5.2.2 Undo Redo State Diagram after `Undo` command executed_ image::UndoRedoActivityDiagram.png[caption="Fig 5.3 Undo Redo Activity Diagram", align="center"] _Fig 5.3 Undo Redo Activity Diagram_ **** <<< ** Updated the Model class diagram. **** The following image shows the updated Model Class Diagram. image::ModelClassDiagram.png[caption="Fig 6: Model Class Diagram", align="center"] _Fig 6: Model Class Diagram_ **** ** Updated the Storage class diagram. **** The following image shows the updated Storage Class Diagram. image::StorageClassDiagram.png[width="790", caption="Fig 7: Storage Class Diagram", align="center"] _Fig 7: Storage Class Diagram_ **** * Community: ** PRs reviewed (with non-trivial review comments): [https://github.com/CS2103-AY1819S1-T16-1/main/pull/54[#54]], [https://github.com/CS2103-AY1819S1-T16-1/main/pull/32[#32]] ** Reported bugs and suggestions for other teams in the class [https://github.com/CS2103-AY1819S1-W10-2/main/issues/285[1]], [https://github.com/CS2103-AY1819S1-W10-2/main/issues/276[2]], [https://github.com/CS2103-AY1819S1-W10-2/main/issues/275[3]] ** Raised and resolved issues [https://github.com/CS2103-AY1819S1-T16-1/main/issues/created_by/leongshengmin[1]], [https://github.com/CS2103-AY1819S1-T16-1/main/issues?q=is%3Aissue+assignee%3Aleongshengmin+is%3Aclosed[2]] <<< * Tools: ** Configured `RepoSense`, a Contribution Analysis Tool for the team repo [https://github.com/CS2103-AY1819S1-T16-1/main/pull/62/files[#62]] == Contributions to the User Guide |=== |_Given below are sections I contributed to the User Guide. They showcase my ability to write documentation targeting end-users._ |=== include::../UserGuide.adoc[tag=savingsHistory] == Contributions to the Developer Guide |=== |_Given below are sections I contributed to the Developer Guide. They showcase my ability to write technical documentation and the technical depth of my contributions to the project._ |=== include::../DeveloperGuide.adoc[caption="Savings History", tag=savingsHistory] |=== |_Proposed enhancement for V2.0_ |=== include::../DeveloperGuide.adoc[tag=savingsNotifications, caption="Savings Notifications"] --- <file_sep>/src/test/java/seedu/address/model/VersionedWishBookTest.java package seedu.address.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import static seedu.address.testutil.TypicalWishes.AMY; import static seedu.address.testutil.TypicalWishes.BOB; import static seedu.address.testutil.TypicalWishes.CARL; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import seedu.address.model.versionedmodels.VersionedWishBook; import seedu.address.testutil.WishBookBuilder; public class VersionedWishBookTest { private final ReadOnlyWishBook wishBookWithAmy = new WishBookBuilder().withWish(AMY).build(); private final ReadOnlyWishBook wishBookWithBob = new WishBookBuilder().withWish(BOB).build(); private final ReadOnlyWishBook wishBookWithCarl = new WishBookBuilder().withWish(CARL).build(); private final ReadOnlyWishBook emptyWishBook = new WishBookBuilder().build(); @Test public void commit_singleWishBook_noStatesRemovedCurrentStateSaved() { VersionedWishBook versionedWishBook = prepareWishBookList(emptyWishBook); versionedWishBook.commit(); assertWishBookListStatus(versionedWishBook, Collections.singletonList(emptyWishBook), emptyWishBook, Collections.emptyList()); } @Test public void commit_multipleWishBookPointerAtEndOfStateList_noStatesRemovedCurrentStateSaved() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); versionedWishBook.commit(); assertWishBookListStatus(versionedWishBook, Arrays.asList(emptyWishBook, wishBookWithAmy, wishBookWithBob), wishBookWithBob, Collections.emptyList()); } @Test public void commit_multipleWishBookPointerNotAtEndOfStateList_statesAfterPointerRemovedCurrentStateSaved() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 2); versionedWishBook.commit(); assertWishBookListStatus(versionedWishBook, Collections.singletonList(emptyWishBook), emptyWishBook, Collections.emptyList()); } @Test public void canUndo_multipleWishBookPointerAtEndOfStateList_returnsTrue() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); assertTrue(versionedWishBook.canUndo()); } @Test public void canUndo_multipleWishBookPointerAtStartOfStateList_returnsTrue() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 1); assertTrue(versionedWishBook.canUndo()); } @Test public void canUndo_singleWishBook_returnsFalse() { VersionedWishBook versionedWishBook = prepareWishBookList(emptyWishBook); assertFalse(versionedWishBook.canUndo()); } @Test public void canUndo_multipleWishBookPointerAtStartOfStateList_returnsFalse() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 2); assertFalse(versionedWishBook.canUndo()); } @Test public void canRedo_multipleWishBookPointerNotAtEndOfStateList_returnsTrue() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 1); assertTrue(versionedWishBook.canRedo()); } @Test public void canRedo_multipleWishBookPointerAtStartOfStateList_returnsTrue() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 2); assertTrue(versionedWishBook.canRedo()); } @Test public void canRedo_singleWishBook_returnsFalse() { VersionedWishBook versionedWishBook = prepareWishBookList(emptyWishBook); assertFalse(versionedWishBook.canRedo()); } @Test public void canRedo_multipleWishBookPointerAtEndOfStateList_returnsFalse() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); assertFalse(versionedWishBook.canRedo()); } @Test public void undo_multipleWishBookPointerAtEndOfStateList_success() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); versionedWishBook.undo(); assertWishBookListStatus(versionedWishBook, Collections.singletonList(emptyWishBook), wishBookWithAmy, Collections.singletonList(wishBookWithBob)); } @Test public void undo_multipleWishBookPointerNotAtStartOfStateList_success() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 1); versionedWishBook.undo(); assertWishBookListStatus(versionedWishBook, Collections.emptyList(), emptyWishBook, Arrays.asList(wishBookWithAmy, wishBookWithBob)); } @Test public void undo_singleWishBook_throwsNoUndoableStateException() { VersionedWishBook versionedWishBook = prepareWishBookList(emptyWishBook); assertThrows(VersionedWishBook.NoUndoableStateException.class, versionedWishBook::undo); } @Test public void undo_multipleWishBookPointerAtStartOfStateList_throwsNoUndoableStateException() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 2); assertThrows(VersionedWishBook.NoUndoableStateException.class, versionedWishBook::undo); } @Test public void redo_multipleWishBookPointerNotAtEndOfStateList_success() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 1); versionedWishBook.redo(); assertWishBookListStatus(versionedWishBook, Arrays.asList(emptyWishBook, wishBookWithAmy), wishBookWithBob, Collections.emptyList()); } @Test public void redo_multipleWishBookPointerAtStartOfStateList_success() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 2); versionedWishBook.redo(); assertWishBookListStatus(versionedWishBook, Collections.singletonList(emptyWishBook), wishBookWithAmy, Collections.singletonList(wishBookWithBob)); } @Test public void redo_singleWishBook_throwsNoRedoableStateException() { VersionedWishBook versionedWishBook = prepareWishBookList(emptyWishBook); assertThrows(VersionedWishBook.NoRedoableStateException.class, versionedWishBook::redo); } @Test public void redo_multipleWishBookPointerAtEndOfStateList_throwsNoRedoableStateException() { VersionedWishBook versionedWishBook = prepareWishBookList( emptyWishBook, wishBookWithAmy, wishBookWithBob); assertThrows(VersionedWishBook.NoRedoableStateException.class, versionedWishBook::redo); } @Test public void equals() { VersionedWishBook versionedWishBook = prepareWishBookList(wishBookWithAmy, wishBookWithBob); // same values -> returns true VersionedWishBook copy = prepareWishBookList(wishBookWithAmy, wishBookWithBob); assertTrue(versionedWishBook.equals(copy)); // same object -> returns true assertTrue(versionedWishBook.equals(versionedWishBook)); // null -> returns false assertFalse(versionedWishBook.equals(null)); // different types -> returns false assertFalse(versionedWishBook.equals(1)); // different state list -> returns false VersionedWishBook differentWishBookList = prepareWishBookList(wishBookWithBob, wishBookWithCarl); assertFalse(versionedWishBook.equals(differentWishBookList)); // different current pointer index -> returns false VersionedWishBook differentCurrentStatePointer = prepareWishBookList( wishBookWithAmy, wishBookWithBob); shiftCurrentStatePointerLeftwards(versionedWishBook, 1); assertFalse(versionedWishBook.equals(differentCurrentStatePointer)); } /** * Asserts that {@code versionedWishBook} is currently pointing at {@code expectedCurrentState}, * states before {@code versionedWishBook#currentStatePointer} is equal to {@code expectedStatesBeforePointer}, * and states after {@code versionedWishBook#currentStatePointer} is equal to {@code expectedStatesAfterPointer}. */ private void assertWishBookListStatus(VersionedWishBook versionedWishBook, List<ReadOnlyWishBook> expectedStatesBeforePointer, ReadOnlyWishBook expectedCurrentState, List<ReadOnlyWishBook> expectedStatesAfterPointer) { // check state currently pointing at is correct assertEquals(new WishBook(versionedWishBook), expectedCurrentState); // shift pointer to start of state list while (versionedWishBook.canUndo()) { versionedWishBook.undo(); } // check states before pointer are correct for (ReadOnlyWishBook expectedWishBook : expectedStatesBeforePointer) { assertEquals(expectedWishBook, new WishBook(versionedWishBook)); versionedWishBook.redo(); } // check states after pointer are correct for (ReadOnlyWishBook expectedWishBook : expectedStatesAfterPointer) { versionedWishBook.redo(); assertEquals(expectedWishBook, new WishBook(versionedWishBook)); } // check that there are no more states after pointer assertFalse(versionedWishBook.canRedo()); // revert pointer to original position expectedStatesAfterPointer.forEach(unused -> versionedWishBook.undo()); } /** * Creates and returns a {@code VersionedWishBook} with the {@code wishBookStates} added into it, and the * {@code VersionedWishBook#currentStatePointer} at the end of list. */ private VersionedWishBook prepareWishBookList(ReadOnlyWishBook... wishBookStates) { assertFalse(wishBookStates.length == 0); VersionedWishBook versionedWishBook = new VersionedWishBook(wishBookStates[0]); for (int i = 1; i < wishBookStates.length; i++) { versionedWishBook.resetData(wishBookStates[i]); versionedWishBook.commit(); } return versionedWishBook; } /** * Shifts the {@code versionedWishBook#currentStatePointer} by {@code count} to the left of its list. */ private void shiftCurrentStatePointerLeftwards(VersionedWishBook versionedWishBook, int count) { for (int i = 0; i < count; i++) { versionedWishBook.undo(); } } } <file_sep>/src/test/java/seedu/address/storage/XmlWishBookStorageTest.java package seedu.address.storage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static seedu.address.testutil.TypicalWishes.ALICE; import static seedu.address.testutil.TypicalWishes.HOON; import static seedu.address.testutil.TypicalWishes.IDA; import static seedu.address.testutil.TypicalWishes.getTypicalWishBook; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.model.ReadOnlyWishBook; import seedu.address.model.WishBook; public class XmlWishBookStorageTest { private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "XmlWishBookStorageTest"); @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Test public void readWishBook_nullFilePath_throwsNullPointerException() throws Exception { thrown.expect(NullPointerException.class); readWishBook(null); } private java.util.Optional<ReadOnlyWishBook> readWishBook(String filePath) throws Exception { return new XmlWishBookStorage(Paths.get(filePath)).readWishBook(addToTestDataPathIfNotNull(filePath)); } private Path addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) { return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER.resolve(prefsFileInTestDataFolder) : null; } @Test public void read_missingFile_emptyResult() throws Exception { assertFalse(readWishBook("NonExistentFile.xml").isPresent()); } @Test public void read_notXmlFormat_exceptionThrown() throws Exception { thrown.expect(DataConversionException.class); readWishBook("NotXmlFormatWishBook.xml"); /* IMPORTANT: Any code below an exception-throwing line (like the one above) will be ignored. * That means you should not have more than one exception test in one method */ } @Test public void readWishBook_invalidWishWishBook_throwDataConversionException() throws Exception { thrown.expect(DataConversionException.class); readWishBook("invalidWishWishBook.xml"); } @Test public void readWishBook_invalidAndValidWishWishBook_throwDataConversionException() throws Exception { thrown.expect(DataConversionException.class); readWishBook("invalidAndValidWishWishBook.xml"); } @Test public void readAndSaveWishBook_allInOrder_success() throws Exception { Path filePath = testFolder.getRoot().toPath().resolve("TempWishBook.xml"); WishBook original = getTypicalWishBook(); XmlWishBookStorage xmlWishBookStorage = new XmlWishBookStorage(filePath); //Save in new file and read back xmlWishBookStorage.saveWishBook(original, filePath); ReadOnlyWishBook readBack = xmlWishBookStorage.readWishBook(filePath).get(); assertEquals(original, new WishBook(readBack)); //Modify data, overwrite exiting file, and read back original.addWish(HOON); original.removeWish(ALICE); xmlWishBookStorage.saveWishBook(original, filePath); readBack = xmlWishBookStorage.readWishBook(filePath).get(); assertEquals(original, new WishBook(readBack)); //Save and read without specifying file path original.addWish(IDA); xmlWishBookStorage.saveWishBook(original); //file path not specified readBack = xmlWishBookStorage.readWishBook().get(); //file path not specified assertEquals(original, new WishBook(readBack)); } @Test public void saveWishBook_nullAddressBook_throwsNullPointerException() { thrown.expect(NullPointerException.class); saveWishBook(null, "SomeFile.xml"); } /** * Saves {@code wishbook} at the specified {@code filePath}. */ private void saveWishBook(ReadOnlyWishBook wishBook, String filePath) { try { new XmlWishBookStorage(Paths.get(filePath)) .saveWishBook(wishBook, addToTestDataPathIfNotNull(filePath)); } catch (IOException ioe) { throw new AssertionError("There should not be an error writing to the file.", ioe); } } @Test public void saveWishBook_nullFilePath_throwsNullPointerException() { thrown.expect(NullPointerException.class); saveWishBook(new WishBook(), null); } } <file_sep>/src/main/java/seedu/address/storage/XmlAdaptedWish.java package seedu.address.storage; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import javax.xml.bind.annotation.XmlElement; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.tag.Tag; import seedu.address.model.wish.Date; import seedu.address.model.wish.Name; import seedu.address.model.wish.Price; import seedu.address.model.wish.Remark; import seedu.address.model.wish.SavedAmount; import seedu.address.model.wish.Url; import seedu.address.model.wish.Wish; /** * JAXB-friendly version of the Wish. */ public class XmlAdaptedWish { public static final String MISSING_FIELD_MESSAGE_FORMAT = "Wish's %s field is missing!"; @XmlElement(required = true) private String name; @XmlElement(required = true) private String price; @XmlElement(required = true) private String savedAmount; @XmlElement(required = true) private String date; @XmlElement(required = true) private String url; @XmlElement(required = true) private String remark; @XmlElement(required = true) private String id; @XmlElement private List<XmlAdaptedTag> tagged = new ArrayList<>(); /** * Constructs an XmlAdaptedWish. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedWish() {} /** * Constructs an {@code XmlAdaptedWish} with the given wish details. */ public XmlAdaptedWish(String name, String price, String date, String url, List<XmlAdaptedTag> tagged, String id) { this.name = name; this.price = price; this.date = date; this.url = url; this.savedAmount = "0.00"; this.remark = ""; if (tagged != null) { this.tagged = new ArrayList<>(tagged); } this.id = id; } /** * Converts a given Wish into this class for JAXB use. * * @param source future changes to this will not affect the created XmlAdaptedWish */ public XmlAdaptedWish(Wish source) { name = source.getName().fullName; price = source.getPrice().toString(); date = source.getDate().date; url = source.getUrl().value; savedAmount = source.getSavedAmount().toString(); remark = source.getRemark().value; tagged = source.getTags().stream() .map(XmlAdaptedTag::new) .collect(Collectors.toList()); id = source.getId().toString(); } /** * Converts this jaxb-friendly adapted wish object into the model's Wish object. * * @throws IllegalValueException if there were any data constraints violated in the adapted wish */ public Wish toModelType() throws IllegalValueException { final List<Tag> wishTags = new ArrayList<>(); for (XmlAdaptedTag tag : tagged) { wishTags.add(tag.toModelType()); } if (id == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, UUID.class.getSimpleName())); } final UUID modelId = UUID.fromString(id); if (name == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Name.class.getSimpleName())); } if (!Name.isValidName(name)) { throw new IllegalValueException(Name.MESSAGE_NAME_CONSTRAINTS); } final Name modelName = new Name(name); if (price == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Price.class.getSimpleName())); } if (!Price.isValidPrice(price)) { throw new IllegalValueException(Price.MESSAGE_PRICE_CONSTRAINTS); } final Price modelPrice = new Price(price); if (date == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Date.class.getSimpleName())); } if (!Date.isValidDate(date)) { throw new IllegalValueException(Date.MESSAGE_DATE_CONSTRAINTS); } final Date modelDate = new Date(date); if (url == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Url.class.getSimpleName())); } if (!Url.isValidUrl(url)) { throw new IllegalValueException(Url.MESSAGE_URL_CONSTRAINTS); } final Url modelUrl = new Url(url); if (this.remark == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Remark.class.getSimpleName())); } final Remark modelRemark = new Remark(this.remark); if (this.savedAmount == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, SavedAmount.class.getSimpleName())); } final SavedAmount modelSavedAmount = new SavedAmount(this.savedAmount); final Set<Tag> modelTags = new HashSet<>(wishTags); return new Wish(modelName, modelPrice, modelDate, modelUrl, modelSavedAmount, modelRemark, modelTags, modelId); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof XmlAdaptedWish)) { return false; } XmlAdaptedWish otherWish = (XmlAdaptedWish) other; return Objects.equals(name, otherWish.name) && Objects.equals(price, otherWish.price) && Objects.equals(date, otherWish.date) && Objects.equals(url, otherWish.url) && Objects.equals(remark, otherWish.remark) && tagged.equals(otherWish.tagged) && id.equals(otherWish.id); } } <file_sep>/src/test/java/seedu/address/storage/XmlAdaptedWishWrapperTest.java package seedu.address.storage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.address.testutil.TypicalWishes.getTypicalWishes; import java.util.LinkedList; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; /** * This class performs a unit test on {@code XmlAdaptedWishWrapper} class. */ public class XmlAdaptedWishWrapperTest { private XmlAdaptedWishWrapper emptyWrapper; private XmlAdaptedWishWrapper populatedWrapper; private LinkedList<XmlAdaptedWish> xmlAdaptedWishes; @Before public void init() { this.xmlAdaptedWishes = getTypicalWishes().stream() .map(wish -> new XmlAdaptedWish(wish)) .collect(Collectors.toCollection(LinkedList::new)); this.populatedWrapper = new XmlAdaptedWishWrapper(xmlAdaptedWishes); this.emptyWrapper = new XmlAdaptedWishWrapper(new LinkedList<>()); } @Test(expected = NullPointerException.class) public void createWrapperShouldThrowException() { new XmlAdaptedWishWrapper(null); } @Test public void shouldRetrieveXmlAdaptedWishes() { assertEquals(emptyWrapper.getXmlAdaptedWishes(), new LinkedList<>()); assertEquals(populatedWrapper.getXmlAdaptedWishes(), xmlAdaptedWishes); } @Test public void shouldBeEqual() { assertTrue(emptyWrapper.equals(new XmlAdaptedWishWrapper())); assertTrue(populatedWrapper.equals(new XmlAdaptedWishWrapper(xmlAdaptedWishes))); } } <file_sep>/src/test/java/seedu/address/logic/parser/MoveCommandParserTest.java package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.commands.CommandTestUtil.VALID_SAVED_AMOUNT_AMY; import static seedu.address.logic.commands.MoveCommand.MESSAGE_USAGE; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import static seedu.address.logic.parser.MoveCommandParser.MESSAGE_INVALID_SAME_INDEX; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_WISH; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND_WISH; import org.junit.Test; import seedu.address.commons.core.amount.Amount; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.MoveCommand; public class MoveCommandParserTest { private MoveCommandParser moveCommandParser = new MoveCommandParser(); private Index fromIndex = INDEX_FIRST_WISH; private Index toIndex = INDEX_SECOND_WISH; private int unusedFundsIndex = MoveCommandParser.UNUSED_FUNDS_INDEX; private Amount amountToMove = new Amount(VALID_SAVED_AMOUNT_AMY); @Test public void parse_indexSpecified_success() { final String userInputWishToWish = fromIndex.getOneBased() + " " + toIndex.getOneBased() + " " + amountToMove.toString(); final MoveCommand expectedCommandWishToWish = new MoveCommand(fromIndex, toIndex, amountToMove, MoveCommand.MoveType.WISH_TO_WISH); assertParseSuccess(moveCommandParser, userInputWishToWish, expectedCommandWishToWish); final String userInputUnusedFundsToWish = unusedFundsIndex + " " + toIndex.getOneBased() + " " + amountToMove.toString(); final MoveCommand expectedCommandUnusedFundsToWish = new MoveCommand(null, toIndex, amountToMove, MoveCommand.MoveType.WISH_FROM_UNUSED_FUNDS); assertParseSuccess(moveCommandParser, userInputUnusedFundsToWish, expectedCommandUnusedFundsToWish); final String userInputWishToUnusedFunds = fromIndex.getOneBased() + " " + unusedFundsIndex + " " + amountToMove.toString(); final MoveCommand expectedCommandWishToUnusedFunds = new MoveCommand(fromIndex, null, amountToMove, MoveCommand.MoveType.WISH_TO_UNUSED_FUNDS); assertParseSuccess(moveCommandParser, userInputWishToUnusedFunds, expectedCommandWishToUnusedFunds); } @Test public void parse_missingCompulsoryField_failure() { final String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, MESSAGE_USAGE); final String userInputMissingIndex = fromIndex.getZeroBased() + " " + amountToMove.toString(); assertParseFailure(moveCommandParser, userInputMissingIndex, expectedMessage); final String userInputMissingAmount = fromIndex.getZeroBased() + " " + toIndex.getZeroBased() + " "; assertParseFailure(moveCommandParser, userInputMissingAmount, expectedMessage); } @Test public void parse_sameIndex_failure() { //FROM and TO Index cannot be the same final String expectedMessage = MESSAGE_INVALID_SAME_INDEX; final String userInputSameIndex = fromIndex.getZeroBased() + " " + fromIndex.getZeroBased() + " " + amountToMove.toString(); assertParseFailure(moveCommandParser, userInputSameIndex, expectedMessage); } } <file_sep>/src/main/java/seedu/address/model/WishTransaction.java package seedu.address.model; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import java.util.stream.Collectors; import seedu.address.commons.core.LogsCenter; import seedu.address.model.tag.Tag; import seedu.address.model.wish.Wish; /** * Each {@code WishTransaction} represents a state of the WishBook. * A state contains logs of undeleted wish histories. */ public class WishTransaction implements ActionCommandListener<WishTransaction> { /** * Stores a log of wish histories for this current state. */ protected HashMap<UUID, LinkedList<Wish>> wishMap; /** * Logger associated with this class. */ private final Logger logger; public WishTransaction() { this.logger = getLogger(); this.wishMap = new HashMap<>(); } /** * Creates a WishTransaction using a saved copy of {@code WishTransaction}. * * @param savedCopy saved copy of {@code WishTransaction} stored in file. */ public WishTransaction(WishTransaction savedCopy) { this.logger = savedCopy.logger; resetData(savedCopy); } /** * Creates a WishTransaction using a {@code ReadOnlyWishBook}. * * @param readOnlyWishBook referenced data-containing {@code ReadOnlyWishBook}. */ public WishTransaction(ReadOnlyWishBook readOnlyWishBook) { this(); extractData(readOnlyWishBook); } /** * Constructor to be called when converting XmlWishTransactions object to a WishTransaction object. */ public WishTransaction(HashMap<UUID, LinkedList<Wish>> wishMap) { this.logger = getLogger(); this.wishMap = wishMap; } /** * Returns a deep copy of the the given {@code wishTransaction} object. */ public WishTransaction getCopy(WishTransaction wishTransaction) { WishTransaction copy = new WishTransaction(); wishTransaction.getWishMap().entrySet().forEach(entry -> { copy.wishMap.put(entry.getKey(), getCopy(entry.getValue())); }); return copy; } private LinkedList<Wish> getCopy(LinkedList<Wish> wishList) { LinkedList<Wish> copy = new LinkedList<>(); for (Wish wish : wishList) { copy.add(new Wish(wish)); } return copy; } private Logger getLogger() { return LogsCenter.getLogger(WishTransaction.class); } /** * Extracts data from a {@code ReadOnlyWishBook} object and seeds that data into {@code wishMap}. * @param wishBook object containing data to seed this object with. */ protected void extractData(ReadOnlyWishBook wishBook) { logger.info("Extracting data from ReadOnlyWishBook"); for (Wish wish : wishBook.getWishList()) { addWish(wish); } } /** * Adds a wish to {@code wishMap} using {@code wish} full name as key. * @param wish */ @Override public void addWish(Wish wish) { UUID key = getKey(wish); LinkedList<Wish> wishList = updateWishes(getWishList(key), wish); setValueOfKey(wish, wishList); } /** * Returns the key corresponding to this wish. * @param wish queried wish. * @return key for the corresponding wish. */ private UUID getKey(Wish wish) { return wish.getId(); } /** * Retrieves the wishlist stored at {@code key}. * @param key name of the wish. * @return wishlist stored at {@code key}. */ private LinkedList<Wish> getWishList(UUID key) { return this.wishMap.getOrDefault(key, new LinkedList<>()); } /** * Sets the value of an existing wish to {@code wishes}. * @param existing an existing wish. * @param wishes value to be changed to. */ private void setValueOfKey(Wish existing, LinkedList<Wish> wishes) { this.wishMap.put(getKey(existing), wishes); } /** * Appends the updated wish to the log of saving history for this wish. * @param existingWishes log of saving history. * @param editedWish wish to be updated to. * @return an updated log of saving history. */ private LinkedList<Wish> updateWishes(LinkedList<Wish> existingWishes, Wish editedWish) { existingWishes.add(editedWish); return existingWishes; } /** * Replaces the given wish {@code target} in the list with {@code editedWish}. * {@code target} must exist in the wish book. * The wish identity of {@code editedWish} must not be the same as another existing wish in the wish book. */ @Override public void updateWish(Wish target, Wish editedWish) { // get a reference to the stored wishes LinkedList<Wish> wishes = getWishList(getKey(target)); // update the stored wishes setValueOfKey(target, updateWishes(wishes, editedWish)); } /** * @see WishTransaction#removeWish(UUID). */ @Override public void removeWish(Wish wish) { removeWish(getKey(wish)); } /** * Removes the wish specified by {@code key}. * * @param key name of wish to remove. * @throws NoSuchElementException if key does not exist. */ private void removeWish(UUID key) throws NoSuchElementException { wishMap.remove(key); } /** * Changes recorded log of wish histories for the current state to the {@code newData}. * * @param newData Revisioned log of wish histories. */ @Override public void resetData(WishTransaction newData) { setWishMap(newData.wishMap); } /** * @see WishTransaction#resetData(WishTransaction) */ @Override public void resetData() { wishMap.clear(); } /** * Responds to request to remove tag from all wishes. * @param tag tag to be removed. */ @Override public void removeTagFromAll(Tag tag) { HashMap<UUID, LinkedList<Wish>> copiedWishMap = new HashMap<>(); for (Map.Entry<UUID, LinkedList<Wish>> entries : wishMap.entrySet()) { LinkedList<Wish> wishes = entries.getValue(); // associated wish has a recorded history if (wishes != null) { copiedWishMap = getModifiedMap(tag, wishes, copiedWishMap); } } setWishMap(copiedWishMap); } /** * Removes the given {@code tag} from the given list of {@code wish}es if the tag is present. * @param tag tag to be removed. * @param wishes list of wishes to be searched for tag. */ private HashMap<UUID, LinkedList<Wish>> getModifiedMap(Tag tag, LinkedList<Wish> wishes, HashMap<UUID, LinkedList<Wish>> map) { Wish mostRecent = getMostRecentWish(wishes); if (hasTag(tag, mostRecent)) { return getModifiedMap(tag, mostRecent, map); } else { map.put(getKey(mostRecent), wishes); } return map; } /** * Removes the given tag from the given wish. * @param tag tag to be removed. * @param mostRecent wish to remove the tag from. */ private HashMap<UUID, LinkedList<Wish>> getModifiedMap(Tag tag, Wish mostRecent, HashMap<UUID, LinkedList<Wish>> map) { Set<Tag> updatedTags = getUpdatedTags(mostRecent, tag); Wish updatedWish = getUpdatedWish(updatedTags, mostRecent); LinkedList<Wish> wishList = getWishList(getKey(mostRecent)); map.put(getKey(mostRecent), updateWishes(wishList, updatedWish)); return map; } /** * Returns the most recent wish recorded. * @param wishes list to source for the most recent wish. * @return the most recent wish in {@code wishes}. */ private Wish getMostRecentWish(LinkedList<Wish> wishes) { return wishes.get(wishes.size() - 1); } /** * Checks if the given wish contains the given tag. * @param tag to be checked in the wish. * @param mostRecent wish to be checked for tag. * @return true if the tag is found in the wish, false otherwise. */ private boolean hasTag(Tag tag, Wish mostRecent) { return mostRecent.getTags().contains(tag); } /** * Retrieves the updated tag set belonging to a given wish. * @param mostRecent the given wish. * @param tag the tag to be removed from the old tag set. * @return the new tag set without the given {@code tag}. */ private Set<Tag> getUpdatedTags(Wish mostRecent, Tag tag) { Set<Tag> oldTags = mostRecent.getTags(); return oldTags.stream().filter(t->(!t.equals(tag))).collect(Collectors.toSet()); } /** * Returns a new wish with the tags changed to {@code updatedTags}. * @param updatedTags field to update. * @param target wish to be updated. * @return a new updated wish. */ private Wish getUpdatedWish(Set<Tag> updatedTags, Wish target) { return new Wish(target.getName(), target.getPrice(), target.getDate(), target.getUrl(), target.getSavedAmount(), target.getRemark(), updatedTags, target.getId()); } /** * Sets the current state's wish histories to {@code wishMap}. * @param wishMap updated wish history log. */ public void setWishMap(HashMap<UUID, LinkedList<Wish>> wishMap) { this.wishMap = wishMap; } public HashMap<UUID, LinkedList<Wish>> getWishMap() { return wishMap; } /** * Checks if this object has any values stored in it. */ public boolean isEmpty() { return wishMap.isEmpty(); } @Override public boolean equals(Object obj) { if (obj instanceof WishTransaction) { for (Map.Entry<UUID, LinkedList<Wish>> entries : ((WishTransaction) obj).wishMap.entrySet()) { if (!wishMap.containsKey(entries.getKey()) || !wishMap.containsValue(entries.getValue())) { return false; } } return true; } return false; } @Override public String toString() { wishMap.entrySet().forEach(entry -> { System.out.println(entry.getKey()); entry.getValue().forEach(System.out::println); }); return null; } } <file_sep>/src/main/java/seedu/address/logic/parser/ParserUtil.java package seedu.address.logic.parser; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.time.format.DateTimeParseException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.commons.util.StringUtil; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.tag.Tag; import seedu.address.model.wish.Date; import seedu.address.model.wish.Name; import seedu.address.model.wish.Price; import seedu.address.model.wish.Remark; import seedu.address.model.wish.Url; /** * Contains utility methods used for parsing strings in the various *Parser classes. */ public class ParserUtil { public static final String MESSAGE_INVALID_INDEX = "Index is not a non-zero unsigned integer."; /** * Parses {@code oneBasedIndex} into an {@code Index} and returns it. Leading and trailing whitespaces will be * trimmed. * @throws ParseException if the specified index is invalid (not non-zero unsigned integer). */ public static Index parseIndex(String oneBasedIndex) throws ParseException { String trimmedIndex = oneBasedIndex.trim(); if (!StringUtil.isNonZeroUnsignedInteger(trimmedIndex)) { throw new ParseException(MESSAGE_INVALID_INDEX); } return Index.fromOneBased(Integer.parseInt(trimmedIndex)); } /** * Parses a {@code String name} into a {@code Name}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static Name parseName(String name) throws ParseException { requireNonNull(name); String trimmedName = name.trim(); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_NAME_CONSTRAINTS); } return new Name(trimmedName); } /** * Parses a {@code String price} into a {@code Price}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code price} is invalid. */ public static Price parsePrice(String price) throws ParseException { requireNonNull(price); String trimmedPrice = price.trim(); if (!Price.isValidPrice(trimmedPrice)) { throw new ParseException(Price.MESSAGE_PRICE_CONSTRAINTS); } return new Price(trimmedPrice); } /** * Parses a {@code String url} into an {@code Url}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code url} is invalid. */ public static Url parseUrl(String url) throws ParseException { requireNonNull(url); String trimmedUrl = url.trim(); if (!Url.isValidUrl(trimmedUrl)) { throw new ParseException(Url.MESSAGE_URL_CONSTRAINTS); } return new Url(trimmedUrl); } /** * Parses a {@code String tag} into a {@code Tag}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code tag} is invalid. */ public static Tag parseTag(String tag) throws ParseException { requireNonNull(tag); String trimmedTag = tag.trim(); if (!Tag.isValidTagName(trimmedTag)) { throw new ParseException(Tag.MESSAGE_TAG_CONSTRAINTS); } return new Tag(trimmedTag); } /** * Parses {@code Collection<String> tags} into a {@code Set<Tag>}. */ public static Set<Tag> parseTags(Collection<String> tags) throws ParseException { requireNonNull(tags); final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(parseTag(tagName)); } return tagSet; } /** * Parses a {@code String remark} into a {@code Remark}. */ public static Remark parseRemark(String remark) throws ParseException { requireNonNull(remark); String trimmedRemark = remark.trim(); return new Remark(trimmedRemark); } /** * Parses a {@code String date} into a {@code Date}. */ public static Date parseDate(String date) throws ParseException { requireNonNull(date); String trimmedDate = date.trim(); if (!Date.isValidDate(trimmedDate)) { throw new ParseException(Date.MESSAGE_DATE_CONSTRAINTS); } try { if (!Date.isFutureDate(trimmedDate)) { throw new ParseException(Date.MESSAGE_DATE_OUTDATED); } } catch (java.text.ParseException pe) { throw new ParseException(Date.MESSAGE_DATE_CONSTRAINTS); } return new Date(trimmedDate); } /** * Parses a {@code String period} into a {@code Period}. */ public static Period parsePeriod(String period) throws ParseException { requireNonNull(period); String trimmedPeriod = period.trim(); try { Period.parse("P" + trimmedPeriod); } catch (DateTimeParseException e) { throw new ParseException(String.format(Messages.MESSAGE_INVALID_TIME_FORMAT, period)); } return Period.parse("P" + trimmedPeriod); } /** * Returns the {@code Date}, offset by an input {@code Period} from now. * @param periodString * @return * @throws ParseException */ public static Date getPeriodOffsetFromNow(String periodString) throws ParseException { Period period = parsePeriod(periodString); java.util.Date now = new java.util.Date(); LocalDate localNow = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate finalDate = localNow.plus(period); return ParserUtil.parseDate(String.format("%02d/%02d/%d", finalDate.getDayOfMonth(), finalDate.getMonth().getValue(), finalDate.getYear())); } } <file_sep>/src/main/java/seedu/address/model/wish/SavedAmount.java package seedu.address.model.wish; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; import java.text.DecimalFormat; import seedu.address.commons.core.amount.Amount; /** * Represents a saved Amount for a Wish in the wish book. * Guarantees: immutable; is valid as declared in {@link #isValidSavedAmount(String)} */ public class SavedAmount { public static final String MESSAGE_SAVED_AMOUNT_INVALID = "Invalid saved amount value!"; public static final String MESSAGE_SAVED_AMOUNT_NEGATIVE = "Invalid. Saved amount causes current value to " + "become negative"; public static final String MESSAGE_SAVED_AMOUNT_TOO_LARGE = "Current saved amount for wish is too large!"; public static final String SAVED_AMOUNT_VALIDATION_REGEX = "[-+]?[0-9]+([.]{1}[0-9]{1,2})?"; public final Double value; private DecimalFormat currencyFormat = new DecimalFormat("#.##"); /** * Constructs a {@code SavedAmount}. * * @param savedAmount A valid savedAmount number. */ public SavedAmount(String savedAmount) throws IllegalArgumentException { requireNonNull(savedAmount); checkArgument(isValidSavedAmount(savedAmount), MESSAGE_SAVED_AMOUNT_INVALID); value = Double.parseDouble(savedAmount); if (value.doubleValue() < 0) { throw new IllegalArgumentException(MESSAGE_SAVED_AMOUNT_NEGATIVE); } else if (value.doubleValue() > 1000e12) { throw new IllegalArgumentException(MESSAGE_SAVED_AMOUNT_TOO_LARGE); } } public SavedAmount(SavedAmount savedAmount) { this(savedAmount.value.toString()); } /** * Constructs a {@code SavedAmount} from an increment {@code Amount}. * * @param change A valid {@code Amount} to increment this {@code SavedAmount}. * @return Incremented {@code SavedAmount}. */ public SavedAmount incrementSavedAmount(Amount change) { if (this.value + change.value < 0.0) { throw new IllegalArgumentException(MESSAGE_SAVED_AMOUNT_NEGATIVE); } return new SavedAmount(currencyFormat.format(this.value + change.value)); } /** * Returns a {@code Amount} from the savedAmount. */ public Amount getAmount() { return new Amount("" + this.value); } /** * Returns true if a given string is a valid savedAmount number. */ public static boolean isValidSavedAmount(String test) { return test.matches(SAVED_AMOUNT_VALIDATION_REGEX); } @Override public String toString() { return String.format("%.2f", value); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof SavedAmount // instanceof handles nulls && value.equals(((SavedAmount) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } } <file_sep>/src/test/java/seedu/address/logic/commands/EditWishDescriptorTest.java package seedu.address.logic.commands; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.DESC_AMY; import static seedu.address.logic.commands.CommandTestUtil.DESC_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_2; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_PRICE_BOB; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND; import static seedu.address.logic.commands.CommandTestUtil.VALID_URL_BOB; import org.junit.Test; import seedu.address.logic.commands.EditCommand.EditWishDescriptor; import seedu.address.testutil.EditWishDescriptorBuilder; public class EditWishDescriptorTest { @Test public void equals() { // same values -> returns true EditWishDescriptor descriptorWithSameValues = new EditWishDescriptor(DESC_AMY); assertTrue(DESC_AMY.equals(descriptorWithSameValues)); // same object -> returns true assertTrue(DESC_AMY.equals(DESC_AMY)); // null -> returns false assertFalse(DESC_AMY.equals(null)); // different types -> returns false assertFalse(DESC_AMY.equals(5)); // different values -> returns false assertFalse(DESC_AMY.equals(DESC_BOB)); // different name -> returns false EditWishDescriptor editedAmy = new EditWishDescriptorBuilder(DESC_AMY).withName(VALID_NAME_BOB).build(); assertFalse(DESC_AMY.equals(editedAmy)); // different price -> returns false editedAmy = new EditWishDescriptorBuilder(DESC_AMY).withPrice(VALID_PRICE_BOB).build(); assertFalse(DESC_AMY.equals(editedAmy)); // different email -> returns false editedAmy = new EditWishDescriptorBuilder(DESC_AMY).withDate(VALID_DATE_2).build(); assertFalse(DESC_AMY.equals(editedAmy)); // different address -> returns false editedAmy = new EditWishDescriptorBuilder(DESC_AMY).withAddress(VALID_URL_BOB).build(); assertFalse(DESC_AMY.equals(editedAmy)); // different tags -> returns false editedAmy = new EditWishDescriptorBuilder(DESC_AMY).withTags(VALID_TAG_HUSBAND).build(); assertFalse(DESC_AMY.equals(editedAmy)); } } <file_sep>/src/main/java/seedu/address/storage/WishBookStorage.java package seedu.address.storage; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.model.ReadOnlyWishBook; import seedu.address.model.WishBook; /** * Represents a storage for {@link WishBook}. */ public interface WishBookStorage { /** * Returns the file path of the data file. */ Path getWishBookFilePath(); /** * Returns WishBook data as a {@link ReadOnlyWishBook}. * Returns {@code Optional.empty()} if storage file is not found. * @throws DataConversionException if the data in storage is not in the expected FORMAT. * @throws IOException if there was any problem when reading from the storage. */ Optional<ReadOnlyWishBook> readWishBook() throws DataConversionException, IOException; /** * @see #getWishBookFilePath() */ Optional<ReadOnlyWishBook> readWishBook(Path filePath) throws DataConversionException, IOException; /** * Saves the given {@link ReadOnlyWishBook} to the storage. * @param wishBook cannot be null. * @throws IOException if there was any problem writing to the file. */ void saveWishBook(ReadOnlyWishBook wishBook) throws IOException; /** * @see #saveWishBook(ReadOnlyWishBook) */ void saveWishBook(ReadOnlyWishBook wishBook, Path filePath) throws IOException; /** * @see #saveBackup(Path) */ void saveBackup() throws IOException, DataConversionException; /** * Saves backup copy of wishbook at the corresponding filepath. * @param path filepath of backup file. */ void saveBackup(Path path) throws IOException, DataConversionException; /** * Backs up the given {@link ReadOnlyWishBook} to local storage. * @param wishBook wishBook cannot be null. * @throws IOException if there was any problem writing to the file */ void backupWishBook(ReadOnlyWishBook wishBook) throws IOException; /** * @see #saveWishBook(ReadOnlyWishBook) */ void backupWishBook(ReadOnlyWishBook wishBook, Path filePath) throws IOException; } <file_sep>/src/test/java/seedu/address/model/tag/TagTest.java package seedu.address.model.tag; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_FRIEND; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND; import org.junit.Test; import seedu.address.testutil.Assert; public class TagTest { @Test public void constructor_null_throwsNullPointerException() { Assert.assertThrows(NullPointerException.class, () -> new Tag((String) null)); Assert.assertThrows(NullPointerException.class, () -> new Tag((Tag) null)); } @Test public void constructor_invalidTagName_throwsIllegalArgumentException() { String invalidTagName = ""; Assert.assertThrows(IllegalArgumentException.class, () -> new Tag(invalidTagName)); } @Test public void isValidTagName() { // null tag name Assert.assertThrows(NullPointerException.class, () -> Tag.isValidTagName(null)); } @Test public void equals() { Tag tagHusband = new Tag(VALID_TAG_HUSBAND); Tag tagFriend = new Tag(VALID_TAG_FRIEND); // null -> return false assertFalse(tagHusband.equals(null)); // same object -> returns true assertTrue(tagHusband.equals(tagHusband)); // different type -> returns false assertFalse(tagFriend.equals(99)); // different tag -> returns false assertFalse(tagHusband.equals(tagFriend)); } } <file_sep>/src/main/java/seedu/address/model/ActionCommandListener.java package seedu.address.model; import seedu.address.model.tag.Tag; import seedu.address.model.wish.Wish; /** * This interface is implemented by classes listening on action commands. * An action command is defined to be a command that changes the state of the WishBook. * Examples of action commands include clear, delete, updateWish, add, save, removeTagFromAll, etc. */ public interface ActionCommandListener<T> { /** * Called when a command attempts to add a wish to the wish book. */ void addWish(Wish wish); /** * Called when a command attempts to replace the given wish {@code target} with {@code editedWish}. * {@code target} must exist in the wish book. * */ void updateWish(Wish target, Wish editedWish); /** * Called when a command attempts to remove {@code key} from this {@code WishBook}. * {@code key} must exist in the wish book. */ void removeWish(Wish wish); /** * Called when action commands undo, redo are executed. * @param newData newData to replace the model with. */ void resetData(T newData); /** * Called when action command clear is executed. */ void resetData(); /** * Removes {@code tag} from all {@code wish}s in this {@code WishBook}. */ void removeTagFromAll(Tag tag); } <file_sep>/src/main/java/seedu/address/model/ReadOnlyWishBook.java package seedu.address.model; import javafx.collections.ObservableList; import seedu.address.model.wish.SavedAmount; import seedu.address.model.wish.Wish; /** * Unmodifiable view of a wish book */ public interface ReadOnlyWishBook { /** * Returns an unmodifiable view of the wish list. * This list will not contain any duplicate wishes. */ ObservableList<Wish> getWishList(); /** * Returns an unmodifiable view of the unusedFunds amount. */ SavedAmount getUnusedFunds(); } <file_sep>/src/test/java/seedu/address/logic/parser/ListCommandParserTest.java package seedu.address.logic.parser; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import org.junit.Test; import seedu.address.logic.commands.ListCommand; public class ListCommandParserTest { private ListCommandParser parser = new ListCommandParser(); @Test public void parse_emptyArgs_returnsListAll() { assertParseSuccess(parser, " ", new ListCommand(ListCommand.ListType.SHOW_ALL)); } @Test public void parse_validArgs_returnsCorrectList() { ListCommand completedListCommand = new ListCommand(ListCommand.ListType.SHOW_COMPLETED); ListCommand uncompletedListCommand = new ListCommand(ListCommand.ListType.SHOW_UNCOMPLETED); assertParseSuccess(parser, "-c", completedListCommand); assertParseSuccess(parser, "-u", uncompletedListCommand); } } <file_sep>/src/test/java/seedu/address/logic/commands/ListCommandTest.java package seedu.address.logic.commands; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.CommandTestUtil.showWishAtIndex; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_WISH; import static seedu.address.testutil.TypicalWishes.getTypicalWishBook; import static seedu.address.testutil.TypicalWishes.getTypicalWishTransaction; import org.junit.Before; import org.junit.Test; import seedu.address.logic.CommandHistory; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.wish.WishCompletedPredicate; /** * Contains integration tests (interaction with the Model) and unit tests for ListCommand. */ public class ListCommandTest { private Model model; private Model expectedModel; private CommandHistory commandHistory = new CommandHistory(); @Before public void setUp() { model = new ModelManager(getTypicalWishBook(), getTypicalWishTransaction(), new UserPrefs()); expectedModel = new ModelManager(model.getWishBook(), model.getWishTransaction(), new UserPrefs()); } @Test public void execute_listIsNotFiltered_showsSameList() { assertCommandSuccess(new ListCommand(ListCommand.ListType.SHOW_ALL), model, commandHistory, ListCommand.MESSAGE_SUCCESS, expectedModel); } @Test public void execute_listIsFiltered_showsEverything() { showWishAtIndex(model, INDEX_FIRST_WISH); assertCommandSuccess(new ListCommand(ListCommand.ListType.SHOW_ALL), model, commandHistory, ListCommand.MESSAGE_SUCCESS, expectedModel); } @Test public void execute_showListCompleted_success() { expectedModel.updateFilteredWishList(new WishCompletedPredicate(true)); assertCommandSuccess(new ListCommand(ListCommand.ListType.SHOW_COMPLETED), model, commandHistory, ListCommand.MESSAGE_SHOWED_COMPLETED, expectedModel); } @Test public void execute_showListUncompleted_success() { expectedModel.updateFilteredWishList(new WishCompletedPredicate(false)); assertCommandSuccess(new ListCommand(ListCommand.ListType.SHOW_UNCOMPLETED), model, commandHistory, ListCommand.MESSAGE_SHOWED_UNCOMPLETED, expectedModel); } } <file_sep>/src/main/java/seedu/address/logic/parser/MoveCommandParser.java package seedu.address.logic.parser; import static java.util.Objects.requireNonNull; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_AMOUNT; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import seedu.address.commons.core.amount.Amount; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.MoveCommand; import seedu.address.logic.parser.exceptions.ParseException; /** * Parses input arguments and creates a new MoveCommand object. */ public class MoveCommandParser implements Parser<MoveCommand> { public static final int UNUSED_FUNDS_INDEX = 0; public static final String MESSAGE_INVALID_SAME_INDEX = "Invalid! FROM and TO index cannot be the same."; /** * Parses the given {@code String} of arguments in the context of the MoveCommand * and returns a MoveCommand object for execution. * @throws ParseException if the user input does not conform the expected FORMAT * @throws IllegalArgumentException if the user enters an invalid argument */ @Override public MoveCommand parse(String args) throws ParseException, IllegalArgumentException { requireNonNull(args); String trimmedArgs = args.trim(); if (trimmedArgs.isEmpty()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MoveCommand.MESSAGE_USAGE)); } String[] arguments = trimmedArgs.split(" "); if (arguments.length != 3) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MoveCommand.MESSAGE_USAGE)); } MoveCommand.MoveType moveCommandType; Index fromIndex; Index toIndex; //Cannot parse the same index for FROM and TO if (arguments[0].equals(arguments[1])) { throw new ParseException(MESSAGE_INVALID_SAME_INDEX); } Amount amount; try { amount = new Amount(arguments[2]); } catch (IllegalArgumentException iae) { throw new ParseException(String.format(MESSAGE_INVALID_AMOUNT, arguments[2])); } try { if (Integer.parseInt(arguments[0]) == UNUSED_FUNDS_INDEX) { fromIndex = null; toIndex = ParserUtil.parseIndex(arguments[1]); moveCommandType = MoveCommand.MoveType.WISH_FROM_UNUSED_FUNDS; } else if (Integer.parseInt(arguments[1]) == UNUSED_FUNDS_INDEX) { fromIndex = ParserUtil.parseIndex(arguments[0]); toIndex = null; moveCommandType = MoveCommand.MoveType.WISH_TO_UNUSED_FUNDS; } else { fromIndex = ParserUtil.parseIndex(arguments[0]); toIndex = ParserUtil.parseIndex(arguments[1]); moveCommandType = MoveCommand.MoveType.WISH_TO_WISH; } } catch (ParseException pe) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MoveCommand.MESSAGE_USAGE)); } return new MoveCommand(fromIndex, toIndex, amount, moveCommandType); } } <file_sep>/docs/team/bannified.adoc = <NAME> (bannified) - Project Portfolio :site-section: AboutUs :imagesDir: ../images :stylesDir: ../stylesheets ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :experimental: endif::[] == PROJECT: WishBook --- == Overview WishBook is a desktop application used to help one allocate one's disposable income to a number of desired products. WishBook enables users to better organize their desirables, allowing them to visualize their spendings in a pleasant way. The user interacts with it by using a Command Line Interface (CLI), and it has a GUI created with JavaFX. WishBook was developed by the GaveSoals team, a team of students based in the School of Computing, National University of Singapore. image::Ui.png[width="790"] WishBook is an application that promotes sustainable and responsible consumerism, by having users be more frugal with their income while rewarding themselves at appropriate times, when they can afford to. Wishbook is an application adapted from addressbook-level4, the original application developed by the se-edu team. The source code of addressbook-level4 can be found https://github.com/nus-cs2103-AY1819S1/addressbook-level4[here]. The main features of WishBook are: * Add a Wish (of a desired item) to the WishBook * Add funds to a Wish to make progress in fulfilling a Wish * Add remarks to a Wish * Add funds to WishBook without an explicit Wish * Keep track of the user's progress to fulfilling a Wish, so that the user can buy it. * Chang the details of a Wish after it has been added * Find Wishes by name or tags * View all completed or uncompleted Wishes * Delete an unwanted Wish * View of the Wish's product page (if applicable) * Undo and Redo commands * View history of savings == Summary of contributions Mentioned below are the contributions I have made with regards to WishBook's development. Major components of the application were delegated to every person in the team, and I was tasked with the Model component. * *Major enhancement*: Add Wish Command ** What it does: allows the user to add a `Wish` by entering a product's details. ** Justification: This feature is one of the core functionalities of the application, as a Wish is the primary entity that a User will interact with when using WishBook. ** Highlights: *** Since this feature is core to the application, defensive programming has to be practiced when implementing this feature, as the Wish will likely affect features being added in the future. *** The Add Command also effectively creates Wish entries for the Wishbook to operate on, and is the entry point of the lifecycle of our application's usage, bugs occurring in this command will cascade to other Wish-related commands, hence its implementation has to be safe and well-tested. * *Minor enhancements*: ** Add an option for the user to state the Duration that a Wish will last, when adding a Wish with Add Command. ** Change syntax of Save Command to make it more user friendly ** Make Save Command show the change in SavedAmount of a wish from before * *Code contributed*: https://nus-cs2103-ay1819s1.github.io/cs2103-dashboard/#=undefined&search=bannified[Project Code Dashboard link] * *Other contributions*: ** As Team Lead of GaveSoals: *** Managed milestones `v1.1` - `v1.4` and one `v1.5` (release) on GitHub *** Handle distribution of tasks and features for the team *** Ensure that development is steady and milestones are met *** Manage issue tracker ** Enhancements to existing features: *** Add age option (for dueDate) when adding a Wish (Pull requests https://github.com/CS2103-AY1819S1-T16-1/main/pull/74[#74]) *** Application-wide refactoring to suit our desired WishBook product (Pull requests https://github.com/CS2103-AY1819S1-T16-1/main/pull/12[#12]) ** Community: *** PR reviewed (with non-trivial comments): https://github.com/CS2103-AY1819S1-T16-1/main/pull/1[#1], https://github.com/CS2103-AY1819S1-T16-1/main/pull/7[#7], https://github.com/CS2103-AY1819S1-T16-1/main/pull/55[#55] *** Reported bugs for other teams https://github.com/CS2103-AY1819S1-W12-2/main/issues/103[1], https://github.com/CS2103-AY1819S1-W12-2/main/issues/105[2], https://github.com/CS2103-AY1819S1-W12-2/main/issues/109[3] == Contributions to the User Guide |=== |_Given below are sections I contributed to the User Guide. They showcase my ability to write documentation targeting end-users._ |=== == Quick Start . Ensure you have Java version `9` or later installed in your Computer. . Download the latest `wishbook.jar` link:{repoURL}/releases[here]. . Copy the file to the folder you want to use as the home folder for your WishBook app. . Double-click the file to start the app. The GUI should appear in a few seconds. + image::Ui.png[width="790"] + . Type the command in the command box and press kbd:[Enter] to execute it. + e.g. typing *`help`* and pressing kbd:[Enter] will open the help window. . Some example commands you can try: * *`list`* : Lists all the items you have set as wishes (sorted by due date). * **`add`**`n/uPhoneXX p/1000 a/5m` : adds an item “uPhoneXX” as a goal to be completed in 5 months. * *`help`*: displays list of command with usage. * *`clear`*: clears view * *`exit`* : exits the app . Refer to <<Features>> for details of each command. [[Features]] == Features ==== *Command Format* * Words in `UPPER_CASE` are the parameters to be supplied by the user e.g. in `add WISH`, `WISH` is a parameter which can be used as add iPhone. * Items in square brackets are optional e.g. in `list [FILTER]`, `FILTER` is an optional parameter, since the list command can be used as `list` to display all wishes in WishBook. ** An exception to this is `TIME_GIVEN` and `END_DATE`, whereby only one of the two can be used in any command. ** The `add` command requires either `TIME_GIVEN` and `END_DATE`. ** The `edit` command can take either or none of them. * Items with `…`​ after them can be used multiple times including zero times e.g. `[t/TAG]...` can be used as `{nbsp}` (i.e. 0 times), `t/broke`, `t/needs` etc. * The `/` symbol between parameters means that you can use either of the parameters types in the command e.g. in `add WISH PRICE [TIME_GIVEN]/[START_DATE to END_DATE]`, you provide either the `TIME_GIVEN` parameter or `START_DATE` and `END_DATE` parameters. ==== === Add a new wish: `add` Add a new wish to the wish list. + Format: `add n/WISH_NAME p/PRICE [a/PERIOD_GIVEN]/[d/END_DATE] [u/URL] [t/TAG]...` [TIP] * `[END_DATE]`: Specified in _dd/mm/yyyy_ format. * `[TIME_GIVEN]`: Specified in terms of years, months, weeks, and days, suffixes (coming after the value) marking such time periods are _‘y’_, _‘m’_, _‘w’_, and _‘d’_ respectively. The order of `[TIME_GIVEN]` must be from the biggest unit of time to the smallest unit of time, meaning that the suffix _`y`_ cannot come after any of the other three suffixes, and _'w'_ cannot come after _'d'_, but can come after _'y'_ and _'m'_. [NOTE] ==== If you enter an invalid date, a warning message will be displayed to prompt the user to reenter a valid date. Until all fields provided are valid, the wish will not be added to `WishBook`. ==== [NOTE] ==== The expiry date you enter must be after current date. ==== Examples: * `add n/XBoxTwo p/999 a/1y` * `add n/kfcBook 13inch p/2300 a/6m3w r/For dad t/family t/computing` * `add n/prinkles p/1.95 d/24/04/2020` * `add n/prinkles p/1.95 d/24/04/2020 u/www.amazon.com/prinkles t/high` === Edit a wish : `edit` Edits an existing wish in the wish list. + Format: `edit INDEX [n/WISH_NAME] [p/PRICE] [a/TIME_GIVEN]/[d/END_DATE] [u/URL] [t/TAG]` **** * Edits the wish at the specified `INDEX`. `INDEX` refers to the index number shown in the displayed list of goals. `INDEX` must be a positive integer 1, 2, 3, … * `INDEX` is labelled at the side of each wish. * At least one of the optional fields must be provided. * Existing values will be updated to the input values. * When editing tags, the existing tags of the wish will be removed i.e. adding of tags is not cumulative. * You can remove all tags by typing `t/` without specifying any tags after it. **** Examples: * `edit 1 n/Macbook Pro t/Broke wishes` + Edits the name of the wish and the tag of the 1st wish to be Macbook Pro and Broke wishes respectively * `edit 2 p/22 a/22w` + Edits the price and time given to accomplish the 2nd wish to 22 (in the chosen currency) and 22 weeks respectively. == Contributions to the Developer Guide |=== |_Given below are sections I contributed to the Developer Guide. They showcase my ability to write technical documentation and the technical depth of my contributions to the project._ |=== === Add Wish feature ==== Current Implementation The Add Wish feature is executed through an `AddCommand` by the user, which after parsing, is facilitated mainly by the `ModelManager` which implements `Model`. It also affects `versionedWishBook` and `versionedWishTransaction` by adding the resultant wish to both of their respective data structures. After adding a `Wish`, the `filteredSortedWishes` is also updated to reflect the latest version of WishBook. The UI is also prompted to refresh through a `WishBookChangedEvent`. `AddCommandParser` parses the user's input for parameters using prefixes, and checks them against their respective regular expressions (regex), specified in their respective classes. ==== The following prefix/parameter pairs are **compulsory**, where a user's input will be rejected if they are not provided: * `n/`: Name * `p/`: Price * One of the following Date parameters: ** `d/`: Exact expiry date ** `a/`: duration (or lifetime) from time when command is entered The following prefix/parameter pairs are **optional**, where a user's input will be successful even if they are not provided: * `t/`: tags (more than one allowed) * `u/`: product's URL (product page) ==== [NOTE] ==== **Regarding Duration (`a/`) vs Date (`d/`)** * If `d/` is used, a valid Date should be used. ** Date comes in the format of `dd/mm/yyyy`, `dd` being days, `mm` being months, `yyyy` being the year, and the ** Specified date should also be a valid date in the future. * If `a/` is used, a valid Duration should be used. ** length instead of `dd/mm/yyyy` format, the format should be `<years>y<months>m<days>d`. * In any command, only `Duration` or `Date` can be used. Never both. * If an invalid string for date or duration is provided, a warning will be displayed to prompt the user to enter a valid date or duration. ==== Given below is an example usage scenario and how an AddCommand is carried out. Step 1. The user types in a valid `AddCommand`, `add n/1 TB Toshiba SSD p/158 a/200d`, and the current date is 2nd October 2017 (2/10/2017). The `AddCommandParser` will employ `ParserUtil` to parse the attributes specified after each prefix. The parsing of the `Duration` attribute which follows `a/` in the command will be discussed below. Since `Duration` prefix is used, the computation of a wish's expiry date is handled internally in the `ParserUtil` class, which `ParserUtil#parseDate()` parses and converts the input string into a `Period` object (if input is valid), and adds the resultant `Period` to the current `Date` to get the desired `Date` of the `Wish`. The resultant `Wish` will have the following properties: * id: `a randomly-generated UUID` * Name: _1TB Toshiba SSD_ * SavedAmount: 0.00 * Price: 158.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `false` * Expired: `false` The resultant wish is pass into `VersionedWishBook#addWish` and `VersionedWishTransaction#addWish`, which tracks the history of the `WishBook` and `Wish` respectively. The list of wishes shown on the UI is also updated to show all wishes again, as `filteredSortedWishes` is updated to have all wishes in `WishBook` and a `WishBookChangedEvent` is fired. The following sequence diagram shows how an `AddCommand` is processed in WB: image::AddWishSequenceDiagram.png[width="800"] Step 2. Some time later, the user decides that she wants the exact same wish, but duplicated, and enters the exact same command, but with an exact `Date` instead of `Duration`, so the command entered is `add n/1 TB Toshiba SSD p/158 d/20/4/2018`. Since `Date` prefix is used, the `ParserUtil` parses the string into a `Date` object, and the resultant object is used directly for the resultant `Wish`. Similar to in Step 1, the command will be parsed successfully and a second `Wish` will be added, albeit with a different (hidden) id generated. The resultant `Wish` will have the following properties: * id: `another randomly-generated UUID` * Name: _1TB Toshiba SSD_ * SavedAmount: 0.00 * Price: 158.00 * Date: 20/4/2018 (20th April 2018) * URL: `empty string` * Remark: `empty string` * Tags: `none` * Fulfilled: `false` * Expired: `false` ==== Design Considerations * **Alternative 1 (current choice)**: Different prefixes for `Duration` and `Date`. ** Pros: More focused user experience. User get more specific feedback depending on their preferred way of inputting date if a wrong input was made. If user uses `a/` and enters an incorrect `Duration`, the user will not receive an error message about the correct format for an exact `Date`, and will only be notified of the correct format of a `Duration`. ** Pros: Easier to implement and handle isolate errors related to respective input parameters. ** Cons: More prefixes for user to remember. * **Alternative 2**: Have `Duration` and `Date` use the same prefix. ** Pros: More natural usage of one prefix to determine `Wish` 's desired expiry date. ** Cons: Conflating implementation of `Duration` and `Date`, hence harder to debug. ** Cons: Tricky to implement, as we are parsing one input for two different desired formats. <file_sep>/src/test/java/seedu/address/testutil/WishBuilder.java package seedu.address.testutil; import java.util.HashSet; import java.util.Set; import java.util.UUID; import seedu.address.commons.core.amount.Amount; import seedu.address.model.tag.Tag; import seedu.address.model.util.SampleDataUtil; import seedu.address.model.wish.Date; import seedu.address.model.wish.Name; import seedu.address.model.wish.Price; import seedu.address.model.wish.Remark; import seedu.address.model.wish.SavedAmount; import seedu.address.model.wish.Url; import seedu.address.model.wish.Wish; /** * A utility class to help with building Wish objects. */ public class WishBuilder { public static final String DEFAULT_NAME = "<NAME>"; public static final String DEFAULT_PRICE = "85.53"; public static final String DEFAULT_SAVED_AMOUNT = "0.00"; public static final String DEFAULT_DATE = "29/10/2021"; public static final String DEFAULT_URL = "https://www.lazada.sg/products/" + "ps4-092-hori-real-arcade-pron-hayabusaps4ps3pc-i223784444-s340908955.html"; public static final String DEFAULT_REMARK = ""; public static final String DEFAULT_ID = "e2762cbc-ea52-4f66-aa73-b9b87cbcf004"; private Name name; private Price price; private SavedAmount savedAmount; private Date date; private Url url; private Remark remark; private Set<Tag> tags; private UUID id; public WishBuilder() { name = new Name(DEFAULT_NAME); price = new Price(DEFAULT_PRICE); savedAmount = new SavedAmount(DEFAULT_SAVED_AMOUNT); date = new Date(DEFAULT_DATE); url = new Url(DEFAULT_URL); remark = new Remark(DEFAULT_REMARK); tags = new HashSet<>(); id = UUID.fromString(DEFAULT_ID); } /** * Initializes the WishBuilder with the data of {@code wishToCopy}. */ public WishBuilder(Wish wishToCopy) { name = wishToCopy.getName(); price = wishToCopy.getPrice(); savedAmount = wishToCopy.getSavedAmount(); date = wishToCopy.getDate(); url = wishToCopy.getUrl(); remark = wishToCopy.getRemark(); tags = new HashSet<>(wishToCopy.getTags()); id = wishToCopy.getId(); } /** * Sets the {@code Name} of the {@code Wish} that we are building. */ public WishBuilder withName(String name) { this.name = new Name(name); return this; } /** * Parses the {@code tags} into a {@code Set<Tag>} and set it to the {@code Wish} that we are building. */ public WishBuilder withTags(String ... tags) { this.tags = SampleDataUtil.getTagSet(tags); return this; } /** * Sets the {@code Url} of the {@code Wish} that we are building. */ public WishBuilder withUrl(String url) { this.url = new Url(url); return this; } /** * Sets the {@code Price} of the {@code Wish} that we are building. */ public WishBuilder withPrice(String price) { this.price = new Price(price); return this; } /** * Increments the default {@code SavedAmount} of the {@code Wish} to be built * with the the given {@code SavedAmount}. */ public WishBuilder withSavedAmountIncrement(String savedAmount) { this.savedAmount = this.savedAmount.incrementSavedAmount(new Amount(savedAmount)); return this; } /** * Sets the {@code Date} of the {@code Wish} that we are building. */ public WishBuilder withDate(String date) { this.date = new Date(date); return this; } /** * Sets the {@code Remark} of the {@code Wish} that we are building. */ public WishBuilder withRemark(String remark) { this.remark = new Remark(remark); return this; } /** * Sets the {@code UUID} of the {@code Wish} that we are building. */ public WishBuilder withId(String id) { this.id = UUID.fromString(id); return this; } public Wish build() { return new Wish(name, price, date, url, savedAmount, remark, tags, id); } } <file_sep>/src/main/java/seedu/address/model/versionedmodels/VersionedModel.java package seedu.address.model.versionedmodels; /** * This interface is implemented by classes which keep track of each state of the wishbook. */ public interface VersionedModel { /** * Saves a copy of the current state. */ void commit(); /** * Restores the model to the previous state. */ void undo(); /** * Restores the model to its previously undone state. */ void redo(); /** * Thrown when trying to {@code undo()} but can't. */ class NoUndoableStateException extends RuntimeException { NoUndoableStateException() { super("Current state pointer at start of wishState list, unable to undo."); } } /** * Thrown when trying to {@code redo()} but can't. */ class NoRedoableStateException extends RuntimeException { NoRedoableStateException() { super("Current state pointer at end of wishState list, unable to redo."); } } } <file_sep>/src/main/java/seedu/address/storage/XmlAdaptedSavedAmount.java package seedu.address.storage; import javax.xml.bind.annotation.XmlValue; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.wish.SavedAmount; /** * JAXB-friendly adapted version of the SavedAmount. */ public class XmlAdaptedSavedAmount { @XmlValue private String savedAmount; /** * Constructs an XmlAdaptedSavedAmount. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedSavedAmount() {} /** * Constructs a {@code XmlAdaptedSavedAmount} with the given {@code amount}. */ public XmlAdaptedSavedAmount(String amount) { this.savedAmount = amount; } /** * Converts a given SavedAmount into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedSavedAmount(SavedAmount source) { this.savedAmount = source.toString(); } /** * Converts this jaxb-friendly adapted tag object into the wish's SavedAmount object. * * @throws IllegalValueException if there were any data constraints violated in the adapted wish */ public SavedAmount toSavedAmountType() throws IllegalValueException { if (!SavedAmount.isValidSavedAmount(savedAmount)) { throw new IllegalValueException(SavedAmount.MESSAGE_SAVED_AMOUNT_INVALID); } return new SavedAmount(savedAmount); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof XmlAdaptedSavedAmount)) { return false; } return savedAmount.equals(((XmlAdaptedSavedAmount) other).savedAmount); } } <file_sep>/src/main/java/seedu/address/commons/events/ui/WishDataUpdatedEvent.java package seedu.address.commons.events.ui; import seedu.address.commons.events.BaseEvent; import seedu.address.model.wish.Wish; /** * Represents a selection change in the Wish List Panel */ public class WishDataUpdatedEvent extends BaseEvent { private final Wish newData; public WishDataUpdatedEvent(Wish newData) { this.newData = newData; } @Override public String toString() { return getClass().getSimpleName(); } public Wish getNewData() { return newData; } } <file_sep>/src/main/java/seedu/address/logic/commands/SaveCommand.java package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_WISHES; import java.util.List; import seedu.address.commons.core.EventsCenter; import seedu.address.commons.core.Messages; import seedu.address.commons.core.amount.Amount; import seedu.address.commons.core.index.Index; import seedu.address.commons.events.ui.WishDataUpdatedEvent; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.wish.Wish; /** * Saves specified amount to a specified wish. */ public class SaveCommand extends Command { public static final String COMMAND_WORD = "save"; public static final String COMMAND_ALIAS = "sv"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Channels saving amount to wish." + "Parameters: INDEX (must be a positive integer) " + "[SAVING_AMOUNT]\n" + "Example: " + COMMAND_WORD + " 1 " + "108.50"; public static final String MESSAGE_SAVE_SUCCESS = "Saved %1$s for wish %2$s%3$s."; public static final String MESSAGE_SAVE_UNUSED_FUNDS = "Saved $%1$s to Unused Funds. " + "Unused Funds now contains $%2$s."; public static final String MESSAGE_SAVE_EXCESS = " with $%1$s in excess. Unused Funds now contains $%2$s"; public static final String MESSAGE_SAVE_DIFFERENCE = " with $%1$s left to completion"; private final Index index; private final Amount amountToSave; private final boolean noWishSpecified; public SaveCommand(Index index, Amount amountToSave) { requireNonNull(index); requireNonNull(amountToSave); this.index = index; this.amountToSave = amountToSave; this.noWishSpecified = false; } /** * This constructor is for a {@Code SaveCommand} that directs the amount to unusedFunds. * @param amountToSave */ public SaveCommand(Amount amountToSave) { requireNonNull(amountToSave); this.index = null; this.amountToSave = amountToSave; this.noWishSpecified = true; } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { List<Wish> lastShownList = model.getFilteredSortedWishList(); if (this.noWishSpecified) { try { model.updateUnusedFunds(this.amountToSave); model.commitWishBook(); return new CommandResult(String.format(MESSAGE_SAVE_UNUSED_FUNDS, amountToSave.toString(), model.getUnusedFunds())); } catch (IllegalArgumentException iae) { throw new CommandException(iae.getMessage()); } } if (index.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_WISH_DISPLAYED_INDEX); } Wish wishToEdit = lastShownList.get(index.getZeroBased()); if (wishToEdit.isFulfilled()) { throw new CommandException(Messages.MESSAGE_WISH_FULFILLED); } String differenceString = ""; try { Wish editedWish = Wish.createWishWithIncrementedSavedAmount(wishToEdit, amountToSave); Amount wishSavedDifference = editedWish.getSavedAmountToPriceDifference(); if (wishSavedDifference.value > 0) { Amount amountToIncrement = wishToEdit.getSavedAmountToPriceDifference().getAbsoluteAmount(); editedWish = Wish.createWishWithIncrementedSavedAmount(wishToEdit, amountToIncrement); model.updateUnusedFunds(wishSavedDifference.getAbsoluteAmount()); differenceString = String.format(MESSAGE_SAVE_EXCESS, wishSavedDifference.getAbsoluteAmount(), model.getWishBook().getUnusedFunds()); } else { differenceString = String.format(MESSAGE_SAVE_DIFFERENCE, wishSavedDifference.getAbsoluteAmount()); } model.updateWish(wishToEdit, editedWish); model.updateFilteredWishList(PREDICATE_SHOW_ALL_WISHES); model.commitWishBook(); EventsCenter.getInstance().post(new WishDataUpdatedEvent(editedWish)); } catch (IllegalArgumentException iae) { throw new CommandException(iae.getMessage()); } return new CommandResult(String.format(MESSAGE_SAVE_SUCCESS, amountToSave.toString(), index.getOneBased(), differenceString)); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof SaveCommand)) { return false; } SaveCommand saveCommand = (SaveCommand) other; if (this.noWishSpecified) { return (this.index == null) && this.amountToSave.equals(saveCommand.amountToSave) && (this.noWishSpecified == saveCommand.noWishSpecified); } return this.index.equals(saveCommand.index) && this.amountToSave.equals(saveCommand.amountToSave) && (this.noWishSpecified == saveCommand.noWishSpecified); } } <file_sep>/docs/old_userguide.md ## User Guide [1. Introduction](#section-1) [2. Quick Start](#section-2) [3. Features](#section-3) [3.1. Viewing help: `help`](#section-3.1) [3.2. Adding a wish: `add`](#section-3.2) [3.3. Listing all wishes: `list`](#section-3.3) [3.4. Viewing your saving history: `history`](#section-3.4) [3.5. Editing a wish: `edit`](#section-3.5) [3.6. Locating a wish: `find`](#section-3.6) [3.7. Deleting a wish: `delete`](#section-3.7) [3.8. Ranking your wishes: `rank`](#section-3.8) [3.9. Reordering the priority of your wishes: `swap`](#section-3.9) [3.10. Save money for a specific wish: `save`](#section-3.10) [3.11. Undoing previous command: `undo`](#section-3.11) [3.12. Redoing the previously undone command: `redo`](#section-3.12) [3.13. Clearing all entries: `clear`](#section-3.13) [3.14. Exiting the program: `exit`](#section-3.14) [4. FAQ](#section-4) [5. Command Summary](#section-5) ### 1. Introduction <a id="section-1"></a> SaveGoals (SG) is a piggy bank in a digital app form, made for people who need a user-friendly solution for keeping track of their disposable income. Not only does SG keep records of your savings, it also allows users to set items as goals for users to work towards, serving as a way to cultivate the habit of saving. SG is made for people who have material wants in life, but are uncertain of purchasing said wants, by helping them to reserve disposable income so that they know they can spend on their wants. So what are you waiting for? Go to Section 2, “Quick Start” and start saving! ### 2. Quick Start <a id="section-2"></a> 1. Ensure you have Java version 9 or later installed on your Computer. 2. Download the latest [savegoals.jar]() here. 3. Copy the file to the folder you want to use as the home folder for your Save Goals app. 4. Double-click the .jar file to start the app. The GUI should appear in a few seconds. image::Ui.png[width="790"] 5. Type the command in the command box and press Enter to execute it. * Typing help and pressing enter will bring up a help window. 6. Here are some commands that you can try: * `list`: Lists all the items you have set as wishes (sorted by due date). * `save AMOUNT` * `save 20.50`: adds $20.50 to your nearest goal that’s in-progress. * `add n/WISH_NAME p/PRICE t/[d/TIME_GIVEN]/[d/END_DATE]` * `add n/uPhoneXX p/1000 d/5m`: adds an item “uPhoneXX” as a goal to be completed in 5 months. * `add n/uPhoneXX p/1000 d/12112018`: adds an item “uPhoneXX” as a goal that costs $1000 and sets it to be completed by 12-11-2018. * `clear`: clears view. * `help`: displays list of command with usage. * `exit`: exits the app command. 7. Refer to [Section 3, “Features”](#section-3) for details of each command. ### 3. Features <a id="section-3"></a> --- #### Command Format >* Words in `UPPER_CASE` are the parameters to be supplied by the user * e.g. in `add WISH`, `WISH` is a parameter which can be used as add iPhone. * Items in square brackets are optional * e.g. in `save AMOUNT [INDEX]`, `INDEX` is an optional parameter, since the save command can be used as `save 40`. * The `/` symbol between parameters means that you can use either of the parameters types in the command * e.g. in `add WISH PRICE [TIME_GIVEN]/[START_DATE to END_DATE]`, you provide either the `TIME_GIVEN` parameter, `START_DATE` and `END_DATE` parameters, or none of them. >* Items with `...` after them can be used multiple times. --- #### 3.1 Viewing help: `help` <a id="section-3.1"></a> Format: `help` #### 3.2 Adding a wish: `add` <a id="section-3.2"></a> Adds a wish to your wish list Format: `add n/WISH_NAME p/PRICE t/[d/TIME_GIVEN]/[d/END_DATE]` --- >* `[END_DATE]`: Specified in _ddmmyyyy_ format. Separators are optional. Allowed separators are either dashes ‘-’, forward slashes ‘/’ or periods ‘.’ >* `[TIME_GIVEN]`: Specified in terms of days, weeks or months or years, prefixes marking such time periods are _‘d’, ‘w’, ‘m’_ and _‘y’_ respectively. --- Examples: * `add n/smallRice p/999 d/2d` * `add n/kfcBook_13inch p/2300 d/6m3w` * `add n/prinkles p/1.95 d/24/04/2020` #### 3.3 Listing all wishes: `list` <a id="section-3.3"></a> Shows a list of all the goals you have set, sorted by date by default. Format: `list` #### 3.4. Viewing your saving history: `history` <a id="section-3.4"></a> Shows a history of wishes you have accomplished, from newest to oldest. Format: `history` #### 3.5 Editing a wish: `edit` <a id="section-3.5"></a> Edits an existing wish in the list Format: `edit INDEX [n/WISH_NAME] [p/PRICE] [d/TIME_GIVEN]/[d/END_DATE] [t/TAG]` --- >* Edits the wish at the specified `INDEX`. `INDEX` refers to the index number shown in the displayed list of goals. `INDEX` must be a positive integer 1, 2, 3, … * At least one of the optional fields must be provided. * Existing values will be updated to the input values. * When editing tags, the existing tags of the wish will be removed i.e. adding of tags is not cumulative. >* You can remove all tags by typing `t/` without specifying any tags after it. --- Examples: * `edit 1 n/Macbook Pro t/Broke wishes` Edits the name of the wish and the tag of the 1st goal to be Macbook Pro and Broke wishes respectively * `edit 2 p/22 d/22w` Edits the price and time given to accomplish the 2nd goal to 22 (in the chosen currency) and 22 weeks respectively. #### 3.6 Locating a wish: `find` <a id="section-3.6"></a> Finds wishes which satisfy the given search predicate. Format: `find SEARCH_PREDICATE [MORE_SEARCH_PREDICATES]` --- >* The user can search using the following search predicates: * `NAME` * `DATE` * `PRICE` * `TAG` * `NAME`is the default search predicate. * The search is case insensitive e.g. watch will match Watch. * Only full words will be matched e.g. wat will not match watch. * Goals matching at least one keyword will be returned e.g. watch will return apple watch, pebble watch. * `DATE` is the creation date of the wish. It should match the correct format as specified in [Section 3.2 Date Format](). >* `PRICE` is the sale price of the item. It should be a positive number corrected to the smallest denomination of the currency. --- Examples: * `find 22d` Returns wish with stipulated time given of 22 days. * `find watch t/broke wishes` Returns any wish with name containing watch, with tag broke wishes. #### 3.7 Deleting a wish: `delete` <a id="section-3.7"></a> Deletes the specified wish from the list. Format: `delete INDEX` --- >* `INDEX` refers to the index number shown in the displayed list. >* `INDEX` must be a positive integer 1, 2, 3... --- Examples: * `list` `delete 2` Deletes the 2nd wish in the list. * `find watch` `delete 1` Deletes the 1st wish in the results of the find command (if any). #### 3.8 Ranking your wishes: `rank` <a id="section-3.8"></a> Ranks the wishes by specified wish field so that future savings are allocated in the order or ranking. Format: `rank WISH_FIELD [RANK_ORDER]` --- > `RANK_ORDER` can be `-a`(ascending) or `-d`(descending). By default it is set to ascending. --- Examples: * `rank Date -d` Ranks the wishes in descending order of date created. * `rank Price` Ranks the wishes in ascending order of sale price #### 3.9 Reordering the priority of your wishes: `swap` <a id="section-3.9"></a> Reorders the priority of wishes by swapping wishes at the specified indices. Format: `reorder OLD_INDEX NEW_INDEX ` --- >* A smaller numerical value for index indicates higher priority. >* Indices must be a positive integer 1, 2, 3... --- Examples: * `swap 7 1` Swaps wishes at index 7 and index 1 * `swap 1 8` Swaps wishes at index 1 and index 8 #### 3.10 Save money for a specific wish: `save` <a id="section-3.10"></a> Channels savings for a specified wish. Format: `save AMOUNT [INDEX]` --- >* `INDEX` should be a positive integer 1, 2, 3… * `AMOUNT` should be a positive value to the smallest denomination of the currency. >* If no `INDEX` is specified, money will be transferred to the wish which has the closest due date. --- Examples: * `save 1000 1` Adds $1000 into the item at index 1. #### 3.11 Undoing previous command: `undo` <a id="section-3.11"></a> Restores SaveGoals to the state before the previous undoable command was executed. Format: `undo` --- > Undoable commands: commands that modify SaveGoals content (`add, delete, edit, save, rank`) --- Examples: * `delete 1` `list ` `undo` Reverses the `delete 1` command. * `list` `find 22d` `undo` The `undo` command fails as there are no undoable commands executed previously. * `delete 1` `clear` `undo` `undo` The first `undo` reverses the `clear` command. The second `undo` reverses the `delete 1` command. #### 3.12 Redoing the previously undone command: `redo` <a id="section-3.12"></a> Reverses the most recent `undo` command. Format: `redo` Examples: * `delete 1` `list` `undo` `redo` `undo` reverses the `delete 1` command. Then, the `redo` command reapplies the `delete 1` command. * `delete 1` `redo` The `redo` command fails as there are no `undo` commands executed previously. #### 3.13 Clearing all entries: `clear` <a id="section-3.13"></a> Clears all entries from SaveGoals. Format: `clear` #### 3.14 Exiting the program: `exit` <a id="section-3.14"></a> Exits the program. Format: `exit` ### 4. FAQ <a id="section-4"></a> * **Q**: How do I transfer my data to another computer? **A**: Install the app in the other computer and overwrite the empty data file it creates with the file that contains the data of your previous SaveGoals folder. ### 5. Command Summary <a id="section-5"></a> * Help: `help` * Add: `add n/WISH_NAME p/PRICE t/[d/TIME_GIVEN]/[d/END_DATE]` e.g. add n/kfcBook_13inch p/2300 d/6m3w * List: `list` * History: `history` * Edit: `edit INDEX [n/WISH_NAME] [p/PRICE] [d/TIME_GIVEN]/[d/END_DATE] [t/TAG]` e.g. edit 1 n/Macbook Pro t/Broke wishes * Find: `find SEARCH_PREDICATE [MORE_SEARCH_PREDICATES]` e.g. find 22d * Delete: `delete INDEX` e.g. delete 1 * Rank: `rank WISH_FIELD [RANK_ORDER]` e.g. rank Date -d * Swap: `swap OLD_INDEX NEW_INDEX` e.g. swap 1 8 * Save: `save AMOUNT [INDEX]` e.g. save 1000 1 * Undo: `undo` * Redo: `redo` * Clear: `clear` * Exit: `exit` <file_sep>/src/main/java/seedu/address/model/versionedmodels/VersionedWishBook.java package seedu.address.model.versionedmodels; import java.util.ArrayList; import java.util.List; import seedu.address.model.ReadOnlyWishBook; import seedu.address.model.WishBook; /** * {@code WishBook} that keeps track of its own history. */ public class VersionedWishBook extends WishBook implements VersionedModel { private final List<ReadOnlyWishBook> wishBookStateList; private int currentStatePointer; public VersionedWishBook(ReadOnlyWishBook initialState) { super(initialState); wishBookStateList = new ArrayList<>(); wishBookStateList.add(new WishBook(initialState)); currentStatePointer = 0; } /** * Saves a copy of the current {@code WishBook} state at the end of the state list. * Undone states are removed from the state list. */ @Override public void commit() { removeStatesAfterCurrentPointer(); wishBookStateList.add(new WishBook(this)); currentStatePointer++; } private void removeStatesAfterCurrentPointer() { wishBookStateList.subList(currentStatePointer + 1, wishBookStateList.size()).clear(); } /** * Restores the address book to its previous state. */ @Override public void undo() { if (!canUndo()) { throw new NoUndoableStateException(); } currentStatePointer--; resetData(wishBookStateList.get(currentStatePointer)); } /** * Restores the address book to its previously undone state. */ @Override public void redo() { if (!canRedo()) { throw new NoRedoableStateException(); } currentStatePointer++; resetData(wishBookStateList.get(currentStatePointer)); } /** * Returns true if {@code undo()} has address book states to undo. */ public boolean canUndo() { return currentStatePointer > 0; } /** * Returns true if {@code redo()} has address book states to redo. */ public boolean canRedo() { return currentStatePointer < wishBookStateList.size() - 1; } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof VersionedWishBook)) { return false; } VersionedWishBook otherVersionedWishBook = (VersionedWishBook) other; // state check return super.equals(otherVersionedWishBook) && wishBookStateList.equals(otherVersionedWishBook.wishBookStateList) && currentStatePointer == otherVersionedWishBook.currentStatePointer; } } <file_sep>/src/main/java/seedu/address/logic/commands/EditCommand.java package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PRICE; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import static seedu.address.logic.parser.CliSyntax.PREFIX_URL; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_WISHES; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.commons.util.CollectionUtil; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.tag.Tag; import seedu.address.model.wish.Date; import seedu.address.model.wish.Name; import seedu.address.model.wish.Price; import seedu.address.model.wish.Remark; import seedu.address.model.wish.SavedAmount; import seedu.address.model.wish.Url; import seedu.address.model.wish.Wish; /** * Edits the details of an existing wish in the address book. */ public class EditCommand extends Command { public static final String COMMAND_WORD = "edit"; public static final String COMMAND_ALIAS = "e"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the details of the wish identified " + "by the index number used in the displayed wish list. " + "Existing values will be overwritten by the input values.\n" + "Parameters: INDEX (must be a positive integer) " + "[" + PREFIX_NAME + "NAME] " + "[" + PREFIX_PRICE + "PRICE] " + "[" + PREFIX_DATE + "DATE] " + "[" + PREFIX_URL + "URL] " + "[" + PREFIX_TAG + "TAG]...\n" + "Example: " + COMMAND_WORD + " 1 " + PREFIX_PRICE + "60.60 " + PREFIX_DATE + "20/11/2021"; public static final String MESSAGE_EDIT_WISH_SUCCESS = "Edited Wish: %1$s"; public static final String MESSAGE_NOT_EDITED = "At least one field to edit must be provided."; public static final String MESSAGE_DUPLICATE_WISH = "This wish already exists in the wish book."; private final Index index; private final EditWishDescriptor editWishDescriptor; /** * @param index of the wish in the filtered wish list to edit * @param editWishDescriptor details to edit the wish with */ public EditCommand(Index index, EditWishDescriptor editWishDescriptor) { requireNonNull(index); requireNonNull(editWishDescriptor); this.index = index; this.editWishDescriptor = new EditWishDescriptor(editWishDescriptor); } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { requireNonNull(model); List<Wish> lastShownList = model.getFilteredSortedWishList(); if (index.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_WISH_DISPLAYED_INDEX); } Wish wishToEdit = lastShownList.get(index.getZeroBased()); Wish editedWish = createEditedWish(wishToEdit, editWishDescriptor); if (!wishToEdit.isSameWish(editedWish) && model.hasWish(editedWish)) { throw new CommandException(MESSAGE_DUPLICATE_WISH); } model.updateWish(wishToEdit, editedWish); model.updateFilteredWishList(PREDICATE_SHOW_ALL_WISHES); model.commitWishBook(); return new CommandResult(String.format(MESSAGE_EDIT_WISH_SUCCESS, editedWish)); } /** * Creates and returns a {@code Wish} with the details of {@code wishToEdit} * edited with {@code editWishDescriptor}. */ private static Wish createEditedWish(Wish wishToEdit, EditWishDescriptor editWishDescriptor) { assert wishToEdit != null; Name updatedName = editWishDescriptor.getName().orElse(wishToEdit.getName()); Price updatedPrice = editWishDescriptor.getPrice().orElse(wishToEdit.getPrice()); Date updatedDate = editWishDescriptor.getDate().orElse(wishToEdit.getDate()); Url updatedUrl = editWishDescriptor.getUrl().orElse(wishToEdit.getUrl()); SavedAmount savedAmount = wishToEdit.getSavedAmount(); // edit command does not allow editing remarks Remark remark = wishToEdit.getRemark(); // cannot modify remark with edit command Set<Tag> updatedTags = editWishDescriptor.getTags().orElse(wishToEdit.getTags()); UUID originalUuid = wishToEdit.getId(); return new Wish(updatedName, updatedPrice, updatedDate, updatedUrl, savedAmount, remark, updatedTags, originalUuid); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof EditCommand)) { return false; } // state check EditCommand e = (EditCommand) other; return index.equals(e.index) && editWishDescriptor.equals(e.editWishDescriptor); } /** * Stores the details to edit the wish with. Each non-empty field value will replace the * corresponding field value of the wish. */ public static class EditWishDescriptor { private Name name; private Price price; private Date date; private Url url; private Set<Tag> tags; public EditWishDescriptor() {} /** * Copy constructor. * A defensive copy of {@code tags} is used internally. */ public EditWishDescriptor(EditWishDescriptor toCopy) { setName(toCopy.name); setPrice(toCopy.price); setDate(toCopy.date); setUrl(toCopy.url); setTags(toCopy.tags); } /** * Returns true if at least one field is edited. */ public boolean isAnyFieldEdited() { return CollectionUtil.isAnyNonNull(name, price, date, url, tags); } public void setName(Name name) { this.name = name; } public Optional<Name> getName() { return Optional.ofNullable(name); } public void setPrice(Price price) { this.price = price; } public Optional<Price> getPrice() { return Optional.ofNullable(price); } public void setDate(Date date) { this.date = date; } public Optional<Date> getDate() { return Optional.ofNullable(date); } public void setUrl(Url url) { this.url = url; } public Optional<Url> getUrl() { return Optional.ofNullable(url); } /** * Sets {@code tags} to this object's {@code tags}. * A defensive copy of {@code tags} is used internally. */ public void setTags(Set<Tag> tags) { this.tags = (tags != null) ? new HashSet<>(tags) : null; } /** * Returns an unmodifiable tag set, which throws {@code UnsupportedOperationException} * if modification is attempted. * Returns {@code Optional#empty()} if {@code tags} is null. */ public Optional<Set<Tag>> getTags() { return (tags != null) ? Optional.of(Collections.unmodifiableSet(tags)) : Optional.empty(); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof EditWishDescriptor)) { return false; } // state check EditWishDescriptor e = (EditWishDescriptor) other; return getName().equals(e.getName()) && getPrice().equals(e.getPrice()) && getDate().equals(e.getDate()) && getUrl().equals(e.getUrl()) && getTags().equals(e.getTags()); } } } <file_sep>/docs/team/dioptrique.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Asciidoctor 1.5.8"> <title><NAME> - Project Portfolio</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"> <style> /* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */ /* Uncomment @import statement below to use as custom stylesheet */ /*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block} audio,canvas,video{display:inline-block} audio:not([controls]){display:none;height:0} script{display:none!important} html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%} a{background:transparent} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} abbr[title]{border-bottom:1px dotted} b,strong{font-weight:bold} dfn{font-style:italic} hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,*::before,*::after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} img,object,svg{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} .center{margin-left:auto;margin-right:auto} .stretch{width:100%} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:none} p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em} ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit} ul.square{list-style-type:square} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help} abbr{text-transform:none} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)} blockquote cite::before{content:"\2014 \0020"} blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}} table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede} table thead,table tfoot{background:#f7f8f7} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table} .clearfix::after,.float-group::after{clear:both} *:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed;word-wrap:break-word} *:not(pre)>code.nobreak{word-wrap:normal} *:not(pre)>code.nowrap{white-space:nowrap} pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed} em em{font-style:normal} strong strong{font-weight:400} .keyseq{color:rgba(51,51,51,.8)} kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menuref{color:#000} .menuseq b:not(.caret),.menuref{font-weight:inherit} .menuseq{word-spacing:-.02em} .menuseq b.caret{font-size:1.25em;line-height:.8} .menuseq i.caret{font-weight:bold;text-align:center;width:.45em} b.button::before,b.button::after{position:relative;top:-1px;font-weight:400} b.button::before{content:"[";padding:0 3px 0 2px} b.button::after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table} #header::after,#content::after,#footnotes::after,#footer::after{clear:both} #content{margin-top:1.25em} #content::before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf} #header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px} #header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span::before{content:"\00a0\2013\00a0"} #header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark::before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber::after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc li{line-height:1.3334;margin-top:.3334em} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} #toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}} @media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}} #content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:rgba(255,255,255,.8);line-height:1.44} #content{margin-bottom:.625em} .sect1{padding-bottom:.625em} @media screen and (min-width:768px){#content{margin-bottom:1.25em} .sect1{padding-bottom:1.25em}} .sect1:last-child{padding-bottom:0} .sect1+.sect1{border-top:1px solid #e7e7e9} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} .audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock.fit-content>caption.title{white-space:nowrap;width:0} .paragraph.lead>p,#preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)} table.tableblock #preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:inherit} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6)} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px} .exampleblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child{margin-bottom:0} .sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} .sidebarblock>:first-child{margin-top:0} .sidebarblock>:last-child{margin-bottom:0} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8} .sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1} .literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;overflow-x:auto;padding:1em;font-size:.8125em} @media screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}} @media screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}} .literalblock pre.nowrap,.literalblock pre.nowrap pre,.listingblock pre.nowrap,.listingblock pre.nowrap pre{white-space:pre;word-wrap:normal} .literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .listingblock>.content{position:relative} .listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999} .listingblock:hover code[data-lang]::before{display:block} .listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:#999} .listingblock.terminal pre .command:not([data-prompt])::before{content:"$"} table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45} table.pyhltable td.code{padding-left:.75em;padding-right:0} pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #dddddf} pre.pygments .lineno{display:inline-block;margin-right:.25em} table.pyhltable .linenodiv{background:none!important;padding-right:0!important} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right} .verseblock{margin:0 1em 1.25em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)} .quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none} .quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0} .quoteblock.abstract{margin:0 1em 1.25em;display:block} .quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center} .quoteblock.excerpt,.quoteblock .quoteblock{margin:0 0 1.25em;padding:0 0 .25em 1em;border-left:.25em solid #dddddf} .quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem} .quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;text-align:left;margin-right:0} table.tableblock{max-width:100%;border-collapse:separate} p.tableblock:last-child{margin-bottom:0} td.tableblock>.content{margin-bottom:-1.25em} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all>thead>tr>.tableblock,table.grid-all>tbody>tr>.tableblock{border-width:0 1px 1px 0} table.grid-all>tfoot>tr>.tableblock{border-width:1px 1px 0 0} table.grid-cols>*>tr>.tableblock{border-width:0 1px 0 0} table.grid-rows>thead>tr>.tableblock,table.grid-rows>tbody>tr>.tableblock{border-width:0 0 1px} table.grid-rows>tfoot>tr>.tableblock{border-width:1px 0 0} table.grid-all>*>tr>.tableblock:last-child,table.grid-cols>*>tr>.tableblock:last-child{border-right-width:0} table.grid-all>tbody>tr:last-child>.tableblock,table.grid-all>thead:last-child>tr>.tableblock,table.grid-rows>tbody>tr:last-child>.tableblock,table.grid-rows>thead:last-child>tr>.tableblock{border-bottom-width:0} table.frame-all{border-width:1px} table.frame-sides{border-width:0 1px} table.frame-topbot,table.frame-ends{border-width:1px 0} table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd){background:#f8f8f7} table.stripes-none tr,table.stripes-odd tr:nth-of-type(even){background:none} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} td>div.verse{white-space:pre} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none} ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em} ul.unstyled,ol.unstyled{margin-left:0} ul.checklist{margin-left:.625em} ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em} ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:.25em} ul.inline{display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em} ul.inline>li{margin-left:1.25em} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em} td.hdlist1{font-weight:bold;padding-bottom:1.25em} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top} .colist td:not([class]):first-child img{max-width:none} .colist td:not([class]):last-child{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd} .imageblock.left{margin:.25em .625em 1.25em 0} .imageblock.right{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none;display:inline-block} a.image object{pointer-events:none} sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super} sup.footnote a,sup.footnoteref a{text-decoration:none} sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0} #footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} .gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0} .gist .file-data>table td.line-data{width:99%} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background-color:#00fafa} .black{color:#000} .black-background{background-color:#000} .blue{color:#0000bf} .blue-background{background-color:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background-color:#fa00fa} .gray{color:#606060} .gray-background{background-color:#7d7d7d} .green{color:#006000} .green-background{background-color:#007d00} .lime{color:#00bf00} .lime-background{background-color:#00fa00} .maroon{color:#600000} .maroon-background{background-color:#7d0000} .navy{color:#000060} .navy-background{background-color:#00007d} .olive{color:#606000} .olive-background{background-color:#7d7d00} .purple{color:#600060} .purple-background{background-color:#7d007d} .red{color:#bf0000} .red-background{background-color:#fa0000} .silver{color:#909090} .silver-background{background-color:#bcbcbc} .teal{color:#006060} .teal-background{background-color:#007d7d} .white{color:#bfbfbf} .white-background{background-color:#fafafa} .yellow{color:#bfbf00} .yellow-background{background-color:#fafa00} span.icon>.fa{cursor:default} a span.icon>.fa{cursor:inherit} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]::after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility} h1,h2,p,td.content,span.alt{letter-spacing:-.01em} p strong,td.content strong,div.footnote strong{letter-spacing:-.005em} p,blockquote,dt,td.content,span.alt{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @page{margin:1.25cm .75cm} @media print{*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important} html{font-size:80%} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]::after{content:" (" attr(title) ")"} pre,blockquote,tr,img,object,svg{page-break-inside:avoid} thead{display:table-header-group} svg{max-width:100%} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span::before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]::before{display:block} #footer{padding:0 .9375em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} @media print,amzn-kf8{#header>h1:first-child{margin-top:1.25rem} .sect1{padding:0!important} .sect1+.sect1{border:0} #footer{background:none} #footer-text{color:rgba(0,0,0,.6);font-size:.9em}} @media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}} </style> </head> <body class="article"> <div id="header"> <h1><NAME> - Project Portfolio</h1> </div> <div id="content"> <div class="sect1"> <h2 id="_project_wishbook">PROJECT: WishBook</h2> <div class="sectionbody"> <hr> </div> </div> <div class="sect1"> <h2 id="_overview">Overview</h2> <div class="sectionbody"> <div class="paragraph"> <p>WishBook (WB) is a piggy bank in a digital app form, made for people who need a user-friendly solution for keeping track of their disposable income. Not only does WB keep records of savings, it also allows users to set items as goals for users to work towards, serving as a way to cultivate the habit of saving. WB is made for people who have material wants in life, but are uncertain of purchasing said wants, by helping them to reserve disposable income so that they know they can spend on their wants. The user interacts with it by using a Command Line Interface (CLI), and it has a GUI created with JavaFX. It is written in Java, and has about 15 kLoC.</p> </div> <div class="paragraph"> <p>WishBook is an application adapted from addressbook-level4, the original application developed by the se-edu team.</p> </div> <div class="paragraph"> <p>The source code of addressbook-level4 can be found <a href="https://github.com/nus-cs2103-AY1819S1/addressbook-level4">here</a>.</p> </div> <div class="paragraph"> <p>This project portfolio consists of the contributions I have made to WishBook over the semester.<br></p> </div> </div> </div> <div class="sect1"> <h2 id="_summary_of_contributions">Summary of contributions</h2> <div class="sectionbody"> <div class="ulist"> <ul> <li> <p><strong>Major enhancement</strong>: Added <strong>the ability to save towards a wish or remove an amount from a wish.</strong></p> <div class="ulist"> <ul> <li> <p>What it does: Allows the user to save a specified amount of money to a particular wish or remove a specified amount from it. A wish will be fulfilled when the user saves up to 100% of a wish&#8217;s price and excess amount cannot be saved towards it any longer.</p> </li> <li> <p>Justification: This feature is a crucial feature in the WishBook as it cannot fulfill its primary requirement without it.The fact that two actions, namely saving and removing can be done with a single command means that there are less commands to remember.</p> </li> <li> <p>Highlights: This enhancement touches multiple components and required thorough consideration of alternative design. Hence it is naturally my most time consuming contribution. Significant effort was also expended in modifying the tests to test this new feature.</p> </li> </ul> </div> </li> <li> <p><strong>Minor enhancement</strong>: Added <strong>the ability to find wishes by name, tag and/or remark with specified level of match with keywords.</strong></p> <div class="ulist"> <ul> <li> <p>Justification: The flexible design of this command allows user to specify varying number of arguments to the wish which gives the user multiple ways to find a wish or a group of wishes for ease of access.</p> </li> <li> <p>Highlights: It required an in-depth analysis of design alternatives. The implementation too was challenging as it required rewriting and adapting the code written for an existing command. Significant effort was also expended in modifying the tests to test this new feature.</p> </li> </ul> </div> </li> <li> <p><strong>Minor enhancement</strong>: Converted email attribute in a wish to date attribute which stores the due date of a wish. The date cannot be earlier or equal to the current date.</p> </li> <li> <p><strong>Minor enhancement</strong>: Made the wish list to be permanently sorted by due date regardless of the commands applied on them.</p> <div class="ulist"> <ul> <li> <p>Highlights: Required modification of test data which led to modification of a significant number of tests.</p> </li> </ul> </div> </li> <li> <p><strong>Minor enhancement</strong>: Made the wishes be identified only by a newly added attribute, UUID. This allows for addition of wishes with the same attribute values, something which was not allowed previously. UUID of a wish also cannot be changed upon addition of a wish.</p> </li> <li> <p><strong>Minor enhancement</strong>: Added a remark command.</p> <div class="ulist"> <ul> <li> <p>Credits: Code was adapted from <a href="https://github.com/se-edu/addressbook-level4/pull/599" class="bare">https://github.com/se-edu/addressbook-level4/pull/599</a>.</p> </li> </ul> </div> </li> <li> <p><strong>Code contributed</strong>: [<a href="https://nus-cs2103-ay1819s1.github.io/cs2103-dashboard/#=undefined&amp;search=dioptrique&amp;sort=displayName&amp;since=2018-09-12&amp;until=&amp;timeframe=day&amp;reverse=false&amp;repoSort=true">Functional code</a>]</p> </li> <li> <p><strong>Other contributions</strong>:</p> <div class="ulist"> <ul> <li> <p>Project management:</p> <div class="ulist"> <ul> <li> <p>Managed release <code>v1.1</code> on GitHub</p> </li> </ul> </div> </li> <li> <p>Documentation:</p> <div class="ulist"> <ul> <li> <p>Did structural changes to User Guide: <a href="https://github.com/CS2103-AY1819S1-T16-1/main/pull/67">#67</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/pull/136">#136</a></p> </li> </ul> </div> </li> <li> <p>Community:</p> <div class="ulist"> <ul> <li> <p>Reported bugs and suggestions for group members (examples: <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/71">#71</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/20">#20</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/127">#127</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/130">#130</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/77">#5</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/70">#6</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/85">#7</a>, <a href="https://github.com/CS2103-AY1819S1-T16-1/main/issues/72">#8</a>)</p> </li> <li> <p>Reported bugs and suggestions for other teams (examples: <a href="https://github.com/CS2103-AY1819S1-F11-3/main/issues/197">#197</a>, <a href="https://github.com/CS2103-AY1819S1-F11-3/main/issues/194">#194</a>, <a href="https://github.com/CS2103-AY1819S1-F11-3/main/issues/189">#189</a>, <a href="https://github.com/CS2103-AY1819S1-F11-3/main/issues/186">#186</a>)</p> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </div> </div> <div class="sect1"> <h2 id="_contributions_to_the_user_guide">Contributions to the User Guide</h2> <div class="sectionbody"> <table class="tableblock frame-all grid-all stretch"> <colgroup> <col style="width: 100%;"> </colgroup> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><em>Given below are sections I contributed to the User Guide. They showcase my ability to write documentation targeting end-users.</em></p></td> </tr> </tbody> </table> <div class="sect2"> <h3 id="_locate_your_wish_with_speed_and_precision_find">Locate your wish with speed and precision: <code>find</code></h3> <div class="paragraph"> <p>Find wishes which match the given search keywords.<br> Format: <code>find [-e] [n/NAME_KEYWORD]&#8230;&#8203; [t/TAG_KEYWORD]&#8230;&#8203; [r/REMARK_KEYWORD]&#8230;&#8203;</code></p> </div> <div class="sidebarblock"> <div class="content"> <div class="ulist"> <ul> <li> <p>At least one keyword must be provided.</p> </li> <li> <p>Searching multiple keywords of the <strong>same prefix</strong> will return wishes whose attribute corresponding to the prefix contain <strong>any</strong> one of the keywords.</p> </li> <li> <p>Searching with keywords of <strong>different prefixes</strong> will return only wishes that match will <strong>all</strong> the keywords of the different prefixes.</p> </li> <li> <p>Using the exact match flag, <code>-e</code> returns wishes whose corresponding attributes contain <strong>all</strong> the keywords.</p> </li> <li> <p>The search is case insensitive. e.g. watch will match Watch.</p> </li> </ul> </div> </div> </div> <div class="paragraph"> <p>Examples:</p> </div> <div class="ulist"> <ul> <li> <p><code>find n/wat</code><br> Returns any wish whose name contains the <em>wat</em>.</p> </li> <li> <p><code>find n/wat n/balloon n/appl</code><br> Returns wishes whose names which contain at least any one of <em>wat</em>, <em>balloon</em> or <em>appl</em>.</p> </li> <li> <p><code>find -e n/wat n/balloon n/appl</code><br> Returns only wishes whose names that contain all of <em>wat</em>, <em>balloon</em> and <em>appl</em>.</p> </li> <li> <p><code>find n/watch t/important</code><br> Returns any wish whose name contains <em>watch</em>, and whose tags contains <em>broke wishes</em>.</p> </li> <li> <p><code>find n/wat n/balloon t/important</code><br> Returns any wish whose name contains <em>wat</em> or <em>balloon</em>, and whose tags contains <em>important</em>.</p> </li> </ul> </div> </div> </div> </div> <div class="sect1"> <h2 id="_contributions_to_the_developer_guide">Contributions to the Developer Guide</h2> <div class="sectionbody"> <table class="tableblock frame-all grid-all stretch"> <colgroup> <col style="width: 100%;"> </colgroup> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><em>Given below are sections I contributed to the Developer Guide. They showcase my ability to write technical documentation and the technical depth of my contributions to the project.</em></p></td> </tr> </tbody> </table> <div class="sect2"> <h3 id="_model">Model</h3> <div class="sect3"> <h4 id="_wish_model">Wish Model</h4> <div class="paragraph"> <p>A wish is uniquely identified by its Universal Unique Identifier (UUID) which is generated randomly only once for a particular wish, upon its creation through the <code>AddCommand</code>. A wish stores the following primary attributes:</p> </div> <div class="ulist"> <ul> <li> <p>Name</p> </li> <li> <p>Price</p> </li> <li> <p>Date</p> </li> <li> <p>Saved Amount</p> </li> <li> <p>Url</p> </li> <li> <p>Remark</p> </li> <li> <p>Tags</p> </li> <li> <p>UUID</p> </li> </ul> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> It is impossible for the user to create a duplicate wish as it is impossible to modify a wish&#8217;s UUID. </td> </tr> </table> </div> </div> <div class="sect3"> <h4 id="_wish_priority">Wish Priority</h4> <div class="paragraph"> <p>A wish needs to be prioritised in a specific order such that the wishes with the highest priority will be visible on the top of the list. In WishBook, the priority is determined primarily by the due date of the wish which is stored in every wish&#8217;s <code>Date</code> attribute. Ties are broken by <code>Name</code>. Further ties are broken by <code>UUID</code> as it is possible for the <code>Date</code> and <code>Name</code> of two wishes to be identical.</p> </div> <div class="paragraph"> <p>The sorting of the displayed results is done by the <code>filteredSortedWishes</code> list. The sorting order is specified by <code>WishComparator</code>.</p> </div> </div> <div class="sect3"> <h4 id="_design_considerations">Design Considerations</h4> <div class="sect4"> <h5 id="_aspect_uniqueness_of_a_wish">Aspect: Uniqueness of a Wish</h5> <div class="ulist"> <ul> <li> <p><strong>Alternative 1(current choice):</strong> Identify a <code>Wish</code> by a randomly generated UUID.</p> <div class="ulist"> <ul> <li> <p>Pros: Extremely low probability of collision.</p> </li> <li> <p>Pros: No extra maintenance required upon generation as every <code>Wish</code> is unique.</p> </li> <li> <p>Cons: UUID does not map to any real world entity and it is used strictly for identification.</p> </li> <li> <p>Cons: It is more difficult to system test the <code>AddCommand</code> with the current group of methods for system tests as UUID is randomly generated each time.</p> </li> </ul> </div> </li> <li> <p><strong>Alternative 2:</strong> Identify a wish by <code>Name</code>, <code>Price</code>, <code>Date</code>, <code>Url</code>, <code>Tags</code>. Wishes with identical values for these attributes will be represented by a single <code>WishCard</code>. The <code>WishCard</code> will be augmented with a <code>Multiplicity</code> to indicate the number of identical wishes.</p> <div class="ulist"> <ul> <li> <p>Pros: WishBook will be more compact and every attribute stored in a <code>Wish</code> maps to a real entity.</p> </li> <li> <p>Cons: Additional attribute <code>Multiplicity</code> may have to be frequently edited as it is another attribute that is affected by multiple commands.</p> </li> </ul> </div> </li> <li> <p><strong>Alternative 3:</strong> Identify a wish by a new attribute <code>CreatedTime</code>, which is derived from the system time when the wish is created.</p> <div class="ulist"> <ul> <li> <p>Pros: The attribute maps to a real entity. It can be an additional information presented to the user about a wish.</p> </li> <li> <p>Cons: There might be collisions in <code>CreatedTime</code> if the the system time is incorrect.</p> </li> </ul> </div> </li> </ul> </div> </div> </div> </div> <div class="sect2"> <h3 id="_find_wish_feature">Find Wish Feature</h3> <div class="sect3"> <h4 id="_current_implementation">Current Implementation</h4> <div class="paragraph"> <p>The find mechanism is supported by <code>FindCommandParser</code>. It implements <code>Parser</code> that implements the following operation:</p> </div> <div class="ulist"> <ul> <li> <p><code>FindCommandParser#parse()</code>&#8201;&#8212;&#8201;Checks the arguments for empty strings and throws a <code>ParseException</code> if empty string is found. It then splits the arguments using <code>ArgumentTokenizer#tokenize()</code> and returns an <code>ArgumentMultimap</code>. Keywords of the same prefix are then grouped using <code>ArgumentMultimap#getAllValues()</code>.</p> </li> </ul> </div> <div class="paragraph"> <p>The find mechanism is also facilitated by <code>FindCommand</code>. It extends <code>Command</code> and implements the following operation:</p> </div> <div class="ulist"> <ul> <li> <p><code>FindCommand#execute()</code>&#8201;&#8212;&#8201;Executes the command by updating the current <code>FilteredSortedWishList</code> with the <code>WishContainsKeywordPredicate</code>.</p> </li> </ul> </div> <div class="paragraph"> <p>The predicate <code>WishContainsKeywordsPredicate</code>, takes in three lists of the keywords for the following attributes:</p> </div> <div class="ulist"> <ul> <li> <p>Name</p> </li> <li> <p>Tags</p> </li> <li> <p>Remark</p> </li> </ul> </div> <div class="paragraph"> <p>and also the <code>isExactMatch</code> argument. The result of the predicate is determined by checking whether a <code>Wish</code> contains the given keywords at their corresponding attributes. The match threshold is dictated by the value of <code>isExactMatch</code>.</p> </div> </div> <div class="sect3"> <h4 id="_example">Example</h4> <div class="paragraph"> <p>Given below is an example usage scenario and how the Find mechanism behaves at each step.</p> </div> <div class="paragraph"> <p>Step 1. The user launches the application for the first time.</p> </div> <div class="paragraph"> <p>Step 2. The user executes <code>find n/wat n/apple t/impor</code> command to get all wishes whose name contains the keywords 'iphone' or 'tablet'.</p> </div> <div class="paragraph"> <p>Step 3. The <code>FindCommandParser#parse()</code> is called and the <code>WishContainsKeywordPredicate</code> is constructed with the arguments of the find command.</p> </div> <div class="paragraph"> <p>Step 4. <code>FindCommand#execute()</code> is then called.</p> </div> <div class="paragraph"> <p>Step 5. The entire list of wishes is filtered by the predicate <code>WishContainsKeywordsPredicate</code>.</p> </div> <div class="paragraph"> <p>Step 6. The filtered list of wishes is returned to the GUI.</p> </div> <div class="imageblock"> <div class="content"> <img src="../images/FindCommandSequenceDiagram.png" alt="FindCommandSequenceDiagram" width="800"> </div> </div> </div> <div class="sect3"> <h4 id="_design_considerations_2">Design Considerations</h4> <div class="sect4"> <h5 id="_aspect_argument_format">Aspect: Argument format</h5> <div class="ulist"> <ul> <li> <p><strong>Alternative 1 (Current choice):</strong> Require the user to prepend every keyword argument with the appropriate Wish attribute prefix.</p> <div class="ulist"> <ul> <li> <p>Pros: Easier to implement as it easier to match keyword against a Wish if the attribute to match against is known.</p> </li> <li> <p>Pros: User has more control over the results returned.</p> </li> <li> <p>Cons: User is required to type slightly more.</p> </li> </ul> </div> </li> <li> <p><strong>Alternative 2:</strong> No prefixes are required in the arguments. Keywords can match with any one of the following chosen wish attributes: <code>Name</code>, <code>Tags</code> or <code>Remark</code>.</p> <div class="ulist"> <ul> <li> <p>Pros: Less typing required from user.</p> </li> <li> <p>Cons: Command might be slightly slower as every keyword has to be checked against all chosen attributes of the wish.</p> </li> <li> <p>Cons: User has less control over the results returned.</p> </li> </ul> </div> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="_aspect_default_threshold_for_match_without_the_exact_match_flag">Aspect: Default threshold for match without the exact match flag</h4> <div class="ulist"> <ul> <li> <p><strong>Alternative 1 (Current choice):</strong> Keywords appended to different prefixes are grouped with a logical AND and keywords appended to the same prefixes are grouped with a logical OR when being matched against a <code>Wish</code>.</p> <div class="ulist"> <ul> <li> <p>Pros: A more intuitive way to find wishes.</p> </li> <li> <p>Cons: Can be restrictive in some situations.</p> </li> </ul> </div> </li> <li> <p><strong>Alternative 2:</strong> Keywords appended to different prefixes are grouped with a logical OR and keywords appended to the same prefixes are grouped with a logical OR when being matched against a <code>Wish</code>.</p> <div class="ulist"> <ul> <li> <p>Pros: Search results will be more inclusive.</p> </li> <li> <p>Cons: Very slim chance for such a use case.</p> </li> </ul> </div> </li> </ul> </div> </div> </div> </div> </div> </div> <div id="footer"> <div id="footer-text"> Last updated 2018-11-12 21:55:45 +0800 </div> </div> </body> </html> <file_sep>/src/main/java/seedu/address/logic/commands/AddCommand.java package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PRICE; import static seedu.address.logic.parser.CliSyntax.PREFIX_REMARK; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import static seedu.address.logic.parser.CliSyntax.PREFIX_URL; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.wish.Wish; /** * Adds a wish to the address book. */ public class AddCommand extends Command { public static final String COMMAND_WORD = "add"; public static final String COMMAND_ALIAS = "a"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a wish to the address book. " + "Parameters: " + PREFIX_NAME + "NAME " + PREFIX_PRICE + "PRICE " + PREFIX_DATE + "DATE " + "[" + PREFIX_URL + "URL] " + "[" + PREFIX_REMARK + "REMARK] " + "[" + PREFIX_TAG + "TAG]...\n" + "Example: " + COMMAND_WORD + " " + PREFIX_NAME + "iPad 10 " + PREFIX_PRICE + "6080.50 " + PREFIX_DATE + "20/11/2021 " + PREFIX_URL + "https://www.amazon.com/gp/product/B07D998212 " + PREFIX_REMARK + "For dad. " + PREFIX_TAG + "electronics " + PREFIX_TAG + "personal "; public static final String MESSAGE_SUCCESS = "New wish added: %1$s"; public static final String MESSAGE_DUPLICATE_WISH = "This wish already exists in the address book"; private final Wish toAdd; /** * Creates an AddCommand to add the specified {@code Wish} */ public AddCommand(Wish wish) { requireNonNull(wish); toAdd = wish; } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { requireNonNull(model); if (model.hasWish(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_WISH); } model.addWish(toAdd); model.commitWishBook(); return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd)); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AddCommand // instanceof handles nulls && toAdd.equals(((AddCommand) other).toAdd)); } /** * A weaker notion of equality between {@code AddCommand}. */ public boolean isSameAs(AddCommand other) { return other == this || toAdd.getName().equals(other.toAdd.getName()) && toAdd.getPrice().equals(other.toAdd.getPrice()) && toAdd.getDate().equals(other.toAdd.getDate()); } } <file_sep>/src/main/java/seedu/address/ui/WishDetailSavingHistory.java package seedu.address.ui; import java.util.ArrayList; import java.util.Collections; import java.util.ListIterator; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.Region; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.events.model.WishBookChangedEvent; import seedu.address.commons.events.ui.WishDataUpdatedEvent; import seedu.address.commons.events.ui.WishPanelSelectionChangedEvent; import seedu.address.model.WishTransaction; import seedu.address.model.wish.Wish; /** * Panel containing the detail of wish. */ public class WishDetailSavingHistory extends UiPart<Region> { private static final String FXML = "WishDetailSavingHistory.fxml"; private final Logger logger = LogsCenter.getLogger(getClass()); private WishTransaction wishTransaction; private ArrayList savingHistoryList = new ArrayList(); private String id; @FXML private ListView<String> savingHistoryListView; public WishDetailSavingHistory(WishTransaction wishTransaction) { super(FXML); this.wishTransaction = wishTransaction; registerAsAnEventHandler(this); } private void setConnections(ObservableList<String> savingHistoryList) { savingHistoryListView.setItems(savingHistoryList); savingHistoryListView.setCellFactory(listView -> new WishDetailSavingHistory.SavingHistoryListViewCell()); } /** * Load the page that shows the detail of wish. */ private void loadWishDetails(Wish wish) { this.savingHistoryList.clear(); this.id = wish.getId().toString(); ListIterator<Wish> entry = wishTransaction.getWishMap().get(wish.getId()).listIterator(1); while (entry.hasNext()) { Wish prevWish = wishTransaction.getWishMap().get(wish.getId()).get(entry.previousIndex()); double prevAmount = prevWish.getSavedAmount().value; double nextAmount = entry.next().getSavedAmount().value; double diff = nextAmount - prevAmount; if (diff > 0) { savingHistoryList.add("Saved $" + String.format("%.2f", diff)); } else if (diff < 0) { savingHistoryList.add("Deducted $" + String.format("%.2f", Math.abs(diff))); } } Collections.reverse(savingHistoryList); ObservableList<String> oSavingHistoryList = FXCollections.observableArrayList(savingHistoryList); setConnections(oSavingHistoryList); } @Subscribe private void handleWishPanelSelectionChangedEvent(WishPanelSelectionChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); loadWishDetails(event.getNewSelection()); } @Subscribe private void handleWishDataUpdatedEvent(WishDataUpdatedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "wish data updated by " + WishDetailSavingHistory.class.getSimpleName())); if (this.id.equals(event.getNewData().getId().toString())) { loadWishDetails(event.getNewData()); } } @Subscribe private void handleWishBookChangedEvent(WishBookChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "handled by " + WishDetailSavingHistory.class.getSimpleName())); this.wishTransaction = event.wishTransaction; } /** * Custom {@code ListCell} that displays the graphics of a {@code String} using a {@code WishSavingHistoryCell}. */ class SavingHistoryListViewCell extends ListCell<String> { @Override protected void updateItem(String savingHistory, boolean empty) { super.updateItem(savingHistory, empty); if (empty || savingHistory == null) { setGraphic(null); setText(null); } else { setGraphic(new SavingHistoryCell(savingHistory).getRoot()); } } } } <file_sep>/src/main/java/seedu/address/model/wish/Wish.java package seedu.address.model.wish; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import seedu.address.commons.core.amount.Amount; import seedu.address.model.tag.Tag; /** * Represents a Wish in the address book. * Guarantees: details are present and not null, field values are validated, immutable. */ public class Wish { // Identity fields private final UUID id; // Data fields private final Name name; private final Price price; private final Date date; private final Url url; private final Remark remark; private final Set<Tag> tags = new HashSet<>(); private final SavedAmount savedAmount; private final boolean fulfilled; private final boolean expired; /** * Constructs an object for an already created {@code Wish}. * Every field must be present and not null. */ public Wish(Name name, Price price, Date date, Url url, SavedAmount savedAmount, Remark remark, Set<Tag> tags, UUID id) { requireAllNonNull(name, price, date, url, tags); fulfilled = isSavedAmountGreaterThanOrEqualToPrice(savedAmount, price); expired = isCurrDateGreaterThanOrEqualToDate(date); this.name = name; this.price = price; this.date = date; this.url = url; this.tags.addAll(tags); this.remark = remark; this.savedAmount = savedAmount; this.id = id; } public Wish(Wish wish) { this(new Name(wish.name), new Price(wish.price), new Date(wish.date), new Url(wish.url), new SavedAmount(wish.savedAmount), new Remark(wish.remark), wish.copyTags(), wish.id); } /** * Every field must be present and not null. */ private Wish(Name name, Price price, Date date, Url url, SavedAmount savedAmount, Remark remark, Set<Tag> tags) { requireAllNonNull(name, price, date, url, tags); fulfilled = isSavedAmountGreaterThanOrEqualToPrice(savedAmount, price); expired = isCurrDateGreaterThanOrEqualToDate(date); this.name = name; this.price = price; this.date = date; this.url = url; this.tags.addAll(tags); this.remark = remark; this.savedAmount = savedAmount; this.id = UUID.randomUUID(); } /** * Performs a deep copy on each tag in {@code tags} and returns the copied set of tags. * @return the deep copied set of tags. */ private Set<Tag> copyTags() { Set<Tag> copy = tags.stream().map(Tag::new).collect(Collectors.toSet()); return copy; } /** * Returns a newly created {@code Wish} with a new id. */ public static Wish createWish(Name name, Price price, Date date, Url url, SavedAmount savedAmount, Remark remark, Set<Tag> tags) { requireAllNonNull(name, price, date, url, tags); return new Wish(name, price, date, url, savedAmount, remark, tags); } /** * Returns a newly created {@code Wish} with an incremented savedAmount. * @param oldWish The wish to increment the saved amount on. * @param amountToIncrement The amount to increment by. */ public static Wish createWishWithIncrementedSavedAmount(Wish oldWish, Amount amountToIncrement) { requireAllNonNull(oldWish, amountToIncrement); return new Wish(oldWish.getName(), oldWish.getPrice(), oldWish.getDate(), oldWish.getUrl(), oldWish.getSavedAmount().incrementSavedAmount(amountToIncrement), oldWish.getRemark(), oldWish.getTags(), oldWish.getId()); } /** * Returns true if SaveAmount exceeds Price of wish. */ private boolean isSavedAmountGreaterThanOrEqualToPrice(SavedAmount savedAmount, Price price) { return savedAmount.value >= price.value; } /* * Returns true if CurrDate exceeds Date of wish. */ private boolean isCurrDateGreaterThanOrEqualToDate(Date date) { return new java.util.Date().after(date.getDateObject()); } public Name getName() { return name; } public Price getPrice() { return price; } public Date getDate() { return date; } public SavedAmount getSavedAmount() { return savedAmount; } public Url getUrl() { return url; } public Remark getRemark() { return remark; } public boolean isFulfilled() { return fulfilled; } public boolean isExpired() { return expired; } public UUID getId() { return id; } /** * Returns an immutable tag set, which throws {@code UnsupportedOperationException} * if modification is attempted. */ public Set<Tag> getTags() { return Collections.unmodifiableSet(tags); } /** * Returns true only if two wishes have the same id. */ public boolean isSameWish(Wish otherWish) { if (otherWish == this) { return true; } return otherWish != null && otherWish.getId().equals(getId()); } /** * Returns the progress for {@code wish}, ranges from 0.0 to 1.0. */ public Double getProgress() { return getSavedAmount().value / getPrice().value; } /** * Returns the {@code savedAmount} - {@code price} for {@code wish}. */ public Amount getSavedAmountToPriceDifference() { return Amount.add(new Amount(savedAmount.toString()), new Amount("-" + price.toString())); } /** * Returns true if both wishes have the same identity and data fields. * This defines a stronger notion of equality between two wishes. */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Wish)) { return false; } Wish otherWish = (Wish) other; return otherWish.getName().equals(getName()) && otherWish.getPrice().equals(getPrice()) && otherWish.getDate().equals(getDate()) && otherWish.getUrl().equals(getUrl()) && otherWish.getTags().equals(getTags()) && otherWish.getId().equals(getId()); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(name, price, date, url, tags); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getName()) .append(" Price: ") .append(getPrice()) .append(" Date: ") .append(getDate()) .append(" Url: ") .append(getUrl()) .append(" Remark: ") .append(getRemark()) .append(" Tags: "); getTags().forEach(builder::append); return builder.toString(); } } <file_sep>/src/test/java/seedu/address/model/wish/PriceTest.java package seedu.address.model.wish; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_PRICE_AMY; import org.junit.Test; import seedu.address.testutil.Assert; public class PriceTest { @Test public void constructor_null_throwsNullPointerException() { Assert.assertThrows(NullPointerException.class, () -> new Price((String) null)); Assert.assertThrows(NullPointerException.class, () -> new Price((Price) null)); } @Test public void constructor_invalidPrice_throwsIllegalArgumentException() { String invalidPrice = ""; Assert.assertThrows(IllegalArgumentException.class, () -> new Price(invalidPrice)); } @Test public void copyConstructor_success() { Price price = new Price("93028"); Price copy = new Price(price); assertEquals(price, copy); } @Test public void isValidPrice() { // null price value Assert.assertThrows(NullPointerException.class, () -> Price.isValidPrice(null)); // invalid prices assertFalse(Price.isValidPrice("")); // empty string assertFalse(Price.isValidPrice(" ")); // spaces only assertFalse(Price.isValidPrice("91..1")); // double dot assertFalse(Price.isValidPrice("price")); // non-numeric assertFalse(Price.isValidPrice("1.0e321")); // exp assertFalse(Price.isValidPrice("9312 1534")); // spaces within digits assertFalse(Price.isValidPrice("2.")); // no digits after decimal point // valid prices assertTrue(Price.isValidPrice("93121534")); // no decimal digit assertTrue(Price.isValidPrice("1.0")); // one decimal digit assertTrue(Price.isValidPrice("1.02")); // two decimal digits } @Test public void toStringTest() { Price price = new Price(VALID_PRICE_AMY); assertTrue(price.toString().equals(VALID_PRICE_AMY)); } @Test public void hashCodeTest() { assertTrue(new Price(VALID_PRICE_AMY).hashCode() == new Price(VALID_PRICE_AMY).hashCode()); } } <file_sep>/src/main/java/seedu/address/model/WishBook.java package seedu.address.model; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javafx.collections.ObservableList; import seedu.address.commons.core.amount.Amount; import seedu.address.model.tag.Tag; import seedu.address.model.wish.SavedAmount; import seedu.address.model.wish.UniqueWishList; import seedu.address.model.wish.Wish; import seedu.address.model.wish.exceptions.DuplicateWishException; /** * Wraps all data at the wish book level * Duplicates are not allowed (by .isSameWish comparison) */ public class WishBook implements ReadOnlyWishBook { private final UniqueWishList wishes; private SavedAmount unusedFunds; /* * The 'unusual' code block below is an non-static initialization block, sometimes used to avoid duplication * between constructors. See https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html * * Note that non-static init blocks are not recommended to use. There are other ways to avoid duplication * among constructors. */ { wishes = new UniqueWishList(); unusedFunds = new SavedAmount("" + 0.0); } public WishBook() {} /** * Creates an WishBook using the Wishes in the {@code toBeCopied} */ public WishBook(ReadOnlyWishBook toBeCopied) { this(); resetData(toBeCopied); } //// list overwrite operations /** * Replaces the contents of the wish list with {@code wishes}. * {@code wishes} must not contain duplicate wishes. */ public void setWishes(List<Wish> wishes) { this.wishes.setWishes(wishes); } /** * Resets the existing data of this {@code WishBook} with {@code newData}. */ public void resetData(ReadOnlyWishBook newData) { requireNonNull(newData); setWishes(newData.getWishList()); setUnusedFunds(newData.getUnusedFunds()); } /** * Update the value of unused funds. * @param change The amount to increment/decrease by. */ public void updateUnusedFunds(Amount change) { this.unusedFunds = this.unusedFunds.incrementSavedAmount(change); } /** * Sets the value of the unused funds. * @param amount The amount to set. */ public void setUnusedFunds(SavedAmount amount) { this.unusedFunds = amount; } @Override public SavedAmount getUnusedFunds() { return this.unusedFunds; } //// wish-level operations /** * Returns true if a wish with the same identity as {@code wish} exists in the wish book. */ public boolean hasWish(Wish wish) { requireNonNull(wish); return wishes.contains(wish); } /** * Adds a wish to the wish book. * The wish must not already exist in the wish book. */ public void addWish(Wish p) { wishes.add(p); } /** * Replaces the given wish {@code target} in the list with {@code editedWish}. * {@code target} must exist in the wish book. * The wish identity of {@code editedWish} must not be the same as another existing wish in the wish book. */ public void updateWish(Wish target, Wish editedWish) { requireNonNull(editedWish); wishes.setWish(target, editedWish); } /** * Removes {@code key} from this {@code WishBook}. * {@code key} must exist in the wish book. */ public void removeWish(Wish key) { if (!key.isFulfilled()) { updateUnusedFunds(key.getSavedAmount().getAmount()); } wishes.remove(key); } /** * Removes {@code tag} from all {@code wish}es in this {@code WishBook}. * @throws DuplicateWishException if there's a duplicate {@code Wish} in this {@code WishBook}. */ public void removeTagFromAll(Tag tag) throws DuplicateWishException { ArrayList<Wish> modifiedWishes = new ArrayList<>(); for (Wish wish : wishes.asUnmodifiableObservableList()) { Set<Tag> modifiedTags = new HashSet(wish.getTags()); modifiedTags.removeIf(t -> t == tag); Wish modifiedWish = new Wish(wish.getName(), wish.getPrice(), wish.getDate(), wish.getUrl(), wish.getSavedAmount(), wish.getRemark(), modifiedTags, wish.getId()); modifiedWishes.add(modifiedWish); } wishes.setWishes(modifiedWishes); } //// util methods @Override public String toString() { return wishes.asUnmodifiableObservableList().size() + " wishes"; // TODO: refine later } @Override public ObservableList<Wish> getWishList() { return wishes.asUnmodifiableObservableList(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof WishBook // instanceof handles nulls && wishes.equals(((WishBook) other).wishes) && unusedFunds.equals(((WishBook) other).unusedFunds)); } @Override public int hashCode() { return wishes.hashCode(); } } <file_sep>/docs/team/dioptrique.adoc = <NAME> - Project Portfolio :site-section: AboutUs :imagesDir: ../images :stylesDir: ../stylesheets == PROJECT: WishBook --- == Overview WishBook (WB) is a piggy bank in a digital app form, made for people who need a user-friendly solution for keeping track of their disposable income. Not only does WB keep records of savings, it also allows users to set items as goals for users to work towards, serving as a way to cultivate the habit of saving. WB is made for people who have material wants in life, but are uncertain of purchasing said wants, by helping them to reserve disposable income so that they know they can spend on their wants. The user interacts with it by using a Command Line Interface (CLI), and it has a GUI created with JavaFX. It is written in Java, and has about 15 kLoC. WishBook is an application adapted from addressbook-level4, the original application developed by the se-edu team. The source code of addressbook-level4 can be found https://github.com/nus-cs2103-AY1819S1/addressbook-level4[here]. This project portfolio consists of the contributions I have made to WishBook over the semester. + == Summary of contributions * *Major enhancement*: Added *the ability to save towards a wish or remove an amount from a wish.* ** What it does: Allows the user to save a specified amount of money to a particular wish or remove a specified amount from it. A wish will be fulfilled when the user saves up to 100% of a wish's price and excess amount cannot be saved towards it any longer. ** Justification: This feature is a crucial feature in the WishBook as it cannot fulfill its primary requirement without it.The fact that two actions, namely saving and removing can be done with a single command means that there are less commands to remember. ** Highlights: This enhancement touches multiple components and required thorough consideration of alternative design. Hence it is naturally my most time consuming contribution. Significant effort was also expended in modifying the tests to test this new feature. * *Minor enhancement*: Added *the ability to find wishes by name, tag and/or remark with specified level of match with keywords.* ** Justification: The flexible design of this command allows user to specify varying number of arguments to the wish which gives the user multiple ways to find a wish or a group of wishes for ease of access. ** Highlights: It required an in-depth analysis of design alternatives. The implementation too was challenging as it required rewriting and adapting the code written for an existing command. Significant effort was also expended in modifying the tests to test this new feature. * *Minor enhancement*: Converted email attribute in a wish to date attribute which stores the due date of a wish. The date cannot be earlier or equal to the current date. * *Minor enhancement*: Made the wish list to be permanently sorted by due date regardless of the commands applied on them. ** Highlights: Required modification of test data which led to modification of a significant number of tests. * *Minor enhancement*: Made the wishes be identified only by a newly added attribute, UUID. This allows for addition of wishes with the same attribute values, something which was not allowed previously. UUID of a wish also cannot be changed upon addition of a wish. * *Minor enhancement*: Added a remark command. ** Credits: Code was adapted from https://github.com/se-edu/addressbook-level4/pull/599. * *Code contributed*: [https://nus-cs2103-ay1819s1.github.io/cs2103-dashboard/#=undefined&search=dioptrique&sort=displayName&since=2018-09-12&until=&timeframe=day&reverse=false&repoSort=true[Project Code Dashboard link]] * *Other contributions*: ** Project management: *** Managed release `v1.1` on GitHub ** Documentation: *** Did structural changes to User Guide: https://github.com/CS2103-AY1819S1-T16-1/main/pull/67[#67], https://github.com/CS2103-AY1819S1-T16-1/main/pull/136[#136] ** Community: *** Reported bugs and suggestions for group members (examples: https://github.com/CS2103-AY1819S1-T16-1/main/issues/71[#71], https://github.com/CS2103-AY1819S1-T16-1/main/issues/20[#20], https://github.com/CS2103-AY1819S1-T16-1/main/issues/127[#127], https://github.com/CS2103-AY1819S1-T16-1/main/issues/130[#130], https://github.com/CS2103-AY1819S1-T16-1/main/issues/77[#5], https://github.com/CS2103-AY1819S1-T16-1/main/issues/70[#6], https://github.com/CS2103-AY1819S1-T16-1/main/issues/85[#7], https://github.com/CS2103-AY1819S1-T16-1/main/issues/72[#8]) *** Reported bugs and suggestions for other teams (examples: https://github.com/CS2103-AY1819S1-F11-3/main/issues/197[#197], https://github.com/CS2103-AY1819S1-F11-3/main/issues/194[#194], https://github.com/CS2103-AY1819S1-F11-3/main/issues/189[#189], https://github.com/CS2103-AY1819S1-F11-3/main/issues/186[#186]) == Contributions to the User Guide |=== |_Given below are sections I contributed to the User Guide. They showcase my ability to write documentation targeting end-users._ |=== include::../UserGuide.adoc[tag=find] == Contributions to the Developer Guide |=== |_Given below are sections I contributed to the Developer Guide. They showcase my ability to write technical documentation and the technical depth of my contributions to the project._ |=== include::../DeveloperGuide.adoc[tag=implementationmodel] include::../DeveloperGuide.adoc[tag=find] <file_sep>/docs/AboutUs.adoc = About Us :site-section: AboutUs :relfileprefix: team/ :imagesDir: images :stylesDir: stylesheets WishBook was developed by the https://github.com/orgs/CS2103-AY1819S1-T16-1/teams/developers[GaveSoals] team. + We are a team based in the http://www.comp.nus.edu.sg[School of Computing, National University of Singapore]. The original application (addressbook-level4) was developed by the https://se-edu.github.io/docs/Team.html[se-edu] team. + The source code can be found https://github.com/nus-cs2103-AY1819S1/addressbook-level4[here]. == Project Team === <NAME>, Dominic image::bannified.png[width="150", align="left"] {empty} [https://github.com/bannified[github]] [<<bannified#, portfolio>>] Role: Team Lead + Responsibilities: Scheduling and Tasking, In charge of Model ''' === <NAME> image::leongshengmin.png[width="150", align="left"] {empty}[http://github.com/leongshengmin[github]] [<<leongshengmin#, portfolio>>] Role: Developer + Responsibilities: Code Quality, In charge of Storage ''' === <NAME> image::dioptrique.png[width="150", align="left"] {empty}[http://github.com/dioptrique[github]] [<<dioptrique#, portfolio>>] Role: Developer + Responsibilities: Testing, Integration ''' === <NAME> image::lionelat.png[width="150", align="left"] {empty}[http://github.com/lionelat[github]] [<<lionelat#, portfolio>>] Role: Developer + Responsibilities: Documentation, In charge of Logic, Deliverables and Deadlines ''' === <NAME> image::jiholim.png[width="150", align="left"] {empty}[https://mobbin.design/[homepage]] [http://github.com/jiholim[github]] [<<jiholim_ppp#, portfolio>>] Role: Developer + Responsibilities: UI, In charge of UI component ''' <file_sep>/src/test/java/seedu/address/testutil/EditWishDescriptorBuilder.java package seedu.address.testutil; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import seedu.address.logic.commands.EditCommand.EditWishDescriptor; import seedu.address.model.tag.Tag; import seedu.address.model.wish.Date; import seedu.address.model.wish.Name; import seedu.address.model.wish.Price; import seedu.address.model.wish.Url; import seedu.address.model.wish.Wish; /** * A utility class to help with building EditWishDescriptor objects. */ public class EditWishDescriptorBuilder { private EditWishDescriptor descriptor; public EditWishDescriptorBuilder() { descriptor = new EditWishDescriptor(); } public EditWishDescriptorBuilder(EditWishDescriptor descriptor) { this.descriptor = new EditWishDescriptor(descriptor); } /** * Returns an {@code EditWishDescriptor} with fields containing {@code wish}'s details */ public EditWishDescriptorBuilder(Wish wish) { descriptor = new EditWishDescriptor(); descriptor.setName(wish.getName()); descriptor.setPrice(wish.getPrice()); descriptor.setDate(wish.getDate()); descriptor.setUrl(wish.getUrl()); descriptor.setTags(wish.getTags()); } /** * Sets the {@code Name} of the {@code EditWishDescriptor} that we are building. */ public EditWishDescriptorBuilder withName(String name) { descriptor.setName(new Name(name)); return this; } /** * Sets the {@code Price} of the {@code EditWishDescriptor} that we are building. */ public EditWishDescriptorBuilder withPrice(String price) { descriptor.setPrice(new Price(price)); return this; } /** * Sets the {@code Date} of the {@code EditWishDescriptor} that we are building. * @param date */ public EditWishDescriptorBuilder withDate(String date) { descriptor.setDate(new Date(date)); return this; } /** * Sets the {@code Url} of the {@code EditWishDescriptor} that we are building. */ public EditWishDescriptorBuilder withAddress(String url) { descriptor.setUrl(new Url(url)); return this; } /** * Parses the {@code tags} into a {@code Set<Tag>} and set it to the {@code EditWishDescriptor} * that we are building. */ public EditWishDescriptorBuilder withTags(String... tags) { Set<Tag> tagSet = Stream.of(tags).map(Tag::new).collect(Collectors.toSet()); descriptor.setTags(tagSet); return this; } public EditWishDescriptor build() { return descriptor; } } <file_sep>/src/main/java/seedu/address/storage/XmlWishTransactionStorage.java package seedu.address.storage; import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.logging.Logger; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.commons.util.FileUtil; import seedu.address.model.WishTransaction; /** * A class to access WishTransaction data stored as an xml file on the hard disk. */ public class XmlWishTransactionStorage implements WishTransactionStorage { private static final Logger logger = LogsCenter.getLogger(XmlWishBookStorage.class); private Path filePath; public XmlWishTransactionStorage(Path filePath) { this.filePath = filePath; } @Override public Path getWishTransactionFilePath() { return filePath; } @Override public Optional<WishTransaction> readWishTransaction() throws DataConversionException, IOException { return readWishTransaction(filePath); } @Override public Optional<WishTransaction> readWishTransaction(Path filePath) throws DataConversionException, IOException { requireNonNull(filePath); logger.info("Reading wishTransaction in XmlWishTransactionStorage."); if (!Files.exists(filePath)) { logger.info("WishTransaction file " + filePath + " not found"); return Optional.empty(); } XmlWishTransactions xmlWishTransactions = XmlFileStorage.loadWishTransactionDataFromFile(filePath); try { logger.info("Converting WishTransaction from XML to model type in XmlWishTransactionStorage."); WishTransaction wishTransaction = xmlWishTransactions.toModelType(); return Optional.of(wishTransaction); } catch (IllegalValueException ive) { logger.info("Illegal values found in WishTransaction file at " + filePath + ": " + ive.getMessage()); throw new DataConversionException(ive); } } @Override public void saveWishTransaction(WishTransaction wishTransaction) throws IOException { saveWishTransaction(wishTransaction, filePath); } @Override public void saveWishTransaction(WishTransaction wishTransaction, Path filePath) throws IOException { requireNonNull(wishTransaction); requireNonNull(filePath); FileUtil.createIfMissing(filePath); XmlFileStorage.saveDataToFile(filePath, new XmlWishTransactions(wishTransaction)); } } <file_sep>/src/main/java/seedu/address/model/util/WishComparator.java package seedu.address.model.util; import java.util.Comparator; import seedu.address.model.wish.Date; import seedu.address.model.wish.Wish; /** * Compares Wishes using Wish fields. */ public class WishComparator implements Comparator<Wish> { @Override public int compare(Wish o1, Wish o2) { assert(Date.isValidDate(o1.getDate().date)); assert(Date.isValidDate(o1.getDate().date)); java.util.Date date1 = o1.getDate().getDateObject(); java.util.Date date2 = o2.getDate().getDateObject(); int nameComparison = o1.getName().fullName.compareTo(o2.getName().fullName); if (date1.after(date2)) { return 1; } else if (date1.before(date2)) { return -1; } else if (nameComparison == 1) { return 1; } else if (nameComparison == -1) { return -1; } else { return o1.getId().compareTo(o2.getId()); } } @Override public boolean equals(Object obj) { return false; } } <file_sep>/src/test/java/seedu/address/ui/WishCardTest.java package seedu.address.ui; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.address.ui.testutil.GuiTestAssert.assertCardDisplaysWish; import org.junit.Test; import guitests.guihandles.WishCardHandle; import seedu.address.model.wish.Wish; import seedu.address.testutil.WishBuilder; public class WishCardTest extends GuiUnitTest { @Test public void display() { // no tags Wish wishWithNoTags = new WishBuilder().withTags(new String[0]).build(); WishCard wishCard = new WishCard(wishWithNoTags, 1); uiPartRule.setUiPart(wishCard); assertCardDisplay(wishCard, wishWithNoTags, 1); // with tags Wish wishWithTags = new WishBuilder().build(); wishCard = new WishCard(wishWithTags, 2); uiPartRule.setUiPart(wishCard); assertCardDisplay(wishCard, wishWithTags, 2); } @Test public void equals() { Wish wish = new WishBuilder().build(); WishCard wishCard = new WishCard(wish, 0); // same wish, same index -> returns true WishCard copy = new WishCard(wish, 0); assertTrue(wishCard.equals(copy)); // same object -> returns true assertTrue(wishCard.equals(wishCard)); // null -> returns false assertFalse(wishCard.equals(null)); // different types -> returns false assertFalse(wishCard.equals(0)); // different wish, same index -> returns false Wish differentWish = new WishBuilder().withName("differentName").build(); assertFalse(wishCard.equals(new WishCard(differentWish, 0))); // same wish, different index -> returns false assertFalse(wishCard.equals(new WishCard(wish, 1))); } /** * Asserts that {@code wishCard} displays the details of {@code expectedWish} correctly and matches * {@code expectedId}. */ private void assertCardDisplay(WishCard wishCard, Wish expectedWish, int expectedId) { guiRobot.pauseForHuman(); WishCardHandle wishCardHandle = new WishCardHandle(wishCard.getRoot()); // verify id is displayed correctly //assertEquals(Integer.toString(expectedId) + ". ", wishCardHandle.getId()); // verify wish details are displayed correctly assertCardDisplaysWish(expectedWish, wishCardHandle); } } <file_sep>/src/main/java/seedu/address/storage/XmlAdaptedWishWrapper.java package seedu.address.storage; import static java.util.Objects.requireNonNull; import java.util.Iterator; import java.util.LinkedList; import javax.xml.bind.annotation.XmlElementWrapper; /** * This Xml adapted class acts as a wrapper for a collection of {@code XmlAdaptedWish}es. */ public class XmlAdaptedWishWrapper { @XmlElementWrapper private LinkedList<XmlAdaptedWish> xmlAdaptedWishes; public XmlAdaptedWishWrapper() { this.xmlAdaptedWishes = new LinkedList<>(); } public XmlAdaptedWishWrapper(LinkedList<XmlAdaptedWish> xmlAdaptedWishes) { requireNonNull(xmlAdaptedWishes); this.xmlAdaptedWishes = xmlAdaptedWishes; } public LinkedList<XmlAdaptedWish> getXmlAdaptedWishes() { return xmlAdaptedWishes; } @Override public boolean equals(Object obj) { if (!(obj instanceof XmlAdaptedWishWrapper) || !(hasSameNumberOfWishes((XmlAdaptedWishWrapper) obj))) { return false; } if (((XmlAdaptedWishWrapper) obj).xmlAdaptedWishes.isEmpty() && xmlAdaptedWishes.isEmpty()) { return true; } Iterator<XmlAdaptedWish> otherIterator = ((XmlAdaptedWishWrapper) obj).getXmlAdaptedWishes().listIterator(); Iterator<XmlAdaptedWish> thisIterator = xmlAdaptedWishes.listIterator(); while (otherIterator.hasNext()) { if (!thisIterator.next().equals(otherIterator.next())) { return false; } } return true; } /** * Checks if this has the same number of {@code XmlAdaptedWish} objects as the other {@code XmlAdaptedWishWrapper}. */ private boolean hasSameNumberOfWishes(XmlAdaptedWishWrapper other) { return xmlAdaptedWishes.size() == other.getXmlAdaptedWishes().size(); } } <file_sep>/src/test/java/seedu/address/logic/parser/FindCommandParserTest.java package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import java.util.Arrays; import org.junit.Test; import seedu.address.logic.commands.FindCommand; import seedu.address.model.wish.WishContainsKeywordsPredicate; public class FindCommandParserTest { private FindCommandParser parser = new FindCommandParser(); @Test public void parse_emptyArg_throwsParseException() { assertParseFailure(parser, " ", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } @Test public void parse_noPrefix_throwsParseException() { assertParseFailure(parser, "apple", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); assertParseFailure(parser, "-e", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } @Test public void parse_invalidPrefix_throwsParseException() { assertParseFailure(parser, "p/22.30", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } @Test public void parse_validArgs_returnsFindCommand() { /* isExactMatch set to false */ // no leading and trailing whitespaces FindCommand expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList("Water", "Balloon"), Arrays.asList("family", "important"), Arrays.asList("Visa", "must do"), false)); assertParseSuccess(parser, " n/Water n/Balloon t/family t/important r/Visa r/must do", expectedFindCommand); // multiple whitespaces between keywords assertParseSuccess(parser, " n/Water \n n/Balloon " + "t/family \n t/important \n r/Visa r/must do", expectedFindCommand); // No tags keywords expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList("Water", "Balloon"), Arrays.asList(), Arrays.asList("Visa", "must do"), false)); assertParseSuccess(parser, " n/Water n/Balloon r/Visa r/must do", expectedFindCommand); // No remark keywords expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList("Water", "Balloon"), Arrays.asList("family", "important"), Arrays.asList(), false)); assertParseSuccess(parser, " n/Water n/Balloon t/family t/important", expectedFindCommand); // No name keywords expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList(), Arrays.asList("family", "important"), Arrays.asList("Visa", "must do"), false)); assertParseSuccess(parser, " t/family t/important r/Visa r/must do", expectedFindCommand); // invalid preamble expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList("Water", "Balloon"), Arrays.asList("family", "important"), Arrays.asList("Visa", "must do"), false)); assertParseSuccess(parser, " dsfas;dkfjsd n/Water n/Balloon t/family t/important r/Visa r/must do", expectedFindCommand); // valid preamble expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList("Water", "Balloon"), Arrays.asList("family", "important"), Arrays.asList("Visa", "must do"), true)); assertParseSuccess(parser, " -e n/Water n/Balloon t/family t/important r/Visa r/must do", expectedFindCommand); // jumbled up order of prefixes expectedFindCommand = new FindCommand(new WishContainsKeywordsPredicate(Arrays.asList("Water", "Balloon"), Arrays.asList("family", "important"), Arrays.asList("Visa", "must do"), false)); assertParseSuccess(parser, " n/Water r/Visa t/family n/Balloon t/important r/must do", expectedFindCommand); } } <file_sep>/README.adoc = WishBook ifdef::env-github,env-browser[:relfileprefix: docs/] https://travis-ci.org/CS2103-AY1819S1-T16-1/main[image:https://travis-ci.org/se-edu/addressbook-level4.svg?branch=master[Build Status]] https://ci.appveyor.com/project/damithc/addressbook-level4[image:https://ci.appveyor.com/api/projects/status/3boko2x2vr5cc3w2?svg=true[Build status]] https://coveralls.io/github/se-edu/addressbook-level4?branch=master[image:https://coveralls.io/repos/github/se-edu/addressbook-level4/badge.svg?branch=master[Coverage Status]] https://gitter.im/se-edu/Lobby[image:https://badges.gitter.im/se-edu/Lobby.svg[Gitter chat]] ifdef::env-github[] image::docs/images/Ui.png[width="600"] endif::[] ifndef::env-github[] image::images/Ui.png[width="600"] endif::[] ''' _Are you saving for a house deposit, new car, holiday, household bill etc or putting money aside just in case?_ [%hardbreaks] *Get WishBook and keep track of your savings and save more!* ''' * WishBook is a desktop saving assistant application. It has a GUI but most of the user interactions happen using a CLI (Command Line Interface). * It is a Java application built for people who want to set saving goals and keep track of their progress. * The app boasts beautifully designed interface and has cool features like: ** Auto-calculates of the amount you need to save per month/week to reach your goal by the target date. ** Displays how much you have saved as a proportion of your goal. ** Shows how close you are to your target date. == Site Map * <<UserGuide#, User Guide>> * <<DeveloperGuide#, Developer Guide>> * <<AboutUs#, About Us>> * <<ContactUs#, Contact Us>> == Acknowledgements * This application is based on https://github.com/nus-cs2103-AY1819S1/addressbook-level4[Address Book - Level 4] developed by the https://github.com/se-edu/[se-edu] team. * Some parts of this sample application were inspired by the excellent http://code.makery.ch/library/javafx-8-tutorial/[Java FX tutorial] by _<NAME>_. * Libraries used: https://github.com/TestFX/TestFX[TextFX], https://bitbucket.org/controlsfx/controlsfx/[ControlsFX], https://github.com/FasterXML/jackson[Jackson], https://github.com/google/guava[Guava], https://github.com/junit-team/junit5[JUnit5] == Licence : link:LICENSE[MIT] <file_sep>/src/main/java/seedu/address/ui/WishDetailSavingAmount.java package seedu.address.ui; import java.util.logging.Logger; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.Region; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.events.ui.WishDataUpdatedEvent; import seedu.address.commons.events.ui.WishPanelSelectionChangedEvent; import seedu.address.model.wish.Wish; /** * Panel containing the detail of wish. */ public class WishDetailSavingAmount extends UiPart<Region> { private static final String FXML = "WishDetailSavingAmount.fxml"; private final Logger logger = LogsCenter.getLogger(WishDetailSavingAmount.class); @FXML private Label price; @FXML private Label savedAmount; @FXML private Label progress; private String id; public WishDetailSavingAmount() { super(FXML); loadDefaultDetails(); registerAsAnEventHandler(this); } /** * Load the default page. */ public void loadDefaultDetails() { price.setText(""); savedAmount.setText(""); } /** * Load the page that shows the detail of wish. */ private void loadWishDetails(Wish wish) { savedAmount.setText("$" + wish.getSavedAmount().toString()); price.setText("/ $" + wish.getPrice().toString()); progress.setText(getProgressInString(wish)); this.id = wish.getId().toString(); } /** * Returns the progress String (in percentage) for {@code wish}. */ private String getProgressInString(Wish wish) { Double progress = wish.getProgress() * 100; return String.format("%d", progress.intValue()) + "%"; } @Subscribe private void handleWishPanelSelectionChangedEvent(WishPanelSelectionChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); loadWishDetails(event.getNewSelection()); } @Subscribe private void handleWishDataUpdatedEvent(WishDataUpdatedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); if (this.id.equals(event.getNewData().getId().toString())) { loadWishDetails(event.getNewData()); } } } <file_sep>/src/test/java/seedu/address/logic/parser/SaveCommandParserTest.java package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.commands.CommandTestUtil.VALID_SAVED_AMOUNT_AMY; import static seedu.address.logic.commands.SaveCommand.MESSAGE_USAGE; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import static seedu.address.logic.parser.SaveCommandParser.UNUSED_FUNDS_INDEX; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_WISH; import org.junit.Test; import seedu.address.commons.core.amount.Amount; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.SaveCommand; public class SaveCommandParserTest { private SaveCommandParser saveCommandParser = new SaveCommandParser(); private final Index targetIndex = INDEX_FIRST_WISH; private final Amount amount = new Amount(VALID_SAVED_AMOUNT_AMY); @Test public void parse_indexSpecified_success() { final String userInput = targetIndex.getOneBased() + " " + VALID_SAVED_AMOUNT_AMY; final SaveCommand expectedCommand = new SaveCommand(targetIndex, amount); assertParseSuccess(saveCommandParser, userInput, expectedCommand); final String userInputUnusedFundsIndex = UNUSED_FUNDS_INDEX + " " + VALID_SAVED_AMOUNT_AMY; final SaveCommand expectedCommandUnusedFunds = new SaveCommand(amount); assertParseSuccess(saveCommandParser, userInputUnusedFundsIndex, expectedCommandUnusedFunds); } @Test public void parse_missingCompulsoryField_failure() { final String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, MESSAGE_USAGE); final String userInputMissingIndex = VALID_SAVED_AMOUNT_AMY; assertParseFailure(saveCommandParser, userInputMissingIndex, expectedMessage); final String userInputMissingSavingAmount = targetIndex + " "; assertParseFailure(saveCommandParser, userInputMissingSavingAmount, expectedMessage); /*final String userInputMissingSavingAmountAndSavingPrefix = targetIndex + ""; assertParseFailure(saveCommandParser, userInputMissingSavingAmountAndSavingPrefix, expectedMessage);*/ } }
d0da24633fdff2e1fb9ff0649553b23db08ce33f
[ "Markdown", "Java", "HTML", "AsciiDoc" ]
53
AsciiDoc
CS2103-AY1819S1-T16-1/main
b50a23c07423c05c9bf0204887aadad8e4c0c7dc
ee8480b1d795b1f79d6a99ac391362483f13989f
refs/heads/master
<repo_name>gkesh/ExOsEventPlanner<file_sep>/src/com/pck/eventplanner/jFrameUI/UserUI/UserSignIn.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.jFrameUI.UserUI; import com.pck.eventplanner.entity.Users; import com.pck.eventplanner.jFrameUI.timeslotSelect.TimeSlotUI; /** * * @author G-Kesh */ public class UserSignIn extends javax.swing.JFrame { /** * Creates new form UserSignIn */ public UserSignIn() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSeparator2 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); txtFirstName = new javax.swing.JTextField(); txtLastName = new javax.swing.JTextField(); txtEmail = new javax.swing.JTextField(); txtPhoneNumber = new javax.swing.JTextField(); txtUsername = new javax.swing.JTextField(); txtPassword = new javax.swing.JPasswordField(); BtnNext = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Caviar Dreams", 0, 48)); // NOI18N jLabel1.setText("Register New User"); txtFirstName.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtFirstName.setText("First Name"); txtLastName.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtLastName.setText("Last Name"); txtEmail.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtEmail.setText("E-mail"); txtPhoneNumber.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtPhoneNumber.setText("Phone No"); txtPhoneNumber.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtPhoneNumberActionPerformed(evt); } }); txtUsername.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtUsername.setText("Username"); txtUsername.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUsernameActionPerformed(evt); } }); txtPassword.setText("<PASSWORD>"); BtnNext.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N BtnNext.setText("Next"); BtnNext.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { BtnNextMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 215, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtEmail) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtPhoneNumber, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtUsername, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(209, 209, 209)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jSeparator1) .addContainerGap()))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(299, 299, 299) .addComponent(BtnNext, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(318, 318, 318) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 417, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(33, 33, 33) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtFirstName, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE) .addComponent(txtLastName)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(BtnNext, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(115, 115, 115)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtPhoneNumberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPhoneNumberActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtPhoneNumberActionPerformed private void txtUsernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUsernameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUsernameActionPerformed private void BtnNextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_BtnNextMouseClicked Users usr = new Users(); usr.setFirst_name(txtFirstName.getText()); usr.setLast_name(txtLastName.getText()); usr.setEmail_add(txtEmail.getText()); usr.setPhone_no(txtPhoneNumber.getText()); usr.setUsername(txtUsername.getText()); StringBuilder sb = new StringBuilder(); for(char ch : txtPassword.getPassword()){ sb.append(ch); } usr.setPassword(sb.toString()); TimeSlotUI tUi = new TimeSlotUI(usr); tUi.freeSltUI(); setVisible(false); dispose();//Kill the window }//GEN-LAST:event_BtnNextMouseClicked /** * @return */ public Users addUser() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(UserSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UserSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UserSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UserSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new UserSignIn().setVisible(true); } }); return null; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtnNext; private javax.swing.JLabel jLabel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTextField txtEmail; private javax.swing.JTextField txtFirstName; private javax.swing.JTextField txtLastName; private javax.swing.JPasswordField txtPassword; private javax.swing.JTextField txtPhoneNumber; private javax.swing.JTextField txtUsername; // End of variables declaration//GEN-END:variables } <file_sep>/src/com/pck/eventplanner/dao/UserDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.dao; import com.pck.eventplanner.entity.Users; import java.util.List; /** * * @author G-Kesh */ public interface UserDao { public Boolean addUser(Users usr); public Boolean editProfile(Users usr); public Boolean removeUser(Users usr); public List<Users> showAll(); } <file_sep>/src/com/pck/eventplanner/jdbe/DatabaseConnection.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.jdbe; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author G-Kesh */ public class DatabaseConnection { private Connection con; private PreparedStatement st; public void openConnection() throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/socialtime", "root", ""); } public PreparedStatement initComp(String sql) throws SQLException{ st = con.prepareStatement(sql); return st; } public int execute() throws SQLException{ return st.executeUpdate(); } public ResultSet executeQuery() throws SQLException{ return st.executeQuery(); } public void closeConnection() throws SQLException{ if(con!=null && !con.isClosed()){ con=null; con.close(); } } } <file_sep>/README.md # EventPlanner An event planning system with functioning UI and JDBC for data storage This system was created using NetBeans IDE 8.2 It hasn't been compiled yet, its raw codes. It was my first try at programming. It follows the DAO pattern and all code was written solely by me. It allows easy planning by extracting preferable timesolts of various users and then analyzing the optimal timeslot for the event. It also notifies the user of any invitation where they can RSVP. That said, the system is very rudamentary and only has a local scope. <file_sep>/src/com/pck/eventplanner/jFrameUI/timeslotSelect/TimeSlotUI.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.jFrameUI.timeslotSelect; import com.pck.eventplanner.entity.Users; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author G-Kesh */ public class TimeSlotUI extends javax.swing.JFrame { static Users usr = new Users(); ImageIcon img = new ImageIcon("E:\\Web projects\\Synergy\\$images$\\eventplanner.png"); /** * Creates new form TimeSlotUI */ public TimeSlotUI() { initComponents(); } public TimeSlotUI(Users usr) { initComponents(); TimeSlotUI.usr = usr; } /** * * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jComboBox1 = new javax.swing.JComboBox<>(); jTabbedPane6 = new javax.swing.JTabbedPane(); jLabel5 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); freeDays = new javax.swing.JTabbedPane(); jPanel2 = new javax.swing.JPanel(); jScrollPane8 = new javax.swing.JScrollPane(); MondayFree = new javax.swing.JTextArea(); jPanel5 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); TuesdayFree = new javax.swing.JTextArea(); jPanel6 = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); WedFree = new javax.swing.JTextArea(); jPanel7 = new javax.swing.JPanel(); jScrollPane5 = new javax.swing.JScrollPane(); thursFree = new javax.swing.JTextArea(); jPanel8 = new javax.swing.JPanel(); jScrollPane6 = new javax.swing.JScrollPane(); friFree = new javax.swing.JTextArea(); jPanel9 = new javax.swing.JPanel(); jScrollPane7 = new javax.swing.JScrollPane(); SatFree = new javax.swing.JTextArea(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); SunFree = new javax.swing.JTextArea(); goBack = new javax.swing.JButton(); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabel5.setText("Sunday"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setIconImage(img.getImage() ); jLabel1.setFont(new java.awt.Font("Caviar Dreams", 0, 24)); // NOI18N jLabel1.setText("Select Free Time Slots"); jButton2.setText("Next"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); MondayFree.setColumns(20); MondayFree.setRows(5); MondayFree.setText("Enter you time slots in 24hr format...Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane8.setViewportView(MondayFree); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(214, Short.MAX_VALUE)) ); freeDays.addTab("Monday", jPanel2); TuesdayFree.setColumns(20); TuesdayFree.setRows(5); TuesdayFree.setText("Enter you time slots in 24hr format...Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane3.setViewportView(TuesdayFree); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(207, Short.MAX_VALUE)) ); freeDays.addTab("Tuesday", jPanel5); WedFree.setColumns(20); WedFree.setRows(5); WedFree.setText("Enter you time slots in 24hr format...Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane4.setViewportView(WedFree); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 657, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(199, Short.MAX_VALUE)) ); freeDays.addTab("Wednesday", jPanel6); thursFree.setColumns(20); thursFree.setRows(5); thursFree.setText("Enter you time slots in 24hr format... Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane5.setViewportView(thursFree); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE) .addContainerGap()) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(196, Short.MAX_VALUE)) ); freeDays.addTab("Thursday", jPanel7); friFree.setColumns(20); friFree.setRows(5); friFree.setText("Enter you time slots in 24hr format... Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane6.setViewportView(friFree); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE) .addContainerGap()) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(201, Short.MAX_VALUE)) ); freeDays.addTab("Friday", jPanel8); SatFree.setColumns(20); SatFree.setRows(5); SatFree.setText("Enter you time slots in 24hr format... Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane7.setViewportView(SatFree); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE) .addContainerGap()) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(197, Short.MAX_VALUE)) ); freeDays.addTab("Saturday", jPanel9); SunFree.setColumns(20); SunFree.setRows(5); SunFree.setText("Enter you time slots in 24hr format... Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"); jScrollPane1.setViewportView(SunFree); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 651, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(204, Short.MAX_VALUE)) ); freeDays.addTab("Sunday", jPanel1); goBack.setText("Back"); goBack.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { goBackMouseClicked(evt); } }); goBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goBackActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(goBack, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(freeDays, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE) .addComponent(freeDays, javax.swing.GroupLayout.PREFERRED_SIZE, 515, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(232, 232, 232) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(goBack) .addComponent(jButton2)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void goBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goBackActionPerformed }//GEN-LAST:event_goBackActionPerformed private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked List<String> tmSlt = new ArrayList<>(); String chk= "Enter you time slots in 24hr format... Eg... 1-2,4-5,12-13,18-19 (No Spaces or seperated with comma)"; if(!SunFree.getText().equalsIgnoreCase(chk) && SunFree.getText()!=null){ tmSlt.add("Sunday,"+SunFree.getText()); } if(!MondayFree.getText().equalsIgnoreCase(chk) && MondayFree.getText()!=null){ tmSlt.add("Monday,"+MondayFree.getText()); } if(!TuesdayFree.getText().equalsIgnoreCase(chk) && TuesdayFree.getText()!=null){ tmSlt.add("Tuesday,"+TuesdayFree.getText()); } if(!WedFree.getText().equalsIgnoreCase(chk) && WedFree.getText()!=null){ tmSlt.add("Wednesday,"+WedFree.getText()); } if(!thursFree.getText().equalsIgnoreCase(chk) && thursFree.getText()!=null){ tmSlt.add("Thursday,"+thursFree.getText()); } if(!friFree.getText().equalsIgnoreCase(chk) && friFree.getText()!=null){ tmSlt.add("Friday,"+friFree.getText()); } if(!SatFree.getText().equalsIgnoreCase(chk) && SatFree.getText()!=null){ tmSlt.add("Saturday,"+SatFree.getText()); } int count = tmSlt.size(); int counter = 0; String[][] freeSlt = new String[count][]; for(String str : tmSlt){ freeSlt[counter]=str.split(","); counter++; } usr.setFree_slot(freeSlt); BusyTSUI bS = new BusyTSUI(usr); bS.busy(); setVisible(false); dispose(); }//GEN-LAST:event_jButton2MouseClicked private void goBackMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goBackMouseClicked setVisible(false); dispose(); }//GEN-LAST:event_goBackMouseClicked /** */ public void freeSltUI() { JOptionPane.showMessageDialog(null, "If you don't wish to enter data leave the contents unchanged!!"); /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TimeSlotUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TimeSlotUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TimeSlotUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TimeSlotUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new TimeSlotUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea MondayFree; private javax.swing.JTextArea SatFree; private javax.swing.JTextArea SunFree; private javax.swing.JTextArea TuesdayFree; private javax.swing.JTextArea WedFree; private javax.swing.JTabbedPane freeDays; private javax.swing.JTextArea friFree; private javax.swing.JButton goBack; private javax.swing.JButton jButton2; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JTabbedPane jTabbedPane6; private javax.swing.JTextArea thursFree; // End of variables declaration//GEN-END:variables } <file_sep>/src/com/pck/eventplanner/methods/GetAllTimeSlots.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.methods; import com.pck.eventplanner.entity.TimeSlots; import com.pck.eventplanner.entity.Users; import java.util.List; /** * * @author G-Kesh */ public class GetAllTimeSlots { public TimeSlots getAllTimeSlots(List<Users> lst){ TimeSlotMethods tm = new TimeSlotMethods(lst); TimeSlots ts = new TimeSlots(); ts = tm.availTimeSlot(ts); ts = tm.unavailTimeSlot(ts); ts = tm.undecidedTimeSlot(ts); return ts; } } <file_sep>/src/com/pck/eventplanner/jFrameUI/UserUI/innerMenues/ViewProfile.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.jFrameUI.UserUI.innerMenues; import com.pck.eventplanner.entity.Users; import com.pck.eventplanner.jdbe.UserDBMethods; import java.util.List; import javax.swing.JOptionPane; /** * * @author G-Kesh */ public class ViewProfile extends javax.swing.JFrame { Users usr = new Users();//New User to distribute throughout the class /** * Creates new form ViewProfile */ public ViewProfile() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); txtName = new javax.swing.JTextField(); txtUername = new javax.swing.JTextField(); txtEmail = new javax.swing.JTextField(); txtPhoneNumber = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Name"); jLabel2.setText("Username"); jLabel3.setText("Email"); jLabel4.setText("Phone Number"); txtName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNameActionPerformed(evt); } }); txtUername.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUernameActionPerformed(evt); } }); jButton1.setText("Show Data"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jLabel5.setFont(new java.awt.Font("Caviar Dreams", 1, 24)); // NOI18N jLabel5.setText("User Profile"); jButton2.setText("Close"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 73, Short.MAX_VALUE)) .addComponent(txtUername) .addComponent(txtEmail) .addComponent(txtName) .addComponent(txtPhoneNumber)) .addGap(63, 63, 63)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(79, 79, 79))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtUername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap(23, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtNameActionPerformed private void txtUernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUernameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUernameActionPerformed private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked Users user = new Users(); int count = 0; String username = JOptionPane.showInputDialog("Enter the name "); UserDBMethods uD = new UserDBMethods(); List<Users> usrlst = uD.showAll(); for (Users a : usrlst) { if (a.getFirst_name().equalsIgnoreCase(username)) { user = a; count++; txtName.setText(user.getFirst_name() + " " + user.getLast_name()); txtEmail.setText(user.getEmail_add()); txtUername.setText(user.getUsername()); txtPhoneNumber.setText(user.getPhone_no()); } } if(count==0){ JOptionPane.showMessageDialog(null, "Sorry, "+username+" isn't in our records!"); } }//GEN-LAST:event_jButton1MouseClicked private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked setVisible(false); dispose(); }//GEN-LAST:event_jButton2MouseClicked /** * Main Function getting called */ public void showProfile() { System.out.println(usr.toString()); /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new ViewProfile().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField txtEmail; private javax.swing.JTextField txtName; private javax.swing.JTextField txtPhoneNumber; private javax.swing.JTextField txtUername; // End of variables declaration//GEN-END:variables } <file_sep>/src/com/pck/eventplanner/entity/Users.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.entity; import java.sql.Date; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; /** * * @author G-Kesh */ public class Users { /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ private String first_name, last_name, username, password, email_add, phone_no, event_planner; private String[][] free_slot = new String[7][25]; private String[][] busy_slot = new String[7][25]; private String[][] undecided_slot = new String[7][25]; private final String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; private final String[] timeslot = {"0-1", "1-2", "2-3", "3-4", "4-5", "5-6", "6-7", "7-8", "8-9", "9-10", "10-11", "11-12", "12-13", "13-14", "14-15", "15-16", "16-17", "17-18", "18-19", "19-20", "20-21", "21-22", "22-23", "23-24"}; private Timestamp added_date; private Date modified_date; private int id; private String notification; //Constructor public Users() { } //Getter and the setter public String getEvent_planner() { return event_planner; } public void setEvent_planner(String event_planner) { this.event_planner = event_planner; } public Timestamp getAdded_date() { return added_date; } public String getNotification() { return notification; } public void setNotification(String notification) { this.notification = notification; } public void setAdded_date(Timestamp added_date) { this.added_date = added_date; } public Date getModified_date() { return modified_date; } public void setModified_date(Date modified_date) { this.modified_date = modified_date; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String[] getDays() { return days; } public String[] getTimeslot() { return timeslot; } public String[][] getFree_slot() { return free_slot; } public void setFree_slot(String[][] free_slot) { this.free_slot = free_slot; } public void setBusy_slot(String[][] busy_slot) { this.busy_slot = busy_slot; } public void setUndecided_slot(String[][] undecided_slot) { this.undecided_slot = undecided_slot; } public String[][] getBusy_slot() { return busy_slot; } public String[][] getUndecided_slot() { return undecided_slot; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getEmail_add() { return email_add; } public void setEmail_add(String email_add) { this.email_add = email_add; } public String getPhone_no() { return phone_no; } public void setPhone_no(String phone_no) { this.phone_no = phone_no; } //Returns Arrays in String format public String retString(String[][] ar) { StringBuilder stra = new StringBuilder(); for (String[] arr : ar) { for (String str : arr) { if(str == null){ break; } stra.append(str).append(","); } stra.append("\n"); } return stra.toString(); } public String retString(List<String> ar) { StringBuilder stra = new StringBuilder(); for (String arr : ar) { stra.append(arr).append(","); } return stra.toString(); } @Override public String toString() { return "Users{" + "Fisrt name=" + first_name + "Last name=" + last_name + ", username=" + username + ", password=" + <PASSWORD> + ", email_add=" + email_add + ", phone_no=" + phone_no + ", Attendee=" +", free_time=" + Arrays.toString(free_slot) + ", busy_time=" + Arrays.toString(busy_slot) + ", undecided_slot=" + Arrays.toString(undecided_slot) + '}'; } } <file_sep>/src/com/pck/eventplanner/jFrameUI/UserUI/innerMenues/UpdateEvent.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pck.eventplanner.jFrameUI.UserUI.innerMenues; import com.pck.eventplanner.entity.Events; import com.pck.eventplanner.entity.Users; import com.pck.eventplanner.jdbe.EventDBMethods; import com.pck.eventplanner.jdbe.UserDBMethods; import com.pck.eventplanner.methods.TimeSlotProcessor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author G-Kesh */ public class UpdateEvent extends javax.swing.JFrame { ImageIcon img = new ImageIcon("E:\\Web projects\\Synergy\\$images$\\eventplanner.png"); static Events evts = new Events(); /** * Creates new form UpdateEvent */ public UpdateEvent() { initComponents(); } public UpdateEvent(Events evts) { initComponents(); UpdateEvent.evts = evts; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); txtEventName = new javax.swing.JTextField(); txtLocation = new javax.swing.JTextField(); txtDescription = new javax.swing.JTextField(); txtMinimumThreshold = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); txtMinimumAttendes = new javax.swing.JTextField(); btnUpdate = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); txtInvitedAttendees = new javax.swing.JTextArea(); btnUpdate1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setIconImage(img.getImage() ); addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { formFocusGained(evt); } }); addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { formMouseEntered(evt); } }); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jLabel1.setFont(new java.awt.Font("Caviar Dreams", 0, 24)); // NOI18N jLabel1.setText("Update Event"); txtEventName.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtEventName.setText("Event Name"); txtEventName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtEventNameActionPerformed(evt); } }); txtLocation.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtLocation.setText("Location"); txtDescription.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtDescription.setText("Description"); txtDescription.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtDescriptionActionPerformed(evt); } }); txtMinimumThreshold.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtMinimumThreshold.setText("Minimum Threshold"); txtMinimumThreshold.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMinimumThresholdActionPerformed(evt); } }); jLabel2.setText("Invited attendees"); txtMinimumAttendes.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtMinimumAttendes.setText("Minimum Attendes"); btnUpdate.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N btnUpdate.setText("Update"); btnUpdate.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnUpdateMouseClicked(evt); } }); txtInvitedAttendees.setColumns(20); txtInvitedAttendees.setRows(5); jScrollPane2.setViewportView(txtInvitedAttendees); btnUpdate1.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N btnUpdate1.setText("Cancel"); btnUpdate1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnUpdate1MouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(157, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(135, 135, 135)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jSeparator2) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtEventName) .addComponent(txtLocation) .addComponent(txtDescription) .addComponent(txtMinimumThreshold, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE) .addComponent(jScrollPane2) .addComponent(txtMinimumAttendes) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(btnUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnUpdate1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtEventName, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtLocation, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtMinimumThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(txtMinimumAttendes, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(47, 47, 47) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnUpdate1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(62, 62, 62)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtEventNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEventNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtEventNameActionPerformed private void txtDescriptionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDescriptionActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtDescriptionActionPerformed private void txtMinimumThresholdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMinimumThresholdActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtMinimumThresholdActionPerformed private void btnUpdate1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnUpdate1MouseClicked setVisible(false); dispose(); }//GEN-LAST:event_btnUpdate1MouseClicked private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained }//GEN-LAST:event_formFocusGained private void btnUpdateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnUpdateMouseClicked UserDBMethods uD = new UserDBMethods(); List<Users> usrl, usr2 = new ArrayList<>(); usrl = uD.showAll(); for(Users tmpUsr: usrl){ for(String usrn : evts.getAttendees()){ if(usrn.equalsIgnoreCase(tmpUsr.getFirst_name())){ List<String> tmp,tmp2 = new ArrayList<>(); tmp = Arrays.asList(tmpUsr.getNotification().split(",")); for(String s : tmp){ if(!evts.getName().equalsIgnoreCase(s)){ tmp2.add(s); } } tmpUsr.setNotification(tmpUsr.retString(tmp2)); uD.editProfile(tmpUsr); } } } evts.setName(txtEventName.getText()); evts.setDescription(txtDescription.getText()); evts.setAttendees(Arrays.asList(txtInvitedAttendees.getText().split(","))); evts.setLocation(txtLocation.getText()); evts.setMinAttendees(Integer.parseInt(txtMinimumAttendes.getText())); evts.setMinThres(Double.parseDouble(txtMinimumThreshold.getText())); EventDBMethods eD = new EventDBMethods(); boolean tr = eD.editEvent(evts); if(tr){ JOptionPane.showMessageDialog(null, "Event Updated!!"); } for (Users usra : usrl) { for (String str : evts.getAttendees()) { if (usra.getFirst_name().equalsIgnoreCase(str)) { usr2.add(usra); StringBuilder sba = new StringBuilder(); sba.append(usra.getNotification()).append(",").append(evts.getName()); usra.setNotification(sba.toString()); uD.editProfile(usra); } } } TimeSlotProcessor tm = new TimeSlotProcessor(); String[] ans = new String[6]; ans = tm.timeSlotProcessor(usr2); evts.setSelDate(ans); boolean trth = eD.selTimeSlot(ans, evts.getName()); if (trth) { JOptionPane.showMessageDialog(null, "Date Selected!!"); } setVisible(false); //you can't see me! dispose(); //Destroy the JFrame object }//GEN-LAST:event_btnUpdateMouseClicked private void formMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseEntered }//GEN-LAST:event_formMouseEntered private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated txtEventName.setText(evts.getName()); txtDescription.setText(evts.getDescription()); txtInvitedAttendees.setText(evts.getAttendeeString()); txtLocation.setText(evts.getLocation()); txtMinimumAttendes.setText(Integer.toString(evts.getMinAttendees())); txtMinimumThreshold.setText(Double.toString(evts.getMinThres())); }//GEN-LAST:event_formWindowActivated /** * @return */ public Events updateEvt() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(UpdateEvent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UpdateEvent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UpdateEvent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UpdateEvent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new UpdateEvent().setVisible(true); } }); return null; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnUpdate; private javax.swing.JButton btnUpdate1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JTextField txtDescription; private javax.swing.JTextField txtEventName; private javax.swing.JTextArea txtInvitedAttendees; private javax.swing.JTextField txtLocation; private javax.swing.JTextField txtMinimumAttendes; private javax.swing.JTextField txtMinimumThreshold; // End of variables declaration//GEN-END:variables }
adb356ba7a4a5de2133ffc815ea9819689681e5b
[ "Markdown", "Java" ]
9
Java
gkesh/ExOsEventPlanner
936febc480350ea7a20d2d9001f590f8aa7e46cf
f34482791fb6a4c7642521673a52f7b8cc2b16ed
refs/heads/master
<repo_name>kevinmcmahon/bikeracks<file_sep>/aws/lib/StaticWebsiteStack.ts import cdk = require('@aws-cdk/core'); import { CloudFrontWebDistribution, CloudFrontWebDistributionProps, OriginAccessIdentity, } from '@aws-cdk/aws-cloudfront' import { Bucket } from '@aws-cdk/aws-s3'; import { BucketDeployment, Source } from '@aws-cdk/aws-s3-deployment'; import * as semver from 'semver'; export class StaticWebsiteStack extends cdk.Stack { constructor(scope: cdk.App, id: string, staticWebsiteConfig: IStaticWebsiteProps) { super(scope, id, undefined); const resourcePrefix = staticWebsiteConfig.resourcePrefix; const deploymentVersion = semver.inc(staticWebsiteConfig.deploymentVersion, 'patch') || '1.0.0'; const originPath = deploymentVersion.replace(/\./g, '_'); const sourceBucket = new Bucket(this, `S3BucketForWebsite`, { websiteIndexDocument: staticWebsiteConfig.indexDocument || 'index.html', bucketName: `${resourcePrefix}-website`, }); new BucketDeployment(this, 'DeployWebsite', { sources: [Source.asset(staticWebsiteConfig.websiteDistPath)], destinationBucket: sourceBucket, destinationKeyPrefix: originPath, }); const oai = new OriginAccessIdentity(this, `CloudFrontOIA`,{ comment: `OAI for ${resourcePrefix} website.` }); sourceBucket.grantRead(oai); let cloudFrontDistProps: CloudFrontWebDistributionProps; if (staticWebsiteConfig.certificateArn) { cloudFrontDistProps = { originConfigs: [ { s3OriginSource: { s3BucketSource: sourceBucket, originAccessIdentity: oai }, behaviors: [ {isDefaultBehavior: true}], originPath: `/${originPath}`, } ], aliasConfiguration: { acmCertRef: staticWebsiteConfig.certificateArn, names: staticWebsiteConfig.domainNames || [] } }; } else { cloudFrontDistProps = { originConfigs: [ { s3OriginSource: { s3BucketSource: sourceBucket }, behaviors: [ {isDefaultBehavior: true}], originPath: `/${originPath}`, } ] }; } new CloudFrontWebDistribution(this, `${resourcePrefix}-cloudfront`, cloudFrontDistProps); } } export interface IStaticWebsiteProps { websiteDistPath: string; deploymentVersion: string certificateArn?: string; domainNames?: Array<string>; resourcePrefix: string; indexDocument?: string; } <file_sep>/src/routes.js import Vue from 'vue'; import Router from 'vue-router'; import RackDetail from '@/components/RackDetail'; import Search from '@/components/Search'; import Racks from '@/components/Racks'; Vue.use(Router); export default new Router({ mode: 'history', routes: [ { path: '/', name: 'home', component: Search }, { path: '/bikeracks', name: 'bikeracks', component: Racks }, { path: '/bikeracks/:id', name: 'bikerackdetail', component: RackDetail } ] }); <file_sep>/aws/lib/BikeRacksStaticWebsiteStack.ts import cdk = require('@aws-cdk/core'); import { StaticWebsiteStack, IStaticWebsiteProps } from './StaticWebsiteStack'; const config = require('../config-cdk-bikeracks.json'); export class BikeRacksStaticWebsiteStack extends StaticWebsiteStack { constructor(scope: cdk.App, id: string ) { const props: IStaticWebsiteProps = { websiteDistPath: '../dist', deploymentVersion: '1.0.0', certificateArn: config.certificateArn, domainNames: [config.domainNames], resourcePrefix: config.resourcePrefix, indexDocument: 'index.html', }; super(scope, id, props); } } <file_sep>/src/services/api.js import axios from 'axios'; export default axios.create({ baseURL: 'https://bh4i9yrgt9.execute-api.us-west-2.amazonaws.com/Prod/', timeout: 5000, headers: { 'Content-Type': 'application/json' } }); <file_sep>/README.md # Chicago Bike Rack Locator ## What is the purpose of this Chicago Bike Rack Locator? Find bike racks? More specifically though a toy app to play around with some data the City of Chicago publishes and PostGIS extensions for PostgresDB. ## Project setup ``` yarn install ``` ### Compiles and hot-reloads for development ``` yarn serve ``` ### Compiles and minifies for production ``` yarn build ``` ### Lints and fixes files ``` yarn lint ``` ## AWS CDK Stack This project includes an AWS CDK Stack that can be used to easily deploy the site to AWS. A sample settings file has been provided (`config-cdk-bikeracks.json.example`). The certificateArn is optional but should be provided if the site will leverage AWS provided SSL certificates. ``` { "certificateArn": "YOUR_CERTIFICATE_ARN_HERE", "domainNames": "exampledomain.com", "resourcePrefix": "example-prefix" } ``` ### CDK Useful Commands * `yarn run build` compile typescript to js * `yarn run watch` watch for changes and compile * `cdk deploy` deploy this stack to your default AWS account/region * `cdk diff` compare deployed stack with current state * `cdk synth` emits the synthesized CloudFormation template ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). <file_sep>/aws/bin/aws.ts #!/usr/bin/env node import cdk = require('@aws-cdk/core'); import { BikeRacksStaticWebsiteStack } from '../lib/BikeRacksStaticWebsiteStack'; const app = new cdk.App(); new BikeRacksStaticWebsiteStack(app, 'BikeRacksStaticWebsiteStack');
302ecb839309678c51d417e734b618255af14bf6
[ "JavaScript", "TypeScript", "Markdown" ]
6
TypeScript
kevinmcmahon/bikeracks
08b637ce59a9df6dc1100e7959b9c20b14239f1c
957a44537ed558b69ec3501c076bc4e6b83ddcf6
refs/heads/master
<repo_name>Casecommons/lint-config-javascript<file_sep>/docker-compose.yml version: '3' services: app: build: context: . dockerfile: ./Dockerfile args: ARTIFACTORY_API_KEY: ARTIFACTORY_USER: command: 'tail -f /dev/null' environment: NODE_ENV: development volumes: - .:/app - node_modules:/app/node_modules volumes: node_modules: <file_sep>/Dockerfile FROM node:6.13-alpine # Setup environment ARG ARTIFACTORY_API_KEY ARG ARTIFACTORY_USER ENV APP_ROOT /app # Create app dir RUN mkdir $APP_ROOT WORKDIR $APP_ROOT # Configure NPM for Artifactory RUN true \ && apk add --no-cache --virtual .deps-npm-config curl \ && touch ~/.npmrc \ && echo "package-lock=false" >> ~/.npmrc \ && echo "registry=https://casecommons.jfrog.io/casecommons/api/npm/npm/" >> ~/.npmrc \ && echo "save-exact=true" >> ~/.npmrc \ && (test -n "$ARTIFACTORY_API_KEY" || (echo "FATAL: missing ARTIFACTORY_API_KEY" >&2; exit 1)) \ && (test -n "$ARTIFACTORY_USER" || (echo "FATAL: missing ARTIFACTORY_USER" >&2; exit 1)) \ && curl --user "${ARTIFACTORY_USER}":"${ARTIFACTORY_API_KEY}" https://casecommons.jfrog.io/casecommons/api/npm/auth >> ~/.npmrc \ && apk del .deps-npm-config # Install application dependencies COPY package.json $APP_ROOT RUN true \ && apk add --no-cache --virtual .deps-yarn-install git \ && rm -rf node_modules \ && yarn install --no-progress \ && apk del .deps-yarn-install # Copy app COPY . $APP_ROOT <file_sep>/bin/release #!/bin/bash set -e fatal() { echo "FATAL: $1" >&2 exit 1 } version() { docker-compose run --rm app node -e 'console.log(require("./package.json").version)' | tr -d ' \r\n' } # Check state git fetch || fatal 'Could not fetch remote Git' git fetch --tags || fatal 'Could not fetch remote Git' [[ -z "$(git status --porcelain)" ]] || fatal 'Working tree not clean' [[ "$(git rev-parse --abbrev-ref HEAD)" = "master" ]] || fatal 'Not on master branch' git diff --quiet HEAD '@{u}' || fatal 'Branch is not up-to-date with remote' # Publish package docker-compose run --rm app yarn publish --no-git-tag-version # Create commit and tag, and push version="$(version)" git add package.json git commit -m "v$version" git tag -a -m "v$version" "v$version" git push origin HEAD git push origin "v$version" <file_sep>/eslintrc-test.js module.exports = { "extends": [ "@casecommons/eslint-config/eslintrc-base", ], "rules": { "no-magic-numbers": [0], "react/prop-types": [0], }, } <file_sep>/eslintrc-modern.js module.exports = { "env": { "commonjs": true, "es6": true, }, "extends": [ "@casecommons/eslint-config/eslintrc-base", ], "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true, "modules": true, }, "ecmaVersion": '2017', "sourceType": "module", }, "plugins": [ "react", ], "rules": { "arrow-body-style": [2, "as-needed"], "arrow-parens": [2, "always"], "arrow-spacing": [2], "constructor-super": [2], "generator-star-spacing": [2, "after"], "jsx-quotes": [2, "prefer-single"], "no-class-assign": [2], "no-confusing-arrow": [2, {"allowParens": true}], "no-const-assign": [2], "no-dupe-class-members": [2], "no-this-before-super": [2], "no-var": [2], "prefer-arrow-callback": [2], "prefer-const": [2], "prefer-spread": [2], "prefer-template": [2], "react/display-name": [2], "react/jsx-closing-bracket-location": [2, "tag-aligned"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-indent-props": [2, 2], "react/jsx-no-duplicate-props": [2], "react/jsx-no-undef": [2], "react/jsx-uses-react": 1, "react/jsx-uses-vars": 1, "react/no-danger": [2], "react/no-did-mount-set-state": [2], "react/no-did-update-set-state": [2], "react/no-direct-mutation-state": [2], "react/no-unknown-property": [2], "react/prop-types": [2], "react/react-in-jsx-scope": [2], "react/self-closing-comp": [2], "react/sort-comp": [2], "react/sort-prop-types": [2], "require-yield": [2], }, } <file_sep>/eslintrc-base.js module.exports = { "env": { "browser": true, }, "extends": "eslint:recommended", "rules": { "array-bracket-spacing": [2, "never"], "block-spacing": [2, "always"], "brace-style": [2, "1tbs", {"allowSingleLine": true}], "comma-dangle": [2, "always-multiline"], "comma-spacing": [2, {"before": false, "after": true}], "comma-style": [2, "last"], "computed-property-spacing": [2, "never"], "consistent-return": [2], "consistent-this": [2, "self"], "curly": [2, "multi-line"], "dot-notation": [2], "eqeqeq": [2], "func-names": [2], "func-style": [2, "declaration", {"allowArrowFunctions": true}], "indent": [2, 2, {"SwitchCase": 1}], "key-spacing": [2, {"beforeColon": false, "afterColon": true}], "keyword-spacing": [2], "linebreak-style": [2, "unix"], "new-cap": [2, { "capIsNew": false }], "new-parens": [2], "no-alert": [2], "no-array-constructor": [2], "no-caller": [2], "no-console": [1], "no-constant-condition": [2], "no-empty-pattern": [2], "no-eval": [2], "no-extend-native": [2], "no-extra-bind": [2], "no-extra-semi": [2], "no-fallthrough": [2], "no-floating-decimal": [2], "no-implicit-coercion": [2], "no-implied-eval": [2], "no-invalid-this": [2], "no-labels": [2], "no-lone-blocks": [2], "no-lonely-if": [2], "no-loop-func": [2], "no-magic-numbers": [2, {"enforceConst": true, "ignore": [0, 1]}], "no-multi-spaces": [2], "no-multiple-empty-lines": [2, {"max": 1, "maxBOF": 0, "maxEOF": 0}], "no-native-reassign": [2], "no-negated-condition": [2], "no-nested-ternary": [2], "no-new": [2], "no-new-func": [2], "no-new-object": [2], "no-new-wrappers": [2], "no-octal": [2], "no-octal-escape": [2], "no-proto": [2], "no-return-assign": [2], "no-self-compare": [2], "no-sequences": [2], "no-shadow-restricted-names": [2], "no-spaced-func": [2], "no-throw-literal": [2], "no-trailing-spaces": [2], "no-unexpected-multiline": [2], "no-unneeded-ternary": [2], "no-unused-expressions": [2], "no-unused-vars": [2, {"argsIgnorePattern": '^_'}], "no-use-before-define": [2], "no-useless-call": [2], "no-useless-concat": [2], "no-useless-constructor": [2], "no-void": [2], "no-with": [2], "object-curly-spacing": [2, "never"], "one-var": [2, "never"], "operator-assignment": [2, "always"], "operator-linebreak": [2, "after"], "padded-blocks": [2, "never"], "quote-props": [2, "as-needed", {"keywords": true}], "quotes": [2, "single", {"avoidEscape": true}], "radix": [2, "as-needed"], "semi": [2, "never"], "space-before-blocks": [2, "always"], "space-before-function-paren": [2, {"anonymous": "never", "asyncArrow": "always", "named": "never"}], "space-in-parens": [2, "never"], "space-infix-ops": [2], "space-unary-ops": [2, {"words": true, "nonwords": false}], "wrap-iife": [2], "yoda": [2, "never"], }, } <file_sep>/eslintrc-test-modern.js module.exports = { "extends": [ "@casecommons/eslint-config/eslintrc-modern", "@casecommons/eslint-config/eslintrc-test", ], "rules": { "one-var": [0], "react/prop-types": [0], }, } <file_sep>/README.md # Case Commons JavaScript lint config Configuration for [ESLint](http://eslint.org/) per Case Commons style guide. For TypeScript linting, see [lint-config-typescript](https://github.com/Casecommons/lint-config-typescript). ## Usage Add to dev dependencies in your project: ``` yarn add --dev @casecommons/eslint-config ``` Be sure to add ESLint as a dependency in your project and set it up to run as part of the project’s test suite. Use [`extends`](http://eslint.org/docs/user-guide/configuring#using-a-shareable-configuration-package) to include the appropriate lints into `.eslintrc` in your own project. For example: ```javascript // .eslintrc { extends: [ "@casecommons/eslint-config/eslintrc-modern", ], } ``` There are various configurations available: - `@casecommons/eslint-config/eslintrc-base`: Base configuration applicable to any ECMAScript. - `@casecommons/eslint-config/eslintrc-test`: Extension of base configuration for test code. - `@casecommons/eslint-config/eslintrc-modern`: Extension of base configuration for modern (2015+) ECMAScript. - `@casecommons/eslint-config/eslintrc-test-modern`: Extension of modern configuration for test code. ## Development Docker should be used for simpler dev setup. To do so: 1. `cp .env.sample .env` and set values in `.env` accordingly. 2. `docker-compose build` 3. Prefix the usual `yarn`, etc., commands with `docker-compose exec app`/`docker-compose run --rm app` or similar. ### Packaging Run `yarn pack` which will emit a tarball in the package root directory. This is useful for testing the client in another project without having to perform a release (see [package.json local paths](https://docs.npmjs.com/files/package.json#local-paths)). ### Releasing Run `bin/release`.
0bfad7cd30d2a45eefed11917f6ba3970c46ecdb
[ "YAML", "JavaScript", "Markdown", "Dockerfile", "Shell" ]
8
YAML
Casecommons/lint-config-javascript
b97d1a426820179849c1bcf299b4390c32d9dad4
27e596324cb22f3d1783d9af2f75c9d0a41cde53
refs/heads/master
<file_sep>#!/bin/python from bs4 import BeautifulSoup import pandas as pd import requests import re import sys import time url = sys.argv[1] response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # ======== parsing URL for title ======== url_list = url.split('?') urlSansQuery = url_list[0] if urlSansQuery[-1] == '/': urlSansQuery = urlSansQuery[-1] base_url_list = urlSansQuery.split('/') url_ending = base_url_list[-1] # ======== tags ======== t_tags = soup.find_all('title') p_tags = soup.find_all('p') # ======== file name ======== filename = f'{url_ending}-text.txt' # ======== writing file ======== with open(filename, 'w') as f: f.write('-------- title text --------') f.write('\n') f.write('\n') for t in t_tags: f.write(t.text) f.write('\n') f.write('\n') f.write('\n') f.write('-------- article text --------') f.write('\n') f.write('\n') for p in p_tags: f.write(p.text) f.write('\n') f.write('\n') f.close()
133d9dbfdd817e301e75843364867fb68d7a3c57
[ "Python" ]
1
Python
RandomMemorandum/general-web-scraping
3de045259ba82f4b2293396473c6351a5bf2cb1d
5fb7153ed3c0b74db428d2f26bf32e7d615c2199
refs/heads/main
<file_sep>import { getCountry } from "./api/country/get" import { useRouter } from "next/router" const _ = ({ language, currency, country }) => { const { isFallback } = useRouter(); if (isFallback) return <div>Loading...</div> if (!language || !currency || !country) return null; return ( <div> <h1>{country}</h1> <p>{language}</p> <p>{currency}</p> </div> ) } export default _; export const getStaticProps = async ({ params }) => { const { country } = params; const data = await getCountry(country); console.log(data); if (data.status === "success") { return { props: { country, ...data } } } else { return { notFound: true } } } export const getStaticPaths = async () => { return { paths: [ { params: { country: "croatia" }} ], fallback: true, } }
ab49ed623c6d062ca98512d84032837e258edb94
[ "JavaScript" ]
1
JavaScript
jacksonhardaker/next-isg-test
de2811899cec6b30786e3af2598bc2fb53e63438
1541baf0901eec7f5aa30694dbab4960d07b2e73
refs/heads/master
<file_sep>//! This crates provides a performant iterator over a linear range of //! characters. //! //! The iterator is inclusive of its endpoint, and correctly handles //! the surrogate range (`0xD800`-`0xDFFF`). This induces only one //! extra branch (or conditional-move) compared to a direct `x..y` //! integer iterator that doesn't handle the surrogate range. //! //! [Source](https://github.com/huonw/char-iter) //! //! # Installation //! //! Add this to your Cargo.toml: //! //! ```toml //! [dependencies] //! char-iter = "0.1" //! ``` //! //! # Examples //! //! ```rust //! let v: Vec<char> = char_iter::new('a', 'f').collect(); //! assert_eq!(v, &['a', 'b', 'c', 'd', 'e', 'f']); //! ``` //! //! Reverse iteration is supported: //! //! ```rust //! // (codepoints 224 to 230) //! let v: Vec<char> = char_iter::new('à', 'æ').rev().collect(); //! assert_eq!(v, &['æ', 'å', 'ä', 'ã', 'â', 'á', 'à']); //! ``` //! //! The surrogate range is skipped: //! //! ```rust //! let v: Vec<char> = char_iter::new('\u{D7FF}', '\u{E000}').collect(); //! // 0xD800, ... 0xDFFF are missing //! assert_eq!(v, &['\u{D7FF}', '\u{E000}']); //! ``` #![cfg_attr(all(test, feature = "unstable"), feature(test))] /// An iterator over a linear range of characters. /// /// This is constructed by the `new` function at the top level. pub struct Iter { start: char, end: char, finished: bool, } /// Create a new iterator over the characters (specifically Unicode /// Scalar Values) from `start` to `end`, inclusive. /// /// # Panics /// /// This panics if `start > end`. pub fn new(start: char, end: char) -> Iter { assert!(start <= end); Iter { start: start, end: end, finished: false } } const SUR_START: u32 = 0xD800; const SUR_END: u32 = 0xDFFF; const BEFORE_SUR: u32 = SUR_START - 1; const AFTER_SUR: u32 = SUR_END + 1; enum Dir { Forward, Backward } #[inline(always)] fn step(c: char, d: Dir) -> char { let val = c as u32; let new_val = match d { Dir::Forward => if val == BEFORE_SUR {AFTER_SUR} else {val + 1}, Dir::Backward => if val == AFTER_SUR {BEFORE_SUR} else {val - 1}, }; debug_assert!(std::char::from_u32(new_val).is_some()); unsafe {std::mem::transmute(new_val)} } impl Iterator for Iter { type Item = char; fn next(&mut self) -> Option<char> { if self.finished { return None } let ret = Some(self.start); if self.start == self.end { self.finished = true; } else { self.start = step(self.start, Dir::Forward) } ret } fn size_hint(&self) -> (usize, Option<usize>) { let len = if self.finished { 0 } else { let start = self.start as u32; let end = self.end as u32; let naive_count = (end - start + 1) as usize; if start <= BEFORE_SUR && end >= AFTER_SUR { naive_count - (SUR_END - SUR_START + 1) as usize } else { naive_count } }; (len, Some(len)) } } impl DoubleEndedIterator for Iter { fn next_back(&mut self) -> Option<char> { if self.finished { return None } let ret = Some(self.end); if self.start == self.end { self.finished = true; } else { self.end = step(self.end, Dir::Backward) } ret } } impl ExactSizeIterator for Iter {} #[cfg(test)] mod tests { use super::*; #[test] fn smoke() { let v: Vec<char> = new('a', 'f').collect(); assert_eq!(v, &['a', 'b', 'c', 'd', 'e', 'f']); } #[test] fn smoke_rev() { let v: Vec<char> = new('a', 'f').rev().collect(); assert_eq!(v, &['f', 'e', 'd', 'c', 'b', 'a']); } #[test] fn smoke_size_hint() { let mut iter = new('a', 'f'); assert_eq!(iter.size_hint(), (6, Some(6))); for i in (0..6).rev() { iter.next(); assert_eq!(iter.size_hint(), (i, Some(i))); } iter.next(); assert_eq!(iter.size_hint(), (0, Some(0))); } #[test] fn smoke_rev_size_hint() { let mut iter = new('a', 'f').rev(); assert_eq!(iter.size_hint(), (6, Some(6))); for i in (0..6).rev() { iter.next(); assert_eq!(iter.size_hint(), (i, Some(i))); } iter.next(); assert_eq!(iter.size_hint(), (0, Some(0))); } #[test] fn equal() { let v: Vec<char> = new('a', 'a').collect(); assert_eq!(v, &['a']); } #[test] fn equal_rev() { let v: Vec<char> = new('a', 'a').rev().collect(); assert_eq!(v, &['a']); } #[test] fn equal_size_hint() { let mut iter = new('a', 'a'); assert_eq!(iter.size_hint(), (1, Some(1))); for i in (0..1).rev() { iter.next(); assert_eq!(iter.size_hint(), (i, Some(i))); } iter.next(); assert_eq!(iter.size_hint(), (0, Some(0))); } #[test] fn equal_rev_size_hint() { let mut iter = new('a', 'a').rev(); assert_eq!(iter.size_hint(), (1, Some(1))); for i in (0..1).rev() { iter.next(); assert_eq!(iter.size_hint(), (i, Some(i))); } iter.next(); assert_eq!(iter.size_hint(), (0, Some(0))); } const S: char = '\u{D7FF}'; const E: char = '\u{E000}'; #[test] fn surrogate() { let v: Vec<char> = new(S, E).collect(); assert_eq!(v, &[S, E]); } #[test] fn surrogate_rev() { let v: Vec<char> = new(S, E).rev().collect(); assert_eq!(v, &[E, S]); } #[test] fn surrogate_size_hint() { let mut iter = new(S, E); assert_eq!(iter.size_hint(), (2, Some(2))); for i in (0..2).rev() { iter.next(); assert_eq!(iter.size_hint(), (i, Some(i))); } iter.next(); assert_eq!(iter.size_hint(), (0, Some(0))); } #[test] fn surrogate_rev_size_hint() { let mut iter = new(S, E).rev(); assert_eq!(iter.size_hint(), (2, Some(2))); for i in (0..2).rev() { iter.next(); assert_eq!(iter.size_hint(), (i, Some(i))); } iter.next(); assert_eq!(iter.size_hint(), (0, Some(0))); } #[test] fn full_range() { let iter = new('\u{0}', '\u{10FFFF}'); let mut count = 1_114_112 - 2048; assert_eq!(iter.size_hint(), (count, Some(count))); for (i, c) in (0..0xD800).chain(0xE000..0x10FFFF + 1).zip(iter) { assert_eq!(::std::char::from_u32(i).unwrap(), c); count -= 1; } assert_eq!(count, 0); } #[should_panic] #[test] fn invalid() { new('b','a'); } } #[cfg(all(test, feature = "unstable"))] mod benches { use super::*; extern crate test; #[bench] fn count(b: &mut test::Bencher) { b.iter(|| new('\u{0}', '\u{10FFFF}').count()) } #[bench] fn count_baseline(b: &mut test::Bencher) { // this isn't the same range or the same length, but it's // close enough. b.iter(|| (0..0x10FFFF + 1).count()) } } <file_sep>[package] name = "char-iter" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] homepage = "https://github.com/huonw/char-iter" repository = "https://github.com/huonw/char-iter" documentation = "http://huonw.github.io/char-iter" license = "MIT/Apache-2.0" keywords = ["iterator", "unicode"] description = """ A performant iterator over a linear range of characters (`char`s), correctly handling the surrogate range. """ [features] unstable = [] <file_sep># `char-iter` [![Build Status](https://travis-ci.org/huonw/char-iter.png)](https://travis-ci.org/huonw/char-iter) This crates provides a performant iterator over a linear range of characters, correctly handling the surrogate range. [Documentation](http://huonw.github.io/char-iter), [crates.io](https://crates.io/crates/char-iter).
4d695c3c60abb420f9bb335f69e21d2343435348
[ "TOML", "Rust", "Markdown" ]
3
Rust
huonw/char-iter
a3bc84f3d1f23b842814ca35a7b39fd69f5fa771
b09526c489e4658d16ffbe11f959c1a6e7d2c090
refs/heads/master
<repo_name>BrianRuszkowski/ConsoleApps15<file_sep>/ConsoleAppProject/ConsoleHelper.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleAppProject { public static class ConsoleHelper { /// <summary> /// This method makes sure that the user doesn't input the wrong value /// and repeats the process until a correct value is given /// </summary> /// <param name="choices"></param> /// <returns></returns> public static int SelectChoice(string[] choices) { int choiceNo = 0; //Display all the choices foreach (string choice in choices) { choiceNo++; Console.WriteLine($"|{choiceNo}. {choice}"); } choiceNo = InputNumberWithin(choiceNo - choiceNo + 1, choices.Length); return choiceNo; } /// <summary> /// This method checks that the number is within limit /// </summary> /// <param name="prompt"></param> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static double InputNumber(string prompt, double min, double max) { bool isValid; double number; do { number = InputNumber(prompt); if (number < min || number > max) { isValid = false; Console.WriteLine($"Number must be between {min} and {max}"); } else isValid = true; } while (!isValid); return number; } /// <summary> /// This method checks the input number and if number /// is false the method will ask for a different number /// </summary> /// <returns></returns> public static double InputNumber() { double number = 0; bool Isvalid = false; do { Console.Write(">"); string value = Console.ReadLine(); try { number = Convert.ToDouble(value); Isvalid = true; } catch (Exception) { Isvalid = false; Console.WriteLine("Number is INVALID!!!"); } } while (!Isvalid); return number; } /// <summary> /// This method checks the input number and if number /// is false the method will ask for a different number /// </summary> /// <param name="prompt"></param> /// <returns></returns> public static double InputNumber(string prompt) { double number = 0; bool Isvalid = false; do { Console.Write(">"); string value = Console.ReadLine(); try { number = Convert.ToDouble(value); Isvalid = true; } catch (Exception) { Isvalid = false; Console.WriteLine("Number is INVALID!!!"); } } while (!Isvalid); return number; } /// <summary> /// This method checks the value of the number /// </summary> /// <param name="value"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public static bool InRange(double value, double from, double to) { if (value >= from && value <= to) { return true; } else { return false; } } /// <summary> /// This method checks the input number and keeps it within the value /// any number that is greater than will not count /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public static int InputNumberWithin(int from, int to) { int number; bool Isvalid; do { double value = InputNumber(); number = Convert.ToInt32(value); Isvalid = true; if (number < from || number > to) { Console.WriteLine($"Number must be between {from} and {to} !"); Isvalid = false; } } while (!Isvalid); return number; } /// <summary> /// This method displays the student name and the name of the application /// </summary> /// <param name="heading"></param> public static void OutputHeading(string heading) { Console.WriteLine("\n--------------------------------------------"); Console.WriteLine(" {heading} "); Console.WriteLine(" By <NAME> "); Console.WriteLine("--------------------------------------------\n"); } } } <file_sep>/ConsoleAppProject/App03/StudentGrades.cs using System; namespace ConsoleAppProject.App03 { /// <summary> /// This method contains all the information for the program /// such how many marks you need for a certain grade /// </summary> public class StudentGrades { // Constants (Grade Boundaries) public const int LowestMark = 0; public const int LowestGradeD = 40; public const int LowestGradeC = 50; public const int LowestGradeB = 60; public const int LowestGradeA = 70; public const int HighestMark = 100; // Properties public string[] Students { get; set; } public int[] Marks { get; set; } public int[] GradeProfile { get; set; } public double Mean { get; set; } public int Minimum { get; set; } public int Maximum { get; set; } /// <summary> /// This method is for the list of student names whithin the /// application /// </summary> public StudentGrades() { Students = new string[] { "Brian", "Blend", "Eliott", "Tom", "Ash", "Lian", "Jack", "Liam", "Jess", "Shamial" }; GradeProfile = new int[(int)Grades.A + 1]; Marks = new int[Students.Length]; } /// <summary> /// This method outputs the choices for the user and allows them /// to choose what they want to do after a number has been entered /// it will take them to that choice /// </summary> public void OutputMenu() { string[] choices = new string[] { "Input Marks", "Output Marks", "Output Grade Profile", "Quit", "giveMarksTesting()", "giveMarksTo()" }; bool finished = false; do { Console.WriteLine(); switch (ConsoleHelper.SelectChoice(choices)) { case 1: InputMarks(); break; case 2: OutputMarks(); break; case 3: CalculateGradeProfile(); OutputGradeProfile(); break; case 4: Console.WriteLine(@"Now quitting Student Grades"); finished = true; break; case 5: giveMarksTesting(); break; case 6: giveMarksTo(Console.ReadLine(), (int)ConsoleHelper.InputNumber()); break; } } while (!finished); } /// <summary> /// This method allows the user to input marks for all students /// </summary> public void InputMarks() { int i = 0; foreach (string student in Students) { Console.WriteLine($"Enter the marks for {student} >"); Marks[i] += ConsoleHelper.InputNumberWithin(LowestMark, HighestMark); i++; } } /// <summary> /// This method allows the user to input marks for a specific student /// and checks if the name is correct for the student they wish to add /// marks for /// </summary> /// <param name="name"></param> /// <param name="mark"></param> /// <returns></returns> public int giveMarksTo(string name, int mark) { int i = 0; foreach (string student in Students) { if (!ConsoleHelper.InRange(mark, LowestMark, HighestMark)) { return -1; } string correctName = student; if (correctName == name) { Marks[i] += mark; break; } else { i++; } } return Marks[i]; } /// <summary> /// This method displays all marks that each student has /// </summary> public void OutputMarks() { Console.WriteLine("Output Marks :"); Console.WriteLine(); int i = 0; foreach (string student in Students) { Console.WriteLine($" Marks for {student} :| {Marks[i]} |"); i++; } } /// <summary> /// This method converts the amount of marks a student has into /// a specific grade that corresponds with their amount of marks /// </summary> /// <param name="mark"></param> /// <returns></returns> public Grades ConvertToGrade(int mark) { if (ConsoleHelper.InRange(mark, LowestGradeA, HighestMark) || mark > 100) { return Grades.A; } else if (ConsoleHelper.InRange(mark, LowestGradeB, LowestGradeA - 1)) { return Grades.B; } else if (ConsoleHelper.InRange(mark, LowestGradeC, LowestGradeB - 1)) { return Grades.C; } else if (ConsoleHelper.InRange(mark, LowestGradeD, LowestGradeC - 1)) { return Grades.D; } else { return Grades.F; }; } /// <summary> /// This method calculates the students stats and marks /// </summary> public void CalculateStats() { double total = 0; foreach (int mark in Marks) { total = total = mark; } Mean = total / Marks.Length; Maximum = 0; foreach (int mark in Marks) { if (mark > Maximum) { Maximum = mark; } } Minimum = 100; foreach (int mark in Marks) { if (mark < Minimum) { Minimum = mark; } } } /// <summary> /// This method calculates mark to grade /// </summary> public void CalculateGradeProfile() { for (int i = 0; i < GradeProfile.Length; i++) { GradeProfile[i] = 0; } foreach (int mark in Marks) { Grades grade = ConvertToGrade(mark); GradeProfile[(int)grade]++; } } /// <summary> /// This method displays grade profile for the student /// </summary> public void OutputGradeProfile() { Grades grade = Grades.F; Console.WriteLine(); foreach (int count in GradeProfile) { int percentage = count * 100 / Marks.Length; Console.WriteLine($"Grade {grade} {percentage}% Count {count}"); grade++; } Console.WriteLine(); } /// <summary> /// This method gives the user the ability to add marks for testing /// </summary> public void giveMarksTesting() { int i = 0; Random r = new Random(); foreach (string student in Students) { Marks[i] += r.Next(0, 100); Console.WriteLine($"{student} marks : {Marks[i]}"); i++; } } } }<file_sep>/ConsoleAppProject/Program.cs using ConsoleAppProject.App01; using ConsoleAppProject.App02; using ConsoleAppProject.App03; using ConsoleAppProject.App04; using System; namespace ConsoleAppProject { /// <summary> /// The main method in this class is called first /// when the application is started. It will be used /// to start Apps 01 to 05 for CO453 CW1 /// /// This Project has been modified by: /// <NAME> 09/03/2021 /// </summary> public static class Program { private static DistanceConverter converter = new DistanceConverter(); private static BMI calculator = new BMI(); private static StudentGrades grades = new StudentGrades(); private static NetworkApp app04 = new NewtworkApp(); public static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("-----------------------------------------------"); Console.WriteLine("BNU CO453 Applications Programming 2020-2021!"); Console.WriteLine(" By <NAME>"); Console.WriteLine("-----------------------------------------------"); Console.WriteLine(); Console.WriteLine("1. Distance Converter"); Console.WriteLine("2. BMI Calculator"); Console.WriteLine("3. Student Grades"); Console.Write("Please enter your choice of App > "); string choice = Console.ReadLine(); if (choice == "1") { converter.ConvertDistance(); } else if(choice == "2") { calculator.CalculateIndex(); } else if(choice == "3") { grades.OutputMenu(); } else if(choice == "4") { App04.NetwortApp(); } } } } <file_sep>/ConsoleAppProject/App02/BMI.cs using System; namespace ConsoleAppProject.App02 { /// <summary> /// This method allows the program to calculate metric and imperial measurements /// </summary> public enum UnitSystems { Metric, Imperial } /// <summary> /// This class contains methods for calculating /// the user's BMI (Body Mass Index) using /// imperial or metric units /// </summary> /// <author> /// <NAME> App02: version 2.0 /// </author> public class BMI { public const double Underweight = 18.5; public const double NormalRange = 24.9; public const double Overweight = 29.9; public const double ObeseLevel1 = 34.9; public const double ObeseLevel2 = 39.9; public const double ObeseLevel3 = 40.0; public const int InchesInFeet = 12; public const int PoundsInStones = 14; private double index; // Metric Details private double kilograms; private double metres; // Imperial Details private double pounds; private int inches; /// <summary> /// This method outputs the heading for BMI and calculates the either imperial or /// metric and outputs the health message /// </summary> public void CalculateIndex() { ConsoleHelper.OutputHeading("Body Mass Undex Calculator"); UnitSystems unitSystems = SelectUnits(); if (unitSystems == UnitSystems.Metric) { InputMetricDetails(); CalculateMetricBMI(); } else { InputImperialDetails(); CalculateImperialBMI(); } OutputHealthMessage(); } /// <summary> /// This method calculates the metric measurements kilograms and metres /// </summary> public void CalculateMetricBMI() { index = kilograms / (metres * metres); } /// <summary> /// This method calculates the imperial measurements pounds and inches /// </summary> public void CalculateImperialBMI() { index = pounds * 703 / (inches * inches); } /// <summary> /// This method shows the user two choices that he can choose between /// either metric or imperial measurements and choose between one or the other /// </summary> private UnitSystems SelectUnits() { Console.WriteLine("1. Metric"); Console.WriteLine("2. Imperial"); int choice = (int)ConsoleHelper.InputNumber("Please Enter your choice > ", 1, 2); if (choice == 1) { return UnitSystems.Metric; } return UnitSystems.Imperial; } /// <summary> /// This method has the input details for metric details /// this method will output the message for the user to enter his metric details /// </summary> private void InputMetricDetails() { metres = ConsoleHelper.InputNumber( " \n Enter your height in metres > ", 1, 3); kilograms = ConsoleHelper.InputNumber( " Enter your weight in kilograms > "); } /// <summary> /// This method has all the measurement details for /// the imperial measurements and the output message for imperial details /// </summary> private void InputImperialDetails() { int stones = (int)ConsoleHelper.InputNumber( " Enter your weight in stones > "); pounds = (int)ConsoleHelper.InputNumber( " Enter your weight in pounds > "); pounds = pounds + stones * PoundsInStones; int feet = (int)ConsoleHelper.InputNumber("Please Enter your height in feet > "); inches = (int)ConsoleHelper.InputNumber( " Enter your hight in inches > ", 0, 12); } /// <summary> /// This method outputs the health message dependant /// on what your weight is /// </summary> private void OutputHealthMessage() { Console.WriteLine(); if (index < Underweight) { Console.WriteLine($" Your BMI is {index:0.00}, " + $"You are underweight! "); } else if (index <= NormalRange) { Console.WriteLine($" Your BMI is {index:0.00}, " + $"You are in the normal range! "); } else if (index <= Overweight) { Console.WriteLine($" Your BMI is {index:0.00}, " + $"You are overweight! "); } else if (index <= ObeseLevel1) { Console.WriteLine($" Your BMI is {index:0.00}, " + $"You are obese class I! "); } else if (index <= ObeseLevel2) { Console.WriteLine($" Your BMI is {index:0.00}, " + $"You are obese class II! "); } else if (index <= ObeseLevel3) { Console.WriteLine($" Your BMI is {index:0.00}, " + $"You are obese class III! "); } else Console.WriteLine("Something Has Gone Very Wrong!!!"); OutputBameMessage(); } /// <summary> /// This method outputs the bame message at the end when the calculation /// finishes the bame messages shows the user who is at risk /// </summary> private void OutputBameMessage() { Console.WriteLine(); Console.WriteLine(" If you are Black, Asian or other minority"); Console.WriteLine(" ethnic groups, you have a higher risk"); Console.WriteLine(); Console.WriteLine("\t Adults 23.0 or more are at increased risk"); Console.WriteLine("\t Adults 27.5 or more are at high risk"); Console.WriteLine(); } } }<file_sep>/ConsoleAppProject/App01/DistanceConverter.cs using System; namespace ConsoleAppProject.App01 { /// <summary> /// This is my mesurement converter which you can can convert units from and to a /// certain mesurment and get the output and the calculation for the mesurement /// </summary> /// <author> /// <NAME> 21717237 version 1.0 /// </author> ///<summary> ///This code is for the value of each of the mesurement from and to value /// </summary> public class DistanceConverter { public const double FEET_IN_FEET = 1.0; public const double METRES_IN_MILES = 1609.34; public const double FEET_IN_METRES = 3.28084; public const double FEET_IN_MILES = 5280; public const double METRES_IN_METRES = 1.0; public const double MILES_IN_MILES = 1.0; public const double MILES_IN_FEET = 0.000189393939; public const double METRES_IN_FEET = 0.3048; public const double MILES_IN_METRES = 0.000621371192; public const string FEET = "Feet"; public const string METRES = "Metres"; public const string MILES = "Miles"; private double fromDistance; private double toDistance; private string fromUnit; private string toUnit; public DistanceConverter() { fromUnit = MILES; toUnit = FEET; } /// <summary> /// Distance converter this code outputs the comment to select mesurment to and from /// and shows which mesurments you have selected it also calculates both mesurments selected /// </summary> public void ConvertDistance() { ConsoleHelper.OutputHeading("DistanceConverter"); fromUnit = SelectUnit(" Please select the from distance unit > "); toUnit = SelectUnit(" Please select the to distance unit > "); Console.WriteLine($"\n Converting {fromUnit} to {toUnit}"); fromDistance = InputDistance($" Please enter the number of {fromUnit} > "); CalculateDistance(); OutputDistance(); } /// <summary> /// Distance calculator this code allows the user to select the to and from unit /// and giving them the convertion calculation /// </summary> private void CalculateDistance() { if(fromUnit == FEET && toUnit == FEET) { toDistance = fromDistance * FEET_IN_FEET; } else if(fromUnit == FEET && toUnit == MILES) { toDistance = fromDistance / FEET_IN_MILES; } else if(fromUnit == FEET && toUnit == METRES) { toDistance = fromDistance / FEET_IN_METRES; } else if (fromUnit == MILES && toUnit == FEET) { toDistance = fromDistance / MILES_IN_FEET; } else if (fromUnit == MILES && toUnit == MILES) { toDistance = fromDistance / MILES_IN_MILES; } else if (fromUnit == MILES && toUnit == METRES) { toDistance = fromDistance / MILES_IN_METRES; } else if (fromUnit == METRES && toUnit == FEET) { toDistance = fromDistance / METRES_IN_FEET; } else if (fromUnit == METRES && toUnit == METRES) { toDistance = fromDistance / METRES_IN_METRES; } else if (fromUnit == METRES && toUnit == MILES) { toDistance = fromDistance / METRES_IN_MILES; } } /// <summary> /// This code displays which choice the user has selected the to and from measurements /// and shows both units chosen /// </summary> private string SelectUnit(string prompt) { string choice = DisplayChoices(prompt); string unit = ExecuteChoice(choice); Console.WriteLine($"\n You have chosen {unit}"); return unit; } /// <summary> /// This code is for the choices which allow the user to input which /// conversion of measurement they want to choose to and from /// </summary> private static string ExecuteChoice(string choice) { if (choice.Equals("1")) { return FEET; } else if (choice == "2") { return METRES; } else if (choice.Equals("3")) { return MILES; } return null; } /// <summary> /// This code displays options of conversion for the user to unit and from unit /// </summary> private static string DisplayChoices(string prompt) { Console.WriteLine(); Console.WriteLine($" 1. {FEET}"); Console.WriteLine($" 2. {METRES}"); Console.WriteLine($" 3. {MILES}"); Console.WriteLine(); Console.Write(prompt); string choice = Console.ReadLine(); return choice; } /// <summary> /// This code is for the input of the measurement /// </summary> private double InputDistance(string prompt) { Console.Write(prompt); string value = Console.ReadLine(); return Convert.ToDouble(value); } /// <summary> /// This code is for the output of the measurement /// </summary> private void OutputDistance() { Console.WriteLine($"\n {fromDistance} {fromUnit}" + $" is {toDistance} {toUnit}!\n"); } } }
ee49dac1ad3ad946e687099985906dcce14db0f7
[ "C#" ]
5
C#
BrianRuszkowski/ConsoleApps15
1c9e3afa86fdaee5c496776137d1c08de82cfb4c
a0afac8f0f4f80def599a8ededc056ab4f638b2c