branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>cachemoi/olyst<file_sep>/README.md # Olyst Data solution on elderly care<file_sep>/src/App.js import React, { Component } from 'react' import logo from './img/logo.svg' import ampoule from './vid/ampoule.mov' import bridge from './vid/bridge.mov' import care from './vid/care.mov' import cure from './vid/cure.mov' import nodes from './vid/nodes.mov' import office from './vid/office.mov' import tech from './vid/tech.mov' import 'bootstrap/dist/css/bootstrap.css' import './App.css'; const NavBar = () => ( <nav className="navbar fixed-top navbar-dark bg-dark"> <a className="navbar-brand" href="#"> <img src={logo} width="30" height="30" className="d-inline-block align-top" alt=""/> Olyst </a> </nav> ); const Header = () => ( <div className="d-flex flex-column flex-md-row pt-5 bg-vid-wrapper"> <video autoPlay loop className="bg-video"> <source src={tech} type="video/mp4"/> </video> <div className="p-4 m-5 mx-auto"> <img width="300" height="300" className="logo-container" src={logo}/> </div> <div className="text-center bg-transparent-custom p-4 m-5"> <h3 className="p-3">ASSEMBLING <b className="highlight">CURE</b> & <b className="highlight">CARE</b> RELATED DATA</h3> <h3 className="p-3">TO IDENTIFY, BUILD AND PREDICT <b className="highlight">INTERACTIONS</b></h3> <h3 className="p-3">BETWEEN ELDERLY PATIENTS AND THEIR CAREGIVERS </h3> </div> </div> ); const Holistic =() => ( <div className="d-flex flex-column bg-lightgrey p-5"> <div className="text-center flex-column"> <h1 className="pt-5 pb-2">h<b className="highlight">olist</b>ic</h1> <h5 className="p-1"><i>adjective</i> | ho·lis·tic | \ hō-ˈli-stik \ </h5> <h4 className="pt-5 pb-4">Relating to or concerned with wholes or with complete systems rather than with the analysis of, treatement of, or dissection into parts</h4> </div> </div> ); const Problem = () => ( <div className="d-flex flex-column"> <div className="d-flex text-center justify-content-center"> <blockquote className="blockquote text-center p-3 w-75"> <h3 className="m-5"> Improving the healthcare system for an ageing population requires a reliable operational and cost effective <b className="highlight"> PATHWAY </b> between <b className="highlight">CURE</b> (acute) and <b className="highlight">CARE</b> (chronic) related practices </h3> <h3 className="m-5"> For this to happen, healthcare providers must bring together two types of <b className="highlight">DATA SETS</b>... </h3> </blockquote> </div> <div className="d-flex flex-wrap justify-content-center align-items-center"> <div className="d-flex flex-column text-center mini-div m-4 bg-green"> <h4 className="p-4" ><b className="txt-white">CURE</b> related data</h4> <p className="p-1">Vital signs, diagnostics, clinical conditions…</p> <video autoPlay loop className="mini-vid mt-auto"> <source src={cure} type="video/mp4"/> </video> </div> <div className="d-flex flex-column text-center mini-div m-4 bg-blue"> <h4 className="p-4" ><b className="txt-white">CARE</b> related data</h4> <p className="p-1">family, lifestyle, medication adherence…</p> <video autoPlay loop className="mini-vid mt-auto"> <source src={care} type="video/mp4"/> </video> </div> </div> </div> ); const About = () => ( <div className="d-flex flex-column bg-lightgrey"> <div className="text-center m-5"> <h3>OLYST is a (Software as a Service) platform that helps customers… </h3> </div> <div className="d-flex flex-wrap justify-content-center"> <div className="d-flex flex-column text-center mini-div m-4 bg-darkgrey"> <h4 className="p-4" >Learn</h4> <p className="p-1">Why did it happen?</p> <video autoPlay loop className="mini-vid mt-auto"> <source src={office} type="video/mp4"/> </video> </div> <div className="d-flex flex-column text-center mini-div m-4 bg-green"> <h4 className="p-4" >Predict</h4> <p className="p-1">What will happen?</p> <video autoPlay loop className="mini-vid mt-auto"> <source src={bridge} type="video/mp4"/> </video> </div> <div className="d-flex flex-column text-center mini-div m-4 bg-blue"> <h4 className="p-4" >Adapt</h4> <p className="p-1">What can I do to change the outcome?</p> <video autoPlay loop className="mini-vid mt-auto"> <source src={ampoule} type="video/mp4"/> </video> </div> </div> </div> ); const Offer = () => ( <div className="d-flex flex-column"> <div className="m-5 text-center"> <h1>What we do</h1> </div> <div className="d-flex flex-wrap justify-content-center align-content-center"> <div className="m-4 flex-column text-center mini-div bg-darkgrey"> <div className="p-4"> <h3 className="m-5">Matchmaking</h3> <p className="m-3">Bridge the gaps between elderly patients, care givers, and professional caregivers</p> </div> </div> <div className="m-4 text-center mini-div bg-green"> <div className="p-4"> <h3 className="m-5">Data gathering</h3> <p className="m-3"> Collect information on care of elderly people with loss of autonomy</p> </div> </div> <div className="m-4 text-center mini-div bg-blue"> <div className="p-4"> <h3 className="m-5">Analytics</h3> <p className="m-3">Highlight predictive & contextualised models combining care & cure capabilities</p> </div> </div> </div> </div> ); const OutComes =() => ( <div className="d-flex flex-column bg-vid-wrapper"> <video autoPlay loop className="bg-video"> <source src={nodes} type="video/mp4"/> </video> <div className="text-center p-5"> <h1 className="highlight m-5"><b>Outcomes</b></h1> <div className="bg-transparent-custom text-center m-3 p-3"> <h3 className="p-3"><b className="highlight">SHARED</b> CAPABILITIES TO ENGAGE CHRONIC PATIENTS &THEIR CAREGIVERS INTO COLLABORATIVE CURE & CARE PATHWAYS</h3> <h3 className="p-3"><b className="highlight">TRACEABLE</b> CAPABILITIES TO HELP PATIENTS STAY AT HOME IN AFFORDABLE (cost effective), CERTIFIED (regulatorily compliant), ACCESSIBLE (technically feasible) CONDITIONS</h3> <h3 className="p-3"><b className="highlight">RELIABLE</b> CAPABILITIES TO REDUCE COSTS OF HEALTHCARE</h3> </div> </div> </div> ); const Contact = () => ( <div className="d-flex justify-content-center bg-dark"> <div className="flex-column"> <div className="p-4 text-center txt-white"> <h3 className="p-2">Contact us</h3> <h5 className="p-2"><EMAIL></h5> <h5 className="p-2">@olyst</h5> </div> </div> </div> ); class App extends Component { render() { return ( <div> <NavBar/> <Header/> <Holistic/> <Problem/> <About/> <Offer/> <OutComes/> <Contact/> </div> ); } } export default App;
bbdaa3644912281bf78d4436ecfe2b2494d12e91
[ "Markdown", "JavaScript" ]
2
Markdown
cachemoi/olyst
8bc576165036c8476f53218896e9511086739d48
72d84c6c3b726892697d5592e0a881f4bf159f43
refs/heads/gh-pages
<file_sep>from flask import Flask from flask_cors import CORS from flask_jwt_extended import ( JWTManager ) import os import datetime from .db import MyDiaryDatabase app = Flask(__name__) CORS(app) app.config['JWT_SECRET_KEY'] = 'secret' app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access'] jwt = JWTManager(app) db_name = os.environ.get("db_name", None) if db_name == "mydiarydb": app_db = MyDiaryDatabase(db_name) else: db_name = "testdb" app_db = MyDiaryDatabase(db_name) app_db.drop_users_table() app_db.drop_entries_table() pass app_db.new_users_table() app_db.new_entries_table() app_db.new_blacklist() now_time = "".join(str(datetime.datetime.now().day) + "/" + str(datetime.datetime.now().month) + "/" + str(datetime.datetime.now().year)) from . import entries from . import users <file_sep>#!/usr/bin/python import psycopg2 class MyDiaryDatabase: """This defines the database connection and holds methods for creating and deleting tables""" def __init__(self, db_name): self.mydb = 'dbi88r8l9ebmvl' try: self.conn = psycopg2.connect(dbname=self.mydb, user='sodgzedklqgcec', host='ec2-54-227-241-179.compute-1.amazonaws.com', password='<PASSWORD>', port='5432') self.cursor = self.conn.cursor() except Exception as e: print("Unable to connect. Check dbname, user or password inputs.") print(e) def new_users_table(self): self.cursor.execute("""CREATE TABLE IF NOT EXISTS users (user_id SERIAL NOT NULL PRIMARY KEY, name VARCHAR(150) NOT NULL, email VARCHAR(150) NOT NULL, password <PASSWORD>(<PASSWORD>, registered VARCHAR(10) NOT NULL, lastUsed VARCHAR(10) NOT NULL, deletedEntries INTEGER, currentEntries INTEGER, allEntries INTEGER, notifications BOOLEAN);""") self.conn.commit() def new_entries_table(self): self.cursor.execute("""CREATE TABLE IF NOT EXISTS entries (entry_id SERIAL NOT NULL PRIMARY KEY, user_id INTEGER NOT NULL, title VARCHAR(150) NOT NULL, data VARCHAR(5000) NOT NULL, date_modified VARCHAR(10) NOT NULL);""") self.conn.commit() def new_blacklist(self): self.cursor.execute("""CREATE TABLE IF NOT EXISTS blacklist (token VARCHAR(500) NOT NULL, user_id INTEGER NOT NULL);""") self.conn.commit() def drop_entries_table(self): self.cursor.execute("""DROP TABLE IF EXISTS entries;""") self.conn.commit() def drop_users_table(self): self.cursor.execute("""DROP TABLE IF EXISTS users;""") self.conn.commit() def check_table(self,table_name): sql_check_fn = """SELECT * from %s;""" self.cursor.execute(sql_check_fn, (table_name,)) rows = self.cursor.fetchall() return rows<file_sep>// var baseurl = "http://127.0.0.1:5000" var baseurl = "https://balaakagordon.github.io/MyDiary4" function loadLanding() { fetch(baseurl + "/") .then((res) => res.json()) .then(function (data) { if(data["message"] == "welcome") { window.location.href=baseurl + '/index.html' } }) } function addUser() { let name = document.getElementById('uname').value; let email = document.getElementById('mail').value; let password = document.getElementById('pword').value; let confirmpassword = document.getElementById('pword2').value; fetch(baseurl + '/auth/signup', { method:'POST', headers:{ 'Accept': 'application/json', 'Content-type':'application/json' }, body:JSON.stringify({ name: name, email: email, password: <PASSWORD>, confirmpassword: <PASSWORD> }) }) .then((res) => res.json()) .then(function (data) { if(data["message"] == "Invalid input") { document.getElementById('regmessage').innerHTML = data["error"]; } else if(data["message"] == "Registered Successfully!") { window.location.href='./login.html' } else if(data["message"] == "This user already exists!") { document.getElementById('regmessage').innerHTML = data["message"]; } }) } function loginmessage() { let usermessage = sessionStorage.getItem("usermessage") document.getElementById("logmessage").innerHTML = usermessage; sessionStorage.removeItem("usermessage") } function login(){ let email = document.getElementById('mail').value; let password = document.getElementById('pword').value; fetch(baseurl + '/auth/login', { method:'POST', headers:{ 'Accept': 'application/json', 'Content-type':'application/json' }, body:JSON.stringify({"email": email, "password": password}) }) .then((res) => res.json()) .then (function (data) { if(data["message"] == "Login successful") { let Token = data["access_token"] sessionStorage.setItem("token", Token); sessionStorage.setItem("usermessage", "Welcome! You have been logged in, succesfully :)"); window.location.href='./home.html' } else if(data["message"] == "Sorry, incorrect credentials") { document.getElementById('logmessage').innerHTML = data["message"]; } }) .catch((err) => console.log(err)) } function userProfile() { let Token = sessionStorage.getItem("token"); fetch(baseurl + '/profile', { method:'GET', headers: { 'Authorization': 'Bearer ' + Token, 'Content-type':'application/json' }, }) .then(function(res) { appStatus = res.status; return res.json(); }) .then(function (data) { errCatcher(data) document.getElementById("allentries").innerHTML = data.userdata.allEntries document.getElementById("currententries").innerHTML = data.userdata.currentEntries document.getElementById("deletedentries").innerHTML = data.userdata.deletedEntries document.getElementById("registered").innerHTML = data.userdata.registered document.getElementById("lastused").innerHTML = data.userdata.lastUsed }) } function logout() { let Token = sessionStorage.getItem("token"); fetch(baseurl + '/logout', { method:'GET', headers: { 'Authorization': 'Bearer ' + Token, 'Content-type':'application/json' }, }) .then((res) => res.json()) .then(function (data) { if(data["msg"] == "Successfully logged out") { sessionStorage.removeItem('token'); sessionStorage.removeItem('entry_ID'); sessionStorage.removeItem('addoredit'); sessionStorage.setItem("usermessage", data.msg); window.location.href='./login.html'; } }) } function getUserEntries() { var reminder = "" let Token = sessionStorage.getItem("token"); let usermessage = sessionStorage.getItem("usermessage"); let modal = document.getElementById('myModal'); if (usermessage == "Welcome! You have been logged in, succesfully :)") { reminder = "Have you written today? Record some memories for future you! :)" } document.getElementById("homepopup").innerHTML = usermessage; fetch(baseurl + '/api/v1/entries', { method:'GET', headers:{ 'Authorization': 'Bearer ' + Token, 'Content-type':'application/json' }, }) .then(function(res) { appStatus = res.status; return res.json(); }) .then(function (data) { errCatcher(data) let writtenToday = data.writtenToday; console.log("writtenToday value: " + writtenToday) if (writtenToday == false){ document.getElementById("writtenToday").innerHTML = reminder; reminder = "" } if (usermessage == "Welcome! You have been logged in, succesfully :)") { modal.style.display = "block"; } var myTable = document.getElementById("entriesList"); data.entries.forEach(function(entry) { let output = document.createElement("tr"); output.innerHTML = ` <th>${entry.title}</th> <th>${entry.date}</th> <th class="flex-container"> <button id="${entry.entry_id}" type="submit" class="button-edit" onclick="edit(${entry.entry_id})">Edit</button> <button id="${entry.entry_id}" type="submit" class="button-delete" onclick="del(${entry.entry_id})">Delete</button> </th> `; myTable.appendChild(output); }); sessionStorage.removeItem("usermessage"); }) } function closeModal() { let modal = document.getElementById('myModal'); modal.style.display = "none"; } function getOneEntry() { sessionStorage.setItem("addoredit", "edit"); let Token = sessionStorage.getItem("token"); let entry_ID = sessionStorage.getItem("entry_ID"); fetch(baseurl + '/api/v1/entries/' + entry_ID, { method:'GET', headers:{ 'Authorization': 'Bearer ' + Token, 'Content-type':'application/json' }, }) .then(function(res) { appStatus = res.status; return res.json(); }) .then(function (data) { errCatcher(data) document.getElementById('entryTitle').value = data.getEntry.title; document.getElementById('entryDate').innerHTML = data.getEntry.date; document.getElementById('entryText').value = data.getEntry.data; }) } function edit(entryID){ sessionStorage.setItem("entry_ID", entryID); sessionStorage.setItem("addoredit", "edit"); window.location.href='./edit.html' } function add() { sessionStorage.setItem("addoredit", "add"); window.location.href='./edit.html' } function addOrEdit() { let addoredit = sessionStorage.getItem("addoredit"); if(addoredit == "add") { document.getElementById('entryTitle').value = ""; document.getElementById('entryDate').innerHTML = ""; document.getElementById('entryText').value = ""; } else if(addoredit == "edit") { getOneEntry() } } function newOrUpdate() { let addoredit = sessionStorage.getItem("addoredit"); if(addoredit == "add") { addEntry() } else if(addoredit == "edit") { editEntry() } } function addEntry() { let Token = sessionStorage.getItem("token"); let entrytitle = document.getElementById("entryTitle").value; let entrydata = document.getElementById('entryText').value; fetch(baseurl + '/api/v1/entries', { method:'POST', headers: { 'Authorization': 'Bearer ' + Token, 'Accept': 'application/json', 'Content-type':'application/json' }, body:JSON.stringify({"entrytitle": entrytitle, "entrydata": entrydata}) }) .then(function(res) { appStatus = res.status; return res.json(); }) .then(function (data) { errCatcher(data) if(data["message"] == "Null entry field") { document.getElementById('editmessage').innerHTML = "Please write down something, in the entry field, for future you!"; } else if(data["message"] == "Entry already exists") { document.getElementById('editmessage').innerHTML = data["message"] } else if(data["message"] == "Entry added successfully") { if(entrytitle == ""){ entrytitle = "..No Title.." } usermessage = "Your thought titled, '" + entrytitle + "' has been added" sessionStorage.setItem("usermessage", usermessage) window.location.href='./home.html' } }) .catch((err) => console.log(err)); } function errCatcher(data) { if(appStatus == 401) { window.location.href='./401.html' } else if(appStatus == 403) { window.location.href='./403.html' } } function editEntry() { let Token = sessionStorage.getItem("token"); let entrytitle = document.getElementById("entryTitle").value; let entrydata = document.getElementById('entryText').value; let entry_ID = sessionStorage.getItem("entry_ID"); fetch(baseurl + '/api/v1/entries/'+ entry_ID, { method:'PUT', headers: { 'Authorization': 'Bearer ' + Token, 'Accept': 'application/json', 'Content-type':'application/json' }, body:JSON.stringify({"entrytitle": entrytitle, "entrydata": entrydata}) }) // .then((res) => res.json()) .then(function(res) { appStatus = res.status; return res.json(); }) .then(function (data) { errCatcher(data) if(data["message"] == "Null entry field") { document.getElementById('editmessage').innerHTML = "The entry cannot be left blank. Write a note to future you!"; } else if(data["message"] == "Sorry, cannot edit entries made before today") { document.getElementById('editmessage').innerHTML = data["message"] } else if(data["message"] == "Entry edited") { usermessage = "Your thought, '" + entrytitle + "' has just been updated" sessionStorage.setItem("usermessage", usermessage) window.location.href='./home.html' } }) } function del(entryID) { sessionStorage.setItem("entry_ID", entryID); deleteEntry(); } function deleteEntry() { let Token = sessionStorage.getItem("token"); let entry_ID = sessionStorage.getItem("entry_ID"); fetch(baseurl + 'api/v1/entries/'+ entry_ID, { method:'DELETE', headers:{ 'Authorization': 'Bearer ' + Token, 'Accept': 'application/json', 'Content-type':'application/json' }, }) .then(function(res) { appStatus = res.status; return res.json(); }) .then(function (data) { errCatcher(data) sessionStorage.setItem("usermessage", data.message); window.location.href='./home.html'; }) } <file_sep>from flask import Flask, jsonify, json, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_identity, get_raw_jwt ) import datetime from .models import MyDiary, Entries from mydiary import app, app_db, now_time, jwt my_diary_object = MyDiary() my_diary_object.user_entries = Entries() def reg_validation(data): """ This method validates user inputs during registration """ nums = "0123456789" invalid_str = ",.;:!][)(><+-=}{" user_name=data["name"] name_error = False if len(user_name) <= 4: error_msg = "Please enter a valid first and last name" name_error = True elif len(user_name.split()) < 2: error_msg = "Please enter a valid first and last name" name_error = True for letter in user_name: if letter in invalid_str or letter in nums: error_msg = "Invalid character. Please enter a valid first and last name" name_error = True if name_error: return ["error", error_msg, 400] user_email=request.json.get('email', "") email_error = False if "@" not in user_email: email_error = True elif user_email[0] in invalid_str: email_error = True if email_error: return ["error", "Please enter a valid email address", 400] user_password=request.json.get('password', "") if len(user_password) <= 5: return ["error", "Password too short", 411] confirm_password=request.json.get('confirmpassword', "") if user_password != confirm_password: return ["error", "Passwords do not match", 400] return [user_name, user_email, user_password] @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): token = decrypted_token['jti'] blacklisted = my_diary_object.inBlacklist(token) return blacklisted @app.route('/') def landing(): """ This endpoint helps to load the landing page """ return jsonify({"message": "welcome"}), 200 @app.route('/auth/signup', methods=['GET', 'POST']) def register(): """ This method accepts user information to create a profile """ if request.method == 'POST': input_error = False if not request.json: error_msg = "invalid data type" input_error = True elif 'email' not in request.json: error_msg = "Please enter your email address" input_error = True elif 'name' not in request.json: error_msg = "Please enter your name" input_error = True elif 'password' not in request.json: error_msg = "Please enter your password" input_error = True elif 'confirmpassword' not in request.json: error_msg = "Please confirm your password" input_error = True if input_error: return jsonify({"Input error": error_msg}), 400 data = request.get_json() signup_data = reg_validation(data) if signup_data[0] == "error": return jsonify({"message": "Invalid input", "error": signup_data[1]}), signup_data[2] add_user = my_diary_object.addUser(signup_data[0], signup_data[1], signup_data[2], now_time) if add_user == "Registered Successfully!": user = { 'name': signup_data[0], 'email': signup_data[1], } return jsonify({"message": add_user, "user": user}), 201 return jsonify({"message": add_user}), 409 """ links to the login page """ @app.route('/auth/login', methods=['GET', 'POST']) def userlogin(): if request.method == 'POST': input_error = False if not request.json: input_error = True error_msg = "Wrong input data format" if 'email' not in request.json: input_error = True error_msg = "Cannot find email. Please provide valid login credentials" if 'password' not in request.json: input_error = True error_msg = "Cannot find password. Please provide valid login credentials" if input_error: return jsonify({"input error": error_msg}), 400 login_email=request.json.get('email', "") login_password=request.json.get('password', "") user_id = get_jwt_identity() logged_in = my_diary_object.userLogin(login_email, login_password, now_time, user_id) if type(logged_in) == int: expires = datetime.timedelta(hours=1) access_token = create_access_token(identity=logged_in, expires_delta=expires) return jsonify({"message": "Login successful", "access_token": access_token}), 200 return jsonify({"message" : logged_in}), 401 @app.route('/profile', methods=['GET']) @jwt_required def userProfile(): user_id = get_jwt_identity() userData = my_diary_object.checkUserDetails(user_id) return jsonify({"userdata": userData}), 200 @app.route('/logout', methods=['GET']) @jwt_required def logout(): token = get_raw_jwt()['jti'] user_id = get_jwt_identity() logout = my_diary_object.userLogout(token, user_id) if logout == "Successfully logged out": return jsonify({"msg": logout}), 200 else: return jsonify({"msg": "logout failed"}), 400 <file_sep>""" Holds the app's classes and methods """ # -*- coding: utf-8 -*- """importing packages""" from flask import Flask, jsonify from mydiary import app_db """ the diary app is modelled as an object with it's own \ parameters and methods """ class MyDiary: def __init__(self): self.user_entries = None def addUser(self, user_name, user_email, user_password, current_date): sql_check_fn = """SELECT * from users WHERE email = %s;""" app_db.cursor.execute(sql_check_fn, (user_email,)) rows = app_db.cursor.fetchall() if rows == []: sql_insert_fn = """INSERT INTO users (name, email, password, registered, lastUsed, deletedEntries, currentEntries, allEntries, notifications) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s);""" app_db.cursor.execute(sql_insert_fn, ( user_name, user_email, user_password, current_date, current_date, 0, 0, 0, True )) app_db.conn.commit() message = "Registered Successfully!" else: message = "This user already exists!" return message def userLogin(self, login_email, login_password, current_date, user_id): """ login method requires a username and password and returns a user ID """ sql_fn = """SELECT * from users WHERE email = %s AND password = %s;""" app_db.cursor.execute(sql_fn, ( login_email, login_password )) rows = app_db.cursor.fetchall() if rows == []: message = "Sorry, incorrect credentials" return message sql_update_fn = """UPDATE users SET lastUsed = %s WHERE user_id = %s;""" app_db.cursor.execute(sql_update_fn, (current_date, user_id)) app_db.conn.commit() return rows[0][0] def checkUserDetails(self, user_id ): sql_check_fn = """SELECT * from users WHERE user_id = %s;""" app_db.cursor.execute(sql_check_fn, (user_id,)) user_data = app_db.cursor.fetchall() userData = { "registered": user_data[0][4], "lastUsed": user_data[0][5], "currentEntries": user_data[0][7], "deletedEntries": user_data[0][6], "allEntries": user_data[0][8], "notifications": user_data[0][9] } return userData def userLogout(self, token, user_id): """ logout method adds current token to blacklist \ table """ sql_insert_fn = """INSERT INTO blacklist (token, user_id) VALUES(%s, %s);""" app_db.cursor.execute(sql_insert_fn, ( token, user_id )) app_db.conn.commit() return "Successfully logged out" def inBlacklist(self, token): """ Check blacklist for generated token """ sql_check_fn = """SELECT * from blacklist WHERE token = %s;""" app_db.cursor.execute(sql_check_fn, (token,)) rows = app_db.cursor.fetchall() if rows == []: return False return True class Entries: """ Entry lists for each user are modelled as objects with \ parameters and methods """ def __init__(self): pass def addEntry(self, user_id_data, title_data, entry_data, now_time): """ once an entry's data is submitted the server checks whether it exists \ Entries to be added to entrylist """ sql_check_fn = """SELECT * from entries WHERE data = %s AND title = %s AND user_id = %s;""" app_db.cursor.execute(sql_check_fn, ( entry_data, title_data, user_id_data )) rows = app_db.cursor.fetchall() if rows == []: sql_check_fn = """SELECT * from users WHERE user_id = %s;""" sql_insert_fn = """INSERT INTO entries (user_id, title, data, date_modified) VALUES(%s, %s, %s, %s);""" sql_update_fn = """UPDATE users SET currentEntries = %s, allEntries = %s WHERE user_id = %s;""" app_db.cursor.execute(sql_check_fn, (user_id_data,)) user_data = app_db.cursor.fetchall() currentEntries = int(user_data[0][7]) + 1 allEntries = int(user_data[0][8]) + 1 print("allEntries: " + str(allEntries)) print("currentEntries: " + str(currentEntries)) app_db.cursor.execute(sql_insert_fn, ( user_id_data, title_data, entry_data, now_time )) app_db.cursor.execute(sql_update_fn, ( currentEntries, allEntries, user_id_data )) app_db.conn.commit() message = "Entry added successfully" else: message = "Entry already exists" return message def modifyEntry(self, title_data, entry_data, edit_time, entry_id_data, user_id_data): """ edits diary entries """ sql_check_fn = """SELECT * from entries WHERE user_id = %s AND entry_id = %s;""" app_db.cursor.execute(sql_check_fn, (user_id_data, entry_id_data)) rows = app_db.cursor.fetchall() if rows == []: message = "Entry not found" elif rows[0][4] != edit_time: message = "Sorry, cannot edit entries made before today" else: sql_update_fn = """UPDATE entries SET title = %s, data = %s, date_modified = %s WHERE user_id = %s AND entry_id = %s;""" app_db.cursor.execute(sql_update_fn, ( title_data, entry_data, edit_time, user_id_data, entry_id_data )) message = "Entry edited" app_db.conn.commit() return message def getOneEntry(self, user_id, diary_entry_id): sql_check_fn = """SELECT * from entries WHERE user_id = %s AND entry_id = %s;""" app_db.cursor.execute(sql_check_fn, (user_id, diary_entry_id)) row = app_db.cursor.fetchall() if row == []: message = "The specified entry cannot be found" return message entry = { 'entry_id': row[0][0], 'user_id': row[0][1], 'title': row[0][2], 'data': row[0][3], 'date': row[0][4] } return entry def getAllEntries(self, now_time, user_id_data): sql_check_fn = """SELECT * from entries WHERE user_id = %s;""" app_db.cursor.execute(sql_check_fn, [user_id_data]) rows = app_db.cursor.fetchall() entry_list = [] writtenToday = False for row in rows: entry = { 'entry_id': row[0], 'user_id': row[1], 'title': row[2], 'data': row[3], 'date': row[4] } if row[4] == now_time: writtenToday = True entry_list.append(entry) return [entry_list[:], writtenToday] def deleteEntry(self, entry_id_data, user_id_data): """ this method deletes diary entries """ sql_check_fn = """SELECT * from entries WHERE user_id = %s AND entry_id = %s;""" app_db.cursor.execute(sql_check_fn, (user_id_data, entry_id_data)) rows = app_db.cursor.fetchall() if rows == []: message = "Unable to delete. Entry does not exist" else: sql_check_fn = """SELECT * from users WHERE user_id = %s;""" sql_delete_fn = """DELETE from entries where user_id = %s AND entry_id = %s;""" sql_update_fn = """UPDATE users SET currentEntries = %s, allEntries = %s WHERE user_id = %s;""" app_db.cursor.execute(sql_check_fn, (user_id_data,)) user_data = app_db.cursor.fetchall() currentEntries = user_data[7] - 1 deletedEntries = user_data[8] + 1 app_db.cursor.execute(sql_delete_fn, ( user_id_data, entry_id_data )) app_db.cursor.execute(sql_update_fn, ( currentEntries, deletedEntries, user_id_data )) app_db.conn.commit() message = "Entry successfully deleted" return message <file_sep>aniso8601==3.0.2 asn1crypto==0.24.0 certifi==2018.4.16 cffi==1.11.5 chardet==3.0.4 click==6.7 coverage==4.5.1 coveralls==1.3.0 cryptography==2.3 docopt==0.6.2 enum34==1.1.6 Flask==1.0.2 Flask-Cors==3.0.6 Flask-JWT-Extended==3.12.0 Flask-RESTful==0.3.6 foreman==0.9.7 futures==3.2.0 gunicorn==19.9.0 idna==2.7 ipaddress==1.0.22 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 nose==1.3.7 psycopg2==2.7.5 psycopg2-binary==2.7.5 pycparser==2.18 PyJWT==1.6.4 pyOpenSSL==18.0.0 pytz==2018.5 requests==2.19.1 requests-futures==0.9.7 six==1.11.0 urllib3==1.23 Werkzeug==0.14.1 <file_sep>import os from mydiary import app if __name__ == '__main__': os.environ["db_name"] = "mydiarydb" app.run(debug=True)<file_sep># MyDiary_GB MyDiary is an online application where users can note down their thoughts and feelings. Set up your account and begin documenting your emotions. [![Build Status](https://travis-ci.org/balaakagordon/challenge3.svg?branch=finish_feedback)](https://travis-ci.org/balaakagordon/challenge3) [![Coverage Status](https://coveralls.io/repos/github/balaakagordon/challenge3/badge.svg)](https://coveralls.io/github/balaakagordon/challenge3) ## Getting Started These instructions will help you get the application running on your local machine for development and testing. ### Prerequisites * [Python](https://www.python.org/getit/) * [Pip](https://pip.pypa.io/en/stable/installing/) ### Setup * Clone the remote repository on [GitHub](https://github.com/new) ``` $ git clone https://github.com/balaakagordon/test.git $ cd MyDiary_GB ``` * Create a virtual environment for your application and install all relevant requirements ``` $ virtualenv venv $ source venv/bin/activate $ pip install -r requirements.txt ``` ### Database * Set up a database to hold your data ``` CREATE DATABASE mydiary_db ``` * Run the application on a local server ``` $ python mydiaryapp/app.py ``` Check that the application is now be running on the localhost server(http://1192.168.127.12:5000) ### Testing * Run tests on api endpoints to ensure methods work ``` $ curl -i http://localhost:5000/api/v1/entries/1 $ curl -i http://localhost:5000/api/v1/entries $ curl -i -H "Content-Type: application/json" -X POST -d '{"entrytitle":"Plan for today", "entrydata":"Read a book"}' http://localhost:5000/api/v1/entries $ curl -i -H "Content-Type: application/json" -X PUT -d '{"entrytitle":"Today Was Fun", "entrydata":"Went shopping and bought lots of stuff!"}' http://localhost:5000/api/v1/entries/1 ``` | Method | Endpoint | Description | | ------------- |:-------------:| -----| | GET | home/api/v1/entries | Get all entries | GET | home/api/v1/entries/<entry_id> | Get specific entry using an id | | POST | home/api/v1/entries | Create a new entry | | PUT | home/api/v1/entries/<entry_id> | Edit an entry using an id | * Run tests on the application and check the test coverage ``` $ nosetests -v --with-coverage --cover-package=mydiaryapp/tests ``` This application can also be found on [Heroku](https://mydiary3-gbalaaka.herokuapp.com/api/v1/entries) The app's templates can be seen on [GitHub pages](https://balaakagordon.github.io/MyDiary_GB/) This application can also be found on [Heroku](https://mydiary3-gbalaaka.herokuapp.com/api/v1/entries) The api documentation may be found on [Apiary](https://mydiary17.docs.apiary.io/#)<file_sep>""" Contains the tests for the apis """ from flask import json, jsonify import unittest import os from mydiary import app, now_time from mydiary.db import MyDiaryDatabase test_user_1 = { "name": "<NAME>", "email": "<EMAIL>", "password": "<PASSWORD>", "confirmpassword": "<PASSWORD>" } test_user_2 = { "name": "<NAME>", "email": "<EMAIL>", "password": "<PASSWORD>", "confirmpassword": "<PASSWORD>" } test_user_5 = { "name": "<NAME>", "email": "<EMAIL>", "password": "<PASSWORD>", "confirmpassword": "<PASSWORD>" } test_user_6 = { "name": "<NAME>", "email": "<EMAIL>", "password": "<PASSWORD>", "confirmpassword": "<PASSWORD>" } test_entry_1 = { "entrydata": "Test Entry Title 1", "entrytitle": "This is the first entry for my tests" } test_entry_2 = { "entrydata": "Test Entry Title 2", "entrytitle": "This is the second entry for my tests" } test_entry_3 = { "entrydata": "Test Entry Title 3", "entrytitle": "This is the third entry for my tests" } def userInputFields(name, email, password, confirmpassword): test_user = { name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>", confirmpassword: "<PASSWORD>" } return test_user def userInputFields2(email, password): test_user = { email: "<EMAIL>", password: "<PASSWORD>" } return test_user def userCreds(name, email, password, password2): test_user = { "name": name, "email": email, "password": <PASSWORD>, "confirmpassword": <PASSWORD> } return test_user def userCreds2(email, password): login_details = { "email": email, "password": <PASSWORD> } return login_details def entryInputFields(entrydata, entrytitle): test_user = { entrydata: "Test Entry Title 3", entrytitle: "This is the third entry for my tests" } return test_user def entryData(entrydata, entrytitle): test_user = { "entrydata": "<EMAIL>", "entrytitle": "password" } return test_user class Test_apis(unittest.TestCase): """ This class holds all api tests """ def setUp(self): os.environ["db_name"] = "testdb" pass def entryTestPrep(self, tester, testuser): response = tester.post('/auth/signup',\ data=json.dumps(testuser), \ content_type='application/json') response2 = tester.post('/auth/login', \ data=json.dumps(testuser), \ content_type='application/json') tokendata = json.loads(response2.data) mytoken = tokendata["access_token"] return mytoken def test_user_registration(self): """ Test registers a test user successfully """ tester = app.test_client(self) response_reg = tester.post('/auth/signup',\ data=json.dumps(test_user_1), \ content_type='application/json') self.assertEqual(response_reg.status_code, 201) def test_registration_not_json(self): """ Test checks response when request isn't in json format """ tester = app.test_client(self) response = tester.post('/auth/signup',\ data=(test_user_2), \ content_type='html/text') self.assertEqual(response.status_code, 400) def test_registration_no_name_field(self): """ Test checks response when "name" field isn't included """ tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userInputFields( "", "email", "password", "<PASSWORD>")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please enter your name', str(response.data)) def test_registration_no_email_field(self): """ Test checks response when "email" field isn't included """ tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userInputFields( "name", "", "password", "<PASSWORD>")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please enter your email address', str(response.data)) def test_registration_no_password_field(self): """ Test checks response when "password" field isn't included """ tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userInputFields( "name", "email", "", "confirmpassword")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please enter your password', str(response.data)) def test_registration_no_password_confirm_field(self): """ Test checks response when "password" field isn't included """ tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userInputFields( "name", "email", "password", "")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please confirm your password', str(response.data)) def test_registration_user_already_exits(self): tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(test_user_2), \ content_type='application/json') response2 = tester.post('/auth/signup',\ data=json.dumps(test_user_2), \ content_type='application/json') self.assertEqual(response2.status_code, 409) self.assertIn('This user already exists!', str(response2.data)) def test_registration_invalid_names(self): tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userCreds( "t u", "<EMAIL>", "<PASSWORD>", "<PASSWORD>")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please enter a valid first and last name', str(response.data)) def test_registration_only_one_name_given(self): tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userCreds( "third", "<EMAIL>", "<PASSWORD>", "<PASSWORD>")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please enter a valid first and last name', str(response.data)) def test_registration_invalid_name_3(self): tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userCreds( "third us!er", "<EMAIL>", "<PASSWORD>", "<PASSWORD>")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Invalid character. Please enter a valid first and last name', str(response.data)) def test_registration_invalid_email(self): tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userCreds( "third user", "<EMAIL>", "<PASSWORD>", "<PASSWORD>")), \ content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn('Please enter a valid email address', str(response.data)) def test_registration_invalid_password(self): tester = app.test_client(self) response = tester.post('/auth/signup',\ data=json.dumps(userCreds( "third user", "<EMAIL>", "pw", "pw")), \ content_type='application/json') self.assertEqual(response.status_code, 411) self.assertIn('Password too short', str(response.data)) def test_login_wrong_password(self): tester = app.test_client(self) response = tester.post('/auth/login', \ data=json.dumps(userCreds2("<EMAIL>", "<PASSWORD>")), \ content_type='application/json') self.assertIn('Sorry, incorrect credentials', str(response.data)) self.assertEqual(response.status_code, 401) def test_login_no_account(self): tester = app.test_client(self) response = tester.post('/auth/login', \ data=json.dumps(userCreds2("<EMAIL>", "<PASSWORD>")), \ content_type='application/json') self.assertIn('Sorry, incorrect credentials', str(response.data)) self.assertEqual(response.status_code, 401) def test_login_no_email_field(self): tester = app.test_client(self) response = tester.post('/auth/login', \ data=json.dumps(userInputFields2("", "password")), \ content_type='application/json') self.assertIn('Cannot find email. Please provide valid login credentials', str(response.data)) self.assertEqual(response.status_code, 400) def test_login_no_password_field(self): tester = app.test_client(self) response = tester.post('/auth/login', \ data=json.dumps(userInputFields2("email", "")), \ content_type='application/json') self.assertIn('Cannot find password. Please provide valid login credentials', str(response.data)) self.assertEqual(response.status_code, 400) def test_login_successful(self): tester = app.test_client(self) response1 = tester.post('/auth/signup',\ data=json.dumps(test_user_2), \ content_type='application/json') self.assertEqual(response1.status_code, 201) response2 = tester.post('/auth/login', \ data=json.dumps(test_user_2), \ content_type='application/json') self.assertIn('access_token', str(response2.data)) self.assertEqual(response2.status_code, 200) def test_add_new_entry(self): """ a test for the status code returned by the post method """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response3 = tester.post('/api/v1/entries',\ data=json.dumps(test_entry_1),\ content_type='application/json',\ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertIn('Entry added successfully', str(response3.data)) self.assertEqual(response3.status_code, 201) def test_add_new_entry_wrong_data_format(self): """ a test for the status code returned by the post method """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response3 = tester.post('/api/v1/entries',\ data=json.dumps(test_entry_3),\ content_type='html/text',\ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response3.status_code, 400) self.assertIn('please input json data', str(response3.data)) def test_add_new_entry_no_entrydata_field(self): """ a test for the status code returned by the post method """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response3 = tester.post('/api/v1/entries',\ data=json.dumps(entryInputFields("", "entrytitle")),\ content_type='application/json',\ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response3.status_code, 400) self.assertIn('Please enter a title', str(response3.data)) def test_add_new_entry_no_entrytitle_field(self): """ a test for the status code returned by the post method """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response3 = tester.post('/api/v1/entries',\ data=json.dumps(entryInputFields("entrydata", "")),\ content_type='application/json',\ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response3.status_code, 400) self.assertIn('Cannot find diary title', str(response3.data)) def test_add_new_entry_repeated_entry(self): """ a test for the status code returned by the post method """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response1 = tester.post('/api/v1/entries',\ data=json.dumps(test_entry_2),\ content_type='application/json',\ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response1.status_code, 201) response2 = tester.post('/api/v1/entries',\ data=json.dumps(test_entry_2),\ content_type='application/json',\ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response2.status_code, 409) self.assertIn('Entry already exists', str(response2.data)) def test_get_one_entry(self): """ a test for the data returned by the get method and an index """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response2 = tester.get('/api/v1/entries/1',\ content_type='application/json', \ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertIn('This is the first entry for my tests', str(response2.data)) self.assertEqual(response2.status_code, 200) def test_get_one_entry_non_existent_entry_id(self): """ a test for the data returned by the get method and an index """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response = tester.get('/api/v1/entries/5',\ content_type='application/json', \ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertIn('The specified entry cannot be found', str(response.data)) self.assertEqual(response.status_code, 400) def test_get_all_entries(self): """ a test for the data returned by the get method and no entry index """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_5) response = tester.get('/api/v1/entries',\ content_type='application/json', \ headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response.status_code, 200) self.assertIn('This is the first entry for my tests', str(response.data)) self.assertIn('This is the second entry for my tests', str(response.data)) def test_edit_entry_data(self): """ a test for the data returned by the get method and no entry index """ tester = app.test_client(self) mytoken = self.entryTestPrep(tester, test_user_6) response1 = tester.post('/api/v1/entries', data=json.dumps(test_entry_1), content_type='application/json', headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response1.status_code, 201) response = tester.put('/api/v1/entries/3', data=json.dumps({"entrydata": "Testing the put method", "entrytitle": "Test Entry Title 1"}), content_type='application/json', headers={"authorization": 'Bearer ' + str(mytoken)}) self.assertEqual(response.status_code, 201) self.assertIn('Testing the put method', str(response.data)) self.assertNotIn("This is the first entry for my tests", str(response.data)) if __name__ == '__main__': #setUp() unittest.main() <file_sep>function addUser(){ let name = document.getElementById('uname').value; let email = document.getElementById('mail').value; let password = document.getElementById('pword').value; let confirmpassword = document.getElementById('pword2').value; fetch('http://127.0.0.1:5000/auth/signup', { method:'POST', headers:{ 'Content-type':'application/json' }, body:JSON.stringify({name: name, email: email, password:<PASSWORD>, confirmpassword:confirmpassword}) }) .then((res) => res.json()) .then(function (data){ //let serverresponse = data["message"]; if(data["message"] == "Invalid input"){ let errormsg = data["error"]; } else if(serverresponse == "Registered Successfully!"){ login(); } }) } function regResponse(data){ //let serverresponse = data["message"]; if(data["message"] == "Invalid input"){ let errormsg = data["error"]; } else if(serverresponse == "Registered Successfully!"){ window.location.href='./home.html' login(); } } function login(e){ e.preventDefault(); let email = document.getElementById('mail').value; let password = document.getElementById('pword').value; fetch('http://127.0.0.1:5000/auth/login', { method:'POST', headers:{ 'Content-type':'application/json' }, body:json.dumps({"email": email, "password":<PASSWORD>}) }) //.then((res) => res.json()) .then(regResponse(data)) }<file_sep>from flask import Flask, jsonify, request from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_identity ) from .models import MyDiary, Entries from mydiary import app, app_db, now_time my_diary_object = MyDiary() my_diary_object.user_entries = Entries() """ returns a single diary entry """ @app.route('/api/v1/entries/<int:diary_entry_id>', methods=['GET']) @jwt_required def get_entry(diary_entry_id): """ outputs one user entry specified by the id in the url """ user_id = get_jwt_identity() get_entry = my_diary_object.user_entries.getOneEntry( user_id, diary_entry_id ) if get_entry == 'The specified entry cannot be found': return jsonify({'error': get_entry}), 400 return jsonify({'getEntry': get_entry}), 200 """ returns all diary entries """ @app.route('/api/v1/entries', methods=['GET']) @jwt_required def get_all_entries(): """ outputs all entries for the logged in user """ user_id_data = get_jwt_identity() get_entries = my_diary_object.user_entries.getAllEntries(now_time, user_id_data) return jsonify({"entries": get_entries[0], "writtenToday": get_entries[1], "msg": "Authorized"}), 200 """ this route adds single diary entry """ @app.route('/api/v1/entries', methods=['POST']) @jwt_required def post_entry(): """ this method creates a new entry """ if not request.json: return jsonify({"input error": "please input json data"}), 400 if 'entrydata' not in request.json: return jsonify({"message": "Please enter a title"}), 400 if 'entrytitle' not in request.json: return jsonify({"message": "Cannot find diary title"}), 400 entry_data=request.json.get('entrydata', "") title_data=request.json.get('entrytitle', "") if entry_data == "": return jsonify({"message": "Null entry field"}), 404 if title_data == "": title_data = "...No Title..." user_id_data = get_jwt_identity() add_entry = my_diary_object.user_entries.addEntry( user_id_data, title_data, entry_data, now_time ) if add_entry == "Entry added successfully": new_entry = { 'user_id' : user_id_data, 'title' : title_data, 'entrydata' : entry_data, 'datecreated' : now_time } return jsonify({'message' : add_entry, 'entry added' : new_entry}), 201 return jsonify({'message' : add_entry}), 409 """ this route updates a single diary entry """ @app.route('/api/v1/entries/<int:diary_entry_id>', \ methods=['PUT']) @jwt_required def put_entry(diary_entry_id): """ this method updates an entry's data """ if not request.json: return jsonify({"input error": "please input data in json format"}), 400 if 'entrydata' not in request.json: return jsonify({"message": "Diary entry data not found"}), 400 if 'entrytitle' not in request.json: return jsonify({"message": "Diary entry title title"}), 400 data = request.get_json() entry_data=data["entrydata"] title_data=data["entrytitle"] if entry_data == "": return jsonify({"message": "Null entry field"}), 404 if title_data == "": title_data = "...No Title..." edit_time = now_time user_id_data = get_jwt_identity() entry_id_data = diary_entry_id edit_entry = my_diary_object.user_entries.modifyEntry( title_data, entry_data, edit_time, entry_id_data, user_id_data ) if edit_entry == "Entry edited": entry = { 'entry_id': entry_id_data, 'user_id': user_id_data, 'title': title_data, 'entrydata': entry_data, 'datecreated': now_time } return jsonify({'entry':entry, "message": edit_entry}), 201 return jsonify({'message': edit_entry}), 400 """ this route deletes a diary entry """ @app.route('/api/v1/entries/<int:diary_entry_id>', methods=['DELETE']) @jwt_required def delete_entry(diary_entry_id): """ this method deletes an entry """ user_id_data = get_jwt_identity() entry_id_data = diary_entry_id delete_entry = my_diary_object.user_entries.deleteEntry(entry_id_data, user_id_data) return jsonify({'message': delete_entry})
c83d23d6f06f432389a22afa9474d0b2f25c81cb
[ "JavaScript", "Python", "Text", "Markdown" ]
11
Python
balaakagordon/MyDiary4
53949f4105680aa969da87604fcc26a4595ddeb6
6dbd7055a733e30b758f433b74afac29580137a3
refs/heads/master
<repo_name>Shuhei-YOSHIDA/ros_tiny_utils<file_sep>/tiny_conversion/src/nav_msgs_path_to_text_marker_node.cpp /** * @file nav_msgs_path_to_text_marker_node.cpp * @brief Subscribe a path of nav_msgs/Path, and convert it to text marker of visualizing_msgs/MarkerArray */ #include <ros/ros.h> #include <nav_msgs/Path.h> #include <visualization_msgs/MarkerArray.h> #include <tf2_ros/transform_listener.h> #include <geometry_msgs/TransformStamped.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include "color_names/color_names.h" #include "tf2/convert.h" #include "tf2/exceptions.h" #include "tf2_ros/buffer.h" using namespace std; using namespace visualization_msgs; using namespace nav_msgs; using namespace geometry_msgs; ros::Publisher marker_pub; ros::Subscriber path_sub; std::shared_ptr<tf2_ros::Buffer> tf_buffer_ptr; std::shared_ptr<tf2_ros::TransformListener> tf_listener_ptr; string dToStr(double value, int digit=2) { stringstream stream; stream << fixed << setprecision(digit) << value; return stream.str(); } // Parameter for text double font_size = 1.0; string color_name = "black"; string unit = "m"; string delimiter = ","; int digit = 2; string target_frame_id = ""; void paramLoad() { XmlRpc::XmlRpcValue font_data; if (ros::param::get("~font_data", font_data)) { font_size = static_cast<double>(font_data["font_size"]); color_name = static_cast<string>(font_data["color_name"]); unit = static_cast<string>(font_data["unit"]); delimiter = static_cast<string>(font_data["delimiter"]); digit = static_cast<int>(font_data["digit"]); target_frame_id = static_cast<string>(font_data["target_frame_id"]); } } Marker textMarker(PoseStamped poses) { Marker m_msg; m_msg.header = poses.header; m_msg.pose = poses.pose; m_msg.type = Marker::TEXT_VIEW_FACING; m_msg.scale.z = font_size; m_msg.color = color_names::makeColorMsg(color_name); m_msg.text = "(" + dToStr(poses.pose.position.x, digit) + unit + delimiter + dToStr(poses.pose.position.y, digit) + unit + delimiter + dToStr(poses.pose.position.z, digit) + unit + ")"; return m_msg; } void pathCB(const Path::ConstPtr& msg) { static int previous_size = 0; if (previous_size != 0 && previous_size != msg->poses.size()) { Marker delete_msg; delete_msg.action = Marker::DELETEALL; delete_msg.header.stamp = ros::Time::now(); MarkerArray ma_msg; ma_msg.markers.push_back(delete_msg); marker_pub.publish(ma_msg); ROS_WARN("Detected that size of path-msg is changed"); ros::Duration(0.3).sleep(); } previous_size = msg->poses.size(); MarkerArray ma_msg; for (int i = 0; i < msg->poses.size(); i++) { // Convert each pose with target_frame_id Marker m_msg; if (target_frame_id == "") { m_msg = textMarker(msg->poses[i]); } else { geometry_msgs::TransformStamped tf; try { tf = tf_buffer_ptr->lookupTransform(target_frame_id, msg->poses[i].header.frame_id, ros::Time(0)); PoseStamped new_poses; tf2::doTransform(msg->poses[i], new_poses, tf); m_msg = textMarker(new_poses); } catch (tf2::TransformException &ex) { ROS_WARN("%s", ex.what()); continue; } } m_msg.id = i; ma_msg.markers.push_back(m_msg); } marker_pub.publish(ma_msg); } int main(int argc, char** argv) { ros::init(argc, argv, "path_to_text_marker_node"); ros::NodeHandle nh; tf_buffer_ptr = make_shared<tf2_ros::Buffer>(); tf_listener_ptr = make_shared<tf2_ros::TransformListener>(*tf_buffer_ptr); marker_pub = nh.advertise<MarkerArray>("path_text_marker", 1, true); path_sub = nh.subscribe("path", 1, pathCB); paramLoad(); ros::spin(); return 0; } <file_sep>/tiny_conversion/src/tiny_conversion/resolve_path.cpp /** * @file resolve_path.cpp */ #include "tiny_conversion/resolve_path.h" #include <ros/package.h> #include <ros/console.h> #include <boost/filesystem.hpp> //#include <filesystem> using namespace std; vector<string> split(string str, char delimiter) { int first = 0; int last = str.find_first_of(delimiter); vector<string> result; while (first < str.size()) { string subStr(str, first, last - first); result.push_back(subStr); first = last + 1; last = str.find_first_of(delimiter, first); if (last == string::npos) { last = str.size(); } } //if (str.find_last_of(delimiter) == str.size()-1) //{ //result.push_back(""); //} return result; } namespace tiny_conversion { string resolvePathUrlStr(const string& url) { vector<string> splited = split(url, '/'); boost::filesystem::path path; if (url.find("package://") == 0) // Case-insensitive? { string package_name = splited[2]; string file_name; for (int i = 3; i < splited.size(); i++) { if (i == 3) file_name += splited[i]; else file_name += ("/" + splited[i]); } path = ros::package::getPath(package_name); path = path / file_name; } else if (url.find("file://") == 0) { for (int i = 2; i < splited.size(); i++) { if (i == 2) path += splited[i]; else path += ("/" + splited[i]); } } else { path = boost::filesystem::path(url); if (!boost::filesystem::exists(path)) { ROS_ERROR("Invalid or unsupported URL: '%s'", url.c_str()); return ""; } } string resolved_pathstr = path.string(); return resolved_pathstr; } //filesystem::path resolvePath(const string& path) //{ //filesystem::path resolved_path; //return resolved_path; //} } <file_sep>/tiny_conversion/src/relative_gnss_tf_broadcaster_node.cpp /** * @file relative_gnss_tf_broadcaster_node.cpp * @brief Subscribe sensor_msgs/NavSatFix, and broadcast TF of UTM pose relative to particular gps data */ #include <ros/ros.h> #include <sensor_msgs/NavSatFix.h> #include <geometry_msgs/QuaternionStamped.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <geodesy/utm.h> #include <geodesy/wgs84.h> #include <geographic_msgs/GeoPoint.h> #include <geometry_msgs/TransformStamped.h> using namespace std; // base_link ->(rotation)-> gps ->(local utm)-> local_gnss string g_gps_frame_id; string g_base_link_frame_id; bool g_is_gps_frame_inversed = true; // from ENU(gps_frame_id) to body(base_link_frame_id) void gpsCB(const sensor_msgs::NavSatFix::ConstPtr& msg) { static tf2_ros::TransformBroadcaster br; static bool is_first_msg = true; static sensor_msgs::NavSatFix first_msg; static geodesy::UTMPoint first_utm; if (is_first_msg) /// @todo shoule be reset by service { is_first_msg = false; first_msg = *msg; geographic_msgs::GeoPoint gp = geodesy::toMsg(*msg); geodesy::fromMsg(gp, first_utm); } geographic_msgs::GeoPoint gp = geodesy::toMsg(*msg); geodesy::UTMPoint utm; geodesy::fromMsg(gp, utm); geometry_msgs::TransformStamped tf; tf.header.frame_id = g_gps_frame_id; tf.header.stamp = ros::Time::now(); tf.child_frame_id = "local_gnss"; tf.transform.translation.x = first_utm.easting - utm.easting; tf.transform.translation.y = first_utm.northing - utm.northing; tf.transform.translation.z = first_utm.altitude - utm.altitude; tf.transform.rotation.w = 1.0; br.sendTransform(tf); } void attitudeCB(const geometry_msgs::QuaternionStamped::ConstPtr& msg) { static tf2_ros::TransformBroadcaster br; geometry_msgs::TransformStamped tf; tf.header.frame_id = g_base_link_frame_id; tf.header.stamp = ros::Time::now(); tf.child_frame_id = g_gps_frame_id; if (!g_is_gps_frame_inversed) { tf.transform.rotation = msg->quaternion; } else { tf2::Quaternion q; tf2::fromMsg(msg->quaternion, q); q = q.inverse(); tf2::convert(q, tf.transform.rotation); } br.sendTransform(tf); } void usage() { cerr << "Usage:" << endl << "rosrun tiny_conversion relative_gnss_tf_broadcaster_node gps_position:=/your/gps_topic attitude:=/usr/attitude_topic _gps_frame_id:=your_gps_id _base_link_frame_id:=your_body_id" << endl << "-------" << endl << "Example:" << endl << "rosrun tiny_conversion relative_gnss_tf_broadcaster_node gps_position:=/dji_osdk_ros/gps_position attitude:=/dji_osdk_ros/attitude _gps_frame_id:=gps _base_link_frame_id:=body_FLU" << endl << "-------" << endl; } int main(int argc, char** argv) { usage(); ros::init(argc, argv, "relative_gnss_tf_broadcaster_node"); ros::NodeHandle nh; ros::param::param<string>("~gps_frame_id", g_gps_frame_id, "gps"); ros::param::param<string>("~base_link_frame_id", g_base_link_frame_id, "base_link"); ros::param::param<bool>("~is_gps_frame_inversed", g_is_gps_frame_inversed, "true"); ROS_INFO("[~gps_frame_id, ~base_link_frame_id]:[%s, %s]", g_gps_frame_id.c_str(), g_base_link_frame_id.c_str()); if (g_is_gps_frame_inversed) { ROS_INFO("Quaternion of attitude_topic is inversed for rotation from ~base_link_frame_id to ~gps_frame_id(ENU)"); } string gps_topic_name = "gps_position"; string attitude_topic_name = "attitude"; ros::Subscriber gps_sub = nh.subscribe(gps_topic_name, 1, gpsCB); ros::Subscriber attitude_sub = nh.subscribe(attitude_topic_name, 1, attitudeCB); ros::spin(); return 0; } <file_sep>/tiny_conversion/scripts/sample_path_publisher.py #!/usr/bin/env python3 import rospy import numpy as np from nav_msgs.msg import Path from geometry_msgs.msg import PoseStamped def path_publisher(): pub = rospy.Publisher('path', Path, queue_size=1, latch=True) rospy.init_node('sample_path_publisher') path = Path() path.header.frame_id = "world" path.header.stamp = rospy.get_rostime() for i in range(6): rad = i*60*np.pi/180. r = 10. p = PoseStamped() p.header = path.header p.pose.position.x = r*np.cos(rad) p.pose.position.y = r*np.sin(rad) p.pose.position.z = float(i) p.pose.orientation.w = 1 path.poses.append(p) pub.publish(path) rospy.spin() if __name__ == "__main__": try: path_publisher() except rospy.ROSInterruptException: pass <file_sep>/tiny_conversion/README.md tiny_conversion ==== Conversion from something to something for ROS ## rosbag2text.py Convert contents of rosbag to text files. The files is assigned to each topic. This utility is mainly for small rosbag file, which has simple data. ### How to use ```bash $ # ./rosbag2text.py path_to_rosbag [output_directory] $ ./rosbag2text.py test.bag ~/ ``` You can get text files which represent messages of each topic. If output_directory is not set, `/tmp` is used as default. The output files are written by YAML style. The root of YAML is set to `messages'. Hence, for example, you can treat the file by `yq` command. ```bash $ cat output_text.txt | yq .messages # all messages $ cat output_text.txt | yq .messages[1] # 2nd message ``` ## path_to_text_marker Convert a topic of `nav_msgs/Path` into another topic of `visualization_msgs::MarkerArray`. The markers represents positions of the path by using text markers. It is able to change font size, and so on by using ros parameters. Please check `tiny_conversion/params/font_data.yaml`. ### How to use ```bash $ # sample launch file $ roslaunch tiny_conversion sample_nav_msgs_path_to_text_marker.launch ``` ## resolve_path.h Resolve url as string. ```cpp #include "tiny_conversion/resolve_path.h" string url = "package:://tiny_conversion/package.xml"; string resolved_path = tiny_conversion::resolvePathUrlStr(url); // ex. resolved_path: "/home/your_user/catkin_ws/src/ros_tiny_utils/tiny_conversion/package.xml" ``` ## bag_image_extractor Load rosbag file and save image topic as files. ## relative_gnss_tf_broadcaster_node Subscribe topics of sensor_msgs/NavSatFix and geometry_msgs::QuaternionStamped, broadcast TF of the moving body for ENU coodinates. <file_sep>/README.md tiny_utils ==== ROS packages for tiny utilities. ## color_names Utility for std_msgs/ColorRGBA ## easy_marker Utility for visualization_msgs/Marker ## tee_logging Utility to execute ROS console macro (e.g. ROS_INFO) and write log-message to a file at the same time ## tiny_conversion Utility to convert some data-type and so on ## tiny_rviz_plugins RViz plugin to show multiple states of a robot at the same time **If you use ROS noetic, tiny_rviz_plugins pkg cannot be used. Please put CATKIN_IGNORE file** <file_sep>/tiny_conversion/src/sample_resolve_path_node.cpp /** * @file sample_resolve_path_node.cpp */ #include "tiny_conversion/resolve_path.h" #include <ros/console.h> #include <iostream> #include <vector> using namespace std; using namespace tiny_conversion; int main(int argc, char** argv) { vector<string> sample_path_data = { "package://tiny_conversion/src/sample_resolve_path_node.cpp", "file://tiny_conversion/package.xml", "package://tiny_conversion/", "file://tiny_conversion/", "", "foobar", "./package.xml" }; for (auto path : sample_path_data) { string url = path; string resolved_path = resolvePathUrlStr(url); ROS_INFO_STREAM("[" << url << "] : [" << resolved_path << "]"); } return 0; } <file_sep>/tiny_conversion/include/tiny_conversion/resolve_path.h /** * @file resolve_path.h */ #ifndef INCLUDE_TINY_CONVERSION_RESOLVE_PATH_H #define INCLUDE_TINY_CONVERSION_RESOLVE_PATH_H #include <string> //#include <boost/filesystem.hpp> //#include <filesystem> namespace tiny_conversion { std::string resolvePathUrlStr(const std::string& url); //std::filesystem::path resolvePath(const std::string& path); //boost::filesystem::path resolvePath(const std::string& path); } #endif /* INCLUDE_TINY_CONVERSION_RESOLVE_PATH_H */ <file_sep>/tiny_conversion/src/bag_image_extractor.cpp /** * @file bag_image_extractor.cpp * @brief Extract sensor_msgs/Image topic and save it as image files * @note Reference: ros-perception/image_pipeline repository, image_view package */ #include <rosbag/bag.h> #include <rosbag/view.h> #include <sensor_msgs/Image.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/highgui/highgui.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <sys/stat.h> using namespace std; void usage() { cerr << "usage:" << endl << "rosrun tiny_conversion bag_image_extractor_node [bagfile_path] [image_topic_name] [output_dir]" << endl; cerr << "example:" << endl << "rosrun tiny_conversion bag_image_extractor_node ~/test.bag /image_raw /tmp" << endl; return; } int main(int argc, char** argv) { if (argc < 4) { ROS_FATAL("less arguments"); usage(); return -1; } string bagfile_path(argv[1]); string image_topic_name(argv[2]); string output_dir(argv[3]); ROS_INFO("bagfile_path: %s", bagfile_path.c_str()); ROS_INFO("image_topic_name: %s", image_topic_name.c_str()); ROS_INFO("output_dir: %s", output_dir.c_str()); struct stat statBuf; if (stat(output_dir.c_str(), &statBuf) != 0) { ROS_FATAL("output_dir does not exist"); usage(); return -1; } rosbag::Bag bag; try { bag.open(bagfile_path); } catch(rosbag::BagException& e) { ROS_FATAL("Could not open the bagfile"); cerr << e.what() << endl; usage(); return -1; } ROS_INFO("Opened bagfile"); vector<string> topic_names = {image_topic_name}; rosbag::View view(bag, rosbag::TopicQuery(topic_names)); const int size = view.size(); ROS_INFO("Extract images :%d", view.size()); int count = 0; auto wall_time = ros::WallTime::now(); for (auto m : view) { sensor_msgs::Image::ConstPtr img_ptr = m.instantiate<sensor_msgs::Image>(); if (img_ptr == NULL) continue; //ros::Time bag_stamp = m.getTime(); ros::Time header_stamp = img_ptr->header.stamp;; cv::Mat image; try { image = cv_bridge::toCvShare(img_ptr)->image; } catch(cv_bridge::Exception &e) { cerr << e.what() << endl; ROS_FATAL("Failed to convert img message to cv::Mat"); return -1; } if (!image.empty()) { stringstream stamp_ss; stamp_ss << header_stamp.sec << "." << std::setw(9) << std::setfill('0') << header_stamp.nsec << ".png"; string filename = output_dir + "/" + stamp_ss.str(); cv::imwrite(filename, image); } else { ROS_ERROR("image is empty"); } if (ros::WallTime::now() - wall_time > ros::WallDuration(10.0)) { cerr << count << "/" << size << endl;; wall_time = ros::WallTime::now(); } count++; } cout << count << " files are saved" << endl; return 0; }
8f1e3f68324f11a65d93e5c9418cd39619f9b9ff
[ "Markdown", "Python", "C++" ]
9
C++
Shuhei-YOSHIDA/ros_tiny_utils
39a8f3068df7e2766ba853f8a8755854a29b114d
bf33835ae5d00cf38036611aa088f7448be1fc76
refs/heads/main
<file_sep># LeoCode Es un proyecto de Web <file_sep>const currentYear = document.getElementById('currentYear'); currentYear.innerText = new Date().getUTCFullYear();
c2dcf514b27df2837281223af636282b8463c6e5
[ "Markdown", "JavaScript" ]
2
Markdown
crisdamo/LeoCode
47bcf51686ce5d3eef70f6c5d8a6e88d3a3ead17
1286551c5cae3032888e304c3807481b12cf1625
refs/heads/master
<repo_name>ertyazilim/WordPress-Automagic-Widgets<file_sep>/example-usage.php <?php /** * Example usage of the Automagic Widgets class. * * This shows you how you can implement Automagic Widgets * */ require( "SI_Automagic_Widgets.class.php" ); class My_Theme_Sidebars { function __construct() { # Add widgets automagically on theme activate add_action( "after_switch_theme", array( &$this, "register_widgets" ) ); } function register_widgets( $theme_name ) { # Check if it is indeed our theme we're activating, and if we haven't # added the widgets before if ( 'My_Theme_Name' == get_current_theme() && false == get_option( "my_theme_automagic_widgets_added" ) ) { # Check if Automated Widgets class exists if( class_exists( "SI_Automagic_Widgets" ) ) { # Initiate the class $auto_widgets = new SI_Automagic_Widgets; # Add your widgets. # Note that you should to have these sidebars registered by now. $auto_widgets->add_widgets( array( # Add a text widget to my homepage sidebar array( "sidebar" => "homepage_sidebar", "widget" => "text", "args" => array( "title" => "My text widget", "text" => "Lorem ipsum dolor sit amet." ) ), # Add a text widget to my blog sidebar array( "sidebar" => "blog_sidebar", "widget" => "search", "args" => array( "title" => "Search blog" ) ) # Etc... ) ); # Note this action for the future update_option( "my_theme_automagic_widgets_added", 1 ); } } } } # Initiate the class new My_Theme_Sidebars; ?><file_sep>/README.md Automagic Widgets in WordPress ============================== Allows you to programmatically add widgets to specified sidebars in WordPress. Sometimes, usually when you are building a WordPress theme, you want to be able to add a specified set of widgets in specified sidebars programmatically, for instance to populate a certain sidebar of your theme automatically when it's activated. This class allows you to do just that. Please note that when you use this class, you still need to think about at what point the widgets are added. You don't want to add widgets on each page load. ## Example usage Check out example-usage.php to see how it can be implemented. In this example 2 widgets are added when a theme called My_Theme_Name is activated. 1 text widget to a sidebar called homepage_sidebar, and 1 search widget to a sidebar called blog_sidebar. Note that you can also use your own custom widgets by using their widget_id. This code is in beta so use at your own risk. [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/superinteractive/wordpress-automagic-widgets/trend.png)](https://bitdeli.com/free "Bitdeli Badge") <file_sep>/SI_Automagic_Widgets.class.php <?php /** * Super Interactive Automagic Widgets * * Allows you to programmatically add widgets to specified sidebars in WordPress. * * * @author <NAME> <<EMAIL>> * * http://www.superinteractive.com * */ class SI_Automagic_Widgets { protected $sidebar_options = array(); protected $widgets = array(); /** * Add widgets programmatically to the specified sidebars * and using the specified arguments/properties * * @param array $widgets An array of associative arrays in the format * "sidebar" => "sidebar_id", * "widget" => "widget_id", * "args" => "widget_arguments" */ function add_widgets( $widgets ) { # Bounce if we have nothing to digest if( ! count( $widgets ) ) return false; # Get current sidebars_widgets option value $this->sidebar_options = get_option( "sidebars_widgets", array() ); # Walk through widgets to get the current iterations $this->_count_widgets(); foreach( $widgets as $widget ) { # Add the specified widget to the specified sidebar $this->_add_widget( $widget ); } # Save the new sidebar/widget data $this->_save(); } /** * Private method to add a specified widget to a specified sidebar with the specified arguments * * @param array $widget An associative array in the format * "sidebar" => "sidebar_id", * "widget" => "widget_id", * "args" => "widget_arguments" */ function _add_widget( $widget ) { $sidebar_id = $widget["sidebar"]; $widget_id = $widget["widget"]; $widget_args = $widget["args"]; # Get the current widget list of the specified sidebar $sidebar = $this->sidebar_options[$sidebar_id]; # Get the iteration of the specified widget and add 1 for ours if(!isset($this->widgets[$sidebar_id][$widget_id])) $this->widgets[$sidebar_id][$widget_id] = 0; $count = $this->widgets[$sidebar_id][$widget_id] + 1; # Add the widget to the specified sidebars widget list $sidebar[] = "$widget_id-$count"; # Put the new widget list back in the global sidebar set $this->sidebar_options[$sidebar_id] = $sidebar; # Get the current widget contents option value for the specified widget type $widget_contents = get_option( "widget_$widget_id", array() ); # Add the specified arguments as content for our widget $widget_contents[$count] = $widget_args; # Add the widget contents to the global widgets set $this->widgets[$widget_id] = $widget_contents; } /** * Get the current iterations of all widget types * * @return void */ function _count_widgets() { if( $this->sidebar_options ) { # Exclude helpers $exclude = array( "wp_inactive_widgets", "array_version" ); # Walk through all sidebars and widget sets foreach( $this->sidebar_options as $sidebar_id => $sidebar_widgets ) { # Check if sidebar is not in exclude list if( ! in_array( $sidebar_id, $exclude ) ) { # Walk through widgets foreach( $sidebar_widgets as $widget ) { # Get widget name and count $count_arr = explode('-', $widget); $count = (int) end($count_arr); $name = _get_widget_id_base( $widget); //list($name, $count) = preg_split('/-+(?=\S+$)/', $widget); # Set the current widget type count if( !isset( $this->widgets[$sidebar_id][$name]) || $count > $this->widgets[$sidebar_id][$name] ) { $this->widgets[$sidebar_id][$name] = $count; } } } } } } /** * Save updates after processing the sidebars and widgets * * @return void */ function _save() { # Save the new sidebars_widgets option value update_option( "sidebars_widgets", $this->sidebar_options ); # Save each widget content settings if( count( $this->widgets ) ) { foreach( $this->widgets as $widget_id => $widget_contents ) { update_option( "widget_$widget_id", $widget_contents ); } } } } ?>
7ecec5951c46e3727daef1619653241b7cf65031
[ "Markdown", "PHP" ]
3
PHP
ertyazilim/WordPress-Automagic-Widgets
8f2e2d33d63e8a6b6b9c39cbdb1d67f6d9fbd4d2
0e4f75696a21eb806c94e6f68eba1d8533cc5abd
refs/heads/master
<repo_name>Benjijamin/TP2Server<file_sep>/app.js const express = require('express'); const app = express(); const fs = require('fs'); app.get('/calendrier', (req,res) =>{ fs.readFile(__dirname + "/" + "events.json", 'utf8', (err,data)=>{ res.header("Access-Control-Allow-Origin","*"); console.log("data sent: \n" + data); res.end(data); }) }); var server = app.listen(3030, () => { console.log("running"); });
df98842be56f964ca0271529ab6364bf569c6749
[ "JavaScript" ]
1
JavaScript
Benjijamin/TP2Server
c3da68a1817e472d7e1d5d0e4c35f9cef0c9706d
cc74be721d526a8063da55d27ae53658e8253345
refs/heads/master
<repo_name>slodge/MvvmCrossTwitterSearch<file_sep>/TwitterSearch.UI.Touch/TwitterTabletSearchPresenter.cs using System; using Cirrious.MvvmCross.Touch.Interfaces; using Cirrious.MvvmCross.Touch.Views.Presenters; using MonoTouch.UIKit; using TwitterSearch.UI.Touch.Views; namespace TwitterSearch.UI.Touch { public class TwitterTabletSearchPresenter : MvxBaseTouchViewPresenter { private readonly UIApplicationDelegate _applicationDelegate; private readonly UIWindow _window; private readonly SplitViewController _splitView; public TwitterTabletSearchPresenter(UIApplicationDelegate applicationDelegate, UIWindow window) { _applicationDelegate = applicationDelegate; _window = window; _splitView = new SplitViewController(); _window.RootViewController = _splitView; } public override bool ShowView(IMvxTouchView view) { if (view is HomeView) { _splitView.SetPrimaryView(view); } else { _splitView.SetSecondaryView(view); } return true; } public override void NativeModalViewControllerDisappearedOnItsOwn() { throw new NotImplementedException(); } public override void ClearBackStack() { throw new NotImplementedException(); } public override bool GoBack() { throw new NotImplementedException(); } public override bool PresentNativeModalViewController(UIViewController viewController, bool animated) { throw new NotImplementedException(); } } }
036b592e61fcbc08a0028fff05e9c70d26818a6e
[ "C#" ]
1
C#
slodge/MvvmCrossTwitterSearch
a28a5d0dec688185c361b6faeebee0a8815c2b51
1daa63bb1dc4ef0dbe07e2a091ac4e3c62f03ee3
refs/heads/master
<repo_name>colinjhong/poker<file_sep>/README.md # Poker Simulated poker game, final project, ongoing improvements Animation through Processing is not ready yet, played through command line Instructions included at start of game One human player, your choice of number of computer players <file_sep>/poker.py # Poker import random import collections import os import itertools import time # cards with names (for face cards), values, suits class Card: def __init__(self,value,suit): if value=='Ace': self.value=14 self.name='Ace' elif value=='King': self.value=13 self.name='King' elif value=='Queen': self.value=12 self.name='Queen' elif value=='Jack': self.value=11 self.name='Jack' else: self.value=value self.name=value self.suit=suit def __gt__(self,other): return self.value>other.value def __str__(self): return '{0} of {1}'.format(self.name,self.suit) # creates deck as list of card instances class Deck(list): def __init__(self): suits=['Spades','Hearts','Diamonds','Clubs'] values=['Ace',2,3,4,5,6,7,8,9,10,'Jack','Queen','King'] for i in suits: for j in values: card=Card(j,i) self.append(card) def deal(self): a=random.randint(0,len(self)-1) b=self.pop(a) return b # human player, contains methods for betting class Hand: def __init__(self,name): self.name=name self.card1=0 self.card2=0 self.credits=1000 # determines special responsibilities of the position # specific ones will be switched to "true" later self.dealer=False self.small=False self.big=False self.stake=0 self.done=False self.besthand=0 self.besthandstring='' def __str__(self): if self.dealer==True: return ' Dealer: {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) elif self.small==True: return 'Small blind: {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) elif self.big==True: return ' Big blind: {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) else: return ' {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) def __gt__(self,other): return self.credits>other.credits def check(self): print("\n{0} will check.".format(self.name)) print(self) def call(self): global minbet if minbet<=(self.credits+self.stake): self.credits-=(minbet-self.stake) self.stake+=(minbet-self.stake) else: print('***************') print("{0} doesn't have that much money.".format(self.name)) print("{0} will go into the negatives.".format(self.name)) print('***************') self.credits-=(minbet-self.stake) self.stake+=(minbet-self.stake) print("\n{0} will call.".format(self.name)) print(self) def _raise(self,credit): global minbet if minbet>(self.credits+self.stake): if type(self)!=Computer: print("You don't have enough money to raise.") print("You'll automatically call the minimum and go into the negatives.") self.call() elif minbet<=credit<=(self.credits+self.stake): self.credits-=(credit-self.stake) self.stake+=(credit-self.stake) minbet=credit print("\n{0} will raise.".format(self.name)) print('Minimum bet is now:',minbet) elif minbet>credit: print("You can't bet less than the minimum: {0}.".format(minbet)) self._raise(getAmountFromUser('Total amount you want to bet: ')) elif credit>(self.credits+self.stake): if type(self)!=Computer: print("You don't have that much money.") self._raise(getAmountFromUser('Enter an amount you can afford: ')) print(self) def fold(self): global pot global activecount pot+=self.stake self.stake=0 print('\n{0} will fold.'.format(self.name)) self.done=True print(self) activecount=0 for i in player_list: if i.done==False: activecount+=1 print('Active players:',activecount) # computer player w/ decision making class Computer(Hand): def __init__(self,name,aggr): Hand.__init__(self,name) self.aggr=aggr def __str__(self): if self.dealer==True: return ' Dealer: {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) elif self.small==True: return 'Small blind: {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) elif self.big==True: return ' Big blind: {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) else: return ' {0} - Credits: {1}; At stake: {2}'.format(self.name,self.credits,self.stake) def preflop1(self): if minbet==bigblind: if self.small is True: self.stake+=smallblind self.credits-=smallblind # pair if self.card1.value==self.card2.value: if self.aggr>7: self._raise(int(minbet*2)) elif self.aggr>5: self._raise(int(minbet*1.5)) else: if random.randint(1,4)==1: self._raise(int(minbet*2)) else: self.call() # suited high cards if self.card1.value>10 and self.card2.value>10 and self.card1.suit==self.card2.suit: self.call() # high cards elif self.card1.value>10 and self.card2.value>10: self.call() # suited cards elif self.card1.suit==self.card2.suit: self.call() # possibility for straight elif abs(self.card1.value-self.card2.value)<=1: if self.aggr>4: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() elif abs(self.card1.value-self.card2.value)<=2: if self.aggr>4.25: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() elif abs(self.card1.value-self.card2.value)<=3: if self.aggr>4.5: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() elif abs(self.card1.value-self.card2.value)<=4: if self.aggr>4.75: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() # one high card elif self.card1.value>10 or self.card2.value>10: if self.aggr>5: self.call() else: if random.randint(1,4)==1: self.call() else: self.fold() else: if self.aggr>6: self.call() else: if random.randint(1,4)==1: self.call else: self.fold() elif self.big is True: self.stake+=50 self.credits-=50 self.check() else: self.preflop() else: if self.small is True: self.stake+=smallblind self.credits-=smallblind if self.big is True: self.stake+=50 self.credits-=50 self.preflop() def preflop(self): # taking into account how much the bet is prob=(minbet/(self.credits+self.stake)) # benefit of a high card boost=self.card1.value-7 boost2=self.card2.value-7 # general equation # else situation is for taking random chances # difference between aggression and threshold of betting will play into how much they raise ''' if self.aggr>(([1(great)-3(okay)]*(1+prob))-(max(boost,boost2)/[3(value=big influence)-5(value=small influence)])): if (self.aggr-(([1(great)-3(okay)]*(1+prob))-(max(boost,boost2)/[3(value=big influence)-5(value=small influence)])))>4: self._raise(minbet+(10*int(self.aggr-(([1(great)-3(okay)]*(1+prob))-(max(boost,boost2)/[3(value=big influence)-5(value=small influence)])))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() ''' # pair if self.card1.value==self.card2.value: if self.aggr>((1*(1+prob))-(boost/5)): if (self.aggr-((1*(1+prob))-(boost/5)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((1*(1+prob))-(boost/5)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() # suited high cards elif self.card1.value>10 and self.card2.value>10 and self.card1.suit==self.card2.suit: if self.aggr>((1*(1+prob))-(max(boost,boost2)/3)): if (self.aggr-((1*(1+prob))-(max(boost,boost2)/3)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((1*(1+prob))-(max(boost,boost2)/3)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() # high cards elif self.card1.value>10 and self.card2.value>10: if self.aggr>((2*(1+prob))-(max(boost,boost2)/5)): if (self.aggr-((2*(1+prob))-(max(boost,boost2)/5)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((1.5*(1+prob))-(max(boost,boost2)/5)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() # suited cards elif self.card1.suit==self.card2.suit: if self.aggr>((2.5*(1+prob))-(max(boost,boost2)/5)): if (self.aggr-((2.5*(1+prob))-(max(boost,boost2)/5)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((1.75*(1+prob))-(max(boost,boost2)/5)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() # possibility for straight elif abs(self.card1.value-self.card2.value)<=1: if self.aggr>((2.5*(1+prob))-(max(boost,boost2)/4)): if (self.aggr-((2.5*(1+prob))-(max(boost,boost2)/4)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((1.5*(1+prob))-(max(boost,boost2)/4)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() elif abs(self.card1.value-self.card2.value)<=2: if self.aggr>((3*(1+prob))-(max(boost,boost2)/4)): if (self.aggr-((3*(1+prob))-(max(boost,boost2)/4)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((2*(1+prob))-(max(boost,boost2)/4)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() elif abs(self.card1.value-self.card2.value)<=3: if self.aggr>((4*(1+prob))-(max(boost,boost2)/4)): if (self.aggr-((4*(1+prob))-(max(boost,boost2)/4)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((2.5*(1+prob))-(max(boost,boost2)/4)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() elif abs(self.card1.value-self.card2.value)<=4: if self.aggr>((4*(1+prob))-(max(boost,boost2)/4)): if (self.aggr-((4*(1+prob))-(max(boost,boost2)/4)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((2.5*(1+prob))-(max(boost,boost2)/4)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() # one high card elif self.card1.value>10 or self.card2.value>10: if self.aggr>((5*(1+prob))-(max(boost,boost2)/3)): if (self.aggr-((5*(1+prob))-(max(boost,boost2)/3)))>4: self._raise(min(self.credits+self.stake,minbet+(10*int(self.aggr-((3*(1+prob))-(max(boost,boost2)/3)))))) else: self.call() else: if int(self.aggr)==random.randint(1,10): self.call() else: self.fold() else: self.fold() def flop(self): checkok=True for i in player_list: if i.stake!=0: checkok=False # probability of check will depend on aggression/quality of hand if checkok==True: cardlist=[] cardlist.append(self.card1) cardlist.append(self.card2) cardlist+=c tempscore=winning(cardlist,self) if tempscore>=(1000-(100*self.aggr)): if random.randint(1,2)==1: self._raise(min(self.credits+self.stake,minbet+(20*int(tempscore/((11-self.aggr)*15))))) else: self.call() elif tempscore>(1000-(150*self.aggr)): self.call() else: self.check() if checkok==False: betok=False for i in player_list: if i.stake>self.stake: betok=True if betok==True: cardlist=[] cardlist.append(self.card1) cardlist.append(self.card2) cardlist+=c tempscore=winning(cardlist,self) if tempscore<=100: if random.randint(1,int(11-self.aggr))==1: self.call() else: self.fold() elif tempscore>=(1000-(100*self.aggr)): if random.randint(1,2)==1: self._raise(min(self.credits+self.stake,minbet+(20*int(tempscore/((11-self.aggr)*15))))) else: self.call() elif tempscore>(1000-(150*self.aggr)): self.call() elif minbet<((self.credits+self.stake)/(12-self.aggr)): if random.randint(1,5)==1: self.fold() else: self.call() else: self.fold() def turn(self): checkok=True for i in player_list: if i.stake!=0: checkok=False # probability of check will depend on aggression/quality of hand if checkok==True: tempscore=winning(findhand(self,c),self) if tempscore>=(1000-(100*self.aggr)): if random.randint(1,2)==1: self._raise(min(self.credits+self.stake,minbet+(20*int(tempscore/((11-self.aggr)*15))))) else: self.call() elif tempscore>(1000-(150*self.aggr)): self.call() else: self.check() if checkok==False: betok=False for i in player_list: if i.stake>self.stake: betok=True if betok==True: tempscore=winning(findhand(self,c),self) if tempscore<=100: if random.randint(1,int(11-self.aggr))==1: self.call() else: self.fold() elif tempscore>=(1000-(100*self.aggr)): if random.randint(1,2)==1: self._raise(min(self.credits+self.stake,minbet+(20*int(tempscore/((11-self.aggr)*15))))) else: self.call() elif tempscore>(1000-(150*self.aggr)): self.call() elif minbet<((self.credits+self.stake)/(12-self.aggr)): if random.randint(1,5)==1: self.fold() else: self.call() else: self.fold() def river(self): checkok=True for i in player_list: if i.stake!=0: checkok=False # probability of check will depend on aggression/quality of hand if checkok==True: tempscore=winning(findhand(self,c),self) if tempscore>=(1000-(100*self.aggr)): if random.randint(1,2)==1: self._raise(min(self.credits+self.stake,minbet+(20*int(tempscore/((11-self.aggr)*15))))) else: self.call() elif tempscore>(1000-(150*self.aggr)): self.call() else: self.check() if checkok==False: betok=False for i in player_list: if i.stake>self.stake: betok=True if betok==True: tempscore=winning(findhand(self,c),self) if tempscore<=100: if random.randint(1,int(11-self.aggr))==1: self.call() else: self.fold() elif tempscore>=(1000-(100*self.aggr)): if random.randint(1,2)==1: self._raise(min(self.credits+self.stake,minbet+(20*int(tempscore/((11-self.aggr)*15))))) else: self.call() elif tempscore>(1000-(150*self.aggr)): self.call() elif minbet<((self.credits+self.stake)/(12-self.aggr)): if random.randint(1,5)==1: self.fold() else: self.call() else: self.fold() # produces the 5 community cards class Community(list): def __init__(self,deck): self.deck=deck burn=0 def flop(self): burn=self.deck.deal() self.append(self.deck.deal()) burn=self.deck.deal() self.append(self.deck.deal()) burn=self.deck.deal() self.append(self.deck.deal()) print('\nFlop: {0}, {1}, {2}'.format(self[0],self[1],self[2])) def turn(self): burn=self.deck.deal() self.append(self.deck.deal()) print('\nTurn: {0}, {1}, {2}, {3}'.format(self[0],self[1],self[2],self[3])) def river(self): burn=self.deck.deal() self.append(self.deck.deal()) print('\nRiver: {0}, {1}, {2}, {3}, {4}'.format(self[0],self[1],self[2],self[3],self[4])) # assigns dealer, small blind, big blind # if only 2 in list: small blind, big blind def rolePick(): global pot for i in player_list: i.dealer=False i.small=False i.big=False if len(player_list)>2: player_list[-3].dealer=True player_list[-2].small=True player_list[-1].big=True else: player_list[0].small=True player_list[1].big=True # will return float, unless invalid input then it repeats def getAmountFromUser(message): while True: try: return float(input(message)) except ValueError: print('Please enter a valid number.') # references getAmountFromUser with normal message def getBet(): return getAmountFromUser('Total amount you want to bet: ') # only for very first bet preflop def player1Turn(): if h1.small is True: print('\nYou are the small blind.', '\n25 credits are automatically put up.') print('\nYour cards are:') print(h1.card1) print(h1.card2,'\n') h1.stake+=smallblind h1.credits-=smallblind print('Minimum bet is:',minbet) while True: bet=input('Would you like to (2) call, (3) raise, or (4) fold? ') if bet=='2': os.system('clear') h1.call() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break elif h1.big is True: print('\nYou are the big blind.', '\n50 credits are automatically put up.') print('\nYour cards are:') print(h1.card1) print(h1.card2,'\n') h1.stake+=50 h1.credits-=50 print('Minimum bet is:',minbet) if h1.stake==minbet: while True: bet=input('Would you like to (1) check, (3) raise, or (4) fold? ') if bet=='1': os.system('clear') h1.check() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break else: betok=False for i in player_list: if i.stake>h1.stake: betok=True if betok==True: while True: bet=input('Would you like to (2) call, (3) raise, or (4) fold? ') if bet=='2': os.system('clear') h1.call() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break elif h1.dealer is True: print('\nYou are the dealer.') print('\nYour cards are:') print(h1.card1) print(h1.card2,'\n') print('Minimum bet is:',minbet) while True: bet=input('Would you like to (2) call, (3) raise, or (4) fold? ') if bet=='2': os.system('clear') h1.call() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break else: print('\nYour cards are:') print(h1.card1) print(h1.card2,'\n') print('Minimum bet is:',minbet) while True: bet=input('Would you like to (2) call, (3) raise, or (4) fold? ') if bet=='2': os.system('clear') h1.call() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break # for normal betting turns, sees if checking is ok def playerTurn(): checkok=True for i in player_list: if i.stake!=0: checkok=False if checkok==True: print('\nYour cards are:') print(h1.card1) print(h1.card2,'\n') print('Minimum bet is:',minbet) while True: bet=input('Would you like to (1) check, (2) call, (3) raise, or (4) fold? ') if bet=='1': os.system('clear') h1.check() elif bet=='2': os.system('clear') h1.call() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break if checkok==False: betok=False for i in player_list: if i.stake>h1.stake: betok=True if betok==True: print('\nYour cards are:') print(h1.card1) print(h1.card2,'\n') print('Minimum bet is:',minbet) while True: bet=input('Would you like to (2) call, (3) raise, or (4) fold? ') if bet=='2': os.system('clear') h1.call() elif bet=='3': os.system('clear') h1._raise(getBet()) elif bet=='4': os.system('clear') h1.fold() else: print('Try again.') continue break # returns best 5 card hand for player as list of card objects def findhand(player,community): hand=[player.card1,player.card2]+community scoredict=collections.defaultdict(list) combo=itertools.combinations(hand,5) combos=[] for i in combo: combos.append(list(i)) for i in combos: score=(winning(i,player)) scoredict[score].append(i) # besthand is the float returned by scorehands() besthand=max(scoredict) # best score assigned to player attribute player.besthand=besthand return scoredict[besthand][0] # finds best possible hand (score) out of 5 given cards, returns scorehands() def winning(cardlist,player): valuedict=collections.defaultdict(int) suitdict=collections.defaultdict(int) for i in cardlist: valuedict[i.value]+=1 suitdict[i.suit]+=1 sortedcardlist=sorted(cardlist,key=lambda x:x.value) handmin=sortedcardlist[0] handmax=sortedcardlist[-1] #FLUSH if len(suitdict)==1: kicker=[] checksum=0 for i in cardlist: checksum+=i.value if handmin.value==10 and handmax.value==14: player.besthandstring=('{0} has a royal flush'.format(player.name)) return scorehands('royalflush',handmax,kicker) elif handmax.value==14 and checksum-handmax.value==14: player.besthandstring=('{0} has a 5-high straight flush'.format(player.name)) return scorehands('fivestraightflush',handmax,kicker) elif handmax.value==(handmin.value+4): player.besthandstring=('{0} has a {1}-high straight flush'.format(player.name,handmax.name)) return scorehands('straightflush',handmax,kicker) else: for i in sortedcardlist: if i.value==handmax.value: continue else: kicker.append(i) player.besthandstring=('{0} has a {1}-high flush'.format(player.name,handmax.name)) return scorehands('flush',handmax,kicker) #4 OF A KIND OR FULL HOUSE elif len(valuedict)==2: fourkind=[] threekind=[] pair=[] kicker=[] for i in valuedict: if valuedict[i]==4: for j in sortedcardlist: if j.value==i: fourkind.append(j) if valuedict[i]==3: for j in sortedcardlist: if j.value==i: threekind.append(j) if valuedict[i]==2: for j in sortedcardlist: if j.value==i: pair.append(j) if valuedict[i]==1: for j in sortedcardlist: if j.value==i: kicker.append(j) if fourkind!=[]: player.besthandstring=("{0} has a 4 of a kind of {1}s; kicker: {2}".format(player.name,fourkind[0].name,kicker[0].name)) return scorehands('fourkind',fourkind,kicker) if threekind!=[]: player.besthandstring=("{0} has a full house: {1}s full of {2}s".format(player.name,threekind[0].name,pair[0].name)) return scorehands('fullhouse',threekind,pair) #STRAIGHT OR HIGH CARD elif len(valuedict)==5: kicker=[] checksum=0 for i in cardlist: checksum+=i.value if handmax.value==14 and checksum==14: player.besthandstring=('{0} has a 5-high straight'.format(player.name)) return scorehands('fivestraight',handmax,kicker) if handmax.value==(handmin.value+4): player.besthandstring=('{0} has a {1}-high straight'.format(player.name,handmax.name)) return scorehands('straight',handmax,kicker) else: for i in sortedcardlist: if i.value==handmax.value: continue else: kicker.append(i) player.besthandstring=('{0} has a high card: {1}; kicker: {2}, {3}, {4}, {5}'.format(player.name,handmax.name,kicker[3].name,kicker[2].name,kicker[1].name,kicker[0].name)) return scorehands('highcard',handmax,kicker) #3 OF A KIND OR 2 PAIRS elif len(valuedict)==3: threekind=[] pair=[] kicker=[] for i in valuedict: if valuedict[i]==3: for j in sortedcardlist: if j.value==i: threekind.append(j) if valuedict[i]==2: for j in sortedcardlist: if j.value==i: pair.append(j) for i in sortedcardlist: if i in threekind: continue elif i in pair: continue else: kicker.append(i) if threekind!=[]: player.besthandstring=("{0} has a three of a kind of {1}s; kicker: {2}, {3}".format(player.name,threekind[0].name,kicker[1].name,kicker[0].name)) return scorehands('threekind',threekind,kicker) if pair!=[]: player.besthandstring=("{0} has a 2 pair: {1}s and {2}s; kicker:{3}".format(player.name,pair[0].name,pair[2].name,kicker[0].name)) return scorehands('twopairs',pair,kicker) #PAIR elif len(valuedict)==4: pair=[] kicker=[] for i in valuedict: if valuedict[i]==2: for j in sortedcardlist: if j.value==i: pair.append(j) for i in sortedcardlist: if i in pair: continue else: kicker.append(i) player.besthandstring=("{0} has a pair of {1}s; kicker: {2}, {3}, {4}".format(player.name,pair[0].name,kicker[2].name,kicker[1].name,kicker[0].name)) return scorehands('pair',pair,kicker) # returns float score of hand def scorehands(name, hand, kicker): if name == 'royalflush': return float(900) if name == 'straightflush': return float(800 + hand.value) if name == 'fivestraightflush': return float(805) if name == 'fourkind': return float(700 + hand[0].value + (kicker[0].value/100)) if name == 'fullhouse': return float(600 + hand[0].value + (kicker[0].value/100)) if name == 'flush': sortedkicker=sorted(kicker,key=lambda x:x.value) return float(500 + hand.value + (sortedkicker[3].value/100) + (sortedkicker[2].value/10000) + (sortedkicker[1].value/1000000) + (sortedkicker[0].value/100000000)) if name == 'straight': return float(400 + hand.value) if name == 'fivestraight': return float(405) if name == 'threekind': sortedkicker=sorted(kicker,key=lambda x:x.value) return float(300 + hand[0].value + (sortedkicker[1].value/100) + (sortedkicker[0].value/10000)) if name == 'twopairs': sortedhand=sorted(hand,key=lambda x:x.value) return float(200 + sortedhand[2].value + (sortedhand[0].value/100) + (kicker[0].value/10000)) if name == 'pair': sortedkicker=sorted(kicker,key=lambda x:x.value) return float(100 + hand[0].value + (sortedkicker[2].value/100) + (sortedkicker[1].value/10000) + (sortedkicker[0].value/1000000)) if name == 'highcard': sortedkicker=sorted(kicker,key=lambda x:x.value) return float(hand.value + (sortedkicker[3].value/100) + (sortedkicker[2].value/10000) + (sortedkicker[1].value/1000000)+(sortedkicker[0].value/100000000)) ##Texas hold'em os.system('clear') pot=0 smallblind=25 bigblind=50 h1=Hand(input('Enter player name: ')) # to my understanding, a list that can be rotated player_list=collections.deque([]) player_list.append(h1) playnum=input('How many other people at the table (minimum 2)? ') for i in range(int(playnum)): h=Computer('Computer '+str(i+1),(10*random.random())) player_list.append(h) print('\nCommands are: (1) Check (2) Call (3) Raise (4) Fold', '\n"Call" when you are the first bettor will bet the minimum amount (big blind).' '\nPlayers start with 1000 credits.', '\nSmall blind is {} credits.'.format(smallblind), '\nBig blind is {} credits.'.format(bigblind), '\nTo play the round, the small blind will need to at minimum match big blind.' '\nTo play the round, the big blind only needs to check,' '\nor if there is a higher bet, call.') while True: activecount=len(player_list) d=Deck() pot=0 rolePick() print('\nPot: {0}'.format(pot)) for i in player_list: print(i) # Pre Flop for i in player_list: i.card1=d.deal() i.card2=d.deal() minbet=bigblind for i in player_list: if type(i)==Computer: time.sleep(random.random()*2) i.preflop1() else: player1Turn() checkok=True for i in player_list: if i.stake!=0: checkok=False if checkok==False: # should continue looping until all players (who haven't folded) have the same amount at stake should_restart=True while should_restart: should_restart=False for i in player_list: if i.done==False: if (i.stake==minbet): continue else: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.preflop() else: playerTurn() should_restart=True print() # Everything at stake should go into pot at this point for i in player_list: pot+=i.stake i.stake=0 print('Pot: {0}'.format(pot)) for i in player_list: if i.done==False: print(i) # Flop if activecount>1: print('\n***********************') c=Community(d) c.flop() minbet=bigblind for i in player_list: if i.done==False: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.flop() else: playerTurn() checkok=True for i in player_list: if i.stake!=0: checkok=False if checkok==False: # should continue looping until all players (who haven't folded) have the same amount at stake should_restart=True while should_restart: should_restart=False for i in player_list: if i.done==False: if (i.stake==minbet): continue else: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.flop() else: playerTurn() should_restart=True print() # Everything at stake should go into pot at this point for i in player_list: pot+=i.stake i.stake=0 print('Pot: {0}'.format(pot)) for i in player_list: if i.done==False: print(i) # Turn if activecount>1: print('\n***********************') c.turn() minbet=bigblind for i in player_list: if i.done==False: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.turn() else: playerTurn() checkok=True for i in player_list: if i.stake!=0: checkok=False if checkok==False: # should continue looping until all players (who haven't folded) have the same amount at stake should_restart=True while should_restart: should_restart=False for i in player_list: if i.done==False: if (i.stake==minbet): continue else: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.turn() else: playerTurn() should_restart=True print() # Everything at stake should go into pot at this point for i in player_list: pot+=i.stake i.stake=0 print('Pot: {0}'.format(pot)) for i in player_list: if i.done==False: print(i) # River if activecount>1: print('\n***********************') c.river() minbet=bigblind for i in player_list: if i.done==False: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.river() else: playerTurn() checkok=True for i in player_list: if i.stake!=0: checkok=False if checkok==False: # should continue looping until all players (who haven't folded) have the same amount at stake should_restart=True while should_restart: should_restart=False for i in player_list: if i.done==False: if (i.stake==max(minbet,0)): continue else: if activecount>1: if i.credits>0: if type(i)==Computer: time.sleep(random.random()*2) i.river() else: playerTurn() should_restart=True print() # Everything at stake should go into pot at this point for i in player_list: pot+=i.stake i.stake=0 if activecount>1: print('Pot: {0}'.format(pot)) for i in player_list: if i.done==False: x=findhand(i,c) # runs winning() again with returned value from findhand() (the best hand), to set player's besthandstring to the right hand winning(x,i) for i in player_list: if i.done==False: if activecount>1: print(i.besthandstring) # determines winner/ties winner=0 winnerlist=[] for i in player_list: if i.done==False: if i.besthand>winner: winner=i.besthand for i in player_list: if i.done==False: if i.besthand==winner: winnerlist.append(i) # prints winners/ties if len(winnerlist)==1: print('{0} is the winner'.format(winnerlist[0].name)) else: print('There has been a tie between:') for i in winnerlist: print(i.name) # distributes winnings if len(winnerlist)==1: winnerlist[0].credits+=pot pot=0 else: pot/=len(winnerlist) for i in winnerlist: i.credits+=pot pot=0 else: for i in player_list: if i.done==False: print('{0} is the winner'.format(i.name)) i.credits+=pot break # resets besthand and besthandstring for next round for i in player_list: i.besthand=0 i.besthandstring='' # rotates positions, removes any players with 0 or negative credits, resets their fold attribute player_list.rotate() newplayer_list=collections.deque([]) for i in player_list: i.done=False if i.credits>0: newplayer_list.append(i) player_list=newplayer_list # determines final game winner if len(player_list)==1: print('{0} is the final winner!'.format(player_list[0].name)) exit() print('\n***** New Round *****')
b888ea7933cce319b02016c7aec2c91e1ba82ded
[ "Markdown", "Python" ]
2
Markdown
colinjhong/poker
12a94b9ee8f73804b074646de629054586f5f75a
9c3b74fb1b65fd35263b7ade41942962ab03157c
refs/heads/master
<repo_name>guyanfeng/raptor<file_sep>/README.md # raptor 一个简单的多线程下载工具,有断点续传功能 <file_sep>/Raptor/HttpDownloader.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Net; using System.IO; using JaguarLib.Threading; namespace Raptor { public class WebDownloader { public long DownloadBytes { get; set; } public DateTime StartTime { get; set; } public int Threads { get; set; } public string SaveDir { get; set; } public string FilePath { get; set; } WebRequest _request; public long ContengLength { get; set; } WebDownloaderThread[] _jobs; FileStream _fstream; readonly object _lockWrite = new object(); readonly object _lockWriteConfig = new object(); ThreadLockCount _threadLock; bool _hasError; CookieContainer _cookies; List<DownloadResultConfig> _resumeConfigs; string _resumeConfigPath; public long ResumeBytes { get; set; } /// <summary> /// 是断点续传 /// </summary> public bool IsResume { get; set; } public event EventHandler<DownloadCompletedArgs> Completed; public event EventHandler<DownloadProgressArgs> Progress; public event EventHandler<DownloadThreadStatusChangeArgs> ThreadStatusChanged; public WebDownloader(WebRequest request) { _request = request; _request.Timeout = 6000; Threads = 1; } string GetFileName(WebResponse rep) { var str = rep.Headers["Content-Disposition"]; if (string.IsNullOrEmpty(str)) { return Path.GetFileName(rep.ResponseUri.ToString()); } return new System.Net.Mime.ContentDisposition(str).FileName; } public void StartDownload() { //#if DEBUG // Threads = 1; //#endif if (_request is HttpWebRequest) { _cookies = new CookieContainer(); ((HttpWebRequest)_request).CookieContainer = _cookies; } try { var rep = _request.GetResponse(); FilePath = Path.Combine(SaveDir, GetFileName(rep)); ContengLength = rep.ContentLength; rep.Close(); } catch (Exception ex) { OnCompleted(true, ex.Message); return; } //断点续传 IsResume = false; _resumeConfigPath = Path.ChangeExtension(FilePath, "cnt"); if (File.Exists(_resumeConfigPath)) { try { _resumeConfigs = ReadResumeConfigs(); //续传的线程必须和断点前一致 Threads = _resumeConfigs.Count; ResumeBytes = GetResumeTotalLength(); IsResume = true; } catch (Exception ex) { Console.WriteLine("断点续传配置文件格式不正确:{0}", ex.Message); } } else { _resumeConfigs = new List<DownloadResultConfig>(); } var tmpFile = Path.ChangeExtension(FilePath, "tmp"); try { _fstream = new FileStream(tmpFile, FileMode.OpenOrCreate); } catch (Exception ex) { OnCompleted(true, ex.Message); return; } _jobs = new WebDownloaderThread[Threads]; _threadLock = new ThreadLockCount(Threads); var length = ContengLength; var blockSize = length / Threads; for (int i = 0; i < Threads; i++) { _jobs[i] = new WebDownloaderThread(CloneRequest(_request)) { ThreadIndex = i }; _jobs[i].Completed += HttpDownloader_Completed; _jobs[i].Progress += HttpDownloader_Progress; _jobs[i].StatusChanged += WebDownloader_StatusChanged; if (Threads > 1 || IsResume) { _jobs[i].UseRange = true; } if (IsResume) { if (i == Threads-1) { if (_resumeConfigs[i].To >= ContengLength-1) { //下载完毕 _jobs[i].OnCompleted(false, ""); continue; } else { _jobs[i].RangeStart = _resumeConfigs[i].To + 1; _jobs[i].RangeEnd = ContengLength - 1; } } else { if (_resumeConfigs[i].To+1 >= _resumeConfigs[i+1].From) { //下载完毕 _jobs[i].OnCompleted(false, ""); continue; } else { _jobs[i].RangeStart = _resumeConfigs[i].To + 1; _jobs[i].RangeEnd = _resumeConfigs[i + 1].From - 1; } } } else { _resumeConfigs.Add(new DownloadResultConfig { From = i * blockSize, To = i * blockSize-1, }); _jobs[i].RangeStart = i * blockSize; _jobs[i].RangeEnd = _jobs[i].RangeStart + blockSize - 1; if (i == Threads - 1) { _jobs[i].RangeEnd = ContengLength - 1; } } _jobs[i].Start(); } } List<DownloadResultConfig> ReadResumeConfigs() { using (var stream = new StreamReader(_resumeConfigPath)) { var line = ""; var configs = new List<DownloadResultConfig>(); while ((line = stream.ReadLine()) != null) { var segs = line.Split(','); var from = Convert.ToInt32(segs[0]); var to = Convert.ToInt32(segs[1]); configs.Add(new DownloadResultConfig { From = from, To = to }); } return configs; } } void WriteResumeConfigs() { lock (_lockWriteConfig) { if (_resumeConfigs != null) { using (var stream = new StreamWriter(_resumeConfigPath)) { foreach (var config in _resumeConfigs) { stream.WriteLine("{0},{1}", config.From, config.To); } } } } } long GetResumeTotalLength() { var length = 0L; if (_resumeConfigs != null) { foreach (var config in _resumeConfigs) { length += (config.To - config.From + 1); } } return length; } private void WebDownloader_StatusChanged(object sender, EventArgs e) { if (ThreadStatusChanged != null) { var job = (WebDownloaderThread)sender; ThreadStatusChanged(this, new DownloadThreadStatusChangeArgs { ThreadIndex = job.ThreadIndex, NewStatus = job.Status }); } } void EndDownload() { if (_fstream != null) _fstream.Close(); WriteResumeConfigs(); if (!_hasError) { if (File.Exists(_resumeConfigPath)) { File.Delete(_resumeConfigPath); } while (File.Exists(FilePath)) { FilePath = Path.Combine(Path.GetDirectoryName(FilePath), Path.GetFileNameWithoutExtension(FilePath) + "(1)" + Path.GetExtension(FilePath)); } File.Move(_fstream.Name, FilePath); } OnCompleted(false, null); } private void HttpDownloader_Progress(object sender, DownloadProgressArgs e) { var job = (WebDownloaderThread)sender; lock (_lockWrite) { _fstream.Seek(job.Position, SeekOrigin.Begin); _fstream.Write(e.Buffer, e.Offset, e.Count); DownloadBytes += e.Count; } _resumeConfigs[job.ThreadIndex].To += e.Count; Progress?.Invoke(this, new DownloadProgressArgs() { DownloadBytes = DownloadBytes, TotalBytes = ContengLength }); } private void HttpDownloader_Completed(object sender, DownloadCompletedArgs e) { _hasError = e.IsError; WriteResumeConfigs(); if (_threadLock.Raise()) { EndDownload(); } } WebRequest CloneRequest(WebRequest request) { var req = WebRequest.Create(request.RequestUri); req.Method = request.Method; req.Timeout = request.Timeout; if (req is HttpWebRequest) { ((HttpWebRequest)req).KeepAlive = ((HttpWebRequest)request).KeepAlive; ((HttpWebRequest)req).CookieContainer = ((HttpWebRequest)request).CookieContainer; ((HttpWebRequest)req).UserAgent = ((HttpWebRequest)request).UserAgent; ((HttpWebRequest)req).Accept = ((HttpWebRequest)request).Accept; } return req; } public void Cancel() { if (_jobs != null) { foreach (var job in _jobs) { job.Cancel(); } } } public void OnCompleted(bool isError, string msg) { Completed?.Invoke(this, new DownloadCompletedArgs { IsError = isError, Message = msg }); } } public class WebDownloaderThread { public event EventHandler<DownloadCompletedArgs> Completed; public event EventHandler<DownloadProgressArgs> Progress; public event EventHandler StatusChanged; public WebRequest Request { get; set; } int _bufferSize = 8192; byte[] _buffer; WebHeaderCollection _responseHeaders; public long DownloadBytes { get; set; } public long Position { get; set; } public long TotalBytes { get; set; } public long RangeStart { get; set; } public long RangeEnd { get; set; } public bool UseRange { get; set; } public int ThreadIndex { get; set; } public string Status { get; set; } public DateTime StartTime { get; set; } public WebHeaderCollection ResponseHeaders { get { return _responseHeaders; } } public DateTime SlowTime { get; set; } public WebDownloaderThread(WebRequest request) { Request = request; TotalBytes = request.ContentLength; } public void Start() { Status = "Running"; if (UseRange) { var req = (HttpWebRequest)Request; req.AddRange(RangeStart, RangeEnd); Position = RangeStart; } _buffer = new byte[_bufferSize]; StartTime = DateTime.Now; DownloadBytes = 0; StatusChanged?.Invoke(this, EventArgs.Empty); try { Request.BeginGetResponse((ar) => { WebResponse rep = null; try { rep = Request.EndGetResponse(ar); _responseHeaders = rep.Headers; var stream = rep.GetResponseStream(); while (true) { var readed = stream.Read(_buffer, 0, _buffer.Length); if (readed > 0) { OnProgress(_buffer, 0, readed); } else { OnCompleted(false, null); return; } } } catch (Exception ex) { OnCompleted(true, ex.Message); } finally { if (rep != null) rep.Close(); } }, null); } catch (Exception ex) { OnCompleted(true, ex.Message); } } public void Cancel() { Request.Abort(); } public void OnCompleted(bool isError, string msg) { if (isError) { Status = "Error"; } else { Status = "Completed"; } StatusChanged?.Invoke(this, EventArgs.Empty); Completed?.Invoke(this, new DownloadCompletedArgs { IsError = isError, Message = msg }); } public void OnProgress(byte[] buffer, int offset, int length) { DownloadBytes += length; Progress?.Invoke(this, new DownloadProgressArgs { DownloadBytes = DownloadBytes, TotalBytes = TotalBytes, Buffer = buffer, Offset = offset, Count = length }); Position += length; } } public class DownloadResultConfig { public long From { get; set; } public long To { get; set; } } public class DownloadCompletedArgs : EventArgs { public bool IsCancel { get; set; } public bool IsError { get; set; } public int HttpStatus { get; set; } public string Message { get; set; } } public class DownloadProgressArgs : EventArgs { public long DownloadBytes { get; set; } public long TotalBytes { get; set; } public byte[] Buffer { get; set; } public int Offset { get; set; } public int Count { get; set; } } public class DownloadThreadStatusChangeArgs : EventArgs { public int ThreadIndex { get; set; } public string OldStatus { get; set; } public string NewStatus { get; set; } } } <file_sep>/Raptor/Form1.cs using JaguarLib.Common; using JaguarLib.Net; using JaguarLib.Threading; using JaguarLib.Win32; using JaguarLib.Windows.Forms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace Raptor { public partial class Form1 : Form { int max_rows = 100; WebDownloader _downloader; Stopwatch watch; int _open_type = 0; Config _cfg; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { _cfg = new Config(Path.Combine(Application.StartupPath, "config.xml")); } #region message void AddMessage(string msg, Color color) { if (grid.Rows.Count >= max_rows) grid.Rows.RemoveAt(0); var row = grid.Rows.Add(DateTime.Now.ToString(), msg); grid.Rows[row].Cells[1].Style.ForeColor = color; if (grid.Rows.Count > 10) grid.FirstDisplayedScrollingRowIndex = grid.Rows.Count - 10; } void AddLogs(string msg) { AddMessage(msg, Color.Black); } void AddInfo(string msg) { AddMessage(msg, Color.Green); } void AddError(string msg) { AddMessage(msg, Color.Red); } #endregion #region HttpClientEvent void dl_Downloading(object sender, DownloadProgressArgs e) { Invoke(new Action(() => { var downloader = sender as WebDownloader; status2.Text = string.Format("{0} / {1}", e.DownloadBytes+downloader.ResumeBytes, e.TotalBytes); progress.Value = (int)((e.DownloadBytes + downloader.ResumeBytes) * 100D / e.TotalBytes); })); } void dl_DownloadCompleted(object sender, DownloadCompletedArgs e) { this.Invoke(new Action(() => { if (e.IsError) { AddError(e.Message); } EndDownload(); })); } #endregion #region Download private void btnAdd_Click(object sender, EventArgs e) { if (btnAdd.Text == "开始下载") { //if (!is_valid(txtUrl.Text)) //{ // return; //} if (string.IsNullOrEmpty(txtPath.Text)) { MsgDialog.InfoBox("请选择保存地址"); return; } btnAdd.Text = "取消"; StartDownload(new Uri(txtUrl.Text)); } else { _downloader.Cancel(); AddError("用户取消下载"); EndDownload(); } } void StartDownload(Uri url) { var request = (HttpWebRequest) WebRequest.Create(url); request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36"; request.Proxy = null; _downloader = new WebDownloader(request); _downloader.SaveDir = txtPath.Text; _downloader.Completed += dl_DownloadCompleted; _downloader.Progress += dl_Downloading; _downloader.ThreadStatusChanged += _downloader_ThreadStatusChanged; _downloader.Threads = (int)numThreads.Value; watch = new Stopwatch(); watch.Start(); tmr.Start(); status2.Visible = true; progress.Visible = true; last_receive = 0; AddInfo("开始下载文件 " + url); status.Text = "正在下载..."; _downloader.StartDownload(); } private void _downloader_ThreadStatusChanged(object sender, DownloadThreadStatusChangeArgs e) { Invoke(new Action(() => { var msg = string.Format("线程 {0} : {1}. {2}", e.ThreadIndex+1, e.NewStatus, e.Message); AddInfo(msg); })); } void EndDownload() { EndDownload(null); } void EndDownload(string msg) { tmr.Stop(); status2.Visible = false; progress.Visible = false; btnAdd.Text = "开始下载"; status.Text = "下载完成"; progress.Visible = false; AddInfo(string.Format("下载结束.{0},文件:{1},用时:{2} 秒,平均速度:{3:F2}", msg, _downloader.FilePath, watch.Elapsed.Seconds, _downloader.DownloadBytes / 1024 / (watch.Elapsed.Seconds+0.001))); } #endregion #region Speed long last_receive = 0; private void tmr_Tick(object sender, EventArgs e) { var len = _downloader.DownloadBytes; var speed = 0d; if (last_receive != 0) { speed = (len - last_receive) / 1024d; } last_receive = len; status.Text = string.Format("正在下载 速度: {0:N2} kb/秒", speed); if (_downloader.ContengLength > 0) { status.Text += "; 预计还剩:" + get_remain_time(_downloader.ContengLength - _downloader.DownloadBytes, speed); } } private string get_remain_time(long remain, double speed) { if (remain < 1 || speed == 0) return "0 秒"; var seconds = (int)(remain / 1024 / speed); if (seconds < 60) return seconds + " 秒"; if (seconds < 3600) return (seconds / 60) + " 分 " + (seconds % 60) + " 秒"; var h = seconds / 3600; var m = ((seconds - h * 3600) / 60); var s = seconds % 3600; return h + " 小时 " + m + " 分 " + s + " 秒"; } #endregion private void btnChooseSave_Click(object sender, EventArgs e) { if (dlgFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtPath.Text = dlgFolder.SelectedPath; _cfg["SavePath"] = txtPath.Text; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { _cfg.Save(); } } }
25b0e888157be1603fcc0e219032a9b6f07f0593
[ "Markdown", "C#" ]
3
Markdown
guyanfeng/raptor
90872324bd9de4b37a9d4b85af7ef069a956c105
51f0e5621716a5c233b190dc2dfcbaa6d19d32c9
refs/heads/master
<repo_name>melamber/KnockToWindow<file_sep>/KnockToWindow_v1.5.js /** * KnockToWindow v 1.5 * Date: 2015-03-24 */ (function($) { $.fn.KnockToWindow = function(config) { var self = this, /** * Configuration of the plugin * @type {Object} */ options = $.extend({ position: 'bottom-right', width: '200px', height: 'auto', direction: 'bottom-to-top', duration: 10000, animateOpen: '', animateClose: '', content: '', closeElement: "<button class='KTWClose'>Close</button>", actionOpen: null, actionClose: null }, config), ucFirst = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }, callback = function(func) { if(typeof func === "function") { func(); } }; //Adding classes for the main block on the basis of the configuration self.addClass(function() { var lcString = options.position.toLowerCase(), split = lcString.split('-'), position = (lcString === 'middle-center') ? 'KTW-MC' :''; for(var cur in split) { position += " KTW-Position-" + ucFirst(split[cur]); } return position + " KTW-Direction-" + ucFirst(options.direction); }); /** * Unique ID of the block notice * @type {String} */ var id = self.data('counter') || 'KTW-1'; //calculate the number of the block notice self.data('counter', 'KTW-' + (parseInt(id.replace("KTW-", "")) + 1)); /** * The new block notice with attached event handlers * @type {object|jQuery} */ var notice = $("<div/>") .css({ animation: options.animateOpen, //TODO retain? width: options.width, height: options.height }) .addClass('KTWNotice KTW-Animation-Open') .attr('id', id) .append(options.content) .append(options.closeElement) .appendTo(self) .on('animationstart.KTW', callback(options.actionOpen)) .on('click.KTW', function() { $(this).css('animation', 'none') //TODO retain? .addClass('KTW-Animate-None'); }) .on('click.KTW', '.KTWClose', function() { $(this).parent().remove(); }); //Closing and removing the block notice after specified time if(options.duration != 0) { setTimeout(function() { notice.addClass('KTW-Animation-Close'); if(!notice.hasClass('KTW-Animate-None')) { //TODO retain? notice.css('animation', options.animateClose); } notice.on('animationend.KTW', function() { callback(options.actionClose); this.remove(); }); }, options.duration); } return this; }; })(jQuery);<file_sep>/README.md # KnockToWindow ####_The plugin provides output to display a notification to the user in a convenient location._ Depends: * JQuery version >= 2.1.1 *** ## Overview All blocks of notifications are placed in the main block with ID 'KnockToWindow'", and have class 'KTWNotice'. Elements for closing notification have class 'KTWClose'. Notifications are free to close after a specified time. When you click on the notification, timer of closing is disabled. When the notification is opening or closing, it possible to perform the specified functions. Notification styles are defined in a separate file KTWStyle.css. You can also specify different behavior notifications in plugin configuration. *** ## Instruction 1. **Insert in a page main block(or create an element using js). Block must have ID "KnockToWindow" for use default CSS.** ``` Example: <div id="KnockToWindow"></div> ``` 2. **Connect CSS file. There are many variants. That's the easiest variant:** ``` Example: $('head').append('<link href="KTWStyle.css" type="text/css" rel="stylesheet" />'); ``` 3. **Connect the plugin to that element and configure(default configuration):** _Example with default configuration:_ ``` $("#KnockToWindow").KnockToWindow(); ``` _Example of configuration:_ ``` $("#KnockToWindow").KnockToWindow({ position: 'middle-center', width: '200px', height: 'auto', direction: 'top-to-bottom', content: 'Something...' }); ``` *** ### **Options of configuration** _Default options:_ ``` position: 'bottom-right', width: '200px', height: 'auto', direction: 'bottom-to-top', duration: 10000, animateOpen: '', (see .KTW-Animation-Open in css) animateClose: '', (see .KTW-Animation-Close in css) content: '', closeElement: "<button class='KTWClose'>Close</button>", actionOpen: null, actionClose: null ``` * **position** _[enum]_ - specifies the location on the page. ``` Choose one from possible options: ['top-left', 'top-center', 'top-right', 'middle-left', 'middle-center', 'middle-right', 'bottom-left', 'bottom-center', 'bottom-right']; ``` * **width(height)** _[string]_ - width(height) of the block notice(...px, ...%, auto). ``` Example: width: '200px', height: 'auto', ``` * **direction** _[enum]_ - direction of the adding block notices. ``` Choose one from possible options: ['left-to-right', 'right-to-left', 'top-to-bottom', 'bottom-to-top']; ``` * **duration** _[number]_ - duration of the block notice(5000 = 5sec, 0 = infinite). ``` Example: duration: 8000, ``` * **animateOpen(animateClose)** _[string]_ - params of animation. ``` Example: animateOpen:'show 1s', ``` There are a set of predefined @keyframes: * for opening: _fade-in, show, slide-open-ltr, slide-open-rtl, slide-open-ttb, slide-open-btt;_ * for closing: _fade-out, hide, slide-close-ltr, slide-close-rtl, slide-close-ttb, slide-close-btt;_ Format: [animation](http://www.w3schools.com/cssref/css3_pr_animation.asp). * **actionOpen(actionClose)** _[function]_ - performed action, when block notice opening(closing). ``` Example: funcName, function(){...}; ``` * **content** _[string, object|HTMLElement]_ - content of the block notice. ``` Example: <p>Hello</p>, $('<div/>'), ...; ``` * **closeElement** _[string, object|HTMLElement]_ - HTML Element for closing the block notice. Element must have a class 'KTWClose'. ``` Example: "<a href='#' class='KTWClose'>Close</a>"; ``` ### **Advanced configure** CSS styles are defined by assigning classes to elements. You can change exists classes or create new classes with necessary prefix and assign the name of the class to the desired property. _Example:_ ``` css: .KTW-Position-Custom{ top: 20%; right: 15%; } config: $("#KnockToWindow").KnockToWindow({ position: 'custom' }); ``` * \#KnockToWindow (if this main block or other selector), * .KTWNotice (block notice), * .KTWClose (element of the closing block notice) *** ## Additional information * The plugin uses latest features of CSS3, therefore it correct work in latest versions browsers. * All events of the plugin belong to namespace 'KTW'. * Link on the demonstration page: [KnockToWindow](http://chtoto.besaba.com).
09704dca891dc8673a2a6f381faf10bffffb1a4b
[ "JavaScript", "Markdown" ]
2
JavaScript
melamber/KnockToWindow
c827d508b55dce332eb28fb198f6a6ce958dfe67
cbcb7a4dff872ffb595387c71de2189e36b82e3f
refs/heads/master
<file_sep>####################### # Project 2 Test Code # ####################### # Note: # This is not the final version of test code. # I will change the name of the tthly newtest data, so that you CANNOT # get access to it when you are predicting. # But it shouldn't affect your code. ####################################################################### # prepare data # This chunk of code helps to create train.csv, test.csv, # and the newtest files in the working directory. # You need to put the original train.csv.zip file in the working dir. # Or if you have the newtest files you can comment it out, and change # the newtest file names. newtest.name = 'xxx' source('prepare_data.r') ####################################################################### ####################################################################### # Test code begins train = read.csv("train.csv") test = read.csv("test.csv") source("mymain.R") wae = matrix(0, 20, 4) # weighted mean absolute error (WMAE) and weight for(t in 1:20){ # predict the weekly sales for tth t, # e.g., tth 1 --> 2011-03, and tth 20 --> 2012-10. # Your prediction function should modify three columns of 'test', # and update 'train' predict() # newtest: sales data for this tth; taking the # same format as "train". tmp.filename = paste(newtest.name, t, '.csv', sep=''); newtest = read.csv(tmp.filename) # Evaluate your prediction accuracy for this tth temp.mat = merge(newtest, test, by.x = c('Date', 'Store', 'Dept'), by.y = c('Date', 'Store', 'Dept'), all.x = TRUE ) for (met in 1:3){ wae[t, met] = sum(abs(temp.mat[, 'Weekly_Sales'] - temp.mat[, paste('Weekly_Pred', met, sep = '')]) * ifelse(temp.mat[, 'IsHoliday.x'], 5, 1) ) } wae[t, 4] = sum(ifelse(temp.mat[, 'IsHoliday.x'], 5, 1)) } write.table(wae, 'Error.csv', sep = ',', row.names = FALSE, col.names = FALSE) <file_sep>library(glmnet) # LASSO library(Matrix) # LASSO library(xgboost)# Xgboost train = read.csv('train.csv') test = read.csv('test.csv') # ============== data clean train ============== train <- train[train$GrLivArea<=4000,] # remove 5 unusual observations train$MasVnrType[is.na(train$MasVnrType)]<-"None" nalevel<-c("Alley", "BsmtQual","BsmtCond" ,"BsmtExposure","BsmtFinType1", "BsmtFinType2","FireplaceQu", "GarageType","GarageFinish" ,"GarageQual", "GarageCond" ,"PoolQC" ,"Fence" ,"MiscFeature") nalevelsf<-c("PoolArea" , "GarageArea", "TotalBsmtSF", "BsmtFinSF1" ,"MasVnrArea" ) for(x in nalevel) { levels(train[[x]])<-c(levels(train[[x]]),"None") train[[x]][is.na(train[[x]])]<-"None" } for(x in nalevelsf) { train[[x]][is.na(train[[x]])]<-0 } for(i in 1:ncol(train)) { if(is.factor(train[1,i])==TRUE && sum(is.na(train[,i]))!=0) { train[,i][is.na(train[,i])]<-names(which.max(table(train[i]))) } if(is.factor(train[1,i])!=TRUE && sum(is.na(train[,i]))!=0) { train[,i][is.na(train[,i])]<-mean(train[!is.na(train[,i]),i]) } } # ============== train log transform ============== train$SalePrice<-log(train$SalePrice+1) # ================ data clean test ================ test$MasVnrType[is.na(test$MasVnrType)]<-"None" for(x in nalevel) { levels(test[[x]])<-c(levels(test[[x]]),"None") test[[x]][is.na(test[[x]])]<-"None" } for(x in nalevelsf) { test[[x]][is.na(test[[x]])]<-0 } for(i in 1:ncol(test)) { if(is.factor(test[1,i])==TRUE && sum(is.na(test[,i]))!=0) { test[,i][is.na(test[,i])]<-names(which.max(table(test[i]))) } if(is.factor(test[1,i])!=TRUE && sum(is.na(test[,i]))!=0) { test[,i][is.na(test[,i])]<-mean(test[!is.na(test[,i]),i]) } } #================= selected lm ======================= usefulvar = c("MSZoning", "LotArea","OverallQual", "OverallCond", "YearBuilt","BsmtFinSF1", "TotalBsmtSF","GrLivArea","BsmtFullBath","KitchenAbvGr","KitchenQual", "YearRemodAdd","Fireplaces","GarageCars","ScreenPorch","SaleCondition") # BIC lmmodel<-lm(SalePrice~.,data=train[c(usefulvar,"SalePrice")]) y_lm<-predict(lmmodel,newdata = test) # ================== Bagging LASSO ==================== n<- floor(3*nrow(train)/5) r<- 200 y_round_LASSO<-rep(0,nrow(test)) for (i in 1:r) { round_train<-train[sample(nrow(train))[1:n],] lassoX = data.matrix(round_train[,-c(1,81)]) lassoY = data.matrix(round_train[,81]) # select lambda lam.seq = exp(seq(-4, 2, length=200)) lasso_cv_out = cv.glmnet(lassoX, lassoY, alpha = 1, lambda = lam.seq) mylasso = glmnet(lassoX,lassoY, alpha = 1) best_lambda = lasso_cv_out$lambda.1se #refit mylasso.coef = predict(mylasso, s = best_lambda, type = "coefficients") varLASSO = rownames(mylasso.coef)[which(mylasso.coef != 0)] newlassoX = lassoX[, colnames(lassoX) %in% varLASSO] lm_lasso = lm(lassoY ~ newlassoX) yLASSOre = coef(lm_lasso)[1] + data.matrix(test[,colnames(test) %in% varLASSO]) %*% coef(lm_lasso)[-1] y_round_LASSO<-y_round_LASSO+yLASSOre } y_BaLasso<-y_round_LASSO/r # ================== Xgboost ==================== temp_train<-train temp_test<-test y_train=train$SalePrice train$Id=NULL train$SalePrice=NULL test$Id=NULL #Row binding train & test set for feature engineering train_test = rbind(train, test) ntrain=nrow(train) features=names(train) #convert character into integer for(f in features){ if(class(train_test[[f]])=="character"){ levels=sort(unique(train_test[[f]])) train_test[[f]]=as.integer(factor(train_test[[f]],levels = levels)) } } train_x=train_test[1:ntrain,] test_x=train_test[(ntrain+1):nrow(train_test),] train_x[] <- lapply(train_x, as.numeric) test_x[]<-lapply(test_x, as.numeric) dtrain=xgb.DMatrix(as.matrix(train_x),label= y_train) dtest=xgb.DMatrix(as.matrix(test_x)) #xgboost parameters xgb_params = list( seed = 0, colsample_bytree = 0.5, subsample = 0.8, eta = 0.02, objective = 'reg:linear', max_depth = 12, alpha = 1, gamma = 2, min_child_weight = 1, base_score = 7.76 ) xg_eval_mae <- function (yhat, dtrain) { y = getinfo(dtrain, "label") err= mae(exp(y),exp(yhat) ) return (list(metric = "error", value = err)) } best_n_rounds=1500 #train data gb_dt=xgb.train(xgb_params,dtrain,nrounds = as.integer(best_n_rounds)) y_xg<-predict(gb_dt,dtest) # ================== Write ==================== train<-temp_train test<-temp_test temp = read.csv('test.csv') result_xg = exp(y_xg)-1 result_BaLasso = exp(y_BaLasso)-1 result_lm = exp(y_lm)-1 filexg = data.frame( Id = temp$Id, SalePrice = result_xg ) fileBaLasso = data.frame( Id = temp$Id, SalePrice = result_BaLasso) filelm = data.frame( Id = temp$Id, SalePrice = result_lm) # write.csv(filexg, "result_xgboost.csv", row.names = FALSE) # write.csv(fileBaLasso, "karesult_BaLasso.csv", row.names = FALSE) # write.csv(filelm, "karesult_lm.csv", row.names = FALSE) write.table(filexg,"mysubmission3.txt",row.names = FALSE, sep = ',') write.table(fileBaLasso,"mysubmission2.txt",row.names = FALSE,sep = ',') write.table(filelm,"mysubmission1.txt",row.names = FALSE,sep = ',') <file_sep>library(tm) #library(FeatureHashing) library(Matrix) library(SnowballC) #library(xgboost) #library(slam) #library(bigmemory) library(glmnet) library(wordcloud) library(ggplot2) setwd('C:/Users/mengd/Desktop/Stat/STAT542/IBDM') train <- read.delim("labeledTrainData.tsv", quote = "", as.is = T,encoding="UTF-8") test<-read.delim("TestData.tsv", quote = "", as.is = T,encoding="UTF-8") test<-test[sample(nrow(test))[1:50],] ini_tfidf<-function(x){ temp<-x$review #temp<-tolower(gsub("[^[:alnum:] ]", " ", temp)) corpus <- Corpus(VectorSource(temp)) corpus <- tm_map(corpus, removePunctuation) corpus <- tm_map(corpus, tolower) corpus <- tm_map(corpus, removeWords, stopwords('english')) corpus <- tm_map(corpus, stemDocument) #corpus <- tm_map(corpus, removeWords, stopwords("english")) #corpus <- tm_map(corpus, stripWhitespace) #corpus <- tm_map(corpus, stemDocument, language="english") dtm<- DocumentTermMatrix(corpus, control = list(stopwords = TRUE, removeNumbers = TRUE, removePunctuation = TRUE ,weighting = weightTfIdf )) #dtm = dtm[, term_tfidf >= 0.1] #dtm = dtm[row_sums(dtm) > 0,] dtm <- removeSparseTerms(dtm, 0.999) return(dtm) } get_dict<-function(x){ return(colnames(x)) } trans_tfidf<-function(x,y){ temp <- x$review #temp<-tolower(gsub("[^[:alnum:] ]", " ", temp)) corpus <- Corpus(VectorSource(temp)) corpus <- tm_map(corpus, tolower) corpus <- tm_map(corpus, removePunctuation) #corpus <- tm_map(corpus, PlainTextDocument) corpus <- tm_map(corpus, removeWords, stopwords('english')) corpus <- tm_map(corpus, stemDocument) #corpus <-Corpus(VectorSource(corpus)) dtm<- DocumentTermMatrix(corpus, control = list(dictionary=y,stopwords = TRUE, removeNumbers = TRUE, removePunctuation = TRUE )) #corpus <- tm_map(corpus, removeWords, stopwords("english")) #corpus <- tm_map(corpus, stripWhitespace) #corpus <- tm_map(corpus, stemDocument, language="english") #dtm<- DocumentTermMatrix(corpus, # control = list(dictionary=y,stemming = TRUE, stopwords = TRUE, minWordLength = 3, # weighting = weightTfIdf removeNumbers = TRUE, removePunctuation = TRUE)) return(dtm) } traintm<-ini_tfidf(train) mydictionary<-get_dict(traintm) testtm<-trans_tfidf(test,mydictionary) dtrain<-as.data.frame(as.matrix(traintm)) dtest<-as.data.frame(as.matrix(testtm)) label=as.factor(train$sentiment) logis.fit<-glmnet(as.matrix(dtrain),train$sentiment,family = "binomial",alpha = 0,lambda = 1) coe<- predict(logis.fit, type="coefficients") words<-as.numeric(coe) names(words)<-rownames(coe) words<-words[-1] ######################################################################### for(i in 1:50){ temp<-dtest[i,] fre<-rbind(words,temp) fre<-rbind(fre,rep(0,ncol(temp))) fre<-fre[,fre[2,]!=0] for(j in 1:ncol(fre)){ fre[3,j]=fre[1,j]*fre[2,j] } pf<-fre[3,fre[3,]>0] pname<-names(pf) a<-as.matrix(pf[1,]) dp = data.frame(word=pname, freq=t(a)) # nf<-fre[3,fre[3,]<0] nnames<-names(nf) a<-as.matrix(nf[1,]) dn<-data.frame(word=nnames, freq=t(-a)) picname_p<-paste0("p_wordcloud_",i,".png") picname_n<-paste0("n_wordcloud_",i,".png") png( picname_p, width=1280,height=800) wordcloud(dp$word, dp$X3, max.words=50, scale=c(4,.2), random.order=FALSE, rot.per=.25, colors=brewer.pal(8,"Dark2")) dev.off() png( picname_n, width=1280,height=800) wordcloud(dn$word, dn$X3, max.words=50, scale=c(4,.2), random.order=FALSE, rot.per=.25, colors=brewer.pal(8,"Dark2")) dev.off() } #################################################### prob<-predict(logis.fit,as.matrix(dtest),type="response") prob<-prob-0.5 prob<-prob*2 d<-data.frame(Review=c(1:50),Prob=prob) names(d)[2]<-"Degree" ggplot(d, aes(x = Review, y = Degree,fill = Degree)) + geom_bar(stat = "identity")+ylim(-1,1) <file_sep>library(zoo) # for preproccessing (yearmon) library(randomForest) # for randomForest library(xgboost) # for xgboost # ====================================== # Common preprocessing # ====================================== getid = function(x){ # get test id id = x$id return(id) } getindex = function(x){ # get index of recoveries recind = which(x$recoveries!=0) return(recind) } keepvar<-function(x){ #function to keep useful variables keep<-c( "loan_amnt" ,"funded_amnt" ,"funded_amnt_inv" ,"term" ,"int_rate" ,"installment" ,"grade" ,"emp_length" ,"home_ownership" ,"annual_inc" ,"verification_status" ,"issue_d" ,"label" ,"purpose" ,"addr_state" ,"dti" ,"delinq_2yrs" ,"earliest_cr_line" ,"inq_last_6mths" ,"mths_since_last_delinq" ,"mths_since_last_record" ,"open_acc" ,"pub_rec" ,"revol_bal" ,"revol_util" ,"total_acc" ,"initial_list_status" ,"out_prncp" ,"out_prncp_inv" ,"total_pymnt" ,"total_pymnt_inv" ,"total_rec_prncp" ,"total_rec_int" ,"total_rec_late_fee" ,"recoveries" ,"collection_recovery_fee" ,"last_pymnt_d" ,"last_pymnt_amnt" ,"next_pymnt_d" ,"last_credit_pull_d" ,"collections_12_mths_ex_med" ,"application_type" ,"acc_now_delinq" ,"tot_coll_amt" ,"tot_cur_bal" ,"total_rev_hi_lim" ) traink<-x[,keep] return(traink) } keepvartest<-function(x){ #function to keep useful variables keep<-c( "loan_amnt" ,"funded_amnt" ,"funded_amnt_inv" ,"term" ,"int_rate" ,"installment" ,"grade" ,"emp_length" ,"home_ownership" ,"annual_inc" ,"verification_status" ,"issue_d" ,"purpose" ,"addr_state" ,"dti" ,"delinq_2yrs" ,"earliest_cr_line" ,"inq_last_6mths" ,"mths_since_last_delinq" ,"mths_since_last_record" ,"open_acc" ,"pub_rec" ,"revol_bal" ,"revol_util" ,"total_acc" ,"initial_list_status" ,"out_prncp" ,"out_prncp_inv" ,"total_pymnt" ,"total_pymnt_inv" ,"total_rec_prncp" ,"total_rec_int" ,"total_rec_late_fee" ,"recoveries" ,"collection_recovery_fee" ,"last_pymnt_d" ,"last_pymnt_amnt" ,"next_pymnt_d" ,"last_credit_pull_d" ,"collections_12_mths_ex_med" ,"application_type" ,"acc_now_delinq" ,"tot_coll_amt" ,"tot_cur_bal" ,"total_rev_hi_lim" ) traink<-x[,keep] return(traink) } addlev<-function(x){ # function to add level for last_pymnt_d,next_pymnt_d,last_credit_pull_d levels(x$last_pymnt_d)[levels(x$last_pymnt_d)==""]<-"NoneDate" levels(x$next_pymnt_d)[levels(x$next_pymnt_d)==""]<-"NoneDate" levels(x$last_credit_pull_d)[levels(x$last_credit_pull_d)==""]<-"NoneDate" return(x) } addmiss<-function(x){ # replace numeric missing value by median miss<-c( "annual_inc" ,"delinq_2yrs" ,"inq_last_6mths" ,"open_acc" ,"pub_rec" ,"revol_util" ,"total_acc" ,"collections_12_mths_ex_med" ,"acc_now_delinq" ,"tot_coll_amt" ,"tot_cur_bal" ,"total_rev_hi_lim") for(i in miss) { me<-median(x[,i],na.rm = TRUE) x[,i][is.na(x[,i])]<-me } return(x) } addearly = function(x){ # turn earliest_cr_line to Date, replace missing by median x$earliest_cr_line<-as.character(x$earliest_cr_line) x$earliest_cr_line<-as.yearmon(x$earliest_cr_line,"%b-%Y") x$earliest_cr_line<-as.Date(x$earliest_cr_line) me<-median(x$earliest_cr_line,na.rm = TRUE) x$earliest_cr_line[is.na(x$earliest_cr_line)]<-me return(x) } addmth = function(mydata){ # process mths_since_last_delinq and mths_since_last_record, recode NA into newlevel: NoneDate mydata$mths_since_last_delinq<-as.factor(ceiling(mydata$mths_since_last_delinq/12)) leveldelinq<-levels(mydata$mths_since_last_delinq) leveldelinq[length(leveldelinq)]<-"NoneDate" levels(mydata$mths_since_last_delinq)<-leveldelinq mydata[is.na(mydata$mths_since_last_delinq),"mths_since_last_delinq"]<-"NoneDate" mydata$mths_since_last_record<-as.factor(ceiling(mydata$mths_since_last_record/12)) levelrecord<-levels(mydata$mths_since_last_record) levelrecord[length(levelrecord)]<-"NoneDate" levels(mydata$mths_since_last_record)<-levelrecord mydata[is.na(mydata$mths_since_last_record),"mths_since_last_record"]<-"NoneDate" return(mydata) } addlabel = function(loan){ # add new column label to dataframe label<-sapply(loan$loan_status,function(x){ifelse(x%in%c("Default","Charged Off","Late (16-30 days)","Late (31-120 days)","Does not meet the credit policy. Status:Charged Off"),'1','0')}) names(label)<-NULL label<-as.factor(label) loan$label = label return(loan) } # ====================================== # Random forest preprocessing # ====================================== drop4Date =function(loan){ # drop 4 Date columns before randomforest keep<-c( "loan_amnt" ,"funded_amnt" ,"funded_amnt_inv" ,"term" ,"int_rate" ,"installment" ,"grade" ,"emp_length" ,"home_ownership" ,"annual_inc" ,"verification_status" ,"label" ,"purpose" ,"addr_state" ,"dti" ,"delinq_2yrs" ,"earliest_cr_line" ,"inq_last_6mths" ,"mths_since_last_delinq" ,"mths_since_last_record" ,"open_acc" ,"pub_rec" ,"revol_bal" ,"revol_util" ,"total_acc" ,"initial_list_status" ,"out_prncp" ,"out_prncp_inv" ,"total_pymnt" ,"total_pymnt_inv" ,"total_rec_prncp" ,"total_rec_int" ,"total_rec_late_fee" ,"recoveries" ,"collection_recovery_fee" ,"last_pymnt_amnt" ,"collections_12_mths_ex_med" ,"application_type" ,"acc_now_delinq" ,"tot_coll_amt" ,"tot_cur_bal" ,"total_rev_hi_lim" ) loan = loan[,keep] return(loan) } # ====================================== # ====================================== # = Main = # ====================================== # ====================================== train = read.csv("train.csv") test = read.csv("test.csv") testid = getid(test) recind = getindex(test) newtrain = addlev(train) newtrain = addmiss(newtrain) newtrain = addearly(newtrain) newtrain = addmth(newtrain) newtrain = addlabel(newtrain) newtrain = keepvar(newtrain) newtest = addlev(test) newtest = addmiss(newtest) newtest = addearly(newtest) newtest = addmth(newtest) newtest = keepvartest(newtest) test = addlabel(test) # ====================================== # [Model I] Random forest # ====================================== start.time = Sys.time() rftrain = drop4Date(newtrain) rfModel = randomForest(label~.,data=rftrain, mtry = 7, ntree=400 ) rfPred = predict(rfModel, newtest ,type = "prob") rfProb = rfPred[,"1"] rfProb[recind] = 1 end.time = Sys.time() run.time1 = as.numeric(difftime(end.time, start.time, units = 'sec')) # write file rfdataframe = data.frame(id = testid, prob = rfProb) write.table(rfdataframe,"mysubmission1.txt", row.names = FALSE, sep = ',') # ====================================== # [Model II] xgboost # ====================================== start.time = Sys.time() xgmodel<-function(){ #train_nore<-newtrain[loan$recoveries==0,] train_nore<-subset(newtrain,select=-c(recoveries,collection_recovery_fee)) test_nore<-subset(newtest,select=-c(recoveries,collection_recovery_fee)) #id<-getid(test_nore) numvar<-NULL for (i in names(train_nore)) { if(class(train_nore[1,i])=="numeric") { numvar<-c(numvar,i) } } numvar<-c("label",numvar) train_num<-train_nore[,numvar] test_num<-test_num[,numvar] gettrain<-function(x){ return(subset(x,select=-c(label))) } dtrain=xgb.DMatrix(as.matrix(gettrain(train_num)),label= (as.numeric(train_nore$label)-1)) dtest<-xgb.DMatrix(as.matrix(test_num)) xgb_params = list( booster = "gbtree", objective = "binary:logistic", max.depth = 12, eta = 0.02, nthread = 2, nround = 2, alpha = 1, gamma = 2, min_child_weight = 1, subsample = 0.5, colsample_bytree = 0.5 #num_parallel_tree = 1 ) best_n_rounds=1000# try more rounds #train data gb_dt=xgb.train(xgb_params,dtrain,nrounds = as.integer(best_n_rounds)) result<-predict(gb_dt,dtest) result<-1-result result[recind]<-1 end.time = Sys.time() run.time2 = as.numeric(difftime(end.time, start.time, units = 'sec')) out<-data.frame(id<-testid,prob<-result) write.table(out,file = "mysubmission1.txt",row.names = FALSE,sep = ",") } # ====================================== # evaluation # ====================================== evaluate<-function(result,test) { if(nrow(result)!=nrow(test)) {print("Error")} else{ label<-test$label a<-result[label=="1",]$prob b<-(1-result[label=="0",]$prob) e<-sum(log(a))+sum(log(b)) e<-(-e)/nrow(test) return(e) } } errorxg = evaluate(out,test) errorrf = evaluate(rfdataframe) <file_sep># Forecast Weekly Sales of Department Stores This is a course project I did with <NAME> and <NAME> for STAT 542 Statistical Learning in spring 2017 at UIUC. We projected the sales of Walmart stores based on historical data, captured the seasonal trends and holiday’s impact on sales using autoregressive model. We programmed in R. <file_sep> # coding: utf-8 # In[1]: get_ipython().magic('matplotlib inline') import numpy as np import pandas as pd import scipy as sp import re # In[2]: from bs4 import BeautifulSoup from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.utils import check_random_state from sklearn.model_selection import train_test_split # In[3]: train=pd.read_csv('E:/542/Pro4/labeledTrainData.tsv', header=0,delimiter='\t',quoting=3) test = pd.read_csv("E:/542/Pro4/testData.tsv", header=0, delimiter="\t", quoting=3) # In[4]: num_reviews = train["review"].size clean_train=[] for i in range( 0, num_reviews ): review_text = BeautifulSoup(train["review"][i],'html.parser').get_text() pattern = re.compile(r'[^\w\s]') letnum_only = re.sub(pattern, " ", review_text) clean_train.append(letnum_only) clean_train_df=pd.DataFrame({'text':clean_train}) # In[5]: def model1(X_train, y_train, X_test, random_state): tfidf=TfidfVectorizer(stop_words = 'english',min_df=5,max_df=0.15,ngram_range=(1, 2)) train_X = tfidf.fit_transform(X_train) test_X=tfidf.transform(X_test) model=LogisticRegression(penalty='l2', dual=True,random_state=random_state) model.fit(train_X,y_train) y_pred=model.predict(test_X) y_score=model.predict_proba(test_X) return model,y_pred,y_score # In[6]: clean_test=[] num_test = test["review"].size for i in range( 0, num_test ): review_text = BeautifulSoup(test["review"][i],'html.parser').get_text() pattern = re.compile(r'[^\w\s]') letnum_only = re.sub(pattern, " ", review_text) clean_test.append(letnum_only) clean_test_df=pd.DataFrame({'text':clean_test}) # In[7]: model,y_pred,y_score= model1(clean_train_df['text'], train['sentiment'], clean_test_df['text'],random_state=check_random_state(800)) # In[8]: y_proba=[] for i in range(0,25000): y_proba.append(y_score[i][1]) # In[9]: output=pd.DataFrame({'id':test['id'],'sentiment':y_proba}) output.to_csv("Prediction.csv", index=False, quoting=3) # In[10]: output=pd.DataFrame({'id':test['id'],'sentiment':y_pred}) output.to_csv("Prediction0or1.csv", index=False, quoting=3) # In[ ]: <file_sep># Predicting Housing Price in Ames This is a course project I did with <NAME> and <NAME> for STAT 542 Statistical Learning in spring 2017 at UIUC. We programmed in R and used LASSO regression and xgboost.<file_sep>library(forecast) library(lubridate) #==================== functions ======================== # --------------implement missing value----------------- addmiss=function(train){ exi_record<-table(train$Dept,train$Store) exi<-which(exi_record!=0, arr.ind=TRUE, useNames = FALSE) exi_s<-unique(train$Store) for (i in unique(train$Date)){ holi<-unique(train[train$Date==i,]$IsHoliday) t_d<-unique(train[train$Date==i,]$Date) tmp_train=train[train$Date==i,] records=table(tmp_train$Dept,tmp_train$Store) t_missing_records=which(records==0, arr.ind=TRUE, useNames = FALSE) missing_records<-merge(exi,t_missing_records,all=FALSE) missing_dept<-as.numeric(row.names(exi_record)[missing_records[,1]]) missing_store<-as.numeric(colnames(exi_record)[missing_records[,2]]) if( length(missing_records)>0 | length(missing_dept)>0 ){ store_average=rep(0,length(exi_s)) for( j in 1:length(exi_s)){ store_average[j]=mean(tmp_train[tmp_train$Store==exi_s[j],"Weekly_Sales"]) } store_average=data.frame(Store=exi_s,Weekly_Sales=store_average) missing_add<-data.frame(Store=missing_store,Dept=missing_dept,Date=rep(t_d,length(missing_dept)),IsHoliday=rep(holi,length(missing_dept))) missing_add<-merge(missing_add,store_average, by="Store", all.x = TRUE) train=rbind(train,missing_add) } } return(train) } #--------------add column Wk and Column Yr--------------- addWeek = function(train){ train.wk = train$Date train.wk = train.wk - as.Date("2010-02-05") # date is now 0, 7, 14, ... train.wk = train.wk/7 + 5 # make 2010-2-5 as '5', and date becomes continuous integers, i.e., 5, 6, 7, ... train.wk = as.numeric(train.wk) %% 52 ## 52 weeks in a year train$Wk = train.wk train$Yr = year(train$Date) return(train) } # ------------ subset corresponding test ---------------- subtest = function(test, t){ if (t<=9){ beginday = as.Date(paste("2011-", t+2, "-01",sep = ''),format = "%Y-%m-%d") endday = as.Date(paste("2011-", t+3, "-01",sep = ''),format = "%Y-%m-%d") } else if (t==10){ beginday = as.Date("2011-12-01",format = "%Y-%m-%d") endday = as.Date("2012-01-01",format = "%Y-%m-%d") } else { beginday = as.Date(paste("2012-", t-10, "-01",sep = ''),format = "%Y-%m-%d") endday = as.Date(paste("2012-", t-9, "-01",sep = ''),format = "%Y-%m-%d") } currenttest = test[(beginday <= test$Date) & (test$Date < endday),] return(currenttest) } #================== simple model 1 ==================== simple = function(train, test){ store = sort(unique(test$Store)) n.store = length(store) dept = sort(unique(test$Dept)) n.dept = length(dept) for (s in 1:n.store){ for (d in 1:n.dept){ # cat("[Model 1] Store: ", store[s], "\t Dept ", dept[d], "\n") # find the data for (store, dept) = (s, d) test.id = which(test$Store == store[s] & test$Dept == dept[d]) test.temp = test[test.id, ] train.id = which(train$Store == store[s] & train$Dept == dept[d]) train.temp = train[train.id, ] for (i in 1:length(test.id)){ id = which(train.temp$Wk == test.temp[i,]$Wk & train.temp$Yr == test.temp[i,]$Yr - 1) threeWeeksId = c(id - 1, id, id + 1) ## three weeks in the last year tempSales = train.temp[threeWeeksId, 'Weekly_Sales'] if (length(tempSales) == 0){ test$Weekly_Pred1[test.id[i]] = mean(train.temp$Weekly_Sales) } else { test$Weekly_Pred1[test.id[i]] = mean(tempSales) } } } } # deal with NA and NaN s_d_w<-test[is.na(test$Weekly_Pred1) | is.nan(test$Weekly_Pred1),c("Store","Dept","Wk")] for(k in 1:nrow(s_d_w)) { s <- s_d_w$Store[k] d <- s_d_w$Dept[k] w <- s_d_w$Wk[k] mean_s<-mean(train[train$Store==s,]$Weekly_Sales) test$Weekly_Pred1[test$Store==s & test$Dept==d & test$Wk == w]<- mean_s } # set holiday sales as the same as the week last year s_d_w<-test[test$Wk == 0 | test$Wk == 6 | test$Wk == 47 ,c("Store","Dept","Wk")] for(k in 1:nrow(s_d_w)) { s <- s_d_w$Store[k] d <- s_d_w$Dept[k] w <- s_d_w$Wk[k] salesholiday<-mean(train$Weekly_Sales[train$Store==s & train$Dept == d & train$Wk == w]) test$Weekly_Pred1[test$Store==s & test$Dept==d & test$Wk == w]<- salesholiday } test$Weekly_Pred1[is.nan(test$Weekly_Pred1)] = 0 return(test) } #================== ts model 2 ==================== model2<-function(X,Y) { train_s_d<-unique(X[,c("Store","Dept")]) n_train<-nrow(train_s_d) test_s_d<-unique(Y[,c("Store","Dept")]) n_test<-nrow(test_s_d) #all in# all_s_d<-merge(train_s_d,test_s_d,by=c("Store","Dept")) n_all<-nrow(all_s_d) #predict week# n_pred_w<-nrow(Y[Y$Store==1&Y$Dept==1,]) #pred_w<-test[test$Store==1&test$Dept==1,]$Date for(k in 1: n_all) { s<-all_s_d$Store[k] d<-all_s_d$Dept[k] if (Y$Yr[1]<2012|(Y$Yr[1]==2012&Y$Wk[1]<=5)){ Y[Y$Store==s&Y$Dept==d,]$Weekly_Pred2 <- Y[Y$Store==s&Y$Dept==d,]$Weekly_Pred1 } else{ sale<-X[(X$Store==s)&(X$Dept==d),]$Weekly_Sales #print(d) #print(length(sale)) #aa=X[(X$Store==s)&(X$Dept==d),] #if (nrow(aa)!=108){ # print(tail(aa)) #} ts_sale<-ts(sale,frequency = 52) n_pred<- nrow(Y[Y$Store==s&Y$Dept==d,]) #pred<-stlf(ts_sale, h=n_pred, s.window=3, method='arima',ic='bic') #pred<-forecast.HoltWinters(ts_sale, h=n_pred, seasonal="additive") #pred<- holt(ts_sale, h=n_pred, seasonal="additive") pred<- ses(ts_sale, h=n_pred, initial='simple',alpha=0.2) #pred<- rwf(ts_sale, h=n_pred, drift=T) pred<-as.numeric(pred$mean) Y[Y$Store==s&Y$Dept==d,]$Weekly_Pred2<-pred[1:n_pred] } } #only in test# if(n_all!=n_test){ otest_s_d<-Y[is.na(Y$Weekly_Pred2),c("Store","Dept")] n_otest<-nrow(otest_s_d) for(k in n_otest) { s<-otest_s_d$Store[k] d<-otest_s_d$Dept[k] mean_s<-mean(X[X$Store==s,]$Weekly_Sales) n_pred<- nrow(Y[Y$Store==s&Y$Dept==d,]) Y[Y$Store==s&Y$Dept==d,]$Weekly_Pred2<-rep(mean_s,n_pred) } } na_ix<-which(is.na(Y$Weekly_Pred2)) for(l in na_ix) { Y[l,]$Weekly_Pred2<-mean(X[X$Store==Y[l,"Store"],]$Weekly_Sales) } return(Y) } #================== ts model 3 ===========forecast========= model3<-function(X,Y) { train_s_d<-unique(X[,c("Store","Dept")]) n_train<-nrow(train_s_d) test_s_d<-unique(Y[,c("Store","Dept")]) n_test<-nrow(test_s_d) #all in# all_s_d<-merge(train_s_d,test_s_d,by=c("Store","Dept")) n_all<-nrow(all_s_d) #predict week# n_pred_w<-nrow(Y[Y$Store==1&Y$Dept==1,]) #pred_w<-test[test$Store==1&test$Dept==1,]$Date for(k in 1: n_all) { s<-all_s_d$Store[k] d<-all_s_d$Dept[k] sale<-X[(X$Store==s)&(X$Dept==d),]$Weekly_Sales ts_sale<-ts(sale,frequency = 52) n_pred<- nrow(Y[Y$Store==s&Y$Dept==d,]) pred<-forecast(ts_sale,h=n_pred) pred<-as.numeric(pred$mean) Y[Y$Store==s&Y$Dept==d,]$Weekly_Pred3<-pred[1:n_pred] } #only in test# if(n_all!=n_test){ otest_s_d<-Y[is.na(Y$Weekly_Pred3),c("Store","Dept")] n_otest<-nrow(otest_s_d) for(k in n_otest) { s<-otest_s_d$Storep[k] d<-otest_s_d$Dept[k] mean_s<-mean(X[X$Store==s,]$Weekly_Sales) n_pred<- nrow(Y[Y$Store==s&Y$Dept==d,]) Y[Y$Store==s&Y$Dept==d,]$Weekly_Pred3<-rep(mean_s,n_pred) } } na_ix<-which(is.na(Y$Weekly_Pred3)) for(l in na_ix) { Y[l,]$Weekly_Pred3<-mean(X[X$Store==Y[l,"Store"],]$Weekly_Sales) } return(Y$Weekly_Pred3) } #====================== main ============================ # this part will run when 'source(mymain.r)' # the goal of this part should be setting up some varibales that will be used in functions # these variables, such as dept.names and store.names, won't change during loop train$Date = as.Date(train$Date, '%Y-%m-%d') test$Date = as.Date(test$Date, '%Y-%m-%d') dept.names = sort(unique(train$Dept)) store.names =sort(unique(train$Store)) n.dept=length(dept.names) n.store=length(store.names) #===================== frame of predict() ============== predict = function(){ if(t!=1){ # if not first iteration: update train # t=1, Date=2011-03-04, newtest=NULL train <<- rbind(train,newtest) } # ------------ preprocessing ------------------ train$Date = as.Date(train$Date, '%Y-%m-%d') test$Date = as.Date(test$Date, '%Y-%m-%d') # subset current test currenttest = subtest(test,t) # print(currenttest[is.na(currenttest$Store)]) # add miss currenttrain = addmiss(train) #print(currenttrain[is.na(currenttrain$Store),]) # add Wk and Yr currenttrain = addWeek(currenttrain) currenttest = addWeek(currenttest) table(currenttrain$Store,currenttrain$Dept) # ------------ predict ----------------------- # Call model 1 currentpred = simple(currenttrain, currenttest) # Call model 2 currentpred = model2(currenttrain, currentpred) # Call model 3 currentpred3 = model3(currenttrain, currenttest) #rewite currenttest currentpred$Weekly_Pred3<-currentpred3 #---------------------- merge test ---------------------------- if (t<=9){ beginday = as.Date(paste("2011-", t+2, "-01",sep = ''),format = "%Y-%m-%d") endday = as.Date(paste("2011-", t+3, "-01",sep = ''),format = "%Y-%m-%d") } else if (t==10){ beginday = as.Date("2011-12-01",format = "%Y-%m-%d") endday = as.Date("2012-01-01",format = "%Y-%m-%d") } else { beginday = as.Date(paste("2012-", t-10, "-01",sep = ''),format = "%Y-%m-%d") endday = as.Date(paste("2012-", t-9, "-01",sep = ''),format = "%Y-%m-%d") } testbind = test[(test$Date < beginday) | (test$Date >= endday),] currentpred = subset(currentpred,select = -c(Wk, Yr)) test1 = rbind(testbind, currentpred) test1$Date = as.factor(test1$Date) test <<- test1 } <file_sep># Movie Recommender System This is a course project I did with <NAME> and <NAME> for STAT 542 Statistical Learning in spring 2017 at UIUC. We created a recommender system which recommends movies to users based on 1,000,000 ratings using Collaborative Filtering model. We used R for this project. <file_sep># Statistical Learning Course Projects Collection These are course projects I did with <NAME> and <NAME> for STAT 542 Statistical Learning in spring 2017 at UIUC. **Predicting Housing Price in Ames** + Used LASSO regression and Xgboost to predict housing price in Ames **Forecast Sales** + Projected the sales of Walmart stores based on historical data using autoregressive model + Captured the seasonal trends and holiday’s impact on sales **Prediction of Credit Risk** + Predicted the chance of default for loans using Random Forest + Cleaned 890,000 ro¬ws of loan data of 9 years and selected 40 variables + Ran the model on cloud computing platform Amazon Web Service **Sentiment Analysis of Movie Reviews** + Cleaned and classified 50,000 movie reviews using Bag-of-Words model, achieving 95% accuracy + Visualized text reviews with their labels by word clouds and histograms **Movie Recommender System** + Created a recommender system which recommends movies to users based on 1,000,000 ratings using Collaborative Filtering model <file_sep># Movie Review Sentiment Analysis This is a course project I did with <NAME> and <NAME> for STAT 542 Statistical Learning in spring 2017 at UIUC. We did some preprocessing of text reviews, including removing stop words and tokenization. We tried logistic regression, Recurrent Neural Networks, SVM and Naive Bayes to classify reviews as 'positive' or 'negative' sentiment. We created word cloud visualization of reviews. We used R and Python for this project.<file_sep># Predict Credit Risk This is a course project I did with <NAME> and <NAME> for STAT 542 Statistical Learning in spring 2017 at UIUC. We cleaned 890,000 rows of loan data of 9 years and selected 40 variables, and used Random Forest and Xgboost to predict the chance of default. We programmed in R. We ran our code on AWS.<file_sep>########################## # Project 2 Prepare Data # ########################## train.raw = read.csv(unz('train.csv.zip', 'train.csv')) # str(train.raw) train.date = as.Date(train.raw$Date, '%Y-%m-%d') # training data from 2010-02 to 2011-02. train.start = as.Date('2010-02-01', '%Y-%m-%d') train.end = as.Date('2011-02-28', '%Y-%m-%d') train.id = which(train.date >= train.start & train.date <= train.end) train = train.raw[train.id, ] test = train.raw[-train.id, ] test$Weekly_Sales = NULL test$Weekly_Pred1 = 0 test$Weekly_Pred2 = 0 test$Weekly_Pred3 = 0 write.table(train, file = 'train.csv', quote = FALSE, sep = ',', row.names = FALSE) write.table(test, file = 'test.csv', quote = FALSE, sep = ',', row.names = FALSE) newtest.raw = train.raw[-train.id, ] newtest.date = train.date[-train.id] # month 1 --> 2011-03, and month 20 --> 2012-10. newtest.name = 'xxx' Month = 3 Year = 2011 i = 1 while (i <= 20){ newtest.id = which(as.numeric(format(newtest.date, '%Y')) == Year & as.numeric(format(newtest.date, '%m')) == Month) newtest = newtest.raw[newtest.id, ] write.table(newtest, file = paste(newtest.name, i, '.csv', sep = '') , quote = FALSE, sep = ',', row.names = FALSE) Month = Month + 1 if (Month > 12){ Year = Year + 1 Month = 1 } i = i + 1 } <file_sep>pkg = c('recommenderlab', 'reshape2') # all packages you will use in your code # Do not include unnecessary packages. for (i in pkg){ if (!require(i, character.only = TRUE)){ install.packages(i) } } library(recommenderlab) # realRatingMatrix library(reshape2) # acast # ====================== read train ========================== train = read.table('train.dat', sep = ':', colClasses = c('integer', 'NULL'), header = FALSE ) colnames(train) = c('UserID', 'MovieID', 'Rating', 'Timestamp') # ====================== read test ========================== test = read.csv('test.csv', header = TRUE) # ===================== read movie ========================== movies = readLines('movies.dat') movies = strsplit(movies, split = '::', fixed = TRUE) movies = matrix(unlist(movies), ncol = 3, byrow = TRUE) movies = data.frame(movies, stringsAsFactors = FALSE) colnames(movies) = c('MovieID', 'Title', 'Genres') movies$MovieID = as.integer(movies$MovieID) # ============ User-based Model ==================== ratingmat <- acast(train, UserID~MovieID, value.var = 'Rating') ratingmat = as(ratingmat, 'realRatingMatrix') recommenderRegistry$get_entries(dataType = "realRatingMatrix") UBmodel = Recommender(ratingmat, method = 'UBCF', parameter = list(normalize = 'Z-score', method = 'cosine', nn = 25)) UBrecom = predict(UBmodel, ratingmat, type = 'ratings') # predict ratings. This may be slow. UB_list = as(UBrecom, 'list') # each element are ratings of that user # For all lines in test file, one by one for (u in 1:nrow(test)){ userid = test$user[u] movieid = test$movie[u] rating = UB_list[[userid]][movieid] test$rating[u] = rating } test$rating[is.na(test$rating)] = mean(train$Rating) # write submission file write.table(test, file = 'mysubmission1.csv', row.names = FALSE, col.names = TRUE, sep = ',') # ============ Item-based Model ==================== test$rating = NULL IBmodel <- Recommender(data = ratingmat, method = "IBCF", parameter = list(k = 5)) IBrecom = predict(IBmodel, ratingmat, type = 'ratings') IB_list = as(IBrecom, 'list') # each element are ratings of that user # For all lines in test file, one by one for (u in 1:nrow(test)){ userid = test$user[u] movieid = test$movie[u] rating = IB_list[[userid]][movieid] test$rating[u] = rating } test$rating[is.na(test$rating)] = mean(train$Rating) # write submission file write.table(test, file = 'mysubmission2.csv', row.names = FALSE, col.names = TRUE, sep = ',')
b87fb6524eff9b18c8561879b683da1569ccb6c5
[ "Markdown", "Python", "R" ]
14
R
HongfeiLi365/Statistical-Learning-Projects
19d1857a6fca4305a32cc03ca9b8490b69aaf9e2
90df77b5df667f582792a49630b45d1b0f0fff69
refs/heads/master
<repo_name>lzhb/port-scanner<file_sep>/README.md ## Port Scanner (端口检测工具) ### Usage python3 port_scanner.py ip_address start_port-end_port. For example, python3 port_scanner.py localhost 0-65535 , then the tool will scan all the ports opened in your PC. You can change the timeout value in code. <file_sep>/port_scanner.py #encoding:utf-8 # last edit date: 2018/08/29 # author: lingzhb # LICENSE # Copyright (c) 2016-2018, Forec <<EMAIL>> # Permission to use, copy, modify, and/or distribute this code for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. import sys import threading import time from socket import * class Scanner(threading.Thread): def __init__(self, port): threading.Thread.__init__(self) self.port = port def run(self): sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(8) result = sock.connect_ex((target_ip, self.port)) if result == 0: lock.acquire() print("Port Open:", self.port) lock.release() if __name__=='__main__': host = sys.argv[1] if len(sys.argv) <= 2: start_port = 0 end_port = 65535 else: portstrs = sys.argv[2].split('-') start_port = int(portstrs[0]) end_port = int(portstrs[1]) target_ip = gethostbyname(host) lock = threading.Lock() for port in range(start_port, end_port): Scanner(port).start()
d1ba1100fc8ee1d5a003a793b06902830b3456e0
[ "Markdown", "Python" ]
2
Markdown
lzhb/port-scanner
53eb7aa212a34b4c1b73a1670297237541c64300
b9e972f742c65e375b9b41ec2e6e8639228c77b7
refs/heads/master
<repo_name>somya-dav/qna-proj<file_sep>/file.php <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password,$dbname ); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully <br>"; if (!empty($_POST['form1'])) { //do something here; $ques1 = $_POST["o1"]; $ans1 = $_POST["ans1"]; $sql = "INSERT INTO qna (ques, ans) VALUES ('$ques1','$ans1')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully<br>"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } if (!empty($_POST['form2'])) { //do something here; $ques2 = $_POST["o2"]; $ans2 = $_POST["ans2"]; $sql = "INSERT INTO qna (ques, ans) VALUES ('$ques2','$ans2')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully<br>"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } if (!empty($_POST['form3'])) { //do something here; $ques3 = $_POST["o3"]; $ans3 = $_POST["ans3"]; $sql = "INSERT INTO qna (ques, ans) VALUES ('$ques3','$ans3')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully<br>"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } if (!empty($_POST['form4'])) { //do something here; $ques4 = $_POST["o4"]; $ans4 = $_POST["ans4"]; $sql = "INSERT INTO qna (ques, ans) VALUES ('$ques4','$ans4')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully<br>"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } if (!empty($_POST['form5'])) { //do something here; $ques5 = $_POST["o5"]; $ans5 = $_POST["ans5"]; $sql = "INSERT INTO qna (ques, ans) VALUES ('$ques5','$ans5')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully<br>"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $sql = "SELECT * FROM qna"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "question: " . $row["ques"]. " - Answer: " . $row["ans"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?>
2646300252b297bdcaa7d7be1faa1adbcb7d6aa9
[ "PHP" ]
1
PHP
somya-dav/qna-proj
cf3ceb4bf8453da9ec0ee8980258cab56738d573
c5bb5974e3359edbc449e0db7f8fd57c7f9757fc
refs/heads/main
<file_sep>import { createRouter, createWebHistory } from 'vue-router' import Home from '../views/Home.vue' import Good from '../views/Good.vue' const routes = [{ path: '/', name: 'Home', component: Home }, { path: '/auth', name: 'Auth', component: () => import('../views/Auth.vue') }, // // { // path: '/catalog/:sub1/:sub2', // name: 'Catalog2', // component: () => import('../views/Catalog.vue') // }, // { // path: '/catalog/:sub1', // name: 'Catalog1', // component: () => import('../views/Catalog.vue') // }, { path: '/catalog', name: 'Catalog', component: () => import('../views/Catalog.vue') }, { name: "Catalog1", path: '/:parentpath', component: () => import('../views/Catalog.vue') }, { name: "Goods", path: '/goods/:parentpath', component: () => { console.log('../views/Goods.vue'); return import('../views/Goods.vue') }, }, { name: "Good", path: '/good/:id', component: Good }, { path: '/garbage', name: 'Garbage', component: () => import('../views/Garbage.vue') }, { // 404 ошибка если страничка не найдена path: '/:pathMatch(.*)*', redirect: '/' }, ]; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) export default router <file_sep>import { createStore } from 'vuex' export default createStore({ state: { garbage: [], all_category: [{ id: 1, img_path: "category.png", leaf: false, name: "Комплектующие", path: "copmlect", parents: [] }, { id: 2, img_path: "category.png", leaf: true, name: "Процессоры", path: "procs", parents: ['copmlect',"populyarity"] }, { id: 21, path: "matplat", img_path: "category.png", leaf: true, name: "Материнские платы", parents: ['copmlect'] }, { id: 3, path: "videocarts", img_path: "category.png", leaf: true, name: "Видеокарты", parents: ['copmlect'] }, { id: 4, path: "op", img_path: "category.png", leaf: true, name: "Оперативная память", parents: ['copmlect'] }, { id: 5, path: "bp", img_path: "category.png", leaf: true, name: "Блоки питания", parents: ['copmlect'] }, { id: 6, path: "ssd", img_path: "category.png", leaf: true, name: "SSD", parents: ['copmlect',"populyarity"] }, { id: 7, path: "hd", img_path: "category.png", leaf: true, name: "Жесткие диски", parents: ['copmlect',"populyarity"] }, { id: 8, path: "copmlect-for-server", img_path: "category.png", leaf: false, name: "Комплектующие для сервера", parents: ['copmlect'] }, { id: 9, path: "serv-procs", img_path: "category.png", leaf: true, name: "Серверные процессоры", parents: ['copmlect-for-server'] }, { id: 10, path: "serv-mp", img_path: "category.png", leaf: true, name: "Серверные материнские платы", parents: ['copmlect-for-server'] }, { id: 11, path: "serv-ssd", img_path: "category.png", leaf: true, name: "Серверные SSD", parents: ['copmlect-for-server'] }, { id: 12, path: "serv-hdd", img_path: "category.png", leaf: true, name: "Серверные HDD", parents: ['copmlect-for-server'] }, { id: 30, path: "peref", img_path: "category.png", leaf: false, name: "Переферия", parents: [], }, { id: 32, path: "mouse", img_path: "category.png", leaf: true, name: "Мыши", parents: ['peref'] }, { id: 33, path: "keys", img_path: "category.png", leaf: true, name: "Клавиатуры", parents: ['peref'] }, { id: 15, path: "monitors-and-as", img_path: "category.png", leaf: false, name: "Мониторы и аксессуары", parents: [], }, { id: 16, path: "monitors", img_path: "category.png", leaf: true, name: "Мониторы", parents: ['monitors-and-as'] }, { id: 18, path: "gamemonitors", img_path: "category.png", leaf: true, name: "<NAME>", parents: ['monitors-and-as'] }, { id: 19, path: "noutbooks", img_path: "category.png", leaf: true, name: "Ноутбуки", parents: [] }, { id: 20, path: "planshs", img_path: "category.png", leaf: true, name: "Планшеты", parents: [] } ], goods: [{ id: 1, imgs_description: ["good2.png", "good3.png"], name: "Товар1", description: "Товар1 ИЗ Процессоры", catalogs: [2], price: 1000 }, { id: 2, imgs_description: ["good2.png", "good3.png"], name: "Товар2", description: "Товар2 ИЗ Процессоры", catalogs: [2], price: 11000 }, { id: 3, imgs_description: ["good2.png", "good3.png"], name: "Товар3", description: "Товар3 ИЗ Процессоры", catalogs: [2], price: 12000 }, { id: 4, imgs_description: ["good2.png", "good3.png"], name: "Товар4", description: "Товар4 ИЗ Процессоры", catalogs: [2], price: 10 }, { id: 10, imgs_description: ["good2.png", "good3.png"], name: "Товар1", description: "Товар1 ИЗ Серверные материнские платы", catalogs: [10], price: 5678 }, { id: 11, imgs_description: ["good2.png", "good3.png"], name: "Товар2", description: "Товар2 ИЗ Серверные материнские платы", catalogs: [10], price: 999 }, { id: 12, imgs_description: ["good2.png", "good3.png"], name: "Товар3", description: "Товар3 ИЗ Серверные материнские платы", catalogs: [10], price: 99989 }, { id: 13, imgs_description: ["good2.png", "good3.png"], name: "Товар4", description: "Товар4 ИЗ Серверные материнские платы", catalogs: [10], price: 10009 }] }, getters: { getCategoryies: state => ({ parentpath }) => { return state.all_category.filter(e => { if (!parentpath) return e.parents.length === 0; else { return e.parents.includes(parentpath); } }) }, getGoods: state => ({ parentpath }) => { let cat = state.all_category.filter(e => e.path === parentpath)[0]; return state.goods.filter(e => { return e.catalogs.includes(cat.id); }); }, getPaths: state => ({ parentpath }) => { let findPath = function(data, parentpath, arr) { let cat = data.filter(e => e.path === parentpath)[0]; arr.push(cat); if (cat.parents && cat.parents[0]) { findPath(data, cat.parents[0], arr); } return arr; }; let res = []; findPath(state.all_category, parentpath, res) return res; }, goodById: state => ( id ) => { return state.goods.filter(e => e.id == id)[0]; }, getGarbage: state => () => { return state.garbage; }, garbageCount: state => () => { if (state.garbage && state.garbage.length>0) { let count = 0, summ = 0; for (let i = 0,array = state.garbage; i < array.length; i++) { count += array[i].count; summ += (array[i].count * array[i].price); } return { "count": count, "summ": summ } } else{ return {}; } }, }, mutations: { addToGarbage(state, good) { let obj = Object.assign({}, good); if (state.garbage.findIndex(e => e.id === obj.id) < 0) { obj["count"] = 1; obj["summ"] = () => { return this.count * this.price } state.garbage.push(obj); } else { state.garbage.filter(e => e.id === obj.id)[0].count += 1; } }, removeFromGarbage(state, id) { let ind = state.garbage.findIndex(e => e.id === id) state.garbage.splice(ind, 1) }, }, }); <file_sep>[{ id: 1, img_path: "category.png", name: "Комплектующие", path: "copmlect", parents: [] }, { id: 2, img_path: "category.png", name: "Процессоры", path: "procs", parents: [1] }, { id: 21, path: "matplat", img_path: "category.png", name: "Материнские платы", parents: [1] }, { id: 3, path: "videocarts", img_path: "category.png", name: "Видеокарты", parents: [1] }, { id: 4, path: "op", img_path: "category.png", name: "Оперативная память", parents: [1] }, { id: 5, path: "bp", img_path: "category.png", name: "Блоки питания", parents: [1] }, { id: 6, path: "ssd", img_path: "category.png", name: "SSD", parents: [1] }, { id: 7, path: "hd", img_path: "category.png", name: "Жесткие диски", parents: [1] }, { id: 8, path: "copmlect-for-server", img_path: "category.png", name: "Комплектующие для сервера", parents: [1] }, { id: 9, path: "serv-procs", img_path: "category.png", name: "Серверные процессоры", parents: [8] }, { id: 10, path: "serv-mp", img_path: "category.png", name: "Серверные материнские платы", parents: [8] }, { id: 11, path: "serv-ssd", img_path: "category.png", name: "Серверные SSD", parents: [8] }, { id: 12, path: "serv-hdd", img_path: "category.png", name: "Серверные HDD", parents: [8] }, { id: 30, path: "peref", img_path: "category.png", name: "Переферия", parents: [], }, { id: 32, path: "mouse", img_path: "category.png", name: "Мыши", parents: [30] }, { id: 33, path: "keys", img_path: "category.png", name: "Клавиатуры", parents: [30] }, { id: 15, path: "monitors-and-as", img_path: "category.png", name: "Мониторы и аксессуары", parents: [], } { id: 16, path: "monitors", img_path: "category.png", name: "Мониторы", parents: [15] }, { id: 18, path: "gamemonitors", img_path: "category.png", name: "Игровые мониторы", parents: [15] }, { id: 19, path: "noutbooks", img_path: "category.png", name: "Ноутбуки", parents: [] }, { id: 20, path: "planshs", img_path: "category.png", name: "Планшеты", parents: [] } ] [ { id: 1, imgs_description: ["good2.png", "good3.png"], name: "Товар1", description: "Товар1 ИЗ Процессоры", catalogs: [2] }, { id: 2, imgs_description: ["good2.png", "good3.png"], name: "Товар2", description: "Товар2 ИЗ Процессоры", catalogs: [2] }, { id: 3, imgs_description: ["good2.png", "good3.png"], name: "Товар3", description: "Товар3 ИЗ Процессоры", catalogs: [2] }, { id: 4, imgs_description: ["good2.png", "good3.png"], name: "Товар4", description: "Товар4 ИЗ Процессоры", catalogs: [2] }, { id: 10, imgs_description: ["good2.png", "good3.png"], name: "Товар1", description: "Товар1 ИЗ Серверные материнские платы", catalogs: [10] }, { id: 11, imgs_description: ["good2.png", "good3.png"], name: "Товар2", description: "Товар2 ИЗ Серверные материнские платы", catalogs: [10] }, { id: 12, imgs_description: ["good2.png", "good3.png"], name: "Товар3", description: "Товар3 ИЗ Серверные материнские платы", catalogs: [10] }, { id: 13, imgs_description: ["good2.png", "good3.png"], name: "Товар4", description: "Товар4 ИЗ Серверные материнские платы", catalogs: [10] } ]
7a10b20812a761d6cd8a47e243489e219627a24c
[ "JavaScript" ]
3
JavaScript
Stugi/vue-exam
a6ac6cc3854cc347ba79d82ad2ff6145dee18cb3
432dc2a63b2ed25dfcd4c77bc8e1c923b0d60b0a
refs/heads/master
<repo_name>alisure-ml/Installation<file_sep>/remote_vnc.md # VNC viewer 远程 ## Windows部分 1. 下载 [VNC viewer](https://www.realvnc.com/en/connect/download/viewer/) 2. 安装 3. 配置Linux电脑,并得到其ip地址(参见Linux部分) 4. 在VNC Viewer中输入ip地址进行连接 ## Linux部分 1. 在搜索框搜索 `Sharing` 并打开 2. 设置 `Screen Sharing`, 点击左上角`ON`, 点击勾线`Allow connections to control the screen`,并选择 `Require a password`. 关闭后 `Screen Sharing` 显示为 `Active` 状态。 3. 安装 `dconf-editor` 工具,方便配置 `dconf`. * 打开命令行:`Ctrl + Alt + T` * 命令行中输入:`sudo apt-get install dconf-editor` * 输入密码 4. 设置 `remote-access` * 命令行中输入:`dconf-editor` 打开 `dconf` * 选择 `org->gnome->desktop->remote-access` 中取消 `requre-encryption` 5. 获得ip地址 * 命令行中输入:`ifconfig` <file_sep>/Enviroment.md ### 环境变量 > 解决环境变量问题 出现下列问题: * 运行Tensorflow需要在`Pycharm`中设置`LD_LIBRARY_PATH=/usr/local/cuda/lib64`的问题 * `Pycharm`中不能找到caffe包的问题 ### 解决方法 1. 打开系统环境变量 ``` CTRL + ALT + T sudo gedit /etc/profile ``` 2. 添加环境变量 ``` export PATH=/usr/local/cuda-8.0/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64:$LD_LIBRARY_PATH export PYTHONPATH=/you/path/of/caffe/python:$PYTHONPATH ``` 3. 生效修改 ``` source /etc/profile ``` 4. 此时在命令行中已经生效,但是在Pycharm中还未生效 ``` 重启电脑即可 ``` ### 环境变量 > 有多种设置环境变量的方式,比如:系统级环境变量,用户级环境变量,终端级环境变量 1. 系统级环境变量:对所有用户生效的永久变量 ``` sudo gedit /etc/profile ``` 用`export`指令添加环境变量。 添加完成后新的环境变量不会立即生效,除非你调用source /etc/profile 该文件才会生效。 否则只能在下次重进此用户时才能生效。 ``` source /etc/profile ``` 2. 用户级环境变量:只对当前的用户永久生效 > 在`.bashrc`和`.bash_profile`中都可以设置此类环境变量。 `.bash_profile`文件只会在用户登录的时候读取一次,而`.bashrc`在每次打开终端进行一次新的会话时都会读取。 ``` sudo gedit ~/.bashrc ``` 用`export`指令添加环境变量。 添加完成后新的环境变量不会立即生效,除非你调用source ~/.bash_profile 该文件才会生效。 否则只能在下次重进此用户时才能生效。 3. 终端级环境变量:只对当前shell有效 > 此类环境变量只对当前的shell有效。当退出登录或者关闭终端再重新打开时,这个环境变量就会消失。 直接使用`export`指令添加。 ### 常用指令 * 设置新的环境变量 ``` export MYNAME="ALISURE" ``` * 查看显示环境变量 ``` echo $MYNAME ``` * 修改环境变量 ``` MYNAME="ALISURE2" ``` * 查看所有环境变量 ``` env ``` * 删除一个环境变量 ``` unset MYNAME ``` ### 常用环境变量 * PATH:指定命令的搜索路径 ``` echo $PATH ``` 通过结果可以看出,路径由`:`分隔,所以可以用`export PATH=$PATH:路径`添加搜索路径。 这些搜索路径都是一些可以找到可执行程序的目录列表。 * HOME:指定用户的主工作目录 ``` echo $HOME ``` 用户登录到Linux系统中时的默认目录,即“~”。 * HISTSIZE:保存历史命令记录的条数 ``` echo $HISTSIZE ``` 输入的指令都会被系统保存保存在用户工作主目录“~”下的隐藏文件.bash_history中,可以通过下列指令查看。 ``` history ``` ### Reference * [Linux环境变量及其设置](http://blog.csdn.net/llzk_/article/details/53813266) <file_sep>/connect_net.md # 链接网络 ## 命令行下连接校园网 ``` sudo pppoeconf ``` ## ubuntu ping Name or service not know ``` sudo vim /etc/resolv.conf ``` 找一台正常的电脑,配置成一样,重启即可。 ## Inference * [Ubuntu 命令行连接校园网](https://blog.csdn.net/tengfeixiaoao/article/details/52893394) <file_sep>/Caffe.md ### 安装Caffe * GitHub地址: [https://github.com/BVLC/caffe](https://github.com/BVLC/caffe) * 官方安装地址: [http://caffe.berkeleyvision.org/installation.html](http://caffe.berkeleyvision.org/installation.html) 下载Caffe: ``` git clone https://github.com/BVLC/caffe.git cd caffe ``` ### 注意!!!! * 注意编译的时候python的版本。一定要在执行之前查看python的版本。毕竟工作站中的Linux系统的Python可能会比较乱,原因大家都懂的。 ### Windows 安装 > GitHub地址: [https://github.com/BVLC/caffe/tree/windows](https://github.com/BVLC/caffe/tree/windows) * 有预编译版本,下载后可直接安装。 ### Ubuntu 安装 * GitHub地址: [https://github.com/BVLC/caffe](https://github.com/BVLC/caffe) * 官方安装地址: [http://caffe.berkeleyvision.org/install_apt.html](http://caffe.berkeleyvision.org/install_apt.html) 官方安装步骤如下: 1. [http://caffe.berkeleyvision.org/install_apt.html](http://caffe.berkeleyvision.org/install_apt.html) 2. [http://caffe.berkeleyvision.org/installation.html#compilation](http://caffe.berkeleyvision.org/installation.html#compilation) 16.04 python3.5 安装步骤如下: 1. 安装依赖 ``` sudo apt-get update sudo apt-get install -y build-essential cmake git pkg-config sudo apt-get install -y libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler sudo apt-get install -y libatlas-base-dev sudo apt-get install -y --no-install-recommends libboost-all-dev sudo apt-get install -y libgflags-dev libgoogle-glog-dev liblmdb-dev ``` 2. 安装OpenCV3 * 详见[opencv.md](https://github.com/alisure-ml/Installation/blob/master/opencv.md) 3. 修改配置文件 * 复制配置文件 ``` cp Makefile.config.example Makefile.config ``` * 修改配置项 ``` # 取消注释 CPU_ONLY := 1 OPENCV_VERSION := 3 # 包含和库路径保持同下面一致 INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial /usr/share/OpenCV/3rdparty/lib/ ``` 4. 编译运行 ``` make all make test make runtest make pycaffe ``` 5. 配置环境变量 ``` vim ~/.bashrc ``` ``` export PYTHONPATH=/caffe path/python:$PYTHONPATH ``` * 遇到的问题 0. 注意权限问题!!! 1. 编译时出现OpenCV3问题(OpenCV已成功安装) ``` cv.imread().... 不存在。。。 ``` 原因电脑上OpenCV版本有点多(乱),没有设置好OpenCV。 * 解决办法 修改这一行,将`/usr/share/OpenCV/3rdparty/lib/`去掉: ``` LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial ``` 然后,解开这一行的注释 ``` USE_PKG_CONFIG := 1 ``` * linux下查看opencv版本 ``` pkg-config --modversion opencv ``` 2. make pycaffe ``` /usr/bin/ld: 找不到 -lboost_python3 ``` 首先去/usr/lib/x86_64-linux-gnu目录下查看是否有python3版本的libboost, 如果有类似libboost_python35.so但是没有libboost_python3.so则需要手动建立连接。 * 解决办法 ``` sudo ln -s libboost_python-py35.so libboost_python3.so ``` * reference * [python3编译caffe错误:cannot find -lboost_python3](http://blog.csdn.net/songyu0120/article/details/77895373) 3. make: Nothing to be done for `all' * 解决办法 ``` make clean ``` 4. 注意编译的时候python的版本。一定要在执行之前查看python的版本。毕竟工作站中的Linux系统的Python可能会比较乱,原因大家都懂的。 5. fatal error: hdf5.h:没有那个文件或目录 * 解决办法 ``` 将下句修改: INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include 为: INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial ``` * reference * [深度学习caffe:Ubuntu16.04安装指南(2)](http://www.cnblogs.com/AbcFly/p/6306201.html) <file_sep>/MultiGPUProblem.md ## 多块GPU遇到的问题 > 实验室最近领到了4台4GPU的工作站!!!!!!所以遇到了很多问题,大家很开心也很苦恼!!!!!!!!!!! 1. 设置高性能 > 没有用!!!!!!,可能和BIOS里的设置有关。 * [ubuntu系统切换高性能模式](https://blog.csdn.net/zhanghm1995/article/details/86484096) 2. GPU Lost > 目前原因未知 * 温度 * 功率 3. 性能测试代码 * [ImageNet training in PyTorch](https://github.com/pytorch/examples/tree/master/imagenet) <file_sep>/deb.md ## Install deb ## teamviewer ``` sudo dpkg -i teamviewer_13.1.3026_amd64.deb ``` ``` dpkg: error processing package teamviewer (--install): dependency problems - leaving unconfigured Processing triggers for gnome-menus (3.13.3-6ubuntu3.1) ... Processing triggers for desktop-file-utils (0.22-1ubuntu5.1) ... Processing triggers for bamfdaemon (0.5.3~bzr0+16.04.20160824-0ubuntu1) ... Rebuilding /usr/share/applications/bamf-2.index... Processing triggers for mime-support (3.59ubuntu1) ... Processing triggers for hicolor-icon-theme (0.15-0ubuntu1) ... Errors were encountered while processing: teamviewer ``` ``` sudo apt-get -f -y install sudo dpkg -i teamviewer_13.1.3026_amd64.deb ``` ## Chrome ``` sudo dpkg -i google-chrome-stable_current_63.0.3239.84_amd64.deb ``` ``` dpkg: error processing package google-chrome-stable (--install): dependency problems - leaving unconfigured Processing triggers for gnome-menus (3.13.3-6ubuntu3.1) ... Processing triggers for desktop-file-utils (0.22-1ubuntu5.1) ... Processing triggers for bamfdaemon (0.5.3~bzr0+16.04.20160824-0ubuntu1) ... Rebuilding /usr/share/applications/bamf-2.index... Processing triggers for mime-support (3.59ubuntu1) ... Processing triggers for man-db (2.7.5-1) ... Errors were encountered while processing: google-chrome-stable ``` ``` sudo apt-get -f -y install sudo dpkg -i google-chrome-stable_current_63.0.3239.84_amd64.deb ``` <file_sep>/PyTorch.md # PyTorch ## 方法一:pip安装 * Python3.6+pip安装cpu版本 ``` pip install http://download.pytorch.org/whl/cpu/torch-0.4.0-cp36-cp36m-win_amd64.whl ``` * Python3.5+pip安装cpu版本 ``` pip install http://download.pytorch.org/whl/cpu/torch-0.4.0-cp35-cp35m-win_amd64.whl ``` * Python3.6+pip安装gpu版本 ``` # 目前gpu版本支持cuda8.0,cuda9.0和cuda9.1,请选择对应的版本下载安装,不要同时执行下面三个命令! pip install http://download.pytorch.org/whl/cu80/torch-0.4.0-cp36-cp36m-win_amd64.whl pip install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp36-cp36m-win_amd64.whl pip install http://download.pytorch.org/whl/cu91/torch-0.4.0-cp36-cp36m-win_amd64.whl ``` * Python3.5+pip安装gpu版本 ``` # 目前gpu版本支持cuda8.0,cuda9.0和cuda9.1,请选择对应的版本下载安装,不要同时执行下面三个命令! pip install http://download.pytorch.org/whl/cu80/torch-0.4.0-cp35-cp35m-win_amd64.whl pip install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp35-cp35m-win_amd64.whl pip install http://download.pytorch.org/whl/cu91/torch-0.4.0-cp35-cp35m-win_amd64.whl ``` ## 方法二:Conda安装 * 如果你是Anaconda|Python用户,就不需要区分Python3.5和Python3.6,执行命令: ``` conda install pytorch -c pytorch ``` 就可以完成安装。不过这个默认安装的是cuda8.0的gpu版本,如果你需要安装cuda9.0或cuda1.0的gpu版本,请执行来进行安装: ``` conda install pytorch cuda90 -c pytorch # 或者 conda install pytorch cuda91 -c pytorch ``` ## 测试安装是否成功 ``` import torch print(torch.__version__) ``` 如果输出0.4.0,那么恭喜Windows下的PyTorch0.4.0安装成功! ## 最后需要安装 torchvision: ``` pip install torchvision ``` <file_sep>/Shadowsocks.md ## Shadowsocks的使用 ## 目前方案 > 到vultr上开一台服务器,然后下载东西,使用SSH传过来。 * wget `wget xxx` * curl `curl xxx --output xxx` * axel ``` sudo apt-get install axel axel xxx ``` ## 购买国外服务器 * [https://www.vultr.com/](https://www.vultr.com/), [https://my.vultr.com/](https://my.vultr.com/) * 注册(<EMAIL>, a*A) * 充值 * 选择最便宜的服务器并部署 * 此时,会获得服务器IP、用户名、密码等信息 ## 登录服务器 > 使用SSH客户端连接服务器:BvSshClient或Putty ## 配置防火墙 * 安装 ``` yum install firewalld systemctl start firewalld ``` * 启动 ``` firewall-cmd --permanent --zone=public --add-port=443/tcp firewall-cmd --reload ``` 上述端口号`443`要和Shadowsocks的`server_port`一样。 ## 服务器端安装Shadowsocks * `pip install shadowsocks` * 修改`openssl.py`文件:`vim /usr/local/lib/python3.6/site-packages/shadowsocks/crypto/openssl.py` 将所有`EVP_CIPHER_CTX_cleanup`替换成为`EVP_CIPHER_CTX_reset`(有两处)。 * `vim /etc/shadowsocks.json` ``` { "server":"0.0.0.0", "server_port":443, "local_address": "127.0.0.1", "local_port":1080, "password":"<PASSWORD>", "timeout":300, "method":"aes-256-cfb", "fast_open": false } ``` * 启动Shadowsocks服务 前台启动: ``` ssserver -c /etc/shadowsocks.json ``` 后台启动: ``` nohup ssserver -c /etc/shadowsocks.json & ``` ## 客户端配置 * 下载`Shadowsocks` * 按以下操作设置: 打开->服务器->编辑服务器->设置服务器地址、端口、密码、加密方式、代理端口等(和服务器端的shadowsocks.json设置一样)。 * 设置`系统代理`为`全局代理`。 如果不想用的话,可以设置为`禁用`。 ## 浏览器设置 * 下载插件`SwitchyOmega` * 选择`系统代理`即可,如果不想使用则选择`直接代理`。 ## Reference * [国外服务器如何选择以及搭建ShadowSocks教程](https://segmentfault.com/a/1190000015387870?utm_source=tag-newest) <file_sep>/GitUpSpeed.md ### Linux ## 1 ``` sudo gedit /etc/hosts ``` ``` 192.168.127.12 codeload.github.com 172.16.17.32 github.com 172.16.31.10 github.githubassets.com 172.16.17.32 github.global.ssl.fastly.net 172.16.17.32 s3.amazonaws.com ``` ## 2 ``` sudo /etc/init.d/networking restart ``` ### Windows > 现象:`ping github.com`不通 * 在`C:\Windows\System32\drivers\etc\hosts`中加入一下内容 ``` 172.16.17.32 github.com 192.168.127.12 assets-cdn.github.com 172.16.17.32 assets-cdn.github.com 172.16.31.10 assets-cdn.github.com 192.168.127.12 assets-cdn.github.com 172.16.31.10 github.githubassets.com 172.16.31.10 github.githubassets.com 172.16.58.3 github.githubassets.com 192.168.127.12 github.githubassets.com 172.16.17.32 github.global.ssl.fastly.net ``` * 刷新 ``` ipconfig /flushdns //清除DNS缓存内容 ipconfig /displaydns //显示DNS缓存内容 ``` <file_sep>/CPP.md ## Ubuntu下学习C++ ### 环境 * [Ubuntu快速搭建C++开发环境(VS Code编辑器)](https://www.jianshu.com/p/2b6a3d41f641?night=1) * [解决办法:无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系](https://blog.csdn.net/quantum7/article/details/86416130) * [在Ubuntu下搭建C/C++编程环境](https://blog.csdn.net/weixin_35477207/article/details/78165411) * [gcc: error trying to exec 'cc1plus': execvp: 没有那个文件或目录](https://blog.csdn.net/junweicn/article/details/80942928) * [ubuntu vscode上使用cmake、编译、调试](https://www.cnblogs.com/civftor/p/9860885.html) <file_sep>/dev_disk.md # 磁盘管理 ## 挂载磁盘 > 假设设备为`/dev/sdc1`,要挂载的地方为`/home/ubuntu/ALISURE` 1. 查看是否挂载 ``` df -h ``` 原则上不会显示该磁盘,若出现异常情况,则进行卸载: ``` sudo umount /dev/sdc1 /home/ubuntu/ALISURE ``` 2. 查看是否识别磁盘 ``` sudo fdisk -l ``` 原则上会显示该磁盘。 3. 磁盘格式化(请跳过该步骤,若确实需要格式化磁盘请三思后谨慎操作!!!) ``` sudo mkfs -t ext4 /dev/sdc1 ``` 4. 挂载磁盘 ``` sudo mount /dev/sdc1 /home/ubuntu/ALISURE ``` 可以指定磁盘格式: `ext4`,`vfat`(适用于FAT32),如: ``` sudo mount -t ext4 /dev/sdc1 /home/ubuntu/ALISURE ``` 5. 配置硬盘在系统启动自动挂载(如果是U盘的话,此步不需要) ``` sudo vim /etc/fstab ``` 加入: ``` /dev/sdc1 /home/ubuntu/ALISURE ext4 defaults 0 0 ``` 6. 挂载后设置权限 > 两种解决方案 1. FAT32不支持POSIX权限系统,可以把FAT32格式的U盘格式化为NTFS、Ext3或Ext4格式 2. 或者是挂载时加上参数`-o umask=000`: ``` sudo mount -o umask=000 /dev/sdc1 /home/ubuntu/ALISURE ``` 7. 挂载后文件名汉字乱码 > 挂载时加上参数`-o iocharset=utf8` ``` sudo mount -o umask=000 -o iocharset=utf8 /dev/sdc1 /home/ubuntu/ALISURE ``` 8. 弹出磁盘 > 执行弹出之后,执行`sudo fdisk -l`就识别不了该磁盘了,因为已经弹出来了重新拔出插上才可以。 ``` sudo eject /dev/sdc1 ``` ## 一些命令 ### gparted > gparted是ubuntu上很好的分区调整工具 * 安装 ``` sudo apt-get install gparted ``` * 使用 ``` sudo gparted ``` ### df * 常用命令, 可以查看各个盘分区使用及挂载情况. ``` df ``` * 以GB之类显示而非字节 ``` df -h ``` * 查看分区的文件系统类型 ``` df -T ``` ### lsblk 可以查看各个硬盘以及相应的分区和挂载情况 ``` lsblk ``` ### fdisk 可以查看各个硬盘的分区, 扇区情况等更详尽的信息 ``` sudo fdisk -l ``` ## Inference * [Ubuntu--硬盘的挂载与卸载](https://www.cnblogs.com/cappuccinom/p/8971999.html) * [linux系统挂载U盘,中文文件名乱码解决方案](https://www.cnblogs.com/zhouqinxiong/p/3497293.html) * [解决U盘挂载到linux上没有写和执行的权限](https://blog.csdn.net/zgy0808/article/details/51082087) * [Ubuntu命令行弹出光驱的方法](https://www.cnblogs.com/QuLory/archive/2012/10/23/2735489.html) <file_sep>/Anaconda.md # Anaconda ## 环境错乱 > [conda环境下pip install 无法安装到指定conda环境中](https://www.cnblogs.com/bigtreei/p/15094293.html) ``` 1. sudo vim /home/ubuntu/.conda/envs/alisure36/lib/python3.6/site.py # 默认 USER_SITE、USER_BASE 都为None USER_SITE = '/home/ubuntu/.conda/envs/alisure36/lib/python3.6/site-packages' USER_BASE = '/home/ubuntu/.conda/envs/alisure36' 2. which /home/ubuntu/.conda/envs/alisure36/bin/pip 3. /home/ubuntu/.conda/envs/alisure36/bin/pip install xxx ``` ## 清华大学的源 > [pypi 镜像使用帮助](https://mirrors.tuna.tsinghua.edu.cn/help/pypi/) * 临时使用 ``` pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package ``` 注意,`simple`不能少, 是`https`而不是`http`。 * 设为默认(推荐使用该方法) 升级`pip`到最新的版本(>=10.0.0)后进行配置: ``` pip install pip -U pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple ``` 如果您到`pip`默认源的网络连接较差,临时使用本镜像站来升级`pip`: ``` pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pip -U ``` ## 安装 * 下载:[Anaconda Distribution](https://www.anaconda.com/distribution/) * 安装:直接按照要求安装即可 ``` sh ./Anaconda3-2019.07-Linux-x86_64.sh ``` 有可能需要执行下列命令使环境变量有效: ``` source ~/.bashrc ``` * 检查更新 安装完成后,我们还需要对所有工具包进行升级,以避免可能发生的错误。 ``` conda upgrade --all ``` ## 管理Python包 安装一个 package: ``` conda install package_name ``` 这里 package_name 是需要安装包的名称。 你也可以同时安装多个包,比如同时安装numpy 、scipy 和 pandas,则执行如下命令: ``` conda install numpy scipy pandas ``` 你也可以指定安装的版本,比如安装 1.1 版本的 numpy : ``` conda install numpy=1.10 ``` 移除一个 package: ``` conda remove package_name ``` 升级 package 版本: ``` conda update package_name ``` 查看所有的 packages: ``` conda list ``` 如果你记不清 package 的具体名称,也可以进行模糊查询: ``` conda search search_term ``` ## 管理Python环境 > 新的环境保存在`~/anaconda3/envs`或`~/.conda/envs`中 默认的环境是 root,你也可以创建一个新环境: ``` conda create -n env_name list of packages ``` 其中 -n 代表 name,env_name 是需要创建的环境名称,list of packages 则是列出在新环境中需要安装的工具包。 例如,当我安装了 Python3 版本的 Anaconda 后,默认的 root 环境自然是 Python3,但是我还需要创建一个 Python 2 的环境来运行旧版本的 Python 代码,最好还安装了 pandas 包,于是我们运行以下命令来创建: ``` conda create -n py2 python=2.7 pandas ``` 细心的你一定会发现,py2 环境中不仅安装了 pandas,还安装了 numpy 等一系列 packages,这就是使用 conda 的方便之处,它会自动为你安装相应的依赖包,而不需要你一个个手动安装。 进入名为 env_name 的环境: ``` source activate env_name ``` 或者 ``` conda activate env_name ``` 退出当前环境: ``` source deactivate ``` 或者 ``` conda deactivate ``` 另外注意,在 Windows 系统中,使用 activate env_name 和 deactivate 来进入和退出某个环境。 删除名为 env_name 的环境: ``` conda env remove -n env_name ``` 显示所有的环境: ``` conda env list ``` 当分享代码的时候,同时也需要将运行环境分享给大家,执行如下命令可以将当前环境下的 package 信息存入名为 environment 的 YAML 文件中。 ``` conda env export > environment.yaml ``` 同样,当执行他人的代码时,也需要配置相应的环境。这时你可以用对方分享的 YAML 文件来创建一摸一样的运行环境。 ``` conda env create -f environment.yaml ``` ## condarc 配置代理 `~/.condarc` > [configuration/use-condarc](https://conda.io/projects/conda/en/latest/user-guide/configuration/use-condarc.html) ## 什么是 Anaconda > Anaconda是专注于数据分析的Python发行版本,包含了conda、Python等190多个科学包及其依赖项。 conda 是开源包(packages)和虚拟环境(environment)的管理系统。 * packages 管理: 可以使用 conda 来安装、更新 、卸载工具包 ,并且它更关注于数据科学相关的工具包。 * 虚拟环境管理: 在conda中可以建立多个虚拟环境,用于隔离不同项目所需的不同版本的工具包,以防止版本上的冲突。 ## Anaconda 的优点 > 省时省心、分析利器。 * 省时省心: Anaconda通过管理工具包、开发环境、Python版本,大大简化了你的工作流程。不仅可以方便地安装、更新、卸载工具包,而且安装时能自动安装相应的依赖包,同时还能使用不同的虚拟环境隔离不同要求的项目。 * 分析利器: 适用于企业级大数据分析的Python工具。其包含了720多个数据科学相关的开源包,在数据可视化、机器学习、深度学习等多方面都有涉及。不仅可以做数据分析,甚至可以用在大数据和人工智能领域。 ## Reference * [致Python初学者:Anaconda入门使用指南](http://python.jobbole.com/87522/) <file_sep>/nohup.md ### nohup > 后台挂起执行程序 * `nohup python train.py > ./3.log 2>&1 &` * `PYTHONPATH=. CUDA_VISIBLE_DEVICES=0,1,2,3 nohup python -m torch.distributed.launch --nproc_per_node=4 --master_port=12431 train.py --launcher pytorch > ./work_dirs/3.log 2>&1 &` ### 处理流程 ``` sudo fdisk -l | grep sd sudo mkdir /media/ubuntu/XXX sudo mount /dev/sdXX /media/ubuntu/XXX nohup python train.py > ./3.log 2>&1 & sudo umount /media/ubuntu/XXX ``` <file_sep>/scp.md scp -r E:\data\SS\coco2014\train2014.zip ubuntu@10.193.251.89:/mnt/4T/Data/COCO <file_sep>/DeepLearningEnviroment.md # 安装深度学习环境 ## 安装系统 * 制作系统盘 * 安装系统 * 更新软件 启动系统后会自动弹出更新软件,或者到设置中进行更新检查。 * 更新Source [apt更改为国内源](https://www.jianshu.com/p/71ddb83adc1e) * 安装`vim`,`gcc`,`make`,`lightdm`,`git` ``` sudo apt install vim sudo apt install gcc sudo apt install make sudo apt install lightdm sudo apt install git ``` * 更新`apt` ``` sudo apt-get update sudo apt-get upgrade ``` ## 安装Anaconda.md * 下载、安装Anaconda:请参考[Anaconda.md](https://github.com/alisure-ml/Installation/blob/master/Anaconda.md) * 创建环境 ``` conda create -n alisure36tf python=3.6 ``` * `pypi`镜像:[pypi 镜像使用帮助](https://mirrors.tuna.tsinghua.edu.cn/help/pypi/) ``` pip install pip -U pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple ``` ## 安装NVIDIA显卡驱动 * 下载显卡驱动:[Download Drivers](https://www.nvidia.com/Download/index.aspx) 选择匹配的版本即可,例如`NVIDIA-Linux-x86_64-430.50.run` * 安装显卡驱动:请参考[NVIDIA.md](https://github.com/alisure-ml/Installation/blob/master/NVIDIA.md) ## 安装CUDA * 下载CUDA:[cuda-toolkit-archive](https://developer.nvidia.com/cuda-toolkit-archive) 选择版本,例如`cuda_10.0.130_410.48_linux.run`。 * 安装CUDA,请参考:[CUDA.md](https://github.com/alisure-ml/Installation/blob/master/CUDA.md) ## 安装cudnn * 请参考:[CUDA.md/安装cudnn](https://github.com/alisure-ml/Installation/blob/master/CUDA.md#%E5%AE%89%E8%A3%85cudnn) ## 安装`pycharm` * 下载最新版:[pycharm](https://www.jetbrains.com/pycharm/download/#section=linux) * 解压缩到相应的目录 * 添加程序快捷方式:请参考:[desktop_entry.md](https://github.com/alisure-ml/Installation/blob/master/desktop_entry.md) 还需要添加到收藏夹。 * 破解 > 将 `0.0.0.0 account.jetbrains.com` 添加到 `/etc/hosts`(`sudo gedit /etc/hosts`) 文件中,然后再搜索密钥。 1. [学生授权申请方式](https://sales.jetbrains.com/hc/zh-cn/articles/207154369-%E5%AD%A6%E7%94%9F%E6%8E%88%E6%9D%83%E7%94%B3%E8%AF%B7%E6%96%B9%E5%BC%8F) 2. [lanyus](http://idea.lanyus.com/) 3. [http://lookdiv.com](http://lookdiv.com) 钥匙:1211268069 ## `Tensorflow`环境 * 创建环境 ``` conda create -n alisure36tf python=3.6 conda activate alisure36tf pip install pip -U pip install tensorflow-gpu ``` * 测试环境 ``` import tensorflow as tf sess = tf.Session() a = tf.constant(1) b = tf.constant(2) print(sess.run(a+b)) ``` ## `PyTorch`环境 * 创建环境 ``` conda create -n alisure36torch python=3.6 conda activate alisure36torch pip install pip -U pip install torch torchvision ``` * 测试环境 ``` import torch print(torch.cuda.is_available()) ``` ## Problem * [Ubuntu安装软件时Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)的解决方案](https://blog.csdn.net/qq_22999067/article/details/92851100) <file_sep>/flownet2-tf.md ## make的问题 ### 1 ``` ModuleNotFoundError: No module named 'tensorflow' ``` 忘记激活环境了: ``` source activate alisure36 ``` ### 2 ``` error: #error -- unsupported GNU version! gcc versions later than 6 are not supported! ``` gcc版本太高,所以要降级: ``` sudo apt-get install gcc-6 sudo apt-get install g++-6 ``` 查看安装的gcc: ``` gcc -v ls /usr/bin/gcc* ``` 方法一:更改gcc的优先级: ``` sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-6 ``` 方法二: ``` sudo ln -s /usr/bin/gcc-7 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-7 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-7 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-7 /usr/bin/gcc-ranlib -f ```` ``` sudo ln -s /usr/bin/gcc-6 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-6 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-6 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-6 /usr/bin/gcc-ranlib -f ```` ``` sudo ln -s /usr/bin/gcc-5 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-5 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-5 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-5 /usr/bin/gcc-ranlib -f ``` 参考:[https://blog.csdn.net/qq_28660035/article/details/78703095](https://blog.csdn.net/qq_28660035/article/details/78703095) ### 3 ``` /home/ubuntu/miniconda3/envs/alisure36/lib/python3.6/site-packages/tensorflow/include/tensorflow/core/util/cuda_device_functions.h:32:31: fatal error: cuda/include/cuda.h: No such file or directory #include "cuda/include/cuda.h" ``` 在nvcc中加入下列搜索路径: ``` -I"/usr/local" ``` * 原因分析 当打开`cuda_device_functions.h`会发现: ``` #include <algorithm> #include <complex> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "cuda/include/cuda.h" #include "tensorflow/core/platform/types.h" ``` 所以,是没有把`/usr/local`加入到搜索路径中。 ### 4 ``` /home/ubuntu/miniconda3/envs/alisure36/lib/python3.6/site-packages/tensorflow/include/absl/strings/string_view.h(501): error: constexpr function return is non-constant ``` 在nvcc中加入`-DNDEBUG`即可。 ``` -DNDEBUG ``` 解决办法来自:[https://github.com/tensorflow/tensorflow/issues/22766](https://github.com/tensorflow/tensorflow/issues/22766) ### 5 ``` /home/ubuntu/miniconda3/envs/alisure36/lib/python3.6/site-packages/tensorflow/include/tensorflow/core/util/cuda_device_functions.h(523): error: calling a constexpr __host__ function("real") from a __device__ function("CudaAtomicAdd") is not allowed. The experimental flag '--expt-relaxed-constexpr' can be used to allow this. ``` 按照提示,在nvcc中加入`--expt-relaxed-constexpr`即可。 ``` --expt-relaxed-constexpr ``` ### 总结 ``` GPUCC = nvcc CFLAGS = -std=c++11 -I$(TF_INC) -I"$(CUDA_HOME)/include" -I"/usr/local" -DGOOGLE_CUDA=1 --expt-relaxed-constexpr -DNDEBUG ``` 主要是对gcc不熟,对nvcc命令不熟。以后加强在这方面的学习。 <file_sep>/mount_tmpfs.md ## 加速训练 > 将数据挂载到内存虚拟硬盘,从而加快训练。 ## 步骤 1. 创建目录 ``` sudo mkdir /mnt/4T/tmp_train_data ``` 2. 挂载 ``` sudo mount -t tmpfs -o size=40G tmpfs /mnt/4T/tmp_train_data ``` 3. 查看 ``` df -h ``` 4. 将数据放入使用`/mnt/4T/tmp_train_data`即可 ## Reference 1. [Ubuntu内存虚拟硬盘——tmpfs](https://blog.csdn.net/qq_29912325/article/details/108666516) 2. [liunx 内存文件 tmpfs](https://www.cnblogs.com/zhangeamon/p/5457432.html) 3. [Linux mount命令](https://www.runoob.com/linux/linux-comm-mount.html) 4. [deepinsight/insightface](https://github.com/deepinsight/insightface/blob/master/challenges/iccv21-mfr/tutorial_pytorch_cn.md) <file_sep>/mount.md # Ubuntu挂载U盘 ## 检测存储设备名称 ``` sudo fdisk –l ``` 如查看到设备名为sdb1 ## 挂载存储设备sdb1到挂载点/mnt目录 ``` sudo mount /dev/sdb1 /mnt ``` ## 访问/mnt ``` cd /mnt ``` 可以进行与Ubuntu端其他文件夹一样的操作了 ## 卸载/mnt ``` sudo umount /mnt ``` # Reference * [ubuntu linux读取U盘](https://blog.csdn.net/mengxiangjia_linxi/article/details/78067065) <file_sep>/gcc.md ## 若发生一下错误,需要对gcc降级 ``` error: #error -- unsupported GNU version! gcc versions later than 6 are not supported! ``` gcc版本太高,所以要降级: ``` sudo apt-get install gcc-6 sudo apt-get install g++-6 ``` 查看安装的gcc: ``` gcc -v ls /usr/bin/gcc* ``` 方法一:更改gcc的优先级: ``` sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-6 ``` 方法二:创建软链接: ``` sudo ln -s /usr/bin/gcc-8 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-8 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-8 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-8 /usr/bin/gcc-ranlib -f ```` ``` sudo ln -s /usr/bin/gcc-7 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-7 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-7 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-7 /usr/bin/gcc-ranlib -f ```` ``` sudo ln -s /usr/bin/gcc-6 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-6 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-6 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-6 /usr/bin/gcc-ranlib -f ```` ``` sudo ln -s /usr/bin/gcc-5 /usr/bin/gcc -f sudo ln -s /usr/bin/gcc-ar-5 /usr/bin/gcc-ar -f sudo ln -s /usr/bin/gcc-nm-5 /usr/bin/gcc-nm -f sudo ln -s /usr/bin/gcc-ranlib-5 /usr/bin/gcc-ranlib -f ``` 参考:[https://blog.csdn.net/qq_28660035/article/details/78703095](https://blog.csdn.net/qq_28660035/article/details/78703095) <file_sep>/desktop_entry.md # 添加应用程序快捷方式 ## 以`pycharm`为例 ``` cd /usr/share/applications sudo gedit PyCharm.desktop ``` ``` [Desktop Entry] Version=1.0 Name=PyCharm Exec=/home/ubuntu/pycharm-2019.2.3/bin/pycharm.sh Terminal=false Icon=/home/ubuntu/pycharm-2019.2.3/bin/pycharm.png Type=Application Categories=Development ``` ## Reference * [ubuntu下将应用程序快捷方式添加到启动器](https://blog.csdn.net/weixin_38437243/article/details/78259475) <file_sep>/vcvarsall.md # vcvarsall > 在Win10系统中,执行`pyhton setup.py xxx`时报错:`error: Unable to find vcvarsall.bat` * 环境:Win10 + python3.5 ## 解决办法 * 安装VS2017/VS2015:勾选v140工具集 ## 在解决过程中可能会出现下列错误 ``` fatal error LNK1158: cannot run "rc.exe" error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158 ``` * 解决办法:在`C:\\Program Files (x86)`下搜索`rc.exe`,将所在目录添加到`PATH`环境变量中即可。 比如我的是:`C:\Program Files (x86)\Windows Kits\10\bin\10.0.17134.0\x86` ## Inference * [python3.5 安装报错error: Unable to find vcvarsall.bat](https://www.cnblogs.com/bigvase/p/6512476.html) * [Windows下安装Python扩展模块提示“Unable to find vcvarsall.bat”的问题](https://www.cnblogs.com/yyds/p/7065637.html) * [How to deal with the pain of “unable to find vcvarsall.bat”](https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat) * [error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158](https://www.jianshu.com/p/957621736210) <file_sep>/NVIDIA.md # NVIDIA ## 监控 ``` watch -n1 -d nvidia-smi ``` ## Ubuntu循环登录问题 > 以前的循环登录问题都是实验室另一位大神解决,这次他去陪女朋友了,所以只好自己试着解决了。 1. 进入文本模式,登录 ``` CTRL + ALT + F1 ``` 2. 卸载之前的驱动 ``` sudo apt-get remove nvidia-* sudo apt-get autoremove ``` 3. 从`.run`文件卸载驱动 ``` sudo nvidia-uninstall ``` 4. 此时,重启可正常登录(界面刷新会变慢) ``` sudo reboot ``` 5. 禁用nouveau驱动(具体见下面的`Problem`,不确定是否是可选) 6. 重新安装驱动 下载驱动:[https://www.nvidia.com/Download/index.aspx](https://www.nvidia.com/Download/index.aspx) ``` CTRL + ALT + F1 sudo service lightdm stop sudo chmod +x NVIDIA-Linux-x86_64-xxx.xx.run sudo ./NVIDIA-Linux-x86_64-xxx.xx.run -no-x-check -no-nouveau-check -no-opengl-files ``` 7. 启动`lightdm` ``` sudo service lightdm restart ``` 8. 验证是否安装成功 ``` nvidia-smi ``` ### Problem * `Building kernel modules`出错 安装驱动过程中出现下列错误: ``` ERROR: An error occurred while performing the step: "Building kernel modules". See /var/log/nvidia-installer.log for details. ``` 可能的原因:驱动版本和系统内核版本不匹配。 解决办法:下载最新版本的驱动(或者下载补丁) * 驱动的版本 下载驱动时可能找不到版本,比如我的是`GeForce GTX TITAN X`/`Ubuntu 16.04`,直接查找找不到对应的驱动。 我就随便多选了几个,发现有一个支持该GPU,然后就下载使用了。 * 在解决问题中禁用了nouveau驱动 1. 用`vim`打开`blacklist.conf`文件 ``` sudo vim /etc/modprobe.d/blacklist.conf ``` 2. 在文末添加下列内容 ``` blacklist nouveau options nouveau modeset=0 ``` 3. 使配置生效 ``` sudo update-initramfs -u ``` 4. 重启 ``` sudo reboot ``` 5. 验证是否禁用成功(没有输出即成功) ``` lsmod | grep nouveau ``` * 系统更新后加载不了桌面 解决方法见链接:[ubuntu16.04更新系统后桌面出错的解决办法](https://blog.csdn.net/zhangxue2017/article/details/79937114) ### Reference * [Ubuntu 16.04 用户登录界面死循环问题的解决](http://blog.csdn.net/ssmixi/article/details/73483795) * [Ubuntu系统安装CUDA或NVIDIA驱动后出现循环登录问题的Solution (附:building kernel modules error)](http://blog.csdn.net/xl928471061/article/details/78130165) * [安装Nvidia显卡驱动和CUDA](http://blog.csdn.net/bluewhalerobot/article/details/73658267) * [Ubuntu 16.04安装NVIDIA驱动](http://blog.csdn.net/cosmoshua/article/details/76644029) <file_sep>/CUDA.md ## 安装CUDA和CUDNN ### 安装NVIDIA驱动 可以参考:[Installation/NVIDIA.md](https://github.com/alisure-ml/Installation/blob/master/NVIDIA.md) ### 安装CUDA * 下载完CUDA 9.0之后执行如下语句,运行.run文件 ``` sudo sh cuda_9.0.176_384.81_linux.run ``` 单击回车,一路往下运行。 ``` Do you accept the previously read EULA? accept/decline/quit: accept Install NVIDIA Accelerated Graphics Driver for Linux-x86_64 384.81? (y)es/(n)o/(q)uit: n # 选择否,因为已经安装好驱动程序了 Install the CUDA 9.0 Toolkit? (y)es/(n)o/(q)uit: y Enter Toolkit Location [ default is /usr/local/cuda-9.0 ]: # 记住安装位置, 默认是安装在/usr/local/cuda文件夹下 Do you want to install a symbolic link at /usr/local/cuda? (y)es/(n)o/(q)uit: n # 根据需要选择y或者n Install the CUDA 9.0 Samples? (y)es/(n)o/(q)uit: y Enter CUDA Samples Location [ default is /home/ubuntun ]: Installing the CUDA Toolkit in /usr/local/cuda-9.0 ... Missing recommended library: libGLU.so Missing recommended library: libXmu.so Installing the CUDA Samples in /home/ubuntun ... Copying samples to /home/ubuntun/NVIDIA_CUDA-9.0_Samples now... Finished copying samples. ``` * 配置环境变量,方法一(所有用户,建议使用方法二): 运行如下命令打开profile文件 ``` sudo gedit /etc/profile ``` 打开文件后在文件末尾添加路径,也就是安装目录,命令如下: ``` export PATH=/usr/local/cuda-9.0/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64:$LD_LIBRARY_PATH ``` 保存,然后重启电脑: ``` sudo reboot ``` * 配置环境变量,方法二(当前用户,建议使用该方法): 运行如下命令打开.bashrc文件 ``` sudo gedit ~/.bashrc ``` 打开文件后在文件末尾添加路径,也就是安装目录,命令如下: ``` export PATH=/usr/local/cuda-9.0/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64:$LD_LIBRARY_PATH ``` 保存,然后使之生效: ``` source ~/.bashrc ``` * 测试安装是否成功 ``` cd /usr/local/cuda/samples/1_Utilities/deviceQuery sudo make ./deviceQuery ``` 如果显示关于GPU的信息就是成功了。 * 多个`CUDA`之间切换 ``` sudo rm -rf cuda sudo ln -s /usr/local/cuda-x.x /usr/local/cuda ``` ### 安装cudnn > Inference: [Install_AND_path/install nvidiaDriver_cuda_cudnn.md](https://github.com/waallf/Install_AND_path/blob/master/install%20nvidiaDriver_cuda_cudnn.md) 1. 下载对应版本的[cudnn](https://developer.nvidia.com/cudnn) 2. 需要下载两个版本,runtime版和developer版 ``` cuDNN Runtime Library for Ubuntu18.04 (Deb) cuDNN Developer Library for Ubuntu18.04 (Deb) ``` 3. 将下载的文件格式改为.tgz,然后解压 4. 一个里版本里面有头文件(在include中),一个里面有动态连接文件(在lib中) * 将`include`中头文件`cudnn.h`拷贝到`/usr/local/cuda/include` * 将`lib`中的动态连接文件拷贝到`/usr/local/cuda/lib64` 5. 添加环境变量 > 如果添加过环境变量,就可以不添加。可以通过`echo $LD_LIBRARY_PATH`查看是否添加。 运行如下命令打开.bashrc文件 ``` sudo gedit ~/.bashrc ``` 打开文件后在文件末尾添加路径,也就是安装目录,命令如下: ``` export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH ``` 保存,然后使之生效: ``` source ~/.bashrc ``` 6. 对拷贝进来的两个动态连接库创建软链接 ``` cd /usr/local/cuda/lib64/ sudo ln -s libcudnn.so.7 libcudnn.so # sudo ln -s libcudnn.so.7.x.x libcudnn.so.7 ``` ### 问题一:Pycharm中找不到cuda > Inference: [Install_AND_path/无法找到cuda9.0](https://github.com/waallf/Install_AND_path/blob/master/%E6%97%A0%E6%B3%95%E6%89%BE%E5%88%B0cuda9.0.md) 在添加cuda环境变量后,一直无法找到cuda9.0: 1. 有可能是在sudo下执行的,需要在sudo下添加环境变量 2. 添加lib 打开文件`cuda.conf`: ``` sudo gedit /etc/ld.so.conf.d/cuda.conf ``` 添加如下内容并保存: ``` /usr/local/cuda/lib64 /lib /usr/lib /usr/lib32 ``` ### 问题二:ImportError: libcublas.so.x.x: cannot open shared object file: No such file or directory > Inference: [ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory](https://blog.csdn.net/qq_34374211/article/details/81018320) * 确保安装了对应版本的`CUDA`:否则,回到`安装CUDA`的步骤 * 确保路经在`PATH`环境变量中(`echo $PATH`):否则,回到安装`配置环境变量`的步骤 * 如果还不行,检查`/usr/local/cuda-x.x/lib64`下是否有libcublas.so.x.x:如果有,则`sudo ldconfig /usr/local/cuda-x.x/lib64` <file_sep>/paper_remove_cite_fuhao.py """ 用于检查英语语法时移除引用和符号,需一段一段来。 """ while True: s = input() arr = s.split("\cite{") result = [arr[0].strip()] for one in arr[1:]: a = one.split("}", 1)[1].strip() result.append(a) pass result = "".join(result) print() print() print(result) print() print() while "$" in result: arr = result.split("$", 1) result = arr[0] + "m" + arr[1].split("$", 1)[1] print(result) print() print() pass <file_sep>/README.md # Installation 安装遇到的软件或者框架 <file_sep>/opencv.md # opencv ## 方法一 * pip install opencv-python ## 方法二 * 安装OpenCV的依赖包 ``` # 编译器 sudo apt-get install build-essential # 必须安装 sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodedec-dev libavformat-dev libswscale-dev # 可选安装 sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev ``` * 从源代码构建OpenCV 下载opencv:[https://opencv.org/releases.html](https://opencv.org/releases.html) 解压后运行以下命令: ``` mkdir build cd build cmake –D CMAKE_BUILD_TYPE=Release –D CMAKE_INSTALL_PREFIX=/usr/local .. make make install ``` * 若在python下运行opencv库,必须安装如下 ``` sudo apt-get install python-opencv ``` 完成上述流程即安装完成 * 进行测试,检查opencv是否安装成功 到opencv自带的samples文件夹,然后运行一个.py的文件,如果没有提示出错则正确。例如: ``` python kmeans.py ``` 则会出现kmeans的分类图形。 <file_sep>/remote_pycharm.md ## Pycharm远程 ## 在Pycharm中调试python -m > [在Pycharm中调试python -m](https://muzhan.blog.csdn.net/article/details/120748810?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7.pc_relevant_antiscan&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7.pc_relevant_antiscan&utm_relevant_index=11) 1. Script: `torch.distributed.launch`的路径 2. Script parameters: 所有的参数 3. Working directory: 待执行脚本的目录 ## 服务器端 > 需要有ssh和ssh-server的支持 ``` sudo apt install openssh-server ``` > 若是连接不上,需要启动ssh > ``` /etc/init.d/ssh start ``` | 主机 | 域名 | 负责人 | |---|---|---| | TitanX + 48core + 256G | titanx.ddns.net | - | | TitanX + 48core + 256G | action101.ddns.net | - | | RTX2080Ti + 32core + 128G | faceid.ddns.net | - | | RTX2080Ti + 32core + 128G | zshot.ddns.net | - | ## 客户端(PyCharm 2017) 1. GitHub上新建项目并在PC端下载项目 > 由于我的项目都同步到github上,所以先从这里开始。不在github上,直接下一步即可。 ``` git clone https://github.com/ALISURE/pycharm_remote_demo.git ``` 2. 用pycharm打开项目 3. 配置 * Tools -> Deployment -> Configuration 1. 输入名称,选择Type:SFTP 2. 配置:Connection 和 Mappings * Project Interpreter 1. 在Project配置即可:Add Remote -> SSH Credentials 2. 添加Host、User name、Password、Python interpreter path * Path mappings > 配置路径映射关系即可 4. 测试 * 新建 `demo.py` ``` import platform if __name__ == '__main__': print("os.platform={}".format(platform.platform())) pass ``` * 上传: 在需要上传的文件上`右键 -> Upload to XXXX` 即可 * 运行:输出类似信息即可 ``` os.platform=Linux-4.15.0-106-generic-x86_64-with-debian-buster-sid ``` 5. 控制台 > Tools -> Start SSH Session... <file_sep>/Node.md ## Node ## 下载node [https://nodejs.org/en/](https://nodejs.org/en/) ## Install node and npm ``` tar xf node-....-linux-x64 cd node-....-linux-x64 ln -s ~/alisure/node/node-....-linux-x64/bin/node /usr/local/bin/node ln -s ~/alisure/node/node-....-linux-x64/bin/npm /usr/local/bin/npm ``` <file_sep>/EquipmentDescription.md ## 实验室设备情况说明 > 用来记录实验室设备的故事 ### 门口的工作站 > 该工作站的系统比较老旧,需要重装系统! 1. 重大更新:(2019-11-30) > 系统环境:`CUDA9.2`、`Anaconda2`、`NVIDIA-Linux-x86_64-390.87` > 由于跑`tensorflow`的代码,需要`tensorflow 1.11.0`,从而需要`CUDA9.0`。另一方面,又想安装`Anaconda3`(`Anaconda3-2019.07-Linux-x86_64.sh`)。 * 安装`CUDA9.0`后不管用,折腾了半天,因此想卸载`CUDA9.2`。 * `CUDA9.2`卸载之后,又重新安装`NVIDIA`显卡驱动(`NVIDIA-Linux-x86_64-390.87.run`),之后安装`CUDA9.0`,然后就**神奇的可用了**!!!! 注意,此时没有安装`cudnn`。 > 至此,虽然可用了,但是非常迷惑!!!! * 然后就想着安装了`cudnn`了事。安装的版本是`libcudnn7_7.0.5.15-1+cuda9.0_amd64`,结果报错: ``` Loaded runtime CuDNN library: 7.0.5 but source was compiled with: 7.2.1. ``` > 这么看来,`tensorflow`运行的时候去`/usr/local/cuda-9.0`中寻找了`cudnn`,只不过因为版本不对,报了错误。 因此,猜测肯定在系统中的某个地方有正确的`cudnn`。 * 果然,找到了可疑的地方:`Anaconda2`的`pkgs`中存在`cudnn`。 可能的原因是:运行时调用的`cudnn`是`Anaconda2`中的`cudnn`。 > reference: [Tensorflow的大坑](https://blog.csdn.net/Tilamy/article/details/88616201) * 最终,没有安装`cudnn`,先凑合着用吧,以后会重装系统的。毕竟还有格权限乱用的问题没有解决!!!
f8d9a1a9f22b78e312bf8f63eb6336d2885e22d9
[ "Markdown", "Python" ]
29
Markdown
alisure-ml/Installation
e93f4f0584da28922884bf1106e066d706de9bae
5aa01c912119c19266688566b1924f258b871a1f
refs/heads/master
<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N_P; int N_G; int order[1000]; int wei[1000]; struct pro{ int place; int weight; }pro[1000]; int winner[1000]; int max(int pos, int num){ int i; int index=pos; int max=-1; for(i=pos;i<pos+num;i++){ if(pro[winner[i]].weight>max){ max=pro[winner[i]].weight; index=winner[i]; } } return index; } int main(int argc, char *argv[]){ int i, j; int temp; int group; int win; int count; int num; scanf("%d%d",&N_P,&N_G); for(i=0;i<N_P;i++) scanf("%d",&wei[i]); for(i=0;i<N_P;i++){ scanf("%d",&order[i]); pro[order[i]].weight=wei[order[i]]; } for(i=0;i<1000;i++) winner[i]=order[i]; group=N_P%N_G?(N_P/N_G+1):N_P/N_G; win=N_P; while(win>1){ count=0; for(i=0;i<group;i++){ num=win-i*N_G>=N_G?N_G:win-i*N_G; temp=max(i*N_G,num); for(j=i*N_G;j<i*N_G+num;j++){ if(winner[j]!=temp) pro[winner[j]].place=group+1; } winner[count++]=temp; //for(int k=0;k<N_P;k++) printf("%d %d %d\n",i, k,pro[k].place); //printf("\n"); } win=group; group=win%N_G?(win/N_G+1):win/N_G; } pro[winner[0]].place=1; for(i=0;i<N_P-1;i++) printf("%d ",pro[i].place); printf("%d\n",pro[i].place); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define max 26*26*26 struct record{ int num; int flag; }; struct record record[1000]; int Union[max]; int Time[max]; int Time_total[max]; int head[max]; int check[max]; int cmp(const void *a, const void *b){ struct record *c, *d; c=(struct record*)a; d=(struct record*)b; if(c->flag!=d->flag) return (d->flag)-(c->flag); else return c->num-d->num; } int name_to_num(char *name){ return name[2]-'A'+(name[1]-'A')*26+(name[0]-'A')*26*26; } char *num_to_name(int a){ char *name; name=(char *)malloc(sizeof(char)*4); name[3]=0; name[0]=a/26/26+'A'; name[1]=a%(26*26)/26+'A'; name[2]=a%26+'A'; return name; } int find(int a){ if(Union[a]<0||a==Union[a]) return a; else return Union[a]=find(Union[a]); } void merge(int a, int b){ int x, y; x=find(a); y=find(b); if(x!=y){ if(Union[x]==x) Union[x]=-1+(Union[y]<0?Union[y]:0); else if(Union[x]<0) Union[x]+=(-1+(Union[y]<0?Union[y]:0)); Union[y]=x; } } int main(int argc, char *argv[]){ int N; int K; int count=0, count_temp=0; int temp; int total; char a[4],b[4]; for(int i=0;i<max;i++) Union[i]=i; scanf("%d%d",&N,&K); for(int i=0;i<N;i++){ scanf("%s",a); getchar(); scanf("%s",b); scanf("%d",&temp); Time[name_to_num(a)]+=temp; Time[name_to_num(b)]+=temp; Time_total[name_to_num(a)]+=temp; merge(name_to_num(a),name_to_num(b)); } for(int i=0;i<max;i++) if(Union[i]<=-2) record[count++].num=i; count_temp=count; for(int i=0;i<count;i++){ temp=0; total=0; for(int j=0;j<max;j++){ if(check[i]==-Union[record[i].num]+1) break; if(find(j)==record[i].num){ check[i]++; if(Time[j]>temp){ temp=Time[j]; head[i]=j; } total+=Time_total[j]; } } record[i].num=head[i]; if(total>K) record[i].flag=1; else {record[i].flag=0;count_temp--;} } /*for(int i=0;i<count;i++){ for(int j=0;j<check[i];j++){ printf("%s ",num_to_name(name[i][j])); } printf("%d ",Union[record[i].num]); printf("\n"); } for(int i=0;i<max;i++) if(Union[i]!=i) printf("%s %d\n",num_to_name(i),Union[i]);*/ printf("%d\n",count_temp); qsort(record,count,sizeof(record[0]),cmp); for(int i=0;i<count;i++){ if(!record[i].flag) break; printf("%s %d\n",num_to_name(record[i].num),-Union[find(record[i].num)]+1); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> long long ans[10000][2]; int count; int prime(int x){ if(x==2||x==3) return 1; for(int i=2;i<=sqrt(x);i++){ if(x%i==0) return 0; } return 1; } int main(int argc, char *argv[]){ long long inp; long long temp; int i; scanf("%lld",&inp); temp=inp; //printf("%lf\n",sqrt(inp)); for(i=2;i<=sqrt(inp)&&inp;i++){ if(prime(i)&&inp%i==0){ ans[count][0]=i; while(inp%i==0){ inp/=i; ans[count][1]++; } count++; } //printf("%lf %d\n",sqrt(inp),i); } if(inp>1) ans[count++][0]=inp; if(count==0) ans[count++][0]=1; inp=temp; printf("%lld=",inp); for(i=0;i<count-1;i++) if(ans[i][1]>1) printf("%lld^%lld*",ans[i][0],ans[i][1]); else printf("%lld*",ans[i][0]); if(ans[i][1]>1) printf("%lld^%lld\n",ans[i][0],ans[i][1]); else printf("%lld\n",ans[i][0]); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int K; int N; int Q[1011][1011]; int main(int argc, char *argv[]){ int queen, diff; int flag; scanf("%d", &K); for(int i = 0; i < K; i++){ flag = 1; memset(Q, 0, sizeof(Q)); scanf("%d", &N); for(int j = 1; j <= N; j++){ scanf("%d", &queen); diff = 1; if(Q[queen][j] == -1) flag = 0; if(flag){ for(int k = j + 1; k <= N; k++){ Q[queen][k] = -1; if(queen - diff >= 1) Q[queen-diff][k] = -1; if(queen + diff <= N) Q[queen+diff][k] = -1; diff++; } } } if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int inp[100000]; long long S1, S2; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &inp[i]); } qsort(inp, N, sizeof(int), cmp); for(int i = 0; i < N / 2; i++){ S1 += inp[i]; } for(int i = N / 2; i < N; i++){ S2 += inp[i]; } if(N % 2){ printf("1 "); } else{ printf("0 "); } printf("%lld\n", S2 - S1); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int Union[1001]; int count; int find(int x){ if(Union[x] < 0) return x; else return Union[x] = find(Union[x]); } void merge(int a, int b){ if(find(a) != find(b)){ Union[find(a)] += Union[find(b)]; Union[find(b)] = find(a); } } int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int hobby[1001][1001]; int main(int argc, char *argv[]){ int K; int h; scanf("%d", &N); memset(Union, -1, sizeof(Union)); for(int i = 1; i <= N; i++){ scanf("%d:", &K); for(int j = 0; j < K; j++){ scanf("%d", &h); hobby[h][0]++; hobby[h][hobby[h][0]] = i; hobby[0][h]++; } } for(int i = 1; i <= 1000; i++){ if(hobby[0][i] > 1){ for(int j = 2; j <= hobby[i][0]; j++){ merge(hobby[i][1], hobby[i][j]); } } } qsort(Union + 1, N, sizeof(int), cmp); for(int i = 1; i <= N; i++){ if(Union[i] < 0) count++; else break; } printf("%d\n", count); for(int i = 1;i <= count - 1; i++) printf("%d ", Union[i] * -1); printf("%d\n", Union[count] * -1); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int queue[100]; int inorder[100]; int inp[100]; int count; int head, tail = 1; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } struct node{ int value; int left; int right; }node[100]; void Push(int i){ queue[tail++] = i; } int Pop(){ return queue[head++]; } void Inorder(int i){ if(node[i].left != -1){ Inorder(node[i].left); } inorder[count++] = i; if(node[i].right != -1){ Inorder(node[i].right); } } int main(){ int temp = 0; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d%d", &node[i].left, &node[i].right); } Inorder(0); for(int i = 0; i < N; i++){ scanf("%d", &inp[i]); } qsort(inp, N, sizeof(int), cmp); for(int i = 0; i < N; i++){ node[inorder[i]].value = inp[i]; } count = 0; while(head < tail){ if(head < tail) temp = Pop(); count++; printf("%d",node[temp].value); if(count < N) printf(" "); else printf("\n"); if(node[temp].left != -1) Push(node[temp].left); if(node[temp].right != -1) Push(node[temp].right); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int K; unsigned long len; char inp[2011]; char ans[2011]; int printed[40]; int hash[40]; //0~9 a~z _ int count; int total; char chara[40]; int Hash(char x){ if(x >= '0' && x <= '9'){ return x - '0'; } else if(x == '_') return 36; else return x - 'a' + 10; } int check(int pos){ int i = pos + 1; int flag = 1; if(hash[Hash(inp[pos])] == 1){ return pos; } for(; i < pos + K; i++){ if(inp[i] != inp[pos] || i >= len){ flag = 0; break; } } if(!flag){ hash[Hash(inp[pos])] = 1; return pos; } else{ return pos + K - 1; } } int main(int argc, char *argv[]){ scanf("%d", &K); getchar(); scanf("%s", inp); len = strlen(inp); for(int i = 0; i < len; i++){ i = check(i); } for(int i = 0; i < len; i++){ if(!hash[Hash(inp[i])]){ if(!printed[Hash(inp[i])]){ chara[total++] = inp[i]; printed[Hash(inp[i])] = 1; } i += K - 1; } ans[count++] = inp[i]; } printf("%s\n", chara); printf("%s\n", ans); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> char owner[1000]; char Eva[1000]; int Eva_hash[70]; int owner_hash[70]; char Eva_color[70]; int count; int miss; int hash(char inp){ if(inp >= '0' && inp <= '9') return inp - '0'; if(inp >= 'A' && inp <= 'Z') return inp - 'A' + 10; return inp - 'a' + 36; } int main(){ scanf("%s%s", owner, Eva); for(int i = 0; i < strlen(Eva); i++){ if(!Eva_hash[hash(Eva[i])]){ Eva_color[count++] = Eva[i]; } Eva_hash[hash(Eva[i])]++; } for(int i = 0; i < strlen(owner); i++){ owner_hash[hash(owner[i])]++; } for(int i = 0; i < count; i++){ if(Eva_hash[hash(Eva_color[i])] > owner_hash[hash(Eva_color[i])]) miss += Eva_hash[hash(Eva_color[i])] - owner_hash[hash(Eva_color[i])]; } if(miss) printf("No %d\n", miss); else printf("Yes %ld\n", strlen(owner) - strlen(Eva)); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 2<<29 struct stu{ int name; struct stu *next; }; struct course{ int total; struct stu *next; }; struct course a[2501]; int N; int K; int C; int ans[40001]; int name_to_num(char *name){ return name[3]-'0'+(name[2]-'A')*10+(name[1]-'A')*260+(name[0]-'A')*260*26; } char *num_to_name(int name){ char *ans; ans=(char *)malloc(sizeof(char)*5); ans[0]=name/260/26+'A'; ans[1]=(name%(260*26))/260+'A'; ans[2]=(name%260)/10+'A'; ans[3]=name%10+'0'; ans[4]=0; return ans; } int cmp(const void *a, const void *b){ return *(int *)a-*(int *)b; } int main(int argc, char *argv[]){ int i, j; int num; char name[5]; struct stu *temp; scanf("%d%d",&N,&K); for(i=0;i<N;i++){ getchar(); scanf("%s",name); scanf("%d",&C); for(j=0;j<C;j++){ scanf("%d",&num); a[num].total++; temp=(struct stu*)malloc(sizeof(struct stu)); temp->name=name_to_num(name); temp->next=a[num].next; a[num].next=temp; } } for(i=1;i<=K;i++){ printf("%d %d\n",i,a[i].total); num=0; temp=a[i].next; while(temp){ ans[num++]=temp->name; temp=temp->next; } qsort(ans,num,sizeof(int),cmp); for(j=0;j<num;j++){ printf("%s\n",num_to_name(ans[j])); } } }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct digit{ char dig; int next; int flag; }; struct digit a[100000]; int main(int argc, char *argv[]){ int first1, first2; int addr; int i; int flag=0; scanf("%d%d",&first1, &first2); int N; scanf("%d",&N); for(int i=0;i<N;i++){ scanf("%d",&addr); getchar(); scanf("%c%d",&a[addr].dig,&a[addr].next); } for(i=first1;i!=-1;){ a[i].flag=1; i=a[i].next; } for(i=first2;i!=-1;){ if(a[i].flag) {flag=1;break;} i=a[i].next; } if(flag) printf("%05d\n",i); else printf("-1\n"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> struct stu{ char id[16]; int begin; int end; }; int cmp1(const void *a, const void *b){ struct stu *c, *d; c=(struct stu*)a; d=(struct stu*)b; return c->begin-d->begin; } int cmp2(const void *a, const void *b){ struct stu *c, *d; c=(struct stu*)a; d=(struct stu*)b; return d->end-c->end; } int main(int argc, char *argv[]){ int N; scanf("%d",&N); int i; int hour, min, sec; struct stu a[N]; for(i=0;i<N;i++){ scanf("%s",a[i].id); scanf("%d:%d:%d",&hour, &min, &sec); a[i].begin=hour*3600+min*60+sec; scanf("%d:%d:%d",&hour, &min, &sec); a[i].end=hour*3600+min*60+sec; } qsort(a, N, sizeof(a[0]), cmp1); printf("%s ", a[0].id); qsort(a, N, sizeof(a[0]), cmp2); printf("%s\n",a[0].id); }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 2<<29 int N; long long M; int D[100000]; int min=INT_MAX; int flag=0; int sum; int main(int argc, char *argv[]){ int i, j; scanf("%d%lld",&N,&M); for(i=0;i<N;i++) scanf("%d",&D[i]); for(i=0;i<N;i++){ if(!i) sum=0; else {sum-=D[i-1];sum-=D[j];} for(;j<N;j++){ sum+=D[j]; if(sum==M){ flag=1; printf("%d-%d\n",i+1,j+1); break; } else if(sum>M) break; } } if(!flag){ j=0; for(i=0;i<N;i++){ if(!i) sum=0; else {sum-=D[i-1];sum-=D[j];} for(;j<N;j++){ sum+=D[j]; if(sum<min&&sum>M) {min=sum;break;} else if(sum>min) break; } } j=0; for(i=0;i<N;i++){ if(!i) sum=0; else {sum-=D[i-1];sum-=D[j];} for(;j<N;j++){ sum+=D[j]; if(sum==min) {printf("%d-%d\n",i+1,j+1);break;} else if(sum>min) break; } } } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> struct node{ int id; int level; struct node *next; }node[100]; int N; int M; int level[100]; int max; int Index; void BFS(int Node, int level){ struct node *temp; temp = node[Node].next; while(temp){ node[temp->id].level = level + 1; temp = temp -> next; } temp = node[Node].next; while(temp){ BFS(temp->id, level + 1); temp = temp -> next; } } int main(){ int ID; int K; struct node *temp = NULL; scanf("%d%d", &N, &M); for(int i = 0; i < M; i++){ scanf("%d", &ID); scanf("%d", &K); for(int j = 0; j < K; j++){ temp = (struct node*)malloc(sizeof(struct node)); scanf("%d", &temp->id); temp -> next = node[ID].next; node[ID].next = temp; } } node[1].level = 1; BFS(1, 1); for(int i = 1; i <= N; i++){ level[node[i].level]++; if(level[node[i].level] > max){ max = level[node[i].level]; Index = node[i].level; } } printf("%d %d\n", max, Index); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int len[10000]; double total; int ans; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ scanf("%d", &N); for(int i = 0; i < N; i++) scanf("%d", &len[i]); qsort(len, N, sizeof(int), cmp); total = len[0]; for(int i = 1; i < N; i++){ total += len[i]; total/= 2; } ans = total; printf("%d\n", ans); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #define max 26*26*26 #define maximum 1<<30 int hash[max]; int name[201]; int happy[201]; int cost[201][201]; int num[201]; int happiness[201]; int costs[201]; int visited[201]; int diff[201]; int pre[201]; int ans[201]; int count; int N; int K; int start; int char_to_int(char *name){ return name[2] - 'A' + (name[1] - 'A') * 26 + (name[0] - 'A') * 26 * 26; } char *int_to_char(int num){ char *ans = malloc(sizeof(char) * 4); ans[0] = num / 26 / 26 + 'A'; ans[1] = num % (26 * 26) / 26 + 'A'; ans[2] = num % 26 + 'A'; ans[3] = 0; return ans; } void Dijkstra(){ for(int i = 0; i < N; i++){ costs[i] = maximum; } costs[hash[start]] = 0; while(1){ int min = maximum; int temp = -1; for(int i = 0; i < N; i++){ if(!visited[i] && costs[i] < min){ min = costs[i]; temp = i; } } visited[temp] = 1; if(temp == -1) break; for(int i = 0; i < N; i++){ if(!visited[i]){ if(costs[i] > costs[temp] + cost[temp][i]){ costs[i] = costs[temp] + cost[temp][i]; num[i] = num[temp] + 1; happiness[i] = happiness[temp] + happy[i]; diff[i] = diff[temp]; pre[i] = temp; } else if(costs[i] == costs[temp] + cost[temp][i]){ if(happiness[temp] + happy[i] > happiness[i]){ happiness[i] = happiness[temp] + happy[i]; num[i] = num[temp] + 1; pre[i] = temp; } else if(happiness[temp] + happy[i] == happiness[i]){ if(num[i] > num[temp] + 1){ num[i] = num[temp] + 1; diff[i] = diff[temp] + 1; pre[i] = temp; } } if(temp) diff[i] += diff[temp]; } } } } } int main(){ char name1[4], name2[4]; int roma; scanf("%d%d", &N, &K); getchar(); scanf("%s", name1); start = char_to_int(name1); hash[start] = 0; name[0] = start; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ cost[i][j] = maximum; } diff[i] = 1; } for(int i = 0; i < N -1; i++){ scanf("%s", name1); name[i+1] = char_to_int(name1); hash[name[i+1]] = i + 1; scanf("%d", &happy[hash[name[i+1]]]); getchar(); } for(int i = 0; i < K; i++){ scanf("%s%s", name1, name2); scanf("%d", &cost[hash[char_to_int(name1)]][hash[char_to_int(name2)]]); cost[hash[char_to_int(name2)]][hash[char_to_int(name1)]] = cost[hash[char_to_int(name1)]][hash[char_to_int(name2)]]; getchar(); } Dijkstra(); roma = hash[char_to_int("ROM")]; printf("%d %d %d %d\n", diff[roma], costs[roma], happiness[roma], happiness[roma] / num[roma]); while(roma){ ans[count++] = roma; roma = pre[roma]; } printf("%s->", int_to_char(name[0])); for(int i = count - 1; i > 0; i--){ printf("%s->", int_to_char(name[ans[i]])); } printf("%s\n", int_to_char(name[ans[0]])); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int visited[100]; int ans[100]; int count; int cal(int x){ int res = 0; while(x){ res += x % 10; x /= 10; } return res; } int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ int temp; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &temp); if(!visited[cal(temp)]){ ans[count++] = cal(temp); visited[cal(temp)] = 1; } } qsort(ans, count, sizeof(int), cmp); printf("%d\n", count); for(int i = 0; i < count; i++){ if(i < count - 1) printf("%d ", ans[i]); else printf("%d\n", ans[i]); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> int N; int L; int ans[1001]; int visited[1001]; int sum; struct User{ int num2; int followed[1001]; }user[1001]; void BFS(int temp, int level){ if(level > L) return; visited[temp] = 1; for(int i = 0; i < user[temp].num2; i++){ if(!ans[user[temp].followed[i]]){ sum++; ans[user[temp].followed[i]] = 1; } } for(int i = 0; i < user[temp].num2; i++){ if(visited[user[temp].followed[i]] == 0){ BFS(user[temp].followed[i], level+1); } } } int main(int argc, char *argv[]){ int num; int temp; scanf("%d%d", &N, &L); for(int i = 1; i <= N; i++){ scanf("%d", &num); for(int j = 0; j < num; j++){ scanf("%d", &temp); user[temp].followed[user[temp].num2++] = i; } } scanf("%d", &num); for(int i = 0; i < num; i++){ sum = 0; memset(ans, 0, sizeof(ans)); memset(visited, 0, sizeof(visited)); scanf("%d", &temp); ans[temp] = 1; BFS(temp, 1); printf("%d\n", sum); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<limits.h> int N; int K; int P; int max_count; int count; int tail; int temp[21]; int ans[400]; int fact[400]; int max_fact_sum = -1; void DFS(int pos, int k, int total_sum, int fact_sum){ if(total_sum == N && k == K){ if(fact_sum > max_fact_sum){ max_count = tail; max_fact_sum = fact_sum; memcpy(ans, fact, sizeof(ans)); } return; } if(total_sum > N || k > K) return; if(pos >= 1){ fact[tail++] = pos; DFS(pos, k + 1, total_sum + temp[pos], fact_sum + pos); tail--; DFS(pos - 1, k, total_sum, fact_sum); } } int main(int argc, char *argv[]){ scanf("%d%d%d", &N, &K, &P); for(int i = 0; i < 21; i++){ temp[count++] = pow(i, P); if(pow(i, P) > N) break; } DFS(count - 1, 0, 0, 0); if(max_fact_sum == -1){ printf("Impossible\n"); } else{ printf("%d = %d^%d", N, ans[0], P); for(int i = 1; i < max_count; i++){ printf(" + %d^%d", ans[i], P); } printf("\n"); } return 0; }<file_sep>#include <stdio.h> int main(){ int a1,b1,c1,a2,b2,c2; scanf("%d.%d.%d",&a1,&b1,&c1); scanf("%d.%d.%d",&a2,&b2,&c2); int a,b,c,carry; c=(c1+c2)%29; carry=(c1+c2)/29; b=(b1+b2+carry)%17; carry=(b1+b2+carry)/17; a=a1+a2+carry; printf("%d.%d.%d",a,b,c); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int road[2000*2000][2]; int pre[2000]; int Find(int x){ return pre[x]==x?x:(pre[x]=Find(pre[x])); } void UNION(int x, int y){ x=Find(x); y=Find(y); if(x==y) return; pre[y]=x; } int main(int argc, char *argv[]){ int N, M, K; int i, j, a; int total; scanf("%d%d%d",&N,&M,&K); for(i=0;i<M;i++){ scanf("%d%d",&road[i][0],&road[i][1]); } for(i=0;i<K;i++){ scanf("%d",&a); for(j=0;j<=N;j++) pre[j]=j; for(j=0;j<M;j++) if(road[j][0]!=a&&road[j][1]!=a) UNION(road[j][0],road[j][1]); total=0; for(j=1;j<=N;j++) if(pre[j]==j&&j!=a) total++; printf("%d\n",total-1); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int max(double *a){ if(a[0]>a[1]){ if(a[0]>a[2]) return 0; else{ return 2; } } else{ if(a[1]>a[2]) return 1; else return 2; } } int main(int argc, char *argv[]){ double a[3][3]; int i, j, maxium[3]; for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%lf",&a[i][j]); for(i=0;i<3;i++){ maxium[i]=max(a[i]); switch(maxium[i]){ case 0: printf("W "); break; case 1: printf("T "); break; default: printf("L "); break; } } printf("%.2f\n",(a[0][maxium[0]]*a[1][maxium[1]]*a[2][maxium[2]]*0.65-1)*2); return 0; }<file_sep>#include<stdio.h> #include<string.h> char inp[100010]; long long P, PA, PAT; int main(){ P = PA = PAT = 0; scanf("%s", inp); long len = strlen(inp); for(int i = 0; i < len; i++){ if(inp[i] == 'P') {P++;} if(inp[i] == 'A') {PA += P;} if(inp[i] == 'T') {PAT += PA;} } printf("%lld\n", PAT % 1000000007); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int root; int ans[200]; int queue[200]; int head = 0, tail = 0; int count = 1; struct tree{ int left, right; int father; }tree[20]; void push_queue(int x){ queue[++tail] = x; } void push_ans(int x){ ans[count++] = x; } int pop_queue(){ return queue[head++]; } void level_traversal(){ int temp; queue[0] = root; ans[0] = root; while(head <= tail){ temp = pop_queue(); if(tree[temp].left != -1) push_queue(tree[temp].left); if(tree[temp].right!= -1) push_queue(tree[temp].right); push_ans(tree[temp].left); push_ans(tree[temp].right); } } int main(int argc, char *argv[]){ char left[3], right[3]; int flag = 1; scanf("%d", &N); getchar(); memset(tree, -1, sizeof(tree)); memset(queue, -1, sizeof(queue)); for(int i = 0; i < N; i++){ scanf("%s%s", left, right); if(left[0] != '-') { if(strlen(left) == 1) tree[i].left = left[0] - '0'; else tree[i].left = left[1] - '0' + (left[0] - '0') * 10; tree[tree[i].left].father = i; } if(right[0] != '-') { if(strlen(right) == 1) tree[i].right = right[0] - '0'; else tree[i].right = right[1] - '0' + (right[0] - '0') * 10; tree[tree[i].right].father = i; } } while(tree[root].father != -1){ root = tree[root].father; } level_traversal(); for(int i = 0; i <= N - 1; i++){ if(ans[i] == -1){ flag = 0; break; } } if(flag){ printf("YES %d\n", ans[N-1]); } else printf("NO %d\n", root); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define max 1<<24 int M; int N; int pixel[800][600]; int count[max]; int value[800*600]; int num; int main(int argc, char *argv[]){ int i, j; scanf("%d%d",&M,&N); for(i=0;i<M;i++) for(j=0;j<N;j++){ scanf("%d",&pixel[i][j]); if(count[pixel[i][j]]==0) value[num++]=pixel[i][j]; count[pixel[i][j]]++; } for(i=0;i<num;i++) if(count[value[i]]>M*N/2){printf("%d\n",value[i]);break;} return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> int N; int head; int temp; int count; struct val_1{ int head; int value; int flag; }val1[100000],val[100000]; int addr[100000]; int cmp(const void *a, const void *b){ struct val_1 *c, *d; c=(struct val_1*)a; d=(struct val_1*)b; if(c->flag!=d->flag) return d->flag-c->flag; return c->value-d->value; } int main(int argc, char *argv[]){ scanf("%d%d",&N,&head); if(head==-1) {printf("0 -1\n");return 0;} for(int i=0;i<N;i++){ scanf("%d",&temp); val1[temp].head=temp; scanf("%d",&val1[temp].value); scanf("%d",&addr[temp]); } temp=head; while(temp!=-1){ val1[temp].flag=1; val[count++]=val1[temp]; temp=addr[val1[temp].head]; } qsort(val,N,sizeof(val[0]),cmp); if(count) printf("%d %05d\n",count,val[0].head); else {printf("0\n");return 0;} for(int i=0;i<count-1;i++) printf("%05d %d %05d\n",val[i].head, val[i].value,val[i+1].head); printf("%05d %d %d\n",val[count-1].head, val[count-1].value,-1); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> long long a, b, c, d; long long integer; char ans[6][1000]; char ope[4] = {'+', '-', '*', '/'}; int digit(long long num){ int i = 0; while(num){ num /= 10; i++; } return i; } char *int_to_string(long long num){ char *ans; int i = digit(num); ans = (char *)malloc(sizeof(char) * (i + 3)); if(num < 0) {ans[0] = '('; ans[1] = '-'; ans[i+2] = ')';num *= -1;i++;} else i--; while(num){ ans[i--] = num % 10 + '0'; num /= 10; } return ans; } char *mix_number_to_string(long long integer, long long zi, long long mu){ char *ans; int i = digit(integer) + digit(zi) + digit(mu); int j, k; ans = (char *)malloc(sizeof(char) * (i + 5)); if(integer < 0){ ans[0] = '('; ans[1] = '-'; ans[i+4] = ')'; integer *= -1; i = digit(integer) + 1; j = i + 1 + digit(zi); k = j + 1 + digit(mu); ans[k+2] = 0; } else{ i = digit(integer) - 1; j = i + 1 + digit(zi); k = j + 1 + digit(mu); ans[k+1] = 0; } ans[i + 1] = ' '; ans[j + 1] = '/'; while(integer){ ans[i--] = integer % 10 + '0'; integer /= 10; } while(zi){ ans[j--] = zi % 10 + '0'; zi /= 10; } while(mu){ ans[k--] = mu % 10 + '0'; mu /= 10; } return ans; } char *fraction_to_string(long long zi, long long mu){ char *ans; int i = digit(zi) + digit(mu); int j; ans = (char *)malloc(sizeof(char) * (i + 4)); if(zi < 0){ ans[0] = '('; ans[1] = '-'; ans[i+3] = ')'; zi *= -1; i = digit(zi) + 1; j = i + 1 + digit(mu); ans[j+2] = 0; } else{ i = digit(zi) - 1; j = i + 1 + digit(mu); ans[j+1] = 0; } ans[i + 1] = '/'; while(zi){ ans[i--] = zi % 10 + '0'; zi /= 10; } while(mu){ ans[j--] = mu % 10 + '0'; mu /= 10; } return ans; } long long gcd(long long a, long long b){ long long temp; while(b){ temp = a % b; a = b; b = temp; } return a; } void change(long long num1, long long num2, int num){ long long temp; if(num2 == 0 && num ==5) {strcpy(ans[5], "Inf"); return;} if(!num1) ans[num][0] = '0'; else{ temp = gcd(num1, num2); num1 /= temp; num2 /= temp; if(num1 < 0 || num2 < 0) {num2 = llabs(num2); num1 = llabs(num1) * -1;} if(num1 % num2 == 0){ strcpy(ans[num], int_to_string(num1 / num2)); } else{ if(llabs(num1) > llabs(num2)){ integer = num1 / num2; num1 -= integer * num2; if(integer < 0) {num2 = llabs(num2);num1 = llabs(num1);} strcpy(ans[num], mix_number_to_string(integer, num1, num2)); } else{ strcpy(ans[num], fraction_to_string(num1, num2)); } } } } int main(){ scanf("%lld/%lld%lld/%lld", &a, &b, &c, &d); change(a, b, 0); change(c, d, 1); change(a * d + c * b, b * d, 2); change(a * d - c * b, b * d, 3); change(a * c, b * d, 4); change(a * d, b * c, 5); for(int i = 0; i < 4; i++){ printf("%s %c %s = %s\n", ans[0], ope[i], ans[1], ans[i+2]); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int root = 1; struct node{ char str[11]; int father; struct node *left; struct node *right; }node[21]; void dfs(struct node *a){ if(a->father != 0){ if(a->left || (strcmp(a->str, "-") == 0)){ printf("("); } } if(a->left){ dfs(a->left); } printf("%s", a->str); if(a->right){ dfs(a->right); } if(a->father != 0){ if(a->left || (strcmp(a->str, "-") == 0)){ printf(")"); } } } int main(int argc, char *argv[]){ int left, right; scanf("%d", &N); for(int i = 1; i <= N; i++){ getchar(); scanf("%s", node[i].str); scanf("%d%d", &left, &right); if(left != -1) node[i].left = &node[left]; if(right != -1) node[i].right = &node[right]; if(left != -1) node[left].father = i; if(right != -1) node[right].father = i; } while(node[root].father != 0){ root = node[root].father; } dfs(&node[root]); printf("\n"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define INT_MAX 1<<28 int M, N, C1, C2; int rescue[501]; int road[501][501]; int dis[501]; int visited[501]; int road_count[501]; int rescue_count[501]; void INITIALIZE(){ int i,j; for(i=0; i<501;i++) for(j=0;j<501;j++){ road[i][j]=INT_MAX; } for(i=0;i<501;i++) dis[i]=INT_MAX; memset(visited,0,sizeof(int)*501); memset(road_count,0,sizeof(int)*501); memset(rescue_count,0,sizeof(int)*501); } void dijstra(){ int i,j,temp=C1; int min; dis[C1]=0; road_count[C1]=1; rescue_count[C1]=rescue[C1]; for(;;){ temp=-1; min=INT_MAX; for(j=0;j<N;j++) if(visited[j]==0&&dis[j]<min) {min=dis[j];temp=j;} if(temp==-1) break; visited[temp]=1; for(i=0;i<N;i++){ if(visited[i]==0){ if(dis[i]>dis[temp]+road[temp][i]){ dis[i]=dis[temp]+road[temp][i]; road_count[i]=road_count[temp]; rescue_count[i]=rescue_count[temp]+rescue[i]; } else if(dis[i]==dis[temp]+road[temp][i]){ road_count[i]+=road_count[temp]; rescue_count[i]=rescue_count[temp]+rescue[i]>rescue_count[i]?rescue_count[temp]+rescue[i]:rescue_count[i]; } } } } } int main(int argc, char *argv[]){ int i; int fro, to; INITIALIZE(); scanf("%d%d%d%d",&N, &M, &C1, &C2); for(i=0;i<N;i++) scanf("%d",&rescue[i]); for(i=0;i<M;i++){ scanf("%d%d",&fro, &to); scanf("%d",&road[fro][to]); road[to][fro]=road[fro][to]; } /*for(i=0;i<N;i++){ for(int j=0;j<N;j++) printf("%d \t",road[i][j]); printf("\n"); }*/ dijstra(); printf("%d %d\n",road_count[C2],rescue_count[C2]); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int main(int argc, char *argv[]){ int N; int a[54]; int b[54]; int temp; scanf("%d",&N); for(int i=0;i<54;i++) scanf("%d",&a[i]); for(int i=0;i<54;i++){ temp=i; for(int j=0;j<N;j++){ temp=a[temp]-1; } b[temp]=i; } for(int i=0;i<53;i++){ if(b[i]/13==0) printf("S%d ",b[i]%13+1); else if(b[i]/13==1) printf("H%d ",b[i]%13+1); else if(b[i]/13==2) printf("C%d ",b[i]%13+1); else if(b[i]/13==3) printf("D%d ",b[i]%13+1); else printf("J%d ",b[i]%13+1); } if(b[53]/13==0) printf("S%d",b[53]%13+1); else if(b[53]/13==1) printf("H%d",b[53]%13+1); else if(b[53]/13==2) printf("C%d",b[53]%13+1); else if(b[53]/13==3) printf("D%d",b[53]%13+1); else printf("J%d",b[53]%13+1); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int head, tail; int temp_head, temp_tail; int len; int temp_len; int temp; int inp; int power(int base, int time){ long long ans = 1; if(time < 2) time = 2; for(int i = 0; i < time; i++){ ans *= base; } if(ans > inp) return 0; else return 1; } int main(){ scanf("%d", &inp); if(inp == 1) {printf("1\n1\n");return 0;} temp = inp; for(int i = 2; i <= inp; i++){ if(!temp_head) temp_head = i; if(temp % i == 0){ temp /= i; temp_tail = i; temp_len++; } else{ if(len < temp_len){ head = temp_head; tail = temp_tail; len = temp_len; } if((temp * temp_head) % i == 0){ temp *= temp_head; temp /= i; temp_head++; temp_tail++; } else{ temp = inp; temp_head = 0; temp_tail = 0; temp_len = 0; } } if(!power(temp_head, len)) break; } if(len < temp_len){ head = temp_head; tail = temp_tail; len = temp_len; } if(!len){ len = 1; head = inp; tail = inp; } printf("%d\n", len); for(int i = 0; i < len - 1; i++){ printf("%d*", head + i); } printf("%d\n", head + len - 1); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; long long gcd(long long a, long long b){ long long temp; while(a % b){ temp = b; b = a % b; a = temp; } return b; } long long lcm(long long a, long long b){ return a * b / gcd(a, b); } void change(long long mu1, long long zi1){ if(zi1 == 0) printf("0\n"); else if(llabs(mu1) > llabs(zi1)) if(mu1 * zi1 < 0) printf("-%lld/%lld\n", llabs(zi1), llabs(mu1)); else printf("%lld/%lld\n", zi1, mu1); else if(zi1 % mu1 == 0 && mu1 / zi1 >= 0) printf("%lld\n", zi1/mu1); else if(zi1 % mu1 == 0 && mu1 / zi1 < 0) printf("-%lld\n", zi1/mu1); else if(zi1 < 0){ printf("%lld ", zi1/mu1); printf("%lld/%lld\n", zi1 * -1 % mu1, mu1); } else if (zi1 > 0){ printf("%lld ", zi1/mu1); printf("%lld/%lld\n", zi1 % mu1, mu1); } } int main(int argc, char *argv[]){ long long zi1, mu1, zi2, mu2; long long temp; scanf("%d", &N); scanf("%lld/%lld", &zi1, &mu1); for(int i = 1; i < N; i++){ temp = gcd(zi1, mu1); zi1 /= temp; mu1 /= temp; scanf("%lld/%lld", &zi2, &mu2); temp = gcd(zi2, mu2); zi2 /= temp; mu2 /= temp; zi1 = lcm(mu1, mu2) / mu1 * zi1 + lcm(mu1, mu2) / mu2 * zi2; mu1 = lcm(mu1, mu2); } temp = gcd(zi1, mu1); zi1 /= temp; mu1 /= temp; change(mu1, zi1); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> char inp1[81]; char inp2[81]; char hash[128]; char output[81]; int count; int main(){ scanf("%s%s", inp1, inp2); for(int i = 0, j = 0; i < strlen(inp1); i++){ if(inp1[i] != inp2[j]){ if(!hash[inp1[i]]){ if(inp1[i] >= 'a' && inp1[i] <= 'z'){ hash[inp1[i] + 'A' - 'a'] = 1; output[count++] = inp1[i] + 'A' - 'a'; } else if(inp1[i] >= 'A' && inp1[i] <= 'Z'){ hash[inp1[i] + 'a' - 'A'] = 1; output[count++] = inp1[i]; } else{ output[count++] = inp1[i]; } hash[inp1[i]] = 1; } } else j++; } for(int i = 0; i < count; i++) printf("%c", output[i]); printf("\n"); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int change(int N, int radix){ char digit[25]; int count=0; int i, ans=0; memset(digit,0,sizeof(digit)); while(N){ digit[count++]=N%radix+'0'; N/=radix; } for(i=0;i<=count-1;i++){ ans*=radix; ans+=digit[i]-'0'; } return ans; } int prime(int N){ int i, flag=1; if(N<=1) return 0; if(N==2||N==3) return 1; for(i=2;i<=sqrt(N);i++){ if(N%i==0) {flag=0;break;} } return flag; } int main(int argc, char *argv[]){ int N, radix; int ans; scanf("%d",&N); while(N>0){ scanf("%d",&radix); ans=change(N, radix); if(prime(ans)&&prime(N)) printf("Yes\n"); else printf("No\n"); scanf("%d",&N); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 2<<29 int total; int ans; int N; int M; int dis[100001]; int main(int argc, char *argv[]){ int i, num1, num2; scanf("%d",&N); for(i=1;i<=N;i++) {scanf("%d",&dis[i]);total+=dis[i];dis[i]=total;} scanf("%d",&M); for(i=0;i<M;i++){ scanf("%d%d",&num1,&num2); if(num1>num2) ans=dis[num1-1]-dis[num2-1]; else ans=dis[num2-1]-dis[num1-1]; if(ans<total-ans) printf("%d\n",ans); else printf("%d\n",total-ans); } }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int inp[100000]; int check[10000]; int N; int flag; int main(int argc, char *argv[]){ scanf("%d",&N); for(int i=0;i<N;i++){ scanf("%d",&inp[i]); check[inp[i]]++; } for(int i=0;i<N;i++) if(check[inp[i]]==1){ printf("%d\n",inp[i]); flag=1; break; } if(!flag) printf("None\n"); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #define max 1<<30 int N; int M; int S, D; //source and destination struct pos{ struct info *next; }pos[500]; struct info{ int num; int dis; int time; struct info *next; }; int visited[500]; int path[500]; int Times[500]; int pre[500]; struct fastest{ int time; int pre; int count; }fastest[500]; int ans1[500]; int count1; int ans2[500]; int count2; void Initialize(){ for(int i = 0; i < 500; i++){ path[i] = max; Times[i] = max; fastest[i].time = max; fastest[i].count = max; } memset(pre, -1, sizeof(pre)); } void DFS(){ path[S] = 0; Times[S] = 0; while(1){ int temp = -1, min = max; struct info *tempt; for(int i = 0; i < N; i++){ if(fastest[i].time < min && !visited[i]){ temp = i; min = fastest[i].time; } } if(temp == -1) break; visited[temp] = 1; tempt = pos[temp].next; while(tempt){ if(!visited[tempt->num]){ if(fastest[temp].time + tempt->time < fastest[tempt->num].time){ fastest[tempt->num].time = fastest[temp].time + tempt->time; fastest[tempt->num].pre = temp; fastest[tempt->num].count = fastest[temp].count + 1; } else if(fastest[temp].time + tempt->time == fastest[tempt->num].time){ if(fastest[tempt->num].count > fastest[temp].count + 1){ fastest[tempt->num].pre = temp; fastest[tempt->num].count = fastest[temp].count + 1; } } } tempt = tempt->next; } } } void Dijkstra(){ path[S] = 0; while(1){ int temp = -1, min = max; struct info *tempt; for(int i = 0; i < N; i++){ if(path[i] < min && !visited[i]){ temp = i; min = path[i]; } } if(temp == -1) break; visited[temp] = 1; tempt = pos[temp].next; while(tempt){ if(!visited[tempt->num]){ if(path[temp] + tempt->dis < path[tempt->num]){ path[tempt->num] = path[temp] + tempt->dis; Times[tempt->num] = Times[temp] + tempt->time; pre[tempt->num] = temp; } else if(path[temp] + tempt->dis == path[tempt->num]){ if(Times[tempt->num] > Times[temp] + tempt->time){ Times[tempt->num] = Times[temp] + tempt->time; pre[tempt->num] = temp; } } } tempt = tempt->next; } } } int check(){ if(count1 != count2) return 0; else{ for(int i = count1 - 1; i >= 0; i--){ if(ans1[i] != ans2[i]) return 0; } return 1; } } int main(int argc, char *argv[]){ int a, b; int one_way; int dis, ti; struct info *temp; scanf("%d%d", &N, &M); Initialize(); for(int i = 0; i < M; i++){ temp = (struct info *)malloc(sizeof(struct info)); scanf("%d%d%d%d%d", &a, &b, &one_way, &dis, &ti); temp->dis = dis; temp->time = ti; temp->num = b; temp->next = pos[a].next; pos[a].next = temp; if(!one_way){ temp = (struct info *)malloc(sizeof(struct info)); temp->dis = dis; temp->time = ti; temp->num = a; temp->next = pos[b].next; pos[b].next = temp; } } scanf("%d%d", &S, &D); Dijkstra(); memset(visited, 0, sizeof(visited)); fastest[S].time = 0; fastest[S].count = 1; DFS(); a = D; ans1[count1++] = D; while(a != S){ a = pre[a]; ans1[count1++] = a; } b = D; ans2[count2++] = D; while(b != S){ b = fastest[b].pre; ans2[count2++] = b; } if(check()){ printf("Distance = %d; Time = %d: ", path[D], fastest[D].time); for(int i = count1 - 1; i > 0; i--) printf("%d -> ", ans1[i]); printf("%d\n", ans1[0]); } else{ printf("Distance = %d: ", path[D]); for(int i = count1 - 1; i > 0; i--) printf("%d -> ", ans1[i]); printf("%d\n", ans1[0]); printf("Time = %d: ", fastest[D].time); for(int i = count2 - 1; i > 0; i--) printf("%d -> ", ans2[i]); printf("%d\n", ans2[0]); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int max; int num[100001]; int cmp(const void *a, const void *b){ return *(int *)b - *(int *)a; } int main(int argc, char *argv[]){ int i; scanf("%d", &N); for(i = 1; i <= N; i++){ scanf("%d", &num[i]); } qsort(num + 1, N, sizeof(int), cmp); for(i = 1; i <= N; i++){ if(num[i] <= i) break; } printf("%d\n", i - 1); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> int N; char inp[101][256]; char LCS[256]; int temp_count; int count; void reverse(char *inp){ char temp; for(int i = 0; i < strlen(inp)/2; i++){ temp = inp[i]; inp[i] = inp[strlen(inp) - i - 1]; inp[strlen(inp) - i - 1] = temp; } } int main(int argc, char *argv[]){ scanf("%d", &N); getchar(); for(int i = 0; i < N; i++){ gets(inp[i]); reverse(inp[i]); } for(int i = 0; i < strlen(inp[0]) && i < strlen(inp[1]); i++){ if(inp[0][i] == inp[1][i]){ LCS[temp_count++] = inp[0][i]; } else break; } count = temp_count; if(count){ for(int i = 2; i < N; i++){ temp_count = 0; for(int j = 0; j < count; j++){ if(inp[i][j] == LCS[j]){ temp_count++; } else break; } count = temp_count; if(!count) break; } } LCS[count] = 0; reverse(LCS); if(count) printf("%s\n", LCS); else printf("nai\n"); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<limits.h> int N; int arr[100000]; int max_arr[100000]; int min_arr[100000]; int ans[100000]; int count; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ int maximum = 0, min = INT_MAX; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &arr[i]); } for(int i = 0; i < N; i++){ if(arr[i] > maximum) maximum = arr[i]; max_arr[i] = maximum; } for(int i = N -1; i >= 0; i--){ if(arr[i] < min) min = arr[i]; min_arr[i] = min; } for(int i = 0; i < N; i++){ if(arr[i] == max_arr[i] && arr[i] == min_arr[i]) ans[count++] = arr[i]; } qsort(ans, count, sizeof(int), cmp); printf("%d\n", count); for(int i = 0; i < count - 1; i++){ printf("%d ", ans[i]); } if(count) printf("%d", ans[count-1]); printf("\n"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(int argc, char *argv[]){ int req_num, i; int time=0; scanf("%d",&req_num); int a, b; a=0; for(i=1;i<=req_num;i++){ scanf("%d",&b); if(b>a) time+=(b-a)*6+5; else time+=(a-b)*4+5; a=b; } printf("%d\n",time); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #define maximum 1<<30 int N, M; int F[10001][101]; int coin[10001]; int has[10001][101]; int ans[10001]; int count; int cmp(const void *a, const void *b){ return *(int *)b-*(int *)a; } int main(int argc, const char * argv[]) { scanf("%d%d",&N, &M); for(int i=1; i<=N; i++){ scanf("%d", &coin[i]); } qsort(coin+1, N, sizeof(int), cmp); for(int i=1; i<=N;i++){ for(int j=1; j<=M; j++){ int temp = j-coin[i] >= 0 ? (F[i-1][j-coin[i]] + coin[i]) : 0; if(F[i-1][j] > temp) F[i][j] = F[i-1][j]; else { F[i][j] = temp; has[i][j] = 1; } } } /*for(int i=1;i<=N;i++) for(int j=1;j<=M;j++){ printf("%d %d %d\n", i, j, F[i][j]); printf("%d\n\n", has[i][j]); } */ if(F[N][M]!=M) printf("No Solution\n"); else{ while(M){ while(!has[N][M]) N--; ans[count++] = coin[N]; M -= coin[N]; N--; } for(int i=0; i<count-1;i++) printf("%d ", ans[i]); printf("%d\n", ans[count-1]); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; char inp[10]; char first[13][5] = {"tret","jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"}; char second[13][5] = {"tret", "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"}; int mars_to_num(){ int ans = 0; int flag = 0; char temp[5]; if(strlen(inp) <= 4){ for(int i = 0; i < 13; i++){ if(strcmp(inp, first[i]) == 0){ ans = i; flag = 1; break; } } if(flag == 0){ for(int i = 0; i < 13; i++){ if(strcmp(inp, second[i]) == 0){ ans = i * 13; break; } } } } else{ memcpy(temp, inp, 3); for(int i = 0; i < 13; i++){ if(strcmp(temp, second[i]) == 0){ ans = i * 13; break; } } memcpy(temp, inp + 4, 5); for(int i = 0; i < 13; i++){ if(strcmp(temp, first[i]) == 0){ ans += i; break; } } } return ans; } char *num_to_mars(){ char *ans; int temp; if(strlen(inp) == 3) temp = (inp[0] - '0') *100 + (inp[1] - '0') *10 + (inp[2] - '0'); else if(strlen(inp) == 2) temp = (inp[0] - '0') *10 + inp[1] - '0'; else temp = inp[0] - '0'; ans = (char *)malloc(10); if(temp / 13){ strcpy(ans, second[temp / 13]); if(temp % 13){ ans[3] = ' '; ans[4] = 0; strcpy(ans + 4, first[temp % 13]); } } else{ strcpy(ans, first[temp]); } return ans; } int main(int argc, char *argv[]){ scanf("%d", &N); getchar(); for(int i = 0; i < N; i++){ gets(inp); if(inp[0] >= '0' && inp[1] <= '9') printf("%s\n", num_to_mars()); else printf("%d\n", mars_to_num()); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; double sum; int count; char inp[100][100]; int check(char *inp,unsigned long len){ int dot_count = 0, neg_count = 0; double num; for(int i = 0; i < len; i++){ if(inp[i] == '-' || inp[i] == '.' || (inp[i] >= '0' && inp[i] <= '9')){ if(inp[i] == '.') dot_count++; if(inp[i] == '-') neg_count++; } else{ return 0; break; } } if(dot_count > 1 || neg_count > 1) return 0; if(neg_count == 1 && inp[0] != '-') return 0; if(dot_count == 1 && inp[0] == '.') return 0; if(dot_count == 1){ int i = 0; for(; i < len; i++){ if(inp[i] == '.') break; } if(len - 1 - i > 2) return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> char ans[100]; char *Process(char *N){ char temp[100]; int carry=0; memset(temp,0,sizeof(temp)); memset(ans,0,sizeof(ans)); long i; for(i=strlen(N)-1;i>=0;i--){ temp[i]=(N[i]+N[strlen(N)-1-i]+carry-'0'-'0')%10+'0'; carry=(N[i]+N[strlen(N)-1-i]+carry-'0'-'0')/10; } if(carry) {strcpy(ans+1,temp);ans[0]='1';} else strcpy(ans,temp); return ans; } int Palindromic(char *N){ int i; for(i=0;i<strlen(N)/2;i++){ if(N[i]!=N[strlen(N)-i-1]) break; } if(i!=strlen(N)/2) return 0; else return 1; } int main(int argc, char *argv[]){ char N[100]; int K; int count=0; memset(N,0,sizeof(N)); scanf("%s",N); getchar(); scanf("%d",&K); while(1){ if(!Palindromic(N)&&count<K) {strcpy(N,Process(N));count++;} else {printf("%s\n%d\n",N,count);break;} } }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int max_level; int first, second; int head, tail = -1; struct node{ int value; int level; struct node *left; struct node *right; }*header, queue[1000]; void Insert(int temp){ struct node *tree = header; int temp_level = 1; if(!tree){ tree = (struct node*)malloc(sizeof(struct node)); tree->value = temp; tree->level = 1; tree->left = NULL; tree->right = NULL; header = tree; return; } while(tree){ if(tree->value >= temp){ if(tree->left){ tree = tree->left; temp_level++; } else{ tree->left = (struct node*)malloc(sizeof(struct node)); tree->left->value = temp; tree->left->level = temp_level + 1; tree->left->left = NULL; tree->left->right = NULL; break; } } else{ if(tree->right){ tree = tree->right; temp_level++; } else { tree->right = (struct node*)malloc(sizeof(struct node)); tree->right->value = temp; tree->right->level = temp_level + 1; tree->right->left = NULL; tree->right->right = NULL; break; } } } } void Push(struct node *x){ queue[++tail] = *x; } struct node *Pop(){ return &queue[head++]; } void level_traversal(){ struct node *temp = header; Push(header); while(head <= tail){ temp = Pop(); if(temp->left) Push(temp->left); if(temp->right) Push(temp->right); } } int main(int argc, char *argv[]){ int temp; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &temp); if(temp >= -1000 && temp <= 1000) Insert(temp); } level_traversal(); max_level = queue[tail].level; for(int i = tail; i >= 0; i--){ if(queue[i].level == max_level) first++; else if(queue[i].level == max_level - 1) second++; else break; } printf("%d + %d = %d\n", first, second, first + second); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(int argc, char *argv[]){ char inp[101]; char ans[101]; int i, sum=0, rev_sum=0; scanf("%s",inp); for(i=0;i<strlen(inp);i++) sum+=inp[i]-'0'; i=0; while(sum){ ans[i++]=sum%10+'0'; sum/=10; } ans[i]=0; i--; while(i>=1){ switch(ans[i]){ case '1': printf("one "); break; case '2': printf("two "); break; case '3': printf("three "); break; case '4': printf("four "); break; case '5': printf("five "); break; case '6': printf("six "); break; case '7': printf("seven "); break; case '8': printf("eight "); break; case '9': printf("nine "); break; default: printf("zero "); break; } i--; } switch(ans[i]){ case '1': printf("one\n"); break; case '2': printf("two\n"); break; case '3': printf("three\n"); break; case '4': printf("four\n"); break; case '5': printf("five\n"); break; case '6': printf("six\n"); break; case '7': printf("seven\n"); break; case '8': printf("eight\n"); break; case '9': printf("nine\n"); break; default: printf("zero\n"); break; } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct team{ char account[11]; char password[11]; int flag; }; struct team team[1000], temp[1000]; int N; int cmp(const void *a, const void *b){ struct team *c, *d; c=(struct team*)a; d=(struct team*)b; return d->flag-c->flag; } int main(int argc, char *argv[]){ //char *temp; int count=0; scanf("%d",&N); for(int i=0;i<N;i++){ scanf("%s%s",team[i].account,team[i].password); strcpy(temp[i].account,team[i].account); strcpy(temp[i].password,team[i].password); if(strchr(team[i].password,'1')||strchr(team[i].password,'0')||strchr(team[i].password,'l')||strchr(team[i].password,'O')){ team[i].flag=1; temp[i].flag=1; } } qsort(temp,N,sizeof(team[0]),cmp); if(!temp[0].flag){ if(N>1) printf("There are %d accounts and no account is modified\n", N); else printf("There is 1 account and no account is modified\n"); return 0; } for(int i=0;i<N;i++){ if(team[i].flag){ if(strchr(team[i].password,'1')){ for(int j=0;j<strlen(team[i].password);j++){ if(team[i].password[j]=='1') team[i].password[j]='@'; } } if(strchr(team[i].password,'l')){ for(int j=0;j<strlen(team[i].password);j++){ if(team[i].password[j]=='l') team[i].password[j]='L'; } } if(strchr(team[i].password,'0')){ for(int j=0;j<strlen(team[i].password);j++){ if(team[i].password[j]=='0') team[i].password[j]='%'; } } if(strchr(team[i].password,'O')){ for(int j=0;j<strlen(team[i].password);j++){ if(team[i].password[j]=='O') team[i].password[j]='o'; } } count++; } } printf("%d\n",count); for(int i=0;i<N;i++){ if(team[i].flag) printf("%s %s\n",team[i].account,team[i].password); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> int N; int main(int argc, char *argv[]){ long long a, b, c; long long ans; int flag=1; scanf("%d",&N); for(int i=0;i<N;i++){ flag=1; scanf("%lld%lld%lld",&a,&b,&c); ans=a+b; if(a>=0&&b>=0&&ans<0) flag=1; else if(a<0&&b<0&&ans>=0) flag=0; else{ if(ans<=c) flag=0; } if(flag) printf("Case #%d: true\n",i+1); else printf("Case #%d: false\n",i+1); } }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int K; struct stu{ char name[9]; int height; }stu[10000]; int cmp(const void *a, const void *b){ struct stu *c, *d; c = (struct stu*) a; d = (struct stu*) b; if(c->height != d->height) return c->height - d->height; return strcmp(d->name, c->name); } void change(int head, int tail, int len){ struct stu temp[len]; int flag = 1; int pos = len / 2; for(int i = 0; i < len; i++){ pos += i * flag; temp[pos] = stu[tail - i]; flag *= -1; } for(int i = head; i <= tail; i++) stu[i] = temp[i-head]; } int main(int argc, char *argv[]){ int i; int num; scanf("%d%d", &N, &K); num = N / K; for(i = 0; i < N; i++){ getchar(); scanf("%s", stu[i].name); scanf("%d", &stu[i].height); } qsort(stu, N, sizeof(stu[0]), cmp); for(i = 0; i < K - 1; i++){ change(i * num, i * num + num - 1, num); } change(i * num, N - 1, N - i * num); for(int j = i * num; j < N-1; j++) printf("%s ", stu[j].name); printf("%s\n", stu[N-1].name); for(int j = i - 1; j >= 0; j--){ for(int k = j * num; k < j * num + num - 1; k++){ printf("%s ", stu[k].name); } printf("%s\n", stu[j * num + num - 1].name); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define infinity 2147483647 #define max 501 struct path{ int size;//表示相同最短路径条数(如size=1表示只有一条最短路径) int vertex[max];//用来存放最短路径中上一个定点(包含相同最短路径) }path [max];//建立一个结构数组用来存放每个点的最短路径信息 int dis[max];// int visited[max];//表示某个点是否被访问过 int tmp_vertax[max],top=0;//最短路径 int min_path_vertex[max],v=0;//符合题意的最短路径 int C_max,N,S_p,M;//四个参数 int C[max];//每个站自行车数量 int T[max][max];//相邻站所需时间 int Send=infinity,collect=infinity;//送出数量、取回数量 void Dijkstra();//找出所有最短路径 void Dfs(int S_p);//找出相同最短路径中符合题意的路径 void Print_path();//输出答案 void Scan_parameter();//第一行及第二行输入 void Scan_T();//后M行输入 void Initial_visited_T();//初始化visited和T数组 void Initial_path_dist();//初始化path和dist数组 int main(int argc, const char * argv[]) { Scan_parameter(); Initial_visited_T(); Scan_T(); Initial_path_dist(); visited[0]=1; Dijkstra(); Dfs(S_p); Print_path(); } void Scan_parameter(){ int i; scanf("%d%d%d%d",&C_max,&N,&S_p,&M); for(i=1;i<=N;i++) scanf("%d",&C[i]); } void Scan_T(){ int i,j,k,l; for(l=1;l<=M;l++){ scanf("%d%d%d",&i,&j,&k); T[i][j]=T[j][i]=k; } } void Initial_visited_T(){ int i,j; memset(visited,0,sizeof(visited));//将visited数组全部置零 for(i=0;i<=N;i++) for(j=0;j<=N;j++) if(i==j) T[i][j]=0; else T[i][j]=infinity;//初始化T数组 } void Initial_path_dist(){ int i; for(i=0;i<=N;i++) memset(path[i].vertex,-1,sizeof(path[i].vertex));//所有path结构中vertex数组全部赋值-1 for(i=0;i<=N;i++){ dis[i]=T[0][i]; if(i&&dis[i]!=infinity) path[i].vertex[path[i].size++]=0;//对所有与PMBC邻接的站赋值 } } void Dijkstra(){ int i,j,k=0; int min_dis=infinity; for(i=1;i<=N;i++){ min_dis=infinity; for(j=0;j<=N;j++) if(visited[j]==0&&dis[j]<min_dis){min_dis=dis[j];k=j;}//找出所有未访问点中距离最小的点 visited[k]=1;//该点已经访问过 for(j=0;j<=N;j++){ if(visited[j]==0&&T[k][j]!=infinity){ if(dis[j]>dis[k]+T[k][j]){ dis[j]=dis[k]+T[k][j]; path[j].vertex[0]=k; path[j].size=1; }//假如未访问的点的距离不是最短,则将其置为最短并将其上一个点的值和路径数目改变 else if(dis[j]==dis[k]+T[k][j]) path[j].vertex[path[j].size++]=k;//若发现相同且最短距离,则将最短路径数目增加1 } } } } void Dfs(int S_p){ int i; tmp_vertax[top++]=S_p;//最短路径点储存 if(S_p==0)//若找到了起点0 { int s=0,c=0;//送出数量、取回数量 for(i=top-2;i>=0;i--)//总收回取出数量计算 { c+=-C_max/2+C[tmp_vertax[i]];//当前站应该收回的数量 if(c<0){ s+=-c;//收回数量为负值表示应该送出 c=0; } } if(s<Send||(s==Send&&c<collect))//找到取回PMBC数量最少 { collect=c; Send=s; v=0; for(i=top-1;i>=0;i--) min_path_vertex[v++]=tmp_vertax[i]; } return; } for(i=0;i<path[S_p].size;i++) {Dfs(path[S_p].vertex[i]);top--;}//对每条相同距离路径进行计算 } void Print_path(){ int i; printf("%d ",Send);//输出送出值 for(i=0;i<v-1;i++) printf("%d->",min_path_vertex[i]);//输出除最后一个点之外的路径 printf("%d %d",S_p,collect);//输出最后一个点和取回值 }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; int MSize; int hash[100000]; int prime(int a){ if(a == 1) return 0; if(a == 2 || a == 3) return 1; for(int i = 2; i <= sqrt(a); i++){ if(a % i == 0) return 0; } return 1; } int main(int argc, char *argv[]){ int inp; int flag = 0; memset(hash, -1, sizeof(hash)); scanf("%d%d", &MSize, &N); while(!prime(MSize)) MSize++; for(int i = 0; i < N; i++){ scanf("%d", &inp); flag = 0; for(int j = 0; j < MSize; j++){ if(hash[(inp + j * j) % MSize] == -1){ if(i != N - 1) printf("%d ", (inp + j * j) % MSize); else printf("%d\n", (inp + j * j) % MSize); hash[(inp + j * j) % MSize] = 1; flag = 1; break; } } if(!flag){ if(i == N - 1) printf("-\n"); else printf("- "); } } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct digit{ int M; int num[10000]; }digit[50]; struct numb{ int value; struct numb *next; }head,*temp3,*temp4; int N; int M; int N_C; int N_T; int main(int argc, char *argv[]){ int i, j, k; int temp; int count; scanf("%d",&N); for(i=0;i<N;i++){ head.next=NULL; temp3=NULL; temp4=NULL; count=0; scanf("%d",&digit[i].M); for(j=0;j<digit[i].M;j++){ scanf("%d",&temp); temp3=(struct numb*)malloc(sizeof(struct numb)); temp3->value=temp; if(head.next==NULL){temp3->next=head.next;head.next=temp3;} else{ temp4=&head; while(temp4->next&&temp4->next->value<temp){ temp4=temp4->next; } if(temp4->next){ if(temp4->next->value==temp) count++; else {temp3->next=temp4->next;temp4->next=temp3;} } else{ if(temp4->value<temp) {temp3->next=NULL;temp4->next=temp3;} else if(temp4->value==temp) count++; } } } temp4=head.next; j=0; while(temp4){ digit[i].num[j++]=temp4->value; temp4=temp4->next; } digit[i].M-=count; } /*for(i=0;i<N;i++){ printf("\n%d %d\n",digit[i].M,N); for(j=0;j<digit[i].M;j++) printf("%d ",digit[i].num[j]); }*/ scanf("%d",&M); int temp1, temp2; int head, tail; double ans; for(i=0;i<M;i++){ scanf("%d%d",&temp1,&temp2); N_C=0; N_T=digit[temp1-1].M+digit[temp2-1].M; for(j=0;j<digit[temp1-1].M;j++){ head=0;tail=digit[temp2-1].M-1; while(head<=tail){ temp=digit[temp1-1].num[j]; if(digit[temp2-1].num[(head+tail)/2]>digit[temp1-1].num[j]) tail=(head+tail)/2-1; else if(digit[temp2-1].num[(head+tail)/2]<digit[temp1-1].num[j]) head=(head+tail)/2+1; else {N_C++;break;} } } N_T-=N_C; ans=N_C*100.0/N_T; printf("%.1lf%%\n",ans); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int main(int argc, char *argv[]){ char inp[22]; char dou[22]; int a[10]; int b[10]; int carry=0; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(inp,0,sizeof(inp)); memset(dou,0,sizeof(dou)); scanf("%s",inp); long i; for(i=strlen(inp)-1;i>=0;i--){ a[inp[i]-'0']++; if((inp[i]-'0')*2+carry<10){ dou[i]=(inp[i]-'0')*2+carry+'0'; carry=0; } else{ dou[i]=(inp[i]-'0')*2+carry-10+'0'; carry=1; } b[dou[i]-'0']++; } for(i=0;i<=9;i++) if(a[i]!=b[i]) break; if(i<10||carry) printf("No\n"); else printf("Yes\n"); if(carry) printf("1"); puts(dou); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(int argc, char *argv[]){ int a, b; scanf("%d%d",&a,&b); if(abs(a+b)>=1000&&abs(a+b)<1000000){ if(a+b>0) printf("%d,%03d\n",(a+b)/1000,(a+b)%1000); else printf("-%d,%03d\n",-(a+b)/1000,-(a+b)%1000); } else if(abs(a+b)>=1000000){ if(a+b>=1000000) printf("%d,%03d,%03d\n",(a+b)/1000000,(a+b)%1000000/1000,(a+b)%1000); else printf("-%d,%03d,%03d\n",-(a+b)/1000000,-(a+b)%1000000/1000,-(a+b)%1000); } else { printf("%d\n",a+b); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> char inp1[60],inp2[60],inp3[60],inp4[60]; unsigned long len1, len2, len3, len4; int day; int hour; int min; int main(int argc, char *argv[]){ //scanf("%s%s%s%s",inp1,inp2,inp3,inp4); gets(inp1); gets(inp2); gets(inp3); gets(inp4); len1 = strlen(inp1); len2 = strlen(inp2); len3 = strlen(inp3); len4 = strlen(inp4); int index=0; for(int i=0;i<(len1<len2?len1:len2);i++){ if(inp1[i]>='A'&&inp1[i]<='G'&&inp1[i]==inp2[i]){ day=inp1[i]-'A'+1; index=i; break; } } for(int i=index+1;i<(len1<len2?len1:len2);i++){ if(((inp1[i]>='0'&&inp1[i]<='9')||(inp1[i]>='A'&&inp2[i]<='N'))&&inp1[i]==inp2[i]){ if(inp1[i]>='0'&&inp1[i]<='9') hour=inp1[i]-'0'; else hour=10+inp1[i]-'A'; break; } } for(int i=0;i<(len3<len4?len3:len4);i++){ if(((inp3[i]>='A'&&inp3[i]<='Z')||(inp3[i]>='a'&&inp4[i]<='z'))&&inp3[i]==inp4[i]){ min=i; break; } } switch(day){ case 1: printf("MON ");break; case 2: printf("TUE ");break; case 3: printf("WED ");break; case 4: printf("THU ");break; case 5: printf("FRI ");break; case 6: printf("SAT ");break; default: printf("SUN ");break; } printf("%02d:%02d\n",hour,min); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(int argc, char *argv[]){ int N; scanf("%d",&N); int i; int a[N]; int flag=0; for(i=0;i<N;i++){ scanf("%d",&a[i]); if(a[i]>=0) flag=1; } int temp_sum=0, temp_max=-1, head=a[0], tail=a[0]; int first=head, second=tail; for(i=0;i<N;i++){ temp_sum+=a[i]; tail=a[i]; if(temp_sum<0) {temp_sum=0;head=a[i+1];tail=a[i+1];} if(temp_sum>temp_max){ temp_max=temp_sum; first=head; second=tail; } } if(N==0) return 0; else{ if(!flag) printf("%d %d %d\n", 0, a[0], a[N-1]); else printf("%d %d %d\n",temp_max, first, second); return 0; } }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int a[2][100000];//0 for positive, 1 for negative int b[2][100000]; int NC, ND; int tail_C_P, tail_C_N; int tail_D_P, tail_D_N; long long total; int cmp(const void *a, const void *b){ return abs(*(int *)a)-abs(*(int *)b); } int main(int argc, char *argv[]){ int temp; scanf("%d",&NC); for(int i=0;i<NC;i++){ scanf("%d",&temp); if(temp>0) a[0][tail_C_P++]=temp; else a[1][tail_C_N++]=temp; } qsort(a[0],tail_C_P,sizeof(int),cmp); qsort(a[1],tail_C_N,sizeof(int),cmp); scanf("%d",&ND); for(int i=0;i<ND;i++){ scanf("%d",&temp); if(temp>0) b[0][tail_D_P++]=temp; else b[1][tail_D_N++]=temp; } qsort(b[0],tail_D_P,sizeof(int),cmp); qsort(b[1],tail_D_N,sizeof(int),cmp); while(tail_C_P>=0&&tail_D_P>=0){ total+=a[0][tail_C_P]*b[0][tail_D_P]; tail_C_P--; tail_D_P--; } while(tail_D_N>=0&&tail_D_N>=0){ total+=a[1][tail_C_N]*b[1][tail_D_N]; tail_C_N--; tail_D_N--; } printf("%lld\n",total); return 0; }<file_sep>#include <iostream> #include <cstdio> #include <cstring> using namespace std; int N, M, K; struct edge{ int v1, v2; }edge[10000]; int check[10000]; int check_edge(){ for(int i = 0; i < M; i++){ if(!check[edge[i].v1] && !check[edge[i].v2]) return 0; } return 1; } int main(int argc, char *argv[]){ int Nv = 0, num = 0, flag; cin >> N >> M; for(int i = 0; i < M; i++){ cin >> edge[i].v1 >> edge[i].v2; } cin >> K; while(K--){ cin >> Nv; flag = 1; memset(check, 0, sizeof(check)); while(Nv--){ cin >> num; if(num >= N) flag = 0; else{ check[num] = 1; } } if(!flag) cout << "No" << endl; else{ if(check_edge()) cout << "Yes" << endl; else cout << "No" << endl; } } return 0; }<file_sep>#include <iostream> #include <string> #include <vector> #include <climits> #include <cstdio> #include <stdexcept> #include <map> using namespace std; map<string, int> m; int main(int argc, char *argv[]){ string a, b; int max = -1; getline(cin,a); for(auto i: a){ if(isalnum(i)){ b += tolower(i); } else{ if(b.length()) m[b]++; b.clear(); } } if(b.length()) m[b]++; for(auto i = m.begin(); i != m.end(); i++){ if(i->second > max){ max = i->second; b = i->first; } } cout<<b<<" "<<max<<endl; return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int ini[100], sort[100]; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int check(){ for(int i = 0; i < N; i++){ if(ini[i] != sort[i]) return 0; } return 1; } int check_if_insertion(){ int flag = 1; int i; for(i = 1; i < N; i++){ if(sort[i] < sort[i-1]) {flag = i;break;} } for(; i < N; i++){ if(sort[i] != ini[i]) flag = 0; } return flag; } void Print_insertion(int flag){ int i; puts("Insertion Sort"); for(i = flag - 1; i >= 0; i--){ if(sort[i] < sort[flag]) break; } for(int j = 0; j <= i; j++){ printf("%d ", sort[j]); } if(i != N-2) printf("%d ", sort[flag]); for(int j = i + 1; j < N - 1; j++){ if(j!=flag)printf("%d ", sort[j]); } printf("%d\n", sort[N-1]); } void Print_Merge(){ int i, j; puts("Merge Sort"); for(i = 2; i < N; i*=2){ for(j = 0; j < N; j += i){ if(N - j >= i) qsort(ini + j, i, sizeof(int), cmp); else qsort(ini, N - j, sizeof(int), cmp); } if(check()) break; } i *= 2; if(i > N) i = N; for(j = 0; j < N; j += i){ if(N - j >= i) qsort(ini + j, i , sizeof(int), cmp); else qsort(ini + j, N - j, sizeof(int), cmp); } for(i = 0; i < N - 1; i++){ printf("%d ", ini[i]); } printf("%d\n", ini[N-1]); } int main(){ int i; int flag; scanf("%d", &N); for(i = 0; i < N; i++){ scanf("%d", &ini[i]); } for(i = 0; i < N; i++){ scanf("%d", &sort[i]); } flag = check_if_insertion(); if(flag){ Print_insertion(flag); } else{ Print_Merge(); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; double price; double r; int max; int total; double ans; int Union[100000]; int count[100000]; int find(int pos){ if(Union[pos] == -1) return 1; if(count[pos] != 1) return count[pos]; count[pos] += find(Union[pos]); return count[pos]; } int main(){ scanf("%d%lf%lf", &N, &price, &r); for(int i = 0; i < N; i++){ scanf("%d", &Union[i]); count[i] = 1; } for(int i = 0; i < N; i++){ find(i); if(count[i] > max) max = count[i]; } for(int i = 0; i < N; i++){ if(count[i] == max) total++; } for(int i = 0; i < max - 1; i++){ price *= (1 + r / 100.0); } printf("%.2lf %d\n", price, total); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int M; int N; int L; int T; long long local_count = 0, count; char slice[60][1286][128]; int queue[60*1286*128][3]; int head, tail; void Push(int i, int j, int k){ queue[tail][0] = i; queue[tail][1] = j; queue[tail][2] = k; tail++; } int *Pop(){ return queue[head++]; } void DFS(int i, int j, int k){ int *temp; while(head < tail){ temp = Pop(); i = temp[0]; j = temp[1]; k = temp[2]; local_count++; if(i - 1 >= 0 && slice[i-1][j][k] == 1){ Push(i - 1, j, k); slice[i-1][j][k] = 2; } if(i + 1 < L && slice[i+1][j][k] == 1){ Push(i + 1, j, k); slice[i+1][j][k] = 2; } if(j - 1 >= 0 && slice[i][j-1][k] == 1){ Push(i, j - 1, k); slice[i][j-1][k] = 2; } if(j + 1 < M && slice[i][j+1][k] == 1){ Push(i, j + 1, k); slice[i][j+1][k] = 2; } if(k - 1 >= 0 && slice[i][j][k-1] == 1){ Push(i, j, k - 1); slice[i][j][k-1] = 2; } if(k + 1 < N && slice[i][j][k+1] == 1){ Push(i, j, k + 1); slice[i][j][k+1] = 2; } } } int main(){ scanf("%d%d%d%d", &M, &N, &L, &T); for(int i = 0; i < L; i++){ for(int j = 0; j < M; j++){ for(int k = 0; k < N; k++){ getchar(); scanf("%c", &slice[i][j][k]); slice[i][j][k] -= '0'; } } } for(int i = 0; i < L; i++){ for(int j = 0; j < M; j++){ for(int k = 0; k < N; k++){ if(slice[i][j][k] == 1){ Push(i, j, k); slice[i][j][k] = 2; DFS(i, j, k); if(local_count >= T) count += local_count; local_count = 0; } } } } printf("%lld\n", count); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> int minus[256]; char inp[10000]; char delete[10000]; unsigned long len; int j; int main(int argc, char *argv[]){ gets(inp); gets(delete); len=strlen(inp); for(int i=0;i<strlen(delete);i++) minus[delete[i]]=1; for(int i=0;i<len;i++) if(minus[inp[i]]) inp[i]=0; for(int i=0;i<len;i++) if(inp[i]) inp[j++]=inp[i]; printf("%s\n",inp); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> int N, D; struct mooncake{ double amount; double price; double ave; }a[2000]; int cmp(const void *a, const void *b){ return (((struct mooncake *)b)->ave) > (((struct mooncake *)a)->ave); } int main(int argc, const char * argv[]) { scanf("%d%d", &N, &D); for(int i=0; i<N; i++) scanf("%lf", &a[i].amount); for(int i=0; i<N; i++){ scanf("%lf", &a[i].price); a[i].ave = a[i].price / a[i].amount; } qsort(a, N, sizeof(struct mooncake), cmp); int count = 0; double sum = 0; while(a[count].amount < D && count < N){ sum += a[count].price; D -= a[count++].amount; } if(D) sum += a[count].ave * D; printf("%.2lf\n", sum); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 2<<29 int N; int M; int coin[100000]; int cmp(const void *a, const void *b){ return *(int *)a-*(int *)b; } int dichotomy(int i){ int front=i+1, tail=N-1; int middle; while(front<=tail){ middle=(front+tail)/2; if(coin[middle]==M-coin[i]) return middle; else if(coin[middle]>M-coin[i]) tail=middle-1; else front=middle+1; } return -1; } int main(int argc, char *argv[]){ int i, ans=-1; int flag=0; scanf("%d%d",&N,&M); for(i=0;i<N;i++) scanf("%d",&coin[i]); qsort(coin,N,sizeof(int),cmp); for(i=0;i<N;i++){ ans=dichotomy(i); if(ans!=-1) {flag=1; break;} } if(flag) printf("%d %d\n",coin[i],coin[ans]); else printf("No Solution\n"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> typedef struct node *NODE; struct node{ int ID; int num; int *child; }; int main(int argc, char *argv[]){ int N, M; int i,j; int id, level; scanf("%d%d",&N, &M); int count[1000]; int queue[1000]; int head=0, tail=0, temp=0; memset(count,0,sizeof(count)); struct node a[1000]; for(i=0;i<N;i++) a[i].ID=i; for(i=0;i<M;i++){ scanf("%d",&id); scanf("%d",&a[id].num); a[id].child=malloc(sizeof(int)*a[id].num); for(j=0;j<a[id].num;j++){ scanf("%d",&a[id].child[j]); } } i=0;j=0; level=1; queue[0]=1; while(head<=tail){ if(!a[queue[head]].num) count[level]++; else{ for(i=0;i<a[queue[head]].num;i++){ queue[++tail]=a[queue[head]].child[i]; } } if(head==temp) {level++;temp=tail;} head++; } for(i=1;i<level-1;i++) printf("%d ",count[i]); printf("%d\n",count[i]); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int K; int Q; int max; int trees; int Union[10001]; int find(int x){ if(Union[x] < 0) return x; return Union[x] = find(Union[x]); } void merge(int a, int b){ int x = find(a), y = find(b); if(x != y){ Union[y] += Union[x]; Union[x] = y; } } int main(int argc, char *argv[]){ int bird1, bird2; scanf("%d", &N); memset(Union, -1, sizeof(Union)); for(int i = 0; i < N; i++){ scanf("%d", &K); if(K){ scanf("%d", &bird1); if(bird1 > max) max = bird1; } for(int j = 1; j < K; j++){ scanf("%d", &bird2); if(bird2 > max) max = bird2; merge(bird1, bird2); } } for(int i = 1; i <= max; i++){ if(Union[i] < 0) trees++; } printf("%d %d\n", trees, max); scanf("%d", &Q); for(int i = 0; i < Q; i++){ scanf("%d%d", &bird1, &bird2); if(find(bird1) == find(bird2)) printf("Yes\n"); else printf("No\n"); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct station{ double P_i; double D_i; }; double C_max; double D; double D_avg; int N; struct station a[501]; int cmp(const void *a, const void *b){ return ((struct station*)a)->D_i-(((struct station*)b)->D_i); } int main(int argc, char *argv[]){ int i, j, index, index1; int flag, flag1; double max_dis; double min,min1; double price=0; double remain; scanf("%lf%lf%lf%d",&C_max, &D, &D_avg, &N); for(i=0;i<N;i++){ scanf("%lf%lf",&a[i].P_i,&a[i].D_i); } a[i].P_i=-1; a[i].D_i=D; max_dis=D_avg*C_max; qsort(a,N,sizeof(a[0]),cmp); //for(int i=0;i<N;i++) printf("%.2f %d\n",a[i].P_i,a[i].D_i); remain=0; if(a[0].D_i){ printf("The maximum travel distance = 0.00\n"); return 0; } for(i=0;i<N+1;){ j=i+1; flag=0; flag1=0; index=j; index1=j; min=a[i].P_i; min1=a[i+1].P_i; if(i!=N){ while(a[j].D_i-a[i].D_i<=max_dis&&j<N+1){ if(a[j].P_i<min){ min=a[j].P_i; index=j; flag=1; break; } else if(a[j].P_i<min1){ min1=a[j].P_i; index1=j; flag1=0; } j++; flag1=1; } if(flag){ if(remain*D_avg<a[index].D_i-a[i].D_i){ price+=(a[index].D_i-a[i].D_i-remain*D_avg)/D_avg*a[i].P_i; remain=(a[index].D_i-a[i].D_i)/D_avg; } remain-=(a[index].D_i-a[i].D_i)/D_avg; i=index; } else if(flag1){ price+=(C_max-remain)*a[i].P_i; remain=C_max; remain-=(a[index1].D_i-a[i].D_i)/D_avg; i=index1; } else{ printf("The maximum travel distance = %.2lf\n",a[i].D_i+max_dis); return 0; } } else { i++; } } //for(int i=0;i<N;i++) printf("%.2f %d\n",a[i].P_i,a[i].D_i); printf("%.2lf\n",price); }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int M; int N; int S; int count; char forward[1001][21]; char ans[1001][21]; int check(char *temp){ int flag = 1; for(int i = 0;i < count; i++) if(!strcmp(ans[i], temp)){ flag = 0; break; } return flag; } int main(int argc, char *argv[]){ scanf("%d%d%d", &M, &N, &S); getchar(); for(int i = 1; i <= M; i++){ scanf("%s", forward[i]); } if(S > M) printf("Keep going...\n"); else{ while(S <= M){ if(check(forward[S])) strcpy(ans[count++], forward[S]); else{ while(!check(forward[S]) && S <= M){ S++; } if(check(forward[S])) strcpy(ans[count++], forward[S]); } S += N; } for(int i = 0; i < count; i++) printf("%s\n", ans[i]); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int N, M, K, Q; int window[20][1000]; int T[1000]; int len[20]; int querey[1000]; int past_time[20]; int pos[20]; int main(int argc, char *argv[]){ int i, j, k=0, l; scanf("%d%d%d%d",&N,&M,&K,&Q); int win=0, time=0; int hour=0, min=0; int count=0; int flag=0; memset(T,0,sizeof(T)); memset(len,0,sizeof(len)); memset(pos,0,sizeof(pos)); memset(past_time,0,sizeof(past_time)); for(int i=0;i<K;i++) scanf("%d",&T[i]); for(int i=0;i<Q;i++) scanf("%d",&querey[i]); if(K<=M*N){ for(i=0;i<K;i++){ window[i%N][len[i%N]++]=i; } for(i=0;i<Q;i++){ time=0; win=(querey[i]-1)%N; for(j=0;j<(querey[i]-1)/N;j++) time+=T[window[win][j]]; hour=time/60; min=time-hour*60; if(hour+8>=17) printf("Sorry\n"); else { time+=T[querey[i]-1]; hour=time/60; min=time-hour*60; printf("%02d:%02d\n", hour+8, min); } } } else{ for(i=0;i<M*N;i++){ window[i%N][len[i%N]++]=i; } i=0; while(count<K-M*N){ for(j=0;j<N;j++){ if(pos[j]<len[j]){ if(T[window[j][pos[j]]]+past_time[j]==i){ past_time[j]+=T[window[j][pos[j]]]; pos[j]++; window[j][len[j]++]=N*M+(count++); } } } i++; } /*for(i=0;i<N;i++){ for(j=0;j<len[i];j++){ printf("%d ",window[i][j]+1); } printf("\n"); }*/ for(i=0;i<Q;i++){ time=0; count=0; flag=0; if(querey[i]<=M*N){ win=(querey[i]-1)%N; for(j=0;j<(querey[i]-1)/N;j++) time+=T[window[win][j]]; hour=time/60; min=time-hour*60; if(hour+8>=17) printf("Sorry\n"); else{ time+=T[querey[i]-1]; hour=time/60; min=time-hour*60; printf("%02d:%02d\n",hour+8,min); } } else{ for(j=M;j<1000;j++){ for(k=0;k<N;k++){ if(window[k][j]+1==querey[i]) {flag=1;break;} } if(window[k][j]+1==querey[i]) break; } for(l=0;l<j;l++){ time+=T[window[k][l]]; } //printf("%d\n",time); hour=time/60; min=time-hour*60; if(hour+8>=17) printf("Sorry\n"); else { time+=T[querey[i]-1]; hour=time/60; min=time-hour*60; printf("%02d:%02d\n",hour+8,min); } } } } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> struct pat{ int id; int order; int pro[6]; int perfect; int sum; int submit_with_score; }pat[10010]; int problem[6]; int N; int K; int M; int cmp(const void *a, const void *b){ struct pat *c, *d; c = (struct pat*) a; d = (struct pat*) b; if(c->sum != d->sum) return d->sum - c->sum; if(c->perfect != d->perfect) return d->perfect - c->perfect; if(c->submit_with_score != d->submit_with_score) return d->submit_with_score - c->submit_with_score; return c->id - d->id; } int main(int argc, char *argv[]){ int temp; int num; int score; scanf("%d%d%d", &N, &K, &M); for(int i = 1; i <= K; i++) scanf("%d", &problem[i]); for(int i = 0; i <= N; i++){ memset(pat[i].pro, -1, sizeof(int) * 6); pat[i].id = i; } for(int i = 0; i < M; i++){ scanf("%d%d%d", &temp, &num, &score); if(pat[temp].pro[num] == -1) pat[temp].pro[num] = 0; if(score > pat[temp].pro[num]){ pat[temp].sum -= pat[temp].pro[num]; pat[temp].sum += score; pat[temp].pro[num] = score; if(problem[num] == score) pat[temp].perfect++; } if(score != -1) pat[temp].submit_with_score = 1; } qsort(pat+1, N, sizeof(struct pat), cmp); pat[1].order = 1; if(pat[1].sum > 0 || pat[1].submit_with_score){ printf("%d %05d %d", pat[1].order, pat[1].id, pat[1].sum); for(int i = 1; i <= K; i++){ if(pat[1].pro[i] == -1) printf(" -"); else printf(" %d", pat[1].pro[i]); } printf("\n"); } for(int i = 2; i <= N; i++){ if(pat[i].submit_with_score){ if(pat[i].sum == pat[i-1].sum){ pat[i].order = pat[i-1].order; } else{ pat[i].order = i; } printf("%d %05d %d", pat[i].order, pat[i].id, pat[i].sum); for(int j = 1; j <= K; j++){ if(pat[i].pro[j] == -1) printf(" -"); else printf(" %d", pat[i].pro[j]); } printf("\n"); } else break; } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct book{ char ID[8]; int num; char title[81]; char author[81]; char key[55]; char word[5][11]; char pub[81]; char year[5]; }; int cmp(const void *a, const void *b){ struct book *c=(struct book *)a; struct book *d=(struct book *)b; return strcmp(c->ID,d->ID); } int main(int argc, char *argv[]){ int N, i, j, k; int M; int temp; int count; char que[1000][100]; struct book a[10001]; scanf("%d",&N); getchar(); for(i=0;i<N;i++){ gets(a[i].ID); gets(a[i].title); gets(a[i].author); gets(a[i].key); gets(a[i].pub); gets(a[i].year); count=0; temp=0; for(j=0;j<strlen(a[i].key);j++){ if(a[i].key[j]!=' ') a[i].word[count][temp++]=a[i].key[j]; else {a[i].word[count][temp]=0;count++;temp=0;} } a[i].num=count; } qsort(a,N,sizeof(a[0]),cmp); /*for(i=0;i<N;i++){ printf("%d\n",a[i].num); for(j=0;j<=a[i].num;j++) puts(a[i].word[j]); }*/ scanf("%d",&M); getchar(); for(i=0;i<M;i++){ gets(que[i]); } for(i=0;i<M;i++){ count=0; puts(que[i]); temp=que[i][0]-'0'; if(temp==1){ for(j=0;j<N;j++){ if(strcmp(que[i]+3,a[j].title)==0){printf("%s\n",a[j].ID);count++;} } } else if(temp==2){ for(j=0;j<N;j++){ if(strcmp(que[i]+3,a[j].author)==0){printf("%s\n",a[j].ID);count++;} } } else if(temp==3){ for(j=0;j<N;j++){ for(k=0;k<=a[j].num;k++) if(strcmp(que[i]+3,a[j].word[k])==0){printf("%s\n",a[j].ID);count++;break;} } } else if(temp==4){ for(j=0;j<N;j++){ if(strcmp(que[i]+3,a[j].pub)==0){printf("%s\n",a[j].ID);count++;} } } else { for(j=0;j<N;j++){ if(strcmp(que[i]+3,a[j].year)==0){printf("%s\n",a[j].ID);count++;} } } if(!count) printf("Not Found\n"); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> int inp[100000]; int hash[100000]; int Union[100000]; int count; int flag[100000]; int main(int argc, const char * argv[]) { int N; int temp; int group = 0; int first = 0; scanf("%d", &N); count = N; for(int i=0; i<N;i++) Union[i]=i; for(int i=0; i<N;i++){ scanf("%d",&inp[i]); hash[inp[i]] = i; if(inp[i] == i) count--; } //printf("%d\n",count); temp = hash[0]; flag[temp] = 1; while(temp){ temp = hash[temp]; flag[temp] = 1; } if(inp[0] == 0) first = 0; else first = 1; for(int i=0;i<N;i++){ if(!flag[i] && inp[i] != i){ temp = i; flag[i] = 1; while(hash[temp] != i){ temp = hash[temp]; flag[temp] = 1; } group++; } } if(count) printf("%d\n", count-first+group); else printf("%d\n", count); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; int M; int K; struct app{ int id; int GE; int GI; int total; int rank; int choice[5]; }app[40000]; struct sch{ int quota; int count; int stu[40000]; }sch[100]; int cmp(const void *a, const void *b){ struct app *c, *d; c = (struct app*)a; d = (struct app*)b; if(c->total != d->total) return d->total - c->total; if(c->GE != d->GE) return d->GE - c->GE; return c->choice[0] - d->choice[0]; } int cmp1(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ scanf("%d%d%d", &N, &M, &K); for(int i = 0; i < M; i++){ scanf("%d", &sch[i].quota); } for(int i = 0; i < N; i++){ scanf("%d%d", &app[i].GE, &app[i].GI); app[i].total = app[i].GE + app[i].GI; app[i].id = i; for(int j = 0; j < K; j++){ scanf("%d", &app[i].choice[j]); } } qsort(app, N, sizeof(app[0]), cmp); app[0].rank = 1; for(int i = 1; i < N; i++){ if((app[i].total < app[i-1].total) || (app[i].total == app[i-1].total && app[i].GE < app[i-1].GE)) app[i].rank = app[i-1].rank + 1; else if(app[i].total == app[i-1].total && app[i].GE == app[i-1].GE) app[i].rank = app[i-1].rank; } for(int i = 0; i < N; i++){ for(int j = 0; j < K; j++){ if(sch[app[i].choice[j]].count < sch[app[i].choice[j]].quota){ sch[app[i].choice[j]].stu[sch[app[i].choice[j]].count++] = app[i].id; break; } else{ if(app[app[i].id].rank == app[sch[app[i].choice[j]].stu[sch[app[i].choice[j]].count - 1]].rank){ //printf("i = %d %d %d %d\n", i, app[i].rank, sch[app[i].choice[j]].stu[sch[app[i].choice[j]].count - 1], app[sch[app[i].choice[j]].stu[sch[app[i].choice[j]].count - 1]].rank); sch[app[i].choice[j]].stu[sch[app[i].choice[j]].count++] = app[i].id; break; } } } } for(int i = 0; i < M; i++){ qsort(sch[i].stu, sch[i].count, sizeof(int), cmp1); } for(int i = 0; i < M; i++){ if(sch[i].count == 0){ printf("\n"); continue; } for(int j = 0; j < sch[i].count - 1; j++){ printf("%d ", sch[i].stu[j]); } printf("%d\n", sch[i].stu[sch[i].count-1]); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<math.h> int hash[10010]; struct list{ int value; int next; }list[100010]; struct removed{ int addr; int value; }remained[100010], removed[100010]; int head; int count1, count2; int N; int main(int argc, char *argv[]){ int addr; scanf("%d%d", &head, &N); for(int i = 0; i < N; i++){ scanf("%d", &addr); scanf("%d%d", &list[addr].value, &list[addr].next); } addr = head; while(addr != -1){ if(hash[abs(list[addr].value)]){ removed[count2].value = list[addr].value; removed[count2].addr = addr; count2++; } else{ remained[count1].value = list[addr].value; remained[count1].addr = addr; count1++; hash[abs(list[addr].value)] = 1; } addr = list[addr].next; } for(int i = 0; i < count1 - 1; i++) printf("%05d %d %05d\n", remained[i].addr, remained[i].value, remained[i+1].addr); printf("%05d %d -1\n", remained[count1-1].addr, remained[count1-1].value); for(int i = 0; i < count2 - 1; i++){ printf("%05d %d %05d\n", removed[i].addr, removed[i].value, removed[i+1].addr); } if(count2) printf("%05d %d -1\n", removed[count2-1].addr, removed[count2-1].value); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <limits.h> int c[2000000]; int cmp(const void *a, const void *b){ return *(int *)a-*(int *)b; } int main(int argc, char *argv[]){ int a, b,i; scanf("%d",&a); for(i=0;i<a;i++) scanf("%d",&c[i]); scanf("%d",&b); for(;i<a+b;i++) scanf("%d",&c[i]); qsort(c,a+b,sizeof(int),cmp); printf("%d\n",c[(a+b)%2?(a+b)/2:(a+b)/2-1]); return 0; }<file_sep>#include <stdio.h> #include <string.h> #define MAX 110 struct result{ char d[MAX]; int k; }; struct result getResult(char *a, int n){ struct result r; int firstPos = -1; int pointPos = -1; int index = 0; int i; for (i = 0; a[i]; i++){ if (a[i] == '.'){ pointPos = i; continue; } else if (a[i] == '0' && firstPos == -1) continue; else{ if (firstPos == -1) firstPos = i; if (index < n) { if (index < strlen(a)) r.d[index++] = a[i]; else r.d[index++] = '0'; } } } r.d[index] = 0; if (pointPos == -1) pointPos = i; if (pointPos - firstPos < 0) r.k = pointPos - firstPos + 1; else r.k = pointPos - firstPos; if (index == 0){ int i; for (i = 0; i != n; i++) r.d[i] = '0'; r.d[i] = 0; r.k = 0; } return r; } int main(){ int n; char a[MAX], b[MAX]; scanf("%d%s%s", &n, a, b); struct result r1 = getResult(a, n); struct result r2 = getResult(b, n); if (strcmp(r1.d, r2.d) == 0 && r1.k == r2.k) printf("YES 0.%s*10^%d\n", r1.d, r1.k); else printf("NO 0.%s*10^%d 0.%s*10^%d\n", r1.d, r1.k, r2.d, r2.k); return 0; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; struct node{ int value; int level; struct node *left; struct node *right; }*root; int post[30]; int in[30]; int head, tail = -1; struct node* queue[30]; int ans[30][30]; int count[30]; int final[30]; int total; struct node* build_tree(int post_head, int post_tail, int in_head, int in_tail, int len, int level){ if(len < 1) return NULL; int i; struct node* temp = malloc(sizeof(struct node)); temp->value = post[post_tail]; temp->level = level; temp->left = NULL; temp->right = NULL; for(i = in_head; i <= in_tail; i++){ if(in[i] == post[post_tail]){ break; } } temp->left = build_tree(post_head, post_head + i - in_head - 1, in_head, i - 1, i - in_head, level + 1); temp->right = build_tree(post_head + i - in_head, post_tail - 1, i + 1, in_tail, in_tail - i, level + 1); return temp; } void push(struct node* x){ queue[++tail] = x; ans[x->level][count[x->level]++] = x->value; } struct node* pop(){ return queue[head++]; } void level_traversal(){ struct node* temp; push(root); while(head <= tail){ temp = pop(); if(temp->left) push(temp->left); if(temp->right) push(temp->right); } } int main(int argc, char *argv[]){ int dir = 0, level = 0; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &in[i]); } for(int i = 0; i < N; i++){ scanf("%d", &post[i]); } root = build_tree(0, N - 1, 0, N - 1, N, 0); level_traversal(); while(count[level]){ if(dir){ for(int i = 0; i < count[level]; i++){ final[total++] = ans[level][i]; } dir = 0; } else{ for(int i = count[level] - 1; i >= 0; i--){ final[total++] = ans[level][i]; } dir = 1; } level++; } for(int i = 0; i < total; i++){ if(i < total - 1) printf("%d ", final[i]); else printf("%d\n", final[i]); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int head, tail = -1; int count; struct node{ int value; int height; struct node *left; struct node *right; }*root, *queue[21], *ans[100]; int height(struct node* node){ if(node) return node->height; else return 0; } int max(int a, int b){return a > b ? a : b;} struct node* left_left_rotation(struct node *node){ struct node* temp; temp = node->left; node->left = temp->right; temp->right = node; node->height = max(height(node->left), height(node->right)) + 1; temp->height = max(height(temp->left), height(temp->right)) + 1; return temp; } struct node* right_right_rotation(struct node *node){ struct node* temp; temp = node->right; node->right = temp->left; temp->left = node; node->height = max(height(node->left), height(node->right)) + 1; temp->height = max(height(temp->left), height(node->right)) + 1; return temp; } struct node* left_right_rotation(struct node *node){ node->left = right_right_rotation(node->left); return left_left_rotation(node); } struct node* right_left_rotation(struct node *node){ node->right = left_left_rotation(node->right); return right_right_rotation(node); } struct node* create_node(int x){ struct node* temp = malloc(sizeof(struct node)); temp->value = x; temp->height = 0; temp->left = NULL; temp->right = NULL; return temp; } struct node* insert_node(struct node* node, int x){ if(!node) node = create_node(x); else if(x < node->value){ node->left = insert_node(node->left, x); if(height(node->left) > height(node->right) + 1){ if(node->left->value < x) node = left_right_rotation(node); else node = left_left_rotation(node); } } else{ node->right = insert_node(node->right, x); if(height(node->right) > height(node->left) + 1){ if(node->right->value < x) node = right_right_rotation(node); else node = right_left_rotation(node); } } node->height = max(height(node->left), height(node->right)) + 1; return node; } void push(struct node* x){ queue[++tail] = x; } struct node* pop(){ return queue[head++]; } void level_traversal(){ struct node* temp; push(root); ans[count++] = root; while(head <= tail){ temp = pop(); if(temp->left) {push(temp->left); ans[count++] = temp->left;} else ans[count++] = NULL; if(temp->right) {push(temp->right); ans[count++] = temp->right;} else ans[count++] = NULL; } } int main(int argc, char *argv[]){ int num; int flag = 1; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &num); root = insert_node(root, num); } level_traversal(); for(int i = 0; i <= tail; i++){ if(i < tail) printf("%d ", queue[i]->value); else printf("%d\n", queue[i]->value); } for(int i = 0; i <= tail; i++){ if(!ans[i]){ flag = 0; break; } } if(flag) printf("YES\n"); else printf("NO\n"); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<limits.h> int N; int head; int count; int ans[11]; int queue[11]; int queue_head; int queue_tail = -1; struct tree{ int visited; int father; int left; int right; }tree[11]; void level_traversal(){ queue[++queue_tail] = head; while(queue_head <= queue_tail){ if(tree[queue[queue_head]].left != -1) queue[++queue_tail] = tree[queue[queue_head]].left; if(tree[queue[queue_head]].right != -1) queue[++queue_tail] = tree[queue[queue_head]].right; queue_head++; } for(int i = 0; i < queue_tail; i++) printf("%d ", queue[i]); printf("%d\n", queue[queue_tail]); } void inorder_traversal(int pos){ if(pos == -1) return; inorder_traversal(tree[pos].left); ans[count++] = pos; inorder_traversal(tree[pos].right); } int main(int argc, char *argv[]){ char temp; memset(tree, -1, sizeof(tree)); scanf("%d", &N); getchar(); for(int i = 0; i < N; i++){ scanf("%c", &temp); getchar(); if(temp != '-') { tree[i].right = temp - '0'; tree[tree[i].right].father = i; } scanf("%c", &temp); getchar(); if(temp != '-'){ tree[i].left = temp - '0'; tree[tree[i].left].father = i; } } while(1){ if(tree[head].father != -1) head = tree[head].father; else break; } level_traversal(); inorder_traversal(head); for(int i = 0; i < count - 1; i++) printf("%d ", ans[i]); printf("%d\n", ans[count-1]); return 0; }<file_sep>#include <iostream> #include <cmath> int N; int num(int Z){ int ans = 0; while(Z){ ans++; Z /= 10; } return ans / 2; } int main(int argc, char *argv[]){ int Z = 0; int a = 0, b = 0; long long product = 0; std::cin >> N; while(N--){ std::cin >> Z; b = Z % (int)pow(10, num(Z)); a = (Z - b) / (int)pow(10, num(Z)); product = a * b; if(product == 0) std::cout << "No" << std::endl; else if(Z % product == 0) std::cout << "Yes" << std::endl; else std::cout << "No" << std::endl; } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> long long inp[100001]; int N; int p; int max_len = 1; int temp_len; int cmp(const void *a, const void *b){ return (int)(*(long long *)a - *(long long *)b); } int main(){ scanf("%d%d", &N, &p); for(int i = 0; i < N; i++) scanf("%lld", &inp[i]); qsort(inp, N, sizeof(long long), cmp); for(int i = 0; i < N - 1; i++){ temp_len = N - i; if(temp_len <= max_len) break; int head = i + 1, tail = N - 1, middle = (head + tail) / 2; while(head <= tail){ if(inp[i] * p >= inp[middle]){ head = middle + 1; middle = (head + tail) / 2; } else{ tail = middle - 1; middle = (head + tail) / 2; } } temp_len = middle - i + 1; if(temp_len > max_len) max_len = temp_len; } printf("%d\n", max_len); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> struct poly{ int N; double aN; }; int main(int argc, char *argv[]){ double ans[2001]; memset(ans, 0, sizeof(ans)); int i,j,K1,K2,count=0; scanf("%d",&K1); struct poly a[K1]; for(i=0;i<K1;i++){ scanf("%d%lf",&a[i].N,&a[i].aN); } scanf("%d",&K2); struct poly b[K2]; for(i=0;i<K2;i++){ scanf("%d%lf",&b[i].N,&b[i].aN); } for(i=0;i<K1;i++) for(j=0;j<K2;j++){ ans[a[i].N+b[j].N]+=a[i].aN*b[j].aN; } for(i=2000;i>=0;i--) if(fabs(ans[i])>0) count++; printf("%d",count); for(i=2000;i>=0;i--) if(fabs(ans[i])>0) {printf(" %d %.1f",i,ans[i]);count--;} printf("\n"); }<file_sep>// // main.c // PAT_ADVANCED // // Created by OYMQKUX on 05/06/2017. // Copyright © 2017 zhangzehao. All rights reserved. // 包含所有通过测试的PAT甲级代码(除部分题目必须使用平衡树外,其他使用纯C语言) <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int inp[1000]; int flag1=1; int flag2=1; int N; void check_search_tree(int pos, int len){ if(len==1||len==0) return; int i=pos+1; while(inp[i]<inp[pos]&&i<pos+len) i++; for(int j=i;j<pos+len;j++) if(inp[j]<inp[pos]){ flag1=0; return; } check_search_tree(pos+1,i-pos-1); check_search_tree(i,len-i+pos); } void check_mir_search_tree(int pos, int len){ if(len==1||len==0) return; int i=pos+1; while(inp[i]>=inp[pos]&&i<pos+len) i++; for(int j=i;j<pos+len;j++) if(inp[j]>=inp[pos]){ flag2=0; return; } check_mir_search_tree(pos+1,i-pos-1); check_mir_search_tree(i,len-i+pos); } void Print_2(int pos, int len){ if(len==1){ if(!pos) printf("%d\n",inp[pos]); else printf("%d ",inp[pos]); return; } if(len==0) return; int i=pos+1; while(inp[i]>=inp[pos]&&i<pos+len) i++; Print_2(pos+1,i-pos-1); Print_2(i,len-i+pos); if(pos) printf("%d ",inp[pos]); else printf("%d\n",inp[0]); } void Print_1(int pos, int len){ if(len==1){ if(pos) printf("%d ",inp[pos]); else printf("%d\n",inp[pos]); return; } if(len==0) return; int i=pos+1; while(inp[i]<inp[pos]&&i<pos+len) i++; Print_1(pos+1,i-pos-1); Print_1(i,len-i+pos); if(pos) printf("%d ",inp[pos]); else printf("%d\n",inp[0]); } int main(int argc, char *argv[]){ scanf("%d",&N); for(int i=0;i<N;i++) scanf("%d",&inp[i]); check_search_tree(0,N); check_mir_search_tree(0,N); if(flag1||flag2){ printf("YES\n"); if(flag1) {Print_1(0,N);return 0;} if(flag2) Print_2(0,N); } else printf("NO\n"); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 1<<30 int main(int argc, char *argv[]){ int N, b; scanf("%d%d",&N, &b); int digit[30]={0}; int pos=0, flag=1; while(N){ digit[pos++]=N%b; N/=b; } for(int i=0;i<pos/2;i++){ if(digit[i]!=digit[pos-i-1]) {flag=0;break;} } if(flag) printf("Yes\n"); else printf("No\n"); for(int i=pos-1;i>=1;i--) printf("%d ",digit[i]); printf("%d\n",digit[0]); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef int Type; typedef struct AVLTreeNode{ Type key; int height; struct AVLTreeNode *left; struct AVLTreeNode *right; }Node, *AVLTree; static Node *avltree_create_node(Type key, Node *left, Node *right){ Node *p; if((p = (Node *)malloc(sizeof(Node))) == NULL) return NULL; p->key = key; p->height = 0; p->left = left; p->right = right; return p; } static Node *avltree_maximum(Node *tree){ while(tree->right){ tree = tree->right; } return tree; } static Node *avltree_minimum(Node *tree){ while(tree->left){ tree = tree->left; } return tree; } static Node *avltree_search(Node *tree, Type key){ int flag = 0; while(tree){ if(key < tree->key) tree = tree ->left; else if(key > tree->key) tree = tree->right; else {flag = 1; break;} } if(flag) return tree; else return NULL; } int height(Node *node){ if(node == NULL) return 0; else return node->height; } int MAX(int a, int b) {return a > b ? a : b;} //left-left rotation static Node *left_left_rotation(Node *k2){ Node *k1; k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = MAX(height(k2->left), height(k2->right)) + 1; k1->height = MAX(height(k1->left), k2->height) + 1; return k1; } //right-right rotation static Node *right_right_rotation(Node *k1){ Node *k2; k2 = k1->right; k1->right = k2->left; k2->left = k1; k1->height = MAX(height(k1->left), height(k1->right)) + 1; k2->height = MAX(k1->height, height(k2->right)) + 1; return k2; } //left-right rotation /* Iterative rotation method static Node *left_right_rotation(Node *k3){ Node *k2, *k1; k1 = k3->left; k2 = k1->right; k1->right = k2->left; k2->left = k1; k3->left = k2; k3->left = k2->right; k2->right = k3; k1->height = MAX(height(k1->left), height(k1->right)) + 1; k3->height = MAX(height(k3->left), height(k3->right)) + 1; k2->height = MAX(k1->height, k3->height) + 1; return k2; } */ //recursion method static Node *left_right_rotation(Node *k3){ k3->left = right_right_rotation(k3->left); return left_left_rotation(k3); } //right-right rotation /* Iterative rotation method static Node *right_left_rotation(Node *k1){ Node *k2, *k3; k3 = k1->right; k2 = k3->left; k3->left = k2->right; k2->right = k3; k1->right = k2; k1->right = k2->left; k2->left = k1; k3->height = MAX(height(k3->left), height(k3->right)) + 1; k2->height = MAX(height(k2->left), height(k2->right)) + 1; k1->height = MAX(height(k1->left), height(k1->right)) + 1; return k2; } */ //recursion method static Node *right_left_rotation(Node *k1){ k1->right = left_left_rotation(k1->right); return right_right_rotation(k1); } static Node *insert_node(Node *tree, Type key){ if(tree == NULL){ tree = avltree_create_node(key, NULL, NULL); if(tree == NULL){ printf("ERROR: create avltree node failed!\n"); return NULL; } } else if(key < tree->key){ tree->left = insert_node(tree->left, key); if(height(tree->left) == height(tree->right) + 2){ if(key < tree->left->key) tree = left_left_rotation(tree); else tree = left_right_rotation(tree); } } else if(key > tree->key){ tree->right = insert_node(tree->right, key); if(height(tree->left) + 2 == height(tree->right)){ if(key < tree->right->key) tree = right_left_rotation(tree); else tree = right_right_rotation(tree); } } else{ //key == tree->key printf("Same value can't be added into one tree!\n"); } tree->height = MAX(height(tree->left), height(tree->right)) + 1; return tree; } static Node *delete_node(Node *tree, Node *z){ if(tree == NULL || z==NULL) return NULL; if(z->key < tree->key){ tree->left = delete_node(tree->left, z); if(height(tree->right) == height(tree->left) + 2){ if(height(tree->right->left) > height(tree->right->right)) tree = right_left_rotation(tree); else tree = right_right_rotation(tree); } } else if(z->key > tree->key){ tree->right = delete_node(tree->right, z); if(height(tree->right) + 2 == height(tree->left)){ if(height(tree->left->left) > height(tree->left->right)) tree = left_left_rotation(tree); else tree = left_right_rotation(tree); } } else{ if(tree->left && tree->right){ if(height(tree->left) > height(tree->right)){ Node *max = avltree_maximum(tree->left); tree->key = max->key; tree->left = delete_node(tree->left, max); } else{ Node *min = avltree_minimum(tree->right); tree->key = min->key; tree->right = delete_node(tree->right, min); } } else{ Node *tmp = tree; tree = tree->left ? tree->left: tree->right; free(tmp); } } return tree; } static Node *avltree_delete(Node *tree, Type key){ Node *z; if((z = avltree_search(tree, key))) tree = delete_node(tree, z); else printf("The node you want to delete doesn't exist in this tree!\n"); return tree; } int main(int argc, const char * argv[]) { int N; int inp; Node *tree = NULL; scanf("%d", &N); for(int i=0; i<N; i++){ scanf("%d", &inp); tree = insert_node(tree, inp); } printf("%d\n", tree->key); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #define Infinity 1<<30 struct node{ int weight; int num; struct node *next; }node[1111]; int dis[1111]; int visited[1111]; int N;//number of house int M;//number of candidate location int K;//number of roads connecting houses and the gas stations int D_S;//maximum service range of the gas station int total; void Dijkstra(int start){ dis[start] = 0; while(1){ struct node *temp1 = NULL; int temp = -1; int min = Infinity; for(int i = 1; i <= total; i++){ if(!visited[i] && dis[i] < min){ min = dis[i]; temp = i; } } if(temp == -1) break; visited[temp] = 1; temp1 = node[temp].next; while(temp1){ if(!visited[temp1->num] && min + temp1->weight < dis[temp1->num]) dis[temp1->num] = min +temp1->weight; temp1 = temp1->next; } } } int check(int num){ struct node *temp; int flag = 1; temp = node[num].next; for(int i = 1; i <= N; i++){ if(dis[i] > D_S){ flag = 0; break; } } return flag; } int string_to_num(char *string, unsigned long len){ int ans = 0; for(int i = 0;i < len; i++){ ans *= 10; ans += string[i] - '0'; } return ans; } int change(char *inp){ int ans = 0; if(inp[0] == 'G'){ ans = string_to_num(inp + 1, strlen(inp) - 1); ans += N; } else ans = string_to_num(inp, strlen(inp)); return ans; } void SCANF(){ char inp1[10], inp2[10]; struct node *temp1, *temp2; for(int i = 0; i < K; i++){ scanf("%s", inp1); scanf("%s", inp2); temp1 = (struct node*)malloc(sizeof(struct node)); temp2 = (struct node*)malloc(sizeof(struct node)); temp1->num = change(inp1); temp2->num = change(inp2); scanf("%d", &temp1->weight); temp2->weight = temp1->weight; temp1->next = node[change(inp2)].next; temp2->next = node[change(inp1)].next; node[change(inp2)].next = temp1; node[change(inp1)].next = temp2; } } int main(int argc, char *argv[]){ int max = -1; double ans = Infinity; int temp_min = 0; int flag = 0; int index = 0; double sum = 0.0; scanf("%d%d%d%d", &N, &M, &K, &D_S); total = N + M; SCANF(); for(int i = N+1; i <= total; i++){ memset(visited, 0, sizeof(int) * (total + 1)); for(int j = 1; j<=total; j++) dis[j] = Infinity; Dijkstra(i); if(check(i)){ flag = 1; temp_min = Infinity; sum = 0; for(int j = 1; j <= N; j++){ if(temp_min > dis[j]) temp_min = dis[j]; sum += dis[j]; } if(temp_min > max){ max = temp_min; ans = sum/N; index = i; } else if(temp_min == max){ if(ans > sum/N){ ans = sum/N; index = i; } } } } if(!flag) printf("No Solution\n"); else{ printf("G%d\n", index - N); printf("%.1f ", max*1.0); printf("%.1f\n", (int)(ans * 10 + 0.5) / 10.0); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 1<<30 int N; int M; int S; int count; int ans[100]; struct answer{ int num; char str[100]; }; struct node{ int num; int weight; int father; int child[100]; int total; }; struct node node[100]; struct answer answer[100]; void DFS(int Node){ int i; if(node[Node].num==0){ if(node[Node].total==S) ans[count++]=Node; return; } for(i=0;i<node[Node].num;i++){ node[node[Node].child[i]].total=node[node[Node].child[i]].weight+node[Node].total; DFS(node[Node].child[i]); } } int cmp(const void *a, const void *b){ struct answer *c, *d; c=(struct answer*)a; d=(struct answer*)b; return strcmp(d->str,c->str); } int main(int argc, char *argv[]){ int temp; int i, j; scanf("%d%d%d",&N,&M,&S); for(i=0;i<N;i++) scanf("%d",&node[i].weight); for(i=0;i<M;i++){ scanf("%d",&temp); scanf("%d",&node[temp].num); for(j=0;j<node[temp].num;j++){ scanf("%d",&node[temp].child[j]); node[node[temp].child[j]].father=temp; } } node[0].total=node[0].weight; node[0].father=-1; DFS(0); for(i=0;i<count;i++){ temp=ans[i]; while(temp!=-1){ answer[i].str[answer[i].num++]=node[temp].weight; temp=node[temp].father; } answer[i].str[answer[i].num]=0; } for(i=0;i<count;i++){ for(j=0;j<strlen(answer[i].str)/2;j++){ temp=answer[i].str[j]; answer[i].str[j]=answer[i].str[strlen(answer[i].str)-1-j]; answer[i].str[strlen(answer[i].str)-1-j]=temp; } } qsort(answer, count, sizeof(answer[0]), cmp); for(i=0;i<count;i++){ printf("%d",answer[i].str[0]); for(j=1;j<answer[i].num;j++) printf(" %d",answer[i].str[j]); printf("\n"); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> typedef struct node{ int element; struct node *left; struct node *right; }*tree; tree a[30]; tree in_order(int *post, int *in, int length){ if(!length) return NULL; tree node; int i, index; node=(tree)malloc(sizeof(struct node)); node->element=post[length-1]; for(i=0;i<length;i++){ if(in[i]==node->element) break; } index=i+1; node->left=in_order(post, in, index-1); node->right=in_order(post+index-1, in+index, length-index); return node; } void level_traversal(tree node){ int head=0, tail=0; int count=1; a[0]=node; while(head<=tail){ if(a[head]->left!=NULL){ a[count++]=a[head]->left; } if(a[head]->right!=NULL){ a[count++]=a[head]->right; } if(head==tail){ tail=count-1; } head++; } } int main(int argc, char *argv[]){ int N; scanf("%d",&N); int post[30]; int in[30]; int i; tree root; for(i=0;i<N;i++) scanf("%d",&post[i]); for(i=0;i<N;i++) scanf("%d",&in[i]); root=in_order(post, in, N); level_traversal(root); for(i=0;i<N-1;i++) printf("%d ",a[i]->element); printf("%d\n",a[i]->element); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; double P; double r; int count; int max_level; struct sell{ int count; int level; int *child; }sell[100000]; void DFS(int root, int level){ sell[root].level = level; for(int i = 0; i < sell[root].count; i++){ DFS(sell[root].child[i], level + 1); } } int cmp(const void *a, const void *b){ struct sell *c, *d; c = (struct sell*) a; d = (struct sell*) b; if(c->count != d->count) return c->count - d->count; return c->level - d->level; } double power(int level){ double ans = P; for(int i = 0; i < level; i++){ ans *= (1 + r / 100.0); } return ans; } int main(int argc, char *argv[]){ scanf("%d%lf%lf", &N, &P, &r); for(int i = 0; i < N; i++){ scanf("%d", &sell[i].count); sell[i].child = (int *)malloc(sizeof(int) * sell[i].count); for(int j = 0; j < sell[i].count; j++){ scanf("%d", &sell[i].child[j]); } } DFS(0, 0); qsort(sell, N, sizeof(sell[0]), cmp); max_level = sell[0].level; for(int i = 1; i < N; i++){ if(max_level == sell[i].level) count++; else break; } printf("%.4lf %d\n", power(max_level), count + 1); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; double P; double r; double ans; int retailer[100000]; int count; struct node{ int num; int pro; double price; struct node *next; }node[100000]; void BFS(int x){ struct node *temp; temp = node[x].next; while(temp){ node[temp->num].price = node[x].price * (1.0 + r / 100.0); temp = temp->next; } temp = node[x].next; while(temp){ BFS(temp->num); temp = temp->next; } } int main(int argc, char *argv[]){ int K_i; int id; struct node *temp1, *temp2; scanf("%d%lf%lf", &N, &P, &r); for(int i = 0; i < N; i++){ temp1 = &node[i]; scanf("%d", &K_i); for(int j = 0; j < K_i; j++){ temp2 = (struct node*)malloc(sizeof(struct node)); temp2->next = NULL; scanf("%d", &id); temp2->num = id; temp1->pro = -1; temp1->next = temp2; temp1 = temp1->next; } if(!K_i){ scanf("%d", &temp1->pro); retailer[count++] = i; } } node[0].price = P; BFS(0); for(int i = 0; i < count; i++){ ans += node[retailer[i]].price * node[retailer[i]].pro; } printf("%.1lf\n", ans); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 2<<29 int N; int M; int L; int len[201][10001]; int fav[201]; int given[10001]; int max; void LCS(){ int i, j; for(i=1;i<=M;i++){ for(j=1;j<=L;j++){ max=len[i-1][j-1]; if(max<len[i-1][j]) max=len[i-1][j]; if(max<len[i][j-1]) max=len[i][j-1]; if(given[j-1]==fav[i-1]) len[i][j]=max+1; else len[i][j]=max; } } } int main(int argc, char *argv[]){ int i; scanf("%d",&N); scanf("%d",&M); for(i=0;i<M;i++) scanf("%d",&fav[i]); scanf("%d",&L); for(i=0;i<L;i++) scanf("%d",&given[i]); LCS(); printf("%d\n",len[M][L]); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int couple[100000]; int M; int guests[10000]; int come[100000]; int ans[10000]; int count; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ int cp1, cp2; scanf("%d", &N); memset(couple, -1, sizeof(couple)); for(int i = 0; i < N; i++){ scanf("%d%d", &cp1, &cp2); couple[cp1] = cp2; couple[cp2] = cp1; } scanf("%d", &M); for(int i = 0; i < M; i++){ scanf("%d", &guests[i]); come[guests[i]] = 1; } for(int i = 0; i < M; i++){ if(couple[guests[i]] == -1){ ans[count++] = guests[i]; } else{ if(!come[couple[guests[i]]]){ ans[count++] = guests[i]; } } } qsort(ans, count, sizeof(int), cmp); printf("%d\n", count); for(int i = 0; i < count; i++){ if(i < count - 1) printf("%05d ", ans[i]); else printf("%05d\n", ans[i]); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int max(int a, int b){return a>b?a:b;}; int main(int argc, char *argv[]){ int a_exp=0, b_exp=0, exp; double a_coe, b_coe, coe; int K,i; double a[1001]; memset(a,0,sizeof(a)); double b[1001]; memset(b,0,sizeof(b)); scanf("%d",&K); if(K){ scanf("%d%lf",&a_exp,&a_coe); a[a_exp]=a_coe; for(i=0;i<K-1;i++){ scanf("%d%lf",&exp,&coe); a[exp]=coe; } } scanf("%d",&K); if(K){ scanf("%d%lf",&b_exp, &b_coe); b[b_exp]=b_coe; for(i=0;i<K-1;i++){ scanf("%d%lf",&exp,&coe); b[exp]=coe; } } K=0; for(i=max(a_exp,b_exp);i>=0;i--){ if(a[i]+b[i]) K++; } if(K)printf("%d ",K); else printf("%d\n",K); for(i=max(a_exp,b_exp);i>=0;i--){ if(K>=2){ if(a[i]+b[i]) {printf("%d %.1f ",i,a[i]+b[i]);K--;}} else break; } for(;i>=0;i--) if(a[i]+b[i]) printf("%d %.1f\n",i,a[i]+b[i]); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define MaxVertex 10001 int visited[MaxVertex]; int Union[MaxVertex]; int deep[MaxVertex]; int ans[MaxVertex]; int count; int deepest; typedef int VertexType; typedef int EdgeType; typedef struct node{ int adjvex; EdgeType weight; struct node *next; }EdgeNode; typedef struct VertexNode{ VertexType data; EdgeNode *firstedge; }VertexNode; typedef VertexNode AdjList[MaxVertex]; typedef struct{ AdjList adjList; int numNodes; int numEdges; }GraphAdjList; int cmp(const void *a, const void *b){ return *(int *)a-*(int *)b; } int find(int a){ return Union[a]==a?a:find(Union[a]); } void merge(int a, int b){ a=find(a); b=find(b); if(a!=b) Union[a]=b; } GraphAdjList CreateGraph(GraphAdjList GL){ int i, a, b; EdgeNode *temp1, *temp2; scanf("%d",&GL.numNodes); GL.numEdges=GL.numNodes-1; for(i=0;i<=GL.numNodes;i++) Union[i]=i; for(i=0;i<=GL.numNodes;i++){ GL.adjList[i].data=i; GL.adjList[i].firstedge=NULL; } for(i=0;i<GL.numEdges;i++){ scanf("%d%d",&a, &b); merge(a,b); temp1=(EdgeNode*)malloc(sizeof(EdgeNode)); temp2=(EdgeNode*)malloc(sizeof(EdgeNode)); temp1->adjvex=b; temp1->weight=1; temp2->adjvex=a; temp2->weight=1; temp1->next=GL.adjList[a].firstedge; temp2->next=GL.adjList[b].firstedge; GL.adjList[a].firstedge=temp1; GL.adjList[b].firstedge=temp2; } return GL; } void Initialize(GraphAdjList GL){ memset(visited,0,sizeof(visited)); memset(deep,0,sizeof(deep)); memset(ans,0,sizeof(ans)); } void DFS(GraphAdjList GL,VertexNode root, int dis){ EdgeNode *point=root.firstedge; if(dis>deepest){ deepest=dis; memset(deep,0,sizeof(deep)); count=0; deep[count++]=root.data; } else if(dis==deepest) deep[count++]=root.data; visited[root.data]=1; while(1){ if(point==NULL) break; if(visited[point->adjvex]==0) DFS(GL,GL.adjList[point->adjvex],dis+1); point=point->next; } visited[root.data]=0; } int main(int argc, char *argv[]){ GraphAdjList GL; GL=CreateGraph(GL); Initialize(GL); for(int i=1;i<=GL.numNodes;i++) if(Union[i]==i) count++; if(count>1) printf("Error: %d components\n",count); else{ int i; count=0; DFS(GL,GL.adjList[1],0); for(i=0;i<count;i++) ans[i]=deep[i]; int temp=i; count=0; DFS(GL,GL.adjList[deep[temp-1]],0); for(i=0;i<count;i++) ans[temp++]=deep[i]; qsort(ans,temp,sizeof(int),cmp); count=1; for(i=1;i<temp;i++) if(ans[i]!=ans[i-1]) ans[count++]=ans[i]; for(i=0;i<count;i++) printf("%d\n",ans[i]); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int arr[1000000]; int matrix[1000][1000]; int dire_x[4] = {0, 1, 0, -1}; int dire_y[4] = {1, 0, -1, 0}; int cmp(const void *a, const void *b){ return *(int *)b - *(int *)a; } int find(){ int m; for(m = sqrt(N); m >= 1; m--){ if(N % m == 0){ break; } } return m; } int main(int argc, char *argv[]){ int x = 0, y = 0; int m, n; int direction = 0; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &arr[i]); } qsort(arr, N, sizeof(int), cmp); memset(matrix, -1, sizeof(matrix)); m = find(); n = N / m; if(n > m){ int temp = n; n = m; m = temp; } for(int i = 0; i < N; i++){ matrix[x][y] = arr[i]; if(x + dire_x[direction] >= m || x + dire_x[direction] < 0 || y + dire_y[direction] >= n || y + dire_y[direction] < 0 || matrix[x + dire_x[direction]][y + dire_y[direction]] != -1){ direction++; direction %= 4; } x += dire_x[direction]; y += dire_y[direction]; } for(int i = 0; i < m; i++){ for(int j = 0; j < n - 1; j++){ printf("%d ", matrix[i][j]); } printf("%d\n", matrix[i][n-1]); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 1<<30 int main(int argc, char *argv[]){ char inp[81]; long n1, n2, n3; int i, j; long len; scanf("%s",inp); len=strlen(inp)+2; if(len%3==0){ n1=n2=n3=len/3; } else if(len%3==1){ n2=len/3+1; n1=n3=(len-n2)/2; } else{ n2=len/3+2; n1=n3=(len-n2)/2; } for(i=0;i<n1-1;i++){ printf("%c",inp[i]); for(j=0;j<n2-2;j++) printf(" "); printf("%c\n",inp[strlen(inp)-1-i]); } //printf("n1=%ld n2=%ld n3=%ld\n",n1,n2,n3); for(;i<n1+n2-1;i++) printf("%c",inp[i]); printf("\n"); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int count; int total; struct Union{ int father, mother; int k; int child[5]; int num; int set; int area; }Union[10000]; int visited[10000]; struct ans{ int id; int num; double avg_set; double avg_area; }ans[10000]; int all_id[21000]; int find(int x){ if(Union[x].num < 0) return x; else return Union[x].num = find(Union[x].num); } void merge(int a, int b){ int x, y; x = find(a); y = find(b); if(x != y){ if(x > y){ if(Union[x].num < 0) Union[y].num += Union[x].num; else Union[y].num--; Union[x].num = y; Union[y].set += Union[x].set; Union[y].area += Union[x].area; } else{ if(Union[y].num < 0) Union[x].num += Union[y].num; else Union[x].num--; Union[y].num = x; Union[x].set += Union[y].set; Union[x].area += Union[y].area; } } } int cmp(const void *a, const void *b){ struct ans *c, *d; c = (struct ans*)a; d = (struct ans*)b; if(fabs(c->avg_area - d->avg_area) < 1e-8) return c->id > d->id; else return c->avg_area < d->avg_area; } int main(int argc, char *argv[]){ int id[1005]; scanf("%d", &N); for(int i = 0; i < 10000; i++) Union[i].num = -1; for(int i = 0; i < N; i++){ scanf("%d", &id[i]); if(id[i] != -1) all_id[total++] = id[i]; scanf("%d%d%d", &Union[id[i]].father, &Union[id[i]].mother, &Union[id[i]].k); if(Union[id[i]].father != -1) all_id[total++] = Union[id[i]].father; if(Union[id[i]].mother != -1) all_id[total++] = Union[id[i]].mother; for(int j = 0; j < Union[id[i]].k; j++){ scanf("%d", &Union[id[i]].child[j]); if(Union[id[i]].child[j] != -1) all_id[total++] = Union[id[i]].child[j]; } scanf("%d%d", &Union[id[i]].set, &Union[id[i]].area); } for(int i = 0; i < N; i++){ if(Union[id[i]].father != -1) merge(id[i], Union[id[i]].father); if(Union[id[i]].mother != -1) merge(id[i], Union[id[i]].mother); for(int j = 0; j < Union[id[i]].k; j++){ merge(id[i], Union[id[i]].child[j]); } } for(int i = 0; i < total; i++){ if(!visited[all_id[i]] && Union[all_id[i]].num < 0){ visited[all_id[i]] = 1; ans[count].id = all_id[i]; ans[count].num = Union[all_id[i]].num * -1; ans[count].avg_set = Union[all_id[i]].set * 1.0 / ans[count].num; ans[count].avg_area = Union[all_id[i]].area * 1.0 / ans[count].num; count++; } } qsort(ans, count, sizeof(ans[0]), cmp); printf("%d\n", count); for(int i = 0; i < count; i++) printf("%04d %d %.3f %.3f\n", ans[i].id, ans[i].num, ans[i].avg_set, ans[i].avg_area); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct phone{ char name[50]; int month; int day; int hour; int min; char states[15]; }; int cmp1(const void *a, const void *b){ struct phone *c, *d; c=(struct phone*) a; d=(struct phone*) b; return strcmp(c->name, d->name); } int cmp2(const void *a, const void *b){ struct phone *c, *d; c=(struct phone*) a; d=(struct phone*) b; if(c->day!=d->day) return c->day-d->day; else if(c->hour!=d->hour) return c->hour-d->hour; else if(c->min!=d->min) return c->min-d->min; else return strcmp(d->states, c->states); } int main(int argc, char *argv[]){ int price[25]; int i, j, k; int N; int head=0; int flag=0,count=0; double temp_money=0; double money=0; int temp_day=0, temp_hour=0, temp_min=0; for(i=0;i<24;i++) {scanf("%d",&price[i]);money+=price[i];} price[24]=money; money=0; scanf("%d",&N); struct phone phone[N]; memset(phone,0,sizeof(phone)); for(i=0;i<N;i++){ scanf("%s%d:%d:%d:%d",phone[i].name, &phone[i].month, &phone[i].day, &phone[i].hour, &phone[i].min); getchar(); scanf("%s",phone[i].states); } qsort(phone, N, sizeof(phone[0]),cmp1); for(i=1;i<N;i++){ if(strcmp(phone[i].name,phone[i-1].name)==0) continue; else { qsort(phone+head,i-head,sizeof(phone[0]),cmp2); flag=0; money=0; count=0; for(j=head;j<i;j++){ temp_money=0; if(strcmp(phone[j].states,"on-line")==0){ temp_day=phone[j].day; temp_hour=phone[j].hour; temp_min=phone[j].min; flag=1; } else if(flag&&strcmp(phone[j].states,"off-line")==0){ if(!count){printf("%s %02d\n",phone[head].name, phone[head].month); count++;} printf("%02d:%02d:%02d ",temp_day,temp_hour,temp_min); printf("%02d:%02d:%02d ",phone[j].day,phone[j].hour,phone[j].min); printf("%d ",-(temp_day*60*24+temp_hour*60+temp_min-phone[j].day*60*24-phone[j].hour*60-phone[j].min)); flag=0; if(phone[j].hour==temp_hour&&phone[j].day==temp_day) temp_money=(phone[j].min-temp_min)*price[temp_hour]; else if(phone[j].day==temp_day){ temp_money+=(60-temp_min)*price[temp_hour]; temp_money+=phone[j].min*price[phone[j].hour]; for(k=temp_hour+1;k<=phone[j].hour-1;k++) temp_money+=price[k]*60; } else{ temp_money+=(60-temp_min)*price[temp_hour]; temp_money+=phone[j].min*price[phone[j].hour]; for(k=temp_hour+1;k<24;k++) temp_money+=price[k]*60; for(k=0;k<phone[j].hour;k++) temp_money+=price[k]*60; for(k=temp_day+1;k<phone[j].day;k++) temp_money+=price[24]*60; } printf("$%.2f\n",temp_money/100.0); } money+=temp_money; } if(money)printf("Total amount: $%.2f\n",money/100.0); head=i; } } qsort(phone+head,N-head,sizeof(phone[0]),cmp2); flag=0; money=0; count=0; for(j=head;j<N;j++){ temp_money=0; if(strcmp(phone[j].states,"on-line")==0){ temp_day=phone[j].day; temp_hour=phone[j].hour; temp_min=phone[j].min; flag=1; } else if(flag&&strcmp(phone[j].states,"off-line")==0){ if(!count){printf("%s %02d\n",phone[head].name, phone[head].month);count++;} printf("%02d:%02d:%02d ",temp_day,temp_hour,temp_min); printf("%02d:%02d:%02d ",phone[j].day,phone[j].hour,phone[j].min); printf("%d ",-(temp_day*60*24+temp_hour*60+temp_min-phone[j].day*60*24-phone[j].hour*60-phone[j].min)); flag=0; if(phone[j].hour==temp_hour&&phone[j].day==temp_day) temp_money=(phone[j].min-temp_min)*price[temp_hour]; else if(phone[j].day==temp_day){ temp_money+=(60-temp_min)*price[temp_hour]; temp_money+=phone[j].min*price[phone[j].hour]; for(k=temp_hour+1;k<=phone[j].hour-1;k++) temp_money+=price[k]*60; } else{ temp_money+=(60-temp_min)*price[temp_hour]; temp_money+=phone[j].min*price[phone[j].hour]; for(k=temp_hour+1;k<24;k++) temp_money+=price[k]*60; for(k=0;k<phone[j].hour;k++) temp_money+=price[k]*60; for(k=temp_day+1;k<phone[j].day;k++) temp_money+=price[24]*60; } printf("$%.2f\n",temp_money/100.0); } money+=temp_money; } if(money) printf("Total amount: $%.2f\n",money/100.0); //for(i=0;i<N;i++) printf("%s %02d:%02d:%02d:%02d %s\n",phone[i].name, phone[i].month,phone[i].day,phone[i].hour,phone[i].min,phone[i].states); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int M; int Union[501]; int degree[501]; int odd; int find(int x){ if(Union[x] < 0) return x; else return Union[x] = find(Union[x]); } void merge(int x, int y){ int a = find(x), b = find(y); if(a != b){ Union[a] += Union[b]; Union[b] = a; } } int connected(){ int num = 0; for(int i = 1; i <= N; i++) if(Union[i] < 0) num++; if(num > 1) return 0; else return 1; } int main(int argc, char *argv[]){ int p1, p2; int flag; scanf("%d%d", &N, &M); memset(Union, -1, sizeof(int) * 501); for(int i = 0; i < M; i++){ scanf("%d%d", &p1, &p2); merge(p1, p2); degree[p1]++; degree[p2]++; } for(int i = 1; i <= N; i++){ if(i < N) printf("%d ", degree[i]); else printf("%d\n", degree[i]); if(degree[i] % 2) odd++; } flag = connected(); if(!flag) printf("Non-Eulerian\n"); else{ if(!odd) printf("Eulerian\n"); else if(odd == 2) printf("Semi-Eulerian\n"); else printf("Non-Eulerian\n"); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; int K; int M; int min; int max; int Case=1; struct forbes{ char name[9]; int age; int worth; }inp[100000], inp_copy[100000]; int cmp1(const void *a, const void *b){ struct forbes *c, *d; c=(struct forbes*)a; d=(struct forbes*)b; if(c->worth!=d->worth) return d->worth-c->worth; if(c->age!=d->age) return c->age-d->age; return strcmp(c->name,d->name); } int main(int argc, char *argv[]){ int i, j; int count; scanf("%d%d",&N,&K); for(i=0;i<N;i++){ getchar(); scanf("%s",inp[i].name); scanf("%d%d",&inp[i].age,&inp[i].worth); inp_copy[i]=inp[i]; } qsort(inp,N,sizeof(inp[0]),cmp1); for(i=0;i<K;i++){ count=0; scanf("%d%d%d",&M,&min,&max); printf("Case #%d:\n",Case); Case++; for(j=0;j<N;j++){ if(count==M) break; if(inp[j].age>=min&&inp[j].age<=max){ printf("%s %d %d\n",inp[j].name, inp[j].age, inp[j].worth); count++; } } if(count==0) printf("None\n"); } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> char inp[20010]; char num1[10010]; char num2[10010]; char ans[20010]; int sign; unsigned long len1; unsigned long len2; double num_1; int num_2; int main(int argc, char *argv[]){ scanf("%s",inp); if(inp[0] == '+') sign = 1; else sign = -1; for(unsigned long i = 1; i < strlen(inp); i++){ if(inp[i] == 'E'){ len1 = i-1; break; } } len2 = strlen(inp) - len1 - 3; memcpy(num1, inp + 1, sizeof(char) * len1); memcpy(num2, inp + len1 + 3, sizeof(char) * len2); num_1 = atof(num1); num_2 = atoi(num2); if(num_2 == 0) printf("%s\n", num1); else{ if(inp[len1+2] == '-'){ if(sign == -1) printf("-"); printf("0."); for(int i = 1; i < num_2; i++){ printf("0"); } for(int i = 0; i < len1; i++){ if(num1[i] != '.') printf("%c", num1[i]); } printf("\n"); } else{ if(sign == -1) printf("-"); printf("%c", num1[0]); if(num_2 >= len1 - 2){ printf("%s", num1+2); for(int i = 1; i <= num_2 - len1 + 2; i++){ printf("0"); } printf("\n"); } else{ for(int i = 1; i <= num_2; i++){ printf("%c", num1[i+1]); } printf("."); printf("%s", num1 + num_2 + 2); printf("\n"); } } } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define max 100000 int N; int L; int H; struct people{ int num; int virtue; int talent; int flag; int total; int saga; int nobleman; int fool; int small; }people[max]; int cmp(const void *a, const void *b){ struct people *c, *d; c=(struct people*)a; d=(struct people*)b; if(c->flag!=d->flag) return c->flag-d->flag; if(c->saga!=d->saga) return d->saga-c->saga; if(c->nobleman!=d->nobleman) return d->nobleman-c->nobleman; if(c->fool!=d->fool) return d->fool-c->fool; if(c->small!=d->small) return d->small-c->small; if(c->total!=d->total) return d->total-c->total; if(c->virtue!=d->virtue) return d->virtue-c->virtue; return c->num-d->num; } int main(int argc, char *argv[]){ scanf("%d%d%d",&N,&L,&H); for(int i=0;i<N;i++){ scanf("%d%d%d",&people[i].num,&people[i].virtue,&people[i].talent); if(people[i].virtue>=L&&people[i].talent>=L) people[i].flag=1; else people[i].flag=0; people[i].total=people[i].virtue+people[i].talent; if(people[i].virtue>=H&&people[i].talent>=H) people[i].saga=1; else if(people[i].virtue>=H&&people[i].talent<H) people[i].nobleman=1; else if(people[i].virtue<H&&people[i].talent<H&&people[i].virtue>=people[i].talent) people[i].fool=1; else people[i].small=1; } qsort(people, N, sizeof(people[0]), cmp); int count=0; for(int i=0;i<N;i++) if(!people[i].flag) count++; printf("%d\n",N-count); for(int i=0;i<N;i++){ if(people[i].flag){ printf("%08d %d %d\n",people[i].num, people[i].virtue, people[i].talent); } } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int N; int temp; struct string{ char a[9]; unsigned long len; }; char ans[90000]; struct string str[10000]; int cmp(const void *a, const void *b){ return strcmp((*(struct string*)a).a, (*(struct string*)b).a); } int main(int argc, char *argv[]){ unsigned long i,j; scanf("%d",&N); for(i=0;i<N;i++){ temp=0; getchar(); scanf("%s",str[i].a); str[i].len=strlen(str[i].a); if(str[i].len<8){ for(j=str[i].len;j<8;j++){ str[i].a[j]=str[i].a[temp%str[i].len]; temp++; } } str[i].a[8]=0; } /*for(int i=0;i<N;i++) for(int j=0;j<str[i].len;j++) printf("%c",str[i].a[j]); printf("\n");*/ qsort(str,N,sizeof(str[0]),cmp); temp=0; for(i=0;i<N;i++) for(j=0;j<str[i].len;j++) ans[temp++]=str[i].a[j]; ans[temp]=0; temp=0; while(ans[temp]=='0') temp++; if(temp==strlen(ans)) printf("0"); else printf("%s",ans+temp); /*for(i=0;i<N;i++) if(!temp){ for(j=0;j<str[i].len;j++) if(str[i].a[j]!='0'){ temp=1; printf("%s",str[i].a+j); break; } } else printf("%s",str[i].a);*/ printf("\n"); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct stu{ char name[11]; char gender; char ID[11]; int grade; }; int cmp1(const void *a, const void *b){ struct stu *c, *d; c=(struct stu*)a; d=(struct stu*)b; if(c->gender!=d->gender) return c->gender-d->gender; else return d->grade-c->grade; } int cmp2(const void *a, const void *b){ struct stu *c, *d; c=(struct stu*)a; d=(struct stu*)b; if(c->gender!=d->gender) return d->gender-c->gender; else return c->grade-d->grade; } struct stu stu[1000]; int main(int argc, char *argv[]){ int N; int grade1=-1, grade2=-1; scanf("%d",&N); for(int i=0;i<N;i++){ scanf("%s",stu[i].name); getchar(); scanf("%c",&stu[i].gender); getchar(); scanf("%s",stu[i].ID); scanf("%d",&stu[i].grade); } qsort(stu,N,sizeof(stu[0]),cmp1); if(stu[0].gender=='M') printf("Absent\n"); else { printf("%s %s\n",stu[0].name,stu[0].ID); grade1=stu[0].grade; } qsort(stu,N,sizeof(stu[0]),cmp2); if(stu[0].gender=='F') printf("Absent\n"); else{ printf("%s %s\n",stu[0].name,stu[0].ID); grade2=stu[0].grade; } if(grade1>=0&&grade2>=0) printf("%d\n",grade1-grade2); else printf("NA\n"); return 0; }<file_sep>#include <iostream> #include <cstdio> using namespace std; struct list{ int addr; int value; int next; }inp[100000], tmp[100000], ans[100000]; int pos; int main(int argc, char *argv[]){ int head, N, K; int addr; int len = 0; int i = 0; cin >> head >> N >> K; for(i = 0; i < N; i++){ cin >> addr; inp[addr].addr = addr; cin >> inp[addr].value >> inp[addr].next; } i = 0; while(head != -1){ tmp[i] = inp[head]; head = tmp[i].next; i++; } len = i; for(i = 0; i < len; i++){ if(tmp[i].value < 0) ans[pos++] = tmp[i]; } for(i = 0; i < len; i++){ if(tmp[i].value >= 0 && tmp[i].value <= K) ans[pos++] = tmp[i]; } for(i = 0; i < len; i++){ if(tmp[i].value > K) ans[pos++] = tmp[i]; } for(i = 0; i < len - 1; i++){ printf("%05d %d %05d\n", ans[i].addr, ans[i].value, ans[i+1].addr); } printf("%05d %d -1\n", ans[len-1].addr, ans[len-1].value); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> #define max 24*3600 int N, K; int total; int cars; int num[max][2]; //counting the number of cars for every seconds struct car{ char plate[8]; int time; //record the time int state; // 1 for in, 0 for out int last; //counting the parking time }car[10001], ans[10001]; int cmp(const void *a, const void *b){ struct car *c, *d; c = (struct car*) a; d = (struct car*) b; if(strcmp(c->plate, d->plate)) return strcmp(c->plate, d->plate); else return c->time - d->time; } int cmp1(const void *a, const void *b){ struct car *c, *d; c = (struct car*) a; d = (struct car*) b; if(c->last != d->last) return d->last - c->last; else return strcmp(c->plate, d->plate); } int cmp2(const void *a, const void *b){ struct car *c, *d; c = (struct car*) a; d = (struct car*) b; return c->time - d->time; } void remove_error(){ char temp_id[9]; int flag; qsort(car, N, sizeof(car[0]), cmp); for(int i = 0; i < N; i++){ flag = 0; strcpy(temp_id, car[i].plate); while(strcmp(temp_id, car[i].plate) == 0){ while(car[i].state){ i++; if(strcmp(temp_id, car[i].plate)) {flag = 1; break;} } if(flag) break; if(!i) {i++; continue;} if(strcmp(temp_id, car[i-1].plate) == 0 && car[i-1].state){ ans[cars] = car[i-1]; ans[cars+1] = car[i]; cars += 2; } i++; } i--; } } void analyse_last(){ char temp_id[9]; int last; qsort(ans, cars, sizeof(ans[0]), cmp); for(int i = 0; i < cars; i++){ last = 0; strcpy(temp_id, ans[i].plate); while(strcmp(temp_id, ans[i].plate) == 0){ last += ans[i+1].time - ans[i].time; i += 2; } ans[--i].last = last; } } void analyse_num(){ int temp = 0; total = 1; qsort(ans, cars, sizeof(ans[0]), cmp2); while(temp < cars - 1){ if(!num[ans[temp].time][1]){ if(ans[temp].time) num[ans[temp].time][0] = num[ans[temp].time-1][0]; num[ans[temp].time][1] = 1; } if(ans[temp].state) num[ans[temp].time][0]++; else num[ans[temp].time][0]--; for(int i = ans[temp].time + 1; i < ans[temp+1].time; i++){ num[i][0] = num[i-1][0]; } temp++; } if(!num[ans[temp].time][1]){ num[ans[temp].time][0] = num[ans[temp].time-1][0]; num[ans[temp].time][1] = 1; } if(ans[temp].state) num[ans[temp].time][0]++; else num[ans[temp].time][0]--; for(int i = ans[temp].time + 1; i < max; i++){ num[i][0] = num[i-1][0]; } } int main(int argc, char *argv[]){ char states[4]; int hh, mm, ss; int time; int longest, count = 0; scanf("%d%d", &N, &K); getchar(); for(int i = 0; i < N; i++){ scanf("%s", car[i].plate); scanf("%d:%d:%d", &hh, &mm, &ss); car[i].time = hh * 3600 + mm *60 + ss; getchar(); scanf("%s", states); if(strcmp(states, "in") == 0) car[i].state = 1; else car[i].state = 0; } remove_error(); analyse_last(); analyse_num(); for(int i = 0; i < K; i++){ scanf("%d:%d:%d", &hh, &mm, &ss); time = hh * 3600 + mm * 60 + ss; printf("%d\n", num[time][0]); } qsort(ans, cars, sizeof(ans[0]), cmp1); longest = ans[0].last; for(int i = 0; i < N; i++){ if(ans[i].last != longest) break; count++; } for(int i = 0; i < count; i++){ printf("%s ", ans[i].plate); } printf("%02d:%02d:%02d\n", ans[0].last / 3600, ans[0].last % 3600 / 60, ans[0].last % 60); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int K; struct stu{ int exist; int checked; int rank; }stu[10000]; int prime(int x){ if(x == 2 || x == 3) return 1; for(int i = 2; i <= sqrt(x); i++){ if(x % i == 0) return 0; } return 1; } int main(int argc, char *argv[]){ int id; scanf("%d", &N); for(int i = 1; i <= N; i++){ scanf("%d", &id); stu[id].exist = 1; stu[id].rank = i; } scanf("%d", &K); for(int i = 0; i < K; i++){ scanf("%d", &id); printf("%04d: ", id); if(!stu[id].exist) printf("Are you kidding?\n"); else if(stu[id].checked) printf("Checked\n"); else{ if(stu[id].rank == 1) printf("Mystery Award\n"); else if(prime(stu[id].rank)) printf("Minion\n"); else printf("Chocolate\n"); stu[id].checked = 1; } } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int queue[30]; int count; struct tree{ int value; struct tree *left; struct tree *right; }*root; int pre[30]; int post[30]; int pair_pre[29]; int pair_post[29]; void Build(struct tree *node, int head_pre, int tail_pre, int head_post, int tail_post, int len){ if(len < 1) return; int i; int temp; int temp_len; struct tree *left, *right; right = (struct tree*)malloc(sizeof(struct tree)); temp = pre[head_pre]; for(i = head_post; i <= tail_post; i++) if(post[i] == temp) break; temp_len = i - head_post; if(i == tail_post){ right->value = post[i]; right->left = NULL; right->right = NULL; node->right = right; Build(right, head_pre + 1, tail_pre, head_post, tail_post - 1, len - 1); } else{ left = (struct tree*)malloc(sizeof(struct tree)); left->value = post[i]; left->left = NULL; left->right = NULL; node->left = left; Build(left, head_pre + 1, head_pre + temp_len, head_post, i - 1, temp_len); right->value = pre[head_pre + temp_len + 1]; right->left = NULL; right->right = NULL; node->right = right; Build(right, head_pre + temp_len + 2, tail_pre, i + 1, tail_post - 1, len - temp_len - 2); } } void Inorder_traversal(struct tree *node){ if(node->left) Inorder_traversal(node->left); queue[count++] = node->value; if(node->right) Inorder_traversal(node->right); } int main(int argc, char *argv[]){ int flag = 1; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%d", &pre[i]); if(i) pair_pre[pre[i]] = pre[i-1]; } for(int i = 0; i < N; i++){ scanf("%d", &post[i]); if(i) pair_post[post[i]] = post[i-1]; } for(int i = 1; i < N; i++){ if(pre[i] == pair_post[pair_pre[pre[i]]]){ flag = 0; } } root = (struct tree*)malloc(sizeof(struct tree)); root->value = pre[0]; root->left = NULL; root->right = NULL; Build(root, 1, N - 1, 0, N - 2, N - 1); if(flag) printf("Yes\n"); else printf("No\n"); Inorder_traversal(root); for(int i = 0; i < count - 1; i++) printf("%d ", queue[i]); printf("%d\n", queue[count-1]); return 0; }<file_sep>#include<stdio.h> int inp[10]; char brr[9][6]={" Yi"," Qian"," Bai"," Shi"," Wan"," Qian"," Bai"," Shi", ""}; char crr[10][5]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"}; int flag; int pos; void output(int i,int x){ if(x){ if(pos++) printf(" "); if(flag){ printf("ling "); } flag = 0; printf("%s%s", crr[x], brr[i]); } else{ if(i == 4){ printf(" Wan"); flag = 0; return; } if(i == 8){ return; } flag = 1; } } int main(){ int x,i,j; scanf("%d",&x); if(x == 0){ printf("ling\n"); return 0; } if(x < 0){ printf("Fu "); x = -x; } if(x % 100000000 == 0){ printf("%s Yi\n", crr[x / 100000000]); return 0; } j = 0; i = 100000000; while(i){ inp[j++] = x / i; x %= i; i /= 10; } for(i = 0; i < 9; i++){ if(inp[i]) break; } for(; i < 9; i++){ output(i, inp[i]); } printf("\n"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> char rank[5]="ACME"; struct str{ char id[7]; int C; int M; int E; double A; int rank_C; int rank_M; int rank_E; int rank_A; }; int cmp1(const void *a, const void *b){ struct str *c; struct str *d; c=(struct str *)a; d=(struct str *)b; return d->C-c->C; } int cmp2(const void *a, const void *b){ struct str *c; struct str *d; c=(struct str *)a; d=(struct str *)b; return d->M-c->M; } int cmp3(const void *a, const void *b){ struct str *c; struct str *d; c=(struct str *)a; d=(struct str *)b; return d->E-c->E; } int cmp4(const void *a, const void *b){ struct str *c; struct str *d; c=(struct str *)a; d=(struct str *)b; return d->A>c->A; } //A, C, M, E int max(int a, int b, int c, int d){ int maxium=a; if(b<maxium) maxium=b; if(c<maxium) maxium=c; if(d<maxium) maxium=d; return maxium; } int max_rank(int a, int b, int c, int d){ int maxium=a; int temp=0; if(b<maxium) {maxium=b;temp=1;} if(c<maxium) {maxium=c;temp=2;} if(d<maxium) {maxium=d;temp=3;} return temp; } int main(int argc, char *argv[]){ int N, M; int flag=0; scanf("%d%d",&N,&M); getchar(); int i, j; char temp[7]; memset(temp,0,sizeof(char)*7); struct str stu[N]; for(i=0;i<N;i++){ scanf("%s",stu[i].id); scanf("%d%d%d",&stu[i].C,&stu[i].M,&stu[i].E); stu[i].A=(stu[i].C+stu[i].M+stu[i].E)*1.0/3.0; getchar(); } qsort(stu, N, sizeof(stu[0]), cmp1); for(i=0;i<N;i++){ if(stu[i].C==stu[i-1].C&&i) stu[i].rank_C=stu[i-1].rank_C; else stu[i].rank_C=i; } qsort(stu, N, sizeof(stu[0]), cmp2); for(i=0;i<N;i++){ if(stu[i].M==stu[i-1].M&&i) stu[i].rank_M=stu[i-1].rank_M; else stu[i].rank_M=i; } qsort(stu, N, sizeof(stu[0]), cmp3); for(i=0;i<N;i++){ if(stu[i].E==stu[i-1].E&&i) stu[i].rank_E=stu[i-1].rank_E; else stu[i].rank_E=i; } qsort(stu, N, sizeof(stu[0]), cmp4); for(i=0;i<N;i++){ if(stu[i].A==stu[i-1].A&&i) stu[i].rank_A=stu[i-1].rank_A; else stu[i].rank_A=i; } /*printf("\n"); for(i=0;i<N;i++){ printf("%s %d %d %d %lf\n",stu[i].id,stu[i].C,stu[i].M,stu[i].E,stu[i].A); printf("%d %d %d %d\n",stu[i].rank_C,stu[i].rank_M,stu[i].rank_E,stu[i].rank_A); } printf("%s %d\n",stu[3].id,max_rank(stu[3].rank_A,stu[3].rank_C,stu[3].rank_M,stu[3].E));*/ for(i=0;i<M;i++){ scanf("%s",temp); flag=0; for(j=0;j<N;j++){ if(strcmp(temp,stu[j].id)==0) { printf("%d %c\n",max(stu[j].rank_A,stu[j].rank_C,stu[j].rank_M,stu[j].rank_E)+1, rank[max_rank(stu[j].rank_A,stu[j].rank_C,stu[j].rank_M,stu[j].rank_E)]); flag=1; break; } } if(!flag) printf("N/A\n"); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int g1, g2; int count; int N; struct stu{ char name[11]; char id[11]; int grade; int flag; }stu[100000]; int cmp(const void *a, const void *b){ struct stu *c, *d; c = (struct stu*) a; d = (struct stu*) b; if(c->flag != d->flag) return d->flag - c->flag; return d->grade - c->grade; } int main(){ scanf("%d", &N); for(int i = 0; i < N; i++){ getchar(); scanf("%s", stu[i].name); scanf("%s", stu[i].id); scanf("%d", &stu[i].grade); } scanf("%d%d", &g1, &g2); if(g1 > g2){ g1 = g1 + g2; g2 = g1 - g2; g1 = g1 - g2; } for(int i = 0; i < N; i++){ if(stu[i].grade <= g2 && stu[i].grade >= g1){ stu[i].flag = 1; count++; } else stu[i].flag = 0; } if(count == 0) printf("NONE\n"); else{ qsort(stu, N, sizeof(stu[0]), cmp); for(int i = 0; i < count; i++){ printf("%s %s\n", stu[i].name, stu[i].id); } } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define maximum 1<<30 int num; int char_to_int(char *num){ return (num[0] - '0') * 1000 + (num[1] - '0') * 100 + (num[2] - '0') * 10 + (num[3] - '0'); } char *int_to_char(int num){ char *number; number = (char *) malloc (sizeof(char) * 5); number[0] = num/1000 + '0'; number[1] = (num % 1000) / 100 + '0'; number[2] = (num % 100) / 10 + '0'; number[3] = num %10 + '0'; return number; } char *sort(char *num){ char temp; for(int i = 0; i < 4; i++){ for(int j = i + 1; j < 4; j++){ if(num[i] < num[j]){ temp = num[i]; num[i] = num[j]; num[j] = temp; } } } return num; } int cmp1(const void *a, const void *b){ return *(char *)b - *(char *)a; } int cmp2(const void *a, const void *b){ return *(char *)a - *(char *)b; } int main(int argc, const char * argv[]) { char temp1[5], temp2[5]; scanf("%d",&num); //for(int i=0; i < 10000; i++){ // memcpy(num, int_to_char(i), 5); // printf("if(num == %d) printf(\"", i); do{ memcpy(temp1, int_to_char(num), 5); memcpy(temp2, temp1, 5); qsort(temp1, 4, sizeof(char), cmp1); qsort(temp2, 4, sizeof(char), cmp2); num = char_to_int(temp1) - char_to_int(temp2); printf("%s - %s = %04d", temp1, temp2, num); printf("\n"); }while(num != 6174 && num != 0); // printf("\");"); //} return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> int n; int temp; int count; int temp1[10]; int power(int a, int b){ int sum=1; if(b==0) return 1; for(int i=0;i<b;i++){ sum*=a; } return sum; } int main(int argc, char *argv[]){ int total=0; scanf("%d",&n); count=0; temp=n; while(temp/10){ temp1[count++]=temp%10; temp/=10; } temp1[count]=temp; for(int i=0;i<=count;i++){ if(temp1[i]==0){ total+=power(10,i)*(n/power(10,i+1)); } else if(temp1[i]==1){ total+=power(10,i)*(n/power(10,i+1)?(n/power(10,i+1)):0)+n%power(10,i)+1; } else if(temp1[i]>1){ total+=power(10,i)*(n/power(10,i+1)+1); } } printf("%d\n",total); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define max 26*26*26*10+1 int N, K; int total[max]; int ans[max]; struct stu{ int num; struct stu *next; }; int name_to_num(char *name){ return name[3]-'0'+(name[2]-'A')*10+(name[1]-'A')*260+(name[0]-'A')*26*260; } struct stu a[max]; int cmp(const void *a, const void *b){ return *(int *)a-*(int *)b; } int main(int argc, char *argv[]){ char name[5]; int j, k; int i; int Nj; struct stu *temp; scanf("%d%d",&N,&K); for(k=0;k<K;k++){ scanf("%d",&i); scanf("%d",&Nj); for(j=0;j<Nj;j++){ getchar(); scanf("%s",name); total[name_to_num(name)]++; temp=(struct stu*)malloc(sizeof(struct stu)); temp->num=i; temp->next=a[name_to_num(name)].next; a[name_to_num(name)].next=temp; } } for(i=0;i<N;i++){ k=0; getchar(); scanf("%s",name); printf("%s %d",name,total[name_to_num(name)]); temp=a[name_to_num(name)].next; while(temp){ ans[k++]=temp->num; temp=temp->next; } qsort(ans,k,sizeof(int),cmp); for(j=0;j<k;j++) printf(" %d",ans[j]); printf("\n"); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int M; int K; int edge[201][201]; int v[10000]; int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(int argc, char *argv[]){ int v1, v2; int n; int flag; scanf("%d%d", &N, &M); for(int i = 0; i < M; i++){ scanf("%d%d", &v1, &v2); edge[v1][v2] = edge[v2][v1] = 1; } scanf("%d", &K); for(int i = 0; i < K; i++){ flag = 1; scanf("%d", &n); for(int j = 0; j < n; j++){ scanf("%d", &v[j]); } if(n != N + 1 || v[0] != v[n-1]) printf("NO\n"); else{ for(int j = 0; j < n - 1; j++){ if(!edge[v[j]][v[j+1]]){ flag = 0; break; } } if(!flag) printf("NO\n"); else{ qsort(v, n - 1, sizeof(int), cmp); for(int j = 0; j < n - 1; j++){ if(v[j] != j + 1){ flag = 0; break; } } if(flag) printf("YES\n"); else printf("NO\n"); } } } return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define INT_MAX 1<<30 int visited[500]; int dis[500]; int cost[500][500]; int road[500][500]; int min_cost[500]; int last[500]; int N; int M; int S; int D; int ans[500]; void Dijstra(){ int index=-1; int i; int min; dis[S]=0; min_cost[S]=0; while(1){ index=-1; min=INT_MAX; for(i=0;i<N;i++){ if(dis[i]<min&&!visited[i]){ index=i; min=dis[i]; break; } } visited[index]=1; if(index==-1) break; for(i=0;i<N;i++){ if(!visited[i]){ if(road[i][index]+dis[index]<dis[i]){ dis[i]=road[i][index]+dis[index]; min_cost[i]=cost[i][index]+min_cost[index]; last[i]=index; } else if(road[i][index]+dis[index]==dis[i]){ if(min_cost[i]>cost[i][index]+min_cost[index]){ min_cost[i]=cost[i][index]+min_cost[index]; last[i]=index; } } } } } } int main(int argc, char *argv[]){ int i, j; int a, b; scanf("%d%d%d%d",&N,&M,&S,&D); for(i=0;i<N;i++){ for(j=0;j<N;j++){ road[i][j]=INT_MAX; cost[i][j]=INT_MAX; } dis[i]=INT_MAX; last[i]=i; } for(i=0;i<M;i++){ scanf("%d%d",&a,&b); scanf("%d%d",&road[a][b],&cost[a][b]); road[b][a]=road[a][b]; cost[b][a]=cost[a][b]; } Dijstra(); i=D; j=0; ans[j++]=i; while(i!=S){ i=last[i]; ans[j++]=i; } for(j--;j>=0;j--) printf("%d ",ans[j]); printf("%d %d\n",dis[D],min_cost[D]); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #define INT_MAX 1<<29 int M; int N; int K; int head; int tail; int temp; int flag; int inp; int min1; int min2; int min; int stack[2000]; void push(int num){ stack[tail+1]=num; tail++; } void pop(){ tail--; } void Clear(){ head=tail=0; memset(stack,-1,sizeof(stack)); } int main(int argc, char *argv[]){ scanf("%d%d%d",&M,&N,&K); for(int i=0;i<K;i++){ temp=1; flag=1; min2=-1; for(int j=0;j<N;j++){ scanf("%d",&inp); if(!j) min=min1; else min=min2; if(inp>=temp){ for(int k=min+1;k<=inp;k++){ push(k); if(tail>M){ flag=0; } } pop(); temp=inp; } else{ if(stack[tail]!=inp){ flag=0; } else pop(); } if(inp>min2) min2=inp; } if(tail) flag=0; if(flag) printf("YES\n"); else printf("NO\n"); Clear(); } return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> int N; int arr[30]; int arr_count; int inorder[30]; int inorder_count; int pre_order[30]; int pre_order_count; int post_order[30]; int post_order_count; void traversal(int head1, int head2, int head3, int len){ if(!len) return; int i; int temp1, temp2; post_order[head3 + len - 1] = pre_order[head1]; for(i = head2; i < head2 + len; i++){ if(inorder[i] == pre_order[head1]){ break; } } temp1 = i - head2; temp2 = len - temp1 - 1; traversal(head1 + 1, i - temp1, head3, temp1); traversal(head1 + 1 + temp1, i + 1, head3 + temp1, temp2); } int main(){ char temp[5]; scanf("%d", &N); while(inorder_count < N){ scanf("%s", temp); if(strcmp(temp, "Push") == 0){ scanf("%d", &arr[arr_count++]); pre_order[pre_order_count++] = arr[arr_count - 1]; } else{ inorder[inorder_count++] = arr[arr_count-1]; arr_count--; } } traversal(0, 0, 0, N); for(int i = 0; i < N - 1; i++) printf("%d ", post_order[i]); printf("%d\n", post_order[N-1]); return 0; }<file_sep>#include <stdio.h> struct node{ int value; int next; int previous; }node[100010]; int head; int N; int K; int main(int argc, char *argv[]){ int temp; int temp1 = head, temp2 = head; scanf("%d%d%d", &head, &N, &K); for(int i = 0; i < N; i++){ scanf("%d", &temp); scanf("%d%d", &node[temp].value, &node[temp].next); if(node[temp].next != -1) node[node[temp].next].previous = temp; } N = 0; temp = head; while(temp != -1){ temp = node[temp].next; N++; } if(N >= K){ temp1 = head; temp = head; for(int i = 1; i < K; i++){ temp = node[temp].next; } head = temp; temp2 = node[temp].next; for(int i = 1; i < K; i++){ node[temp].next = node[temp].previous; temp = node[temp].next; } N -= K; } while(N >= K){ temp = temp2; for(int i = 1; i < K; i++){ temp = node[temp].next; } node[temp1].next = temp; temp2 = node[temp].next; for(int i = 1; i < K; i++){ node[temp].next = node[temp].previous; temp = node[temp].next; } temp1 = temp; N -= K; } node[temp1].next = temp2; temp = head; while(temp != -1){ if(node[temp].next != -1){ printf("%05d %d %05d\n", temp, node[temp].value, node[temp].next); } else{ printf("%05d %d %d\n", temp, node[temp].value, node[temp].next); } temp = node[temp].next; } return 0; }<file_sep>#include <stdio.h> int main(int argc, char *argv[]){ int a, b, c; char _a[3],_b[3],_c[3]; scanf("%d%d%d",&a,&b,&c); if(a/13<=9) _a[0]=a/13+'0'; else _a[0]=a/13-10+'A'; if(a%13<=9) _a[1]=a%13+'0'; else _a[1]=a%13-10+'A'; if(b/13<=9) _b[0]=b/13+'0'; else _b[0]=b/13-10+'A'; if(b%13<=9) _b[1]=b%13+'0'; else _b[1]=b%13-10+'A'; if(c/13<=9) _c[0]=c/13+'0'; else _c[0]=c/13-10+'A'; if(c%13<=9) _c[1]=c%13+'0'; else _c[1]=c%13-10+'A'; _a[2]=0;_b[2]=0;_c[2]=0; printf("#%s%s%s\n",_a,_b,_c); return 0; }<file_sep>#include<stdio.h> int N; double sum = 0; int main(int argc, char *argv[]){ double temp; scanf("%d", &N); for(int i = 0; i < N; i++){ scanf("%lf", &temp); sum += temp * (i + 1) * (N - i); } printf("%.2lf\n", sum); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define max 100000 int stack[max]; int tree[max]; char inp[3][11]={"Pop","PeekMedian","Push"}; int N; int last; int lowbit(int x) {return x&-x;} void add(int k, int num){ while(k<=max){ tree[k]+=num; k+=lowbit(k); } } int Read(int k){ int sum=0; while(k){ sum+=tree[k]; k-=lowbit(k); } return sum; } int main(int argc, char *argv[]){ int i; char temp[11]; int value; int head, tail; int count; int middle; scanf("%d",&N); getchar(); for(i=0;i<N;i++){ scanf("%s",temp); if(!strcmp(temp,inp[0])){ if(last>0) { add(stack[last-1],-1); printf("%d\n",stack[last-1]); last--; } else printf("Invalid\n"); } else if(!strcmp(temp,inp[1])){ if(last==0) {printf("Invalid\n");continue;} else{ head=0;tail=max;middle=(head+tail)/2; if(last%2) count=(last+1)/2; else count=last/2; while(1){ if(head>=tail) break; else if(Read(middle)<count){head=middle+1;middle=(head+tail)/2;} else {tail=middle;middle=(head+tail)/2;} } printf("%d\n",middle); } } else if(!strcmp(temp,inp[2])){ scanf("%d",&value); getchar(); add(value,1); stack[last++]=value; } } return 0; }<file_sep>#include <stdio.h> //#include <string.h> #include <stdlib.h> int N; int inp[1000]; int cmp(const void *a, const void *b){ return *(int *)a-*(int *)b; } int power(int base, int index){ int product=1; if(index==0) return 1; for(int i=0;i<index;i++){ product*=base; } return product; } struct tree{ int value; struct tree *left; struct tree *right; }*header; int lg2(int base, int value){ int count=0; int temp=1; while(temp<value){ temp*=base; count++; } return count; } void find_center(int head, int tail, struct tree *tree){ struct tree *temp=(struct tree*)malloc(sizeof(struct tree)); temp->left=temp->right=NULL; int len=tail-head+1; int level=lg2(2,len+1); int remain=len-power(2,level-1)+1; int left_bot, right_bot; if(len<=0) return; if(len==1){ temp->value=inp[head]; if(tree==NULL) {tree=temp;} else{ if(inp[head]>tree->value) tree->right=temp; else tree->left=temp; } return; } if(remain>power(2,level-2)){ left_bot=power(2,level-2); right_bot=remain-left_bot; } else{ left_bot=remain; right_bot=0; } temp->value=inp[head+len-right_bot-power(2,level-2)]; //printf("%d\n",temp->value); if(tree==NULL){ tree=temp; header=tree; find_center(head, head+len-right_bot-power(2,level-2)-1, tree); find_center(head+len-right_bot-power(2,level-2)+1, tail, tree); } else { if(temp->value>tree->value) tree->right=temp; else if(temp->value<tree->value) tree->left=temp; tree=temp; find_center(head, head+len-right_bot-power(2,level-2)-1, tree); find_center(head+len-right_bot-power(2,level-2)+1, tail, tree); } } int main(int argc, char *argv[]){ struct tree *head; struct tree ans[1000]; scanf("%d",&N); for(int i=0; i<N;i++){ scanf("%d",&inp[i]); } qsort(inp, N, sizeof(inp[0]), cmp); find_center(0, N-1, head); //printf("%d\n",header->value); if(N>1){ ans[1]=*header; for(int i=2;i<=N;i++){ if(i%2==0) ans[i]=*ans[i/2].left; else ans[i]=*ans[i/2].right; } for(int i=1;i<N;i++) printf("%d ",ans[i].value); printf("%d\n",ans[N].value);} else printf("%d\n",inp[0]); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <limits.h> struct custom{ int hour, min, sec; int time; int arrive; }; int cmp(const void *a, const void *b){ struct custom *c, *d; c=(struct custom*)a; d=(struct custom*)b; return c->arrive-d->arrive; } int main(int argc, char *argv[]){ int N, K, n=0, pos=0; int hour, min, sec, time; int wait=0; int flag=0; double ave=0.0; scanf("%d%d",&N,&K); int i, j; int win[K]; memset(win,0,sizeof(int)*K); struct custom a[N]; for(i=0;i<N;i++){ scanf("%d:%d:%d%d",&hour,&min,&sec,&time); if((hour*3600+min*60+sec<=17*3600)){ a[n].hour=hour; a[n].min=min; a[n].sec=sec; a[n].time=time; a[n].arrive=hour*3600+min*60+sec; n++; } } qsort(a,n,sizeof(a[0]),cmp); for(i=0;i<K;i++) win[i]=8*3600; //for(i=0;i<K;i++) printf("%d\n",win[i]); //for(i=0;i<n;i++) printf("%d %d %d %d %d\n",a[i].hour, a[i].min, a[i]. sec,a[i].time, a[i].arrive); for(i=0;i<n;i++){ time=INT_MAX; pos=0; flag=0; for(j=0;j<K;j++){ if(a[i].arrive>=win[j]){ win[j]=a[i].arrive+a[i].time*60; flag=1; break; } else{ if(time>win[j]){ time=win[j]; pos=j; } } } if(!flag){ wait+=time-a[i].arrive; win[pos]+=a[i].time*60; } } if(n){ ave=wait*1.0/n; printf("%.1f\n",ave/60.0); } else printf("0.0\n"); return 0; }<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> char inp[1001]; int isSym(char *str, int len){ for(int i=0;i<=len/2-1;i++) if(str[i]!=str[len-i-1]) return 0; return 1; } int main(int argc, char *argv[]){ int max=1; gets(inp); for(int i=0;i<strlen(inp)-1;i++) for(int j=i+1;j<strlen(inp);j++) if(isSym(inp+i,j-i+1)&&j-i+1>max) max=j-i+1; printf("%d\n",max); return 0; }<file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int N; int arr[100]; int sort_arr[100]; int heap[1000]; int Times; int check(){ int i; int flag = 1; for(i = 1; i < N; i++) if(sort_arr[i] < sort_arr[i-1]) break; flag = i; for(;i < N; i++) if(sort_arr[i] != arr[i]) flag = 0; return flag; } void exchange(int pos){ int temp; if(heap[pos * 2 + 1] != -1){ if(heap[pos] < heap[pos * 2] || heap[pos] < heap[pos * 2 + 1]){ if(heap[pos * 2] > heap[pos * 2 + 1]){ temp = heap[pos * 2]; heap[pos * 2] = heap[pos]; heap[pos] = temp; if(heap[pos * 2] < heap[pos * 4] || heap[pos * 2] < heap[pos * 4 + 1]) exchange(pos * 2); } else{ temp = heap[pos * 2 + 1]; heap[pos * 2 + 1] = heap[pos]; heap[pos] = temp; if(heap[pos * 2 + 1] < heap[pos * 4 + 2] || heap[pos * 2 + 1] < heap[pos * 4 + 3]) exchange(pos * 2 + 1); } } } else{ if(heap[pos] < heap[pos * 2]){ temp = heap[pos * 2]; heap[pos * 2] = heap[pos]; heap[pos] = temp; } } } int complete(){ int flag = 1; for(int i = 0; i < N; i++){ if(sort_arr[i] != heap[i+1]) {flag = 0;break;} } return flag; } void build(){ for(int i = 0; i < N; i++) heap[i+1] = arr[i]; for(int i = N; i >= 1; i--){ if(heap[i * 2] != -1){ exchange(i); } } } void operate(){ int temp; int parent; int child; temp = heap[1]; heap[1] = heap[N-Times]; heap[N-Times] = temp; temp = heap[1]; parent = 1; while(1){ child = parent * 2; if(child + 1 >= N - Times) break; if(heap[child + 1] > heap[child]) child++; if(temp < heap[child]){ heap[parent] = heap[child]; parent = child; } else break; } if(child < N - Times && heap[child] > temp) {heap[parent] = heap[child]; parent = child;} heap[parent] = temp; } int main(int argc, char *argv[]){ int flag; int i; scanf("%d", &N); for(i = 0; i < N; i++){ scanf("%d", &arr[i]); } for(i = 0; i < N; i++){ scanf("%d", &sort_arr[i]); } flag = check(); if(flag){ printf("Insertion Sort\n"); for(i = 0; i < N; i++){ if(sort_arr[i] < sort_arr[flag]) printf("%d ", sort_arr[i]); else break; } printf("%d ", sort_arr[flag]); for(; i < N - 1; i++){ if(i != flag) printf("%d ", sort_arr[i]); } printf("%d\n", sort_arr[N-1]); } else{ memset(heap, -1, sizeof(heap)); printf("Heap Sort\n"); build(); //for(int i = 1; i <= N; i++) printf("%d ", heap[i]); //printf("\n"); while(!complete() && Times <= N){ operate(); Times++; //for(int i = 1; i <= N; i++) printf("%d ", heap[i]); //printf("\n"); } if(Times < N) operate(); for(int i = 1; i < N; i++) printf("%d ", heap[i]); printf("%d\n", heap[N]); } return 0; }<file_sep>#include<cstdio> #include<iostream> #include<cstring> #include<cmath> #include<string> #include<vector> #include<map> #include<set> #include<algorithm> #include<sstream> using namespace std; int charToInt(char x)//字符转数字 { if('0'<=x&&x<='9') return x-'0'; else return x-'a'+10; } long long charToDecimal(char* x,long long radix)//字符串转对应进制数字 { int len=strlen(x); long long ans=0; for(int i=0;i<len;++i) { ans*=radix; ans+=charToInt(x[i]); if(ans<0) return -1; } return ans; } int main() { char as[15],bs[15],temp[15]; long long tag,radix,aimNum; int lenA,lenB; scanf("%s%s%lld%lld",as,bs,&tag,&radix); if(tag==1) { strcpy(temp,as); strcpy(as,bs); strcpy(bs,temp); tag=2; } lenA=strlen(as); lenB=strlen(bs); aimNum=charToDecimal(bs,radix); long long low=2;//进制下限 for(int i=0,j;i<lenA;++i) { j=charToInt(as[i]); if(j>=low) low=j+1; } long long high=aimNum+1;//进制上限 long long aimRadix; long long tempAns; bool flag=false; for(;low<=high;)//二分搜索 { aimRadix=(high+low)/2; tempAns=charToDecimal(as,aimRadix); if(tempAns==-1||tempAns>aimNum) high=aimRadix-1; else if(tempAns<aimNum) low=aimRadix+1; else { flag=true; break; } } if(flag) printf("%lld\n",aimRadix); else printf("Impossible\n"); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <limits.h> struct file{ int id; char name[9]; int grade; }; struct file file[100000]; int cmp1(const void *a, const void *b){ struct file *c, *d; c=(struct file*)a; d=(struct file*)b; return c->id-d->id; } int cmp2(const void *a, const void *b){ struct file *c, *d; c=(struct file*)a; d=(struct file*)b; if(strcmp(c->name,d->name)) return strcmp(c->name,d->name); else return c->id-d->id; } int cmp3(const void *a, const void *b){ struct file *c, *d; c=(struct file*)a; d=(struct file*)b; if(c->grade!=d->grade) return c->grade-d->grade; else return c->id-d->id; } int main(int argc, char *argv[]){ int N, C; scanf("%d%d",&N,&C); for(int i=0;i<N;i++){ scanf("%d",&file[i].id); getchar(); scanf("%s",file[i].name); scanf("%d",&file[i].grade); } if(C==1) qsort(file, N, sizeof(file[0]), cmp1); else if(C==2) qsort(file, N, sizeof(file[0]), cmp2); else if(C==3) qsort(file, N, sizeof(file[0]), cmp3); for(int i=0;i<N;i++){ printf("%06d %s %d\n",file[i].id, file[i].name, file[i].grade); } return 0; }<file_sep>#include <cstdio> #include <cstring> #include <string> #include <queue> #include <set> using namespace std; const int N = 10004; const int M = 102; const int close_ = 3600 * 21; struct node { int time; int id; int type; }; // type = 0, table free, 1 person come bool operator<(const node &a,const node &b) { if (a.time > b.time) { return true; } if (a.time < b.time) { return false; } return (a.time > b.time) || ((a.time == b.time) && (a.type < b.type)); } int num[M]; int play[N]; bool isvipperson[N]; bool isviptable[M]; set<int> ordtable; set<int> viptable; set<pair<int,int> > vipperson; set<pair<int,int> > ordperson; priority_queue<node> affair; int gettable() { int r; if (ordtable.empty()) { r = *viptable.begin(); viptable.erase(viptable.begin()); return r; } if (viptable.empty()) { r = *ordtable.begin(); ordtable.erase(ordtable.begin()); return r; } if (*ordtable.begin() < *viptable.begin()) { r = *ordtable.begin(); ordtable.erase(ordtable.begin()); } else { r = *viptable.begin(); viptable.erase(viptable.begin()); } return r; } pair<int,int> getperson() { pair<int,int> r; if (ordperson.empty()) { r = *vipperson.begin(); vipperson.erase(vipperson.begin()); return r; } if (vipperson.empty()) { r = *ordperson.begin(); ordperson.erase(ordperson.begin()); return r; } if (ordperson.begin()->first < vipperson.begin()->first) { r = *ordperson.begin(); ordperson.erase(ordperson.begin()); } else { r = *vipperson.begin(); vipperson.erase(vipperson.begin()); } return r; } void freetable(int x) { if (isviptable[x]) { viptable.insert(x); } else { ordtable.insert(x); } } void print(int x,int y) { printf("%02d:%02d:%02d %02d:%02d:%02d %d\n",x / 3600, x % 3600 / 60, x % 60, y / 3600, y % 3600 / 60, y % 60, (y - x + 30) / 60); } int main() { int n; node temp; scanf("%d",&n); for (int i = 0; i < n; ++i) { int x; int hh,mm,ss; scanf("%d:%d:%d %d%d",&hh,&mm,&ss,&play[i],&x); isvipperson[i] = x; temp.id = i; temp.time = hh * 3600 + mm * 60 + ss; temp.type = 1; play[i] = min(play[i], 120); play[i] *= 60; affair.push(temp); } int a; for (scanf("%d%d",&n,&a);a;--a) { int x; scanf("%d",&x); isviptable[--x] = true; viptable.insert(x); } for (int i = 0; i < n; ++i) { if (!isviptable[i]) { ordtable.insert(i); } } while (!affair.empty()) { temp = affair.top(); affair.pop(); int now = temp.time; if (now >= close_) { break; } if (temp.type == 0) { freetable(temp.id); while ((!affair.empty()) && (affair.top().type == 0) && (affair.top().time == now)) { freetable(affair.top().id); affair.pop(); } while ((!viptable.empty()) && (!vipperson.empty())) { temp.time = now + vipperson.begin()->second; temp.type = 0; ++num[temp.id = *viptable.begin()]; print(vipperson.begin()->first, now); affair.push(temp); viptable.erase(viptable.begin()); vipperson.erase(vipperson.begin()); } while (((!ordperson.empty()) || (!vipperson.empty())) && ((!ordtable.empty()) || (!viptable.empty()))) { pair<int,int> g = getperson(); temp.time = now + g.second; temp.type = 0; ++num[temp.id = gettable()]; print(g.first,now); affair.push(temp); } } else if (isvipperson[temp.id]) { if (!viptable.empty()) { temp.time = now + play[temp.id]; print(now, now); temp.type = 0; ++num[temp.id = *viptable.begin()]; affair.push(temp); viptable.erase(viptable.begin()); } else if (!ordtable.empty()) { temp.time = now + play[temp.id]; print(now, now); temp.type = 0; ++num[temp.id = *ordtable.begin()]; affair.push(temp); ordtable.erase(ordtable.begin()); } else { vipperson.insert(make_pair(now, play[temp.id])); } } else if ((!viptable.empty()) || (!ordtable.empty())) { temp.time = now + play[temp.id]; print(now, now); temp.type = 0; ++num[temp.id = gettable()]; affair.push(temp); } else { ordperson.insert(make_pair(now, play[temp.id])); } } for (int i = 0; i < n; ++i) { if (i) { putchar(' '); } printf("%d",num[i]); } puts(""); return 0; }
c272e72b9b6756e919428e1c49eae23d72d1e2d8
[ "Markdown", "C", "C++" ]
132
C
OYMQKUX/PAT_Advanced
e0cc5ceae16492c9ee651bc7ff413a3a8cc8451d
6245219d011584191dd8cc6a30840f7af3e63cf9
refs/heads/master
<file_sep>using System.Threading.Tasks; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; namespace NetCoreRepositoryAndUnitOfWorkPattern.Service.Services { public interface IProductService { Product GetMySpecialProduct(); Task<Product> GetProductById(int id); } }<file_sep>using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; namespace NetCoreRepositoryAndUnitOfWorkPattern.Data.Repositories { public class ProductRepository : Repository<Product>, IProductRepository { private readonly RepositoryPatternDemoContext _repositoryPatternDemoContextContext; public ProductRepository(RepositoryPatternDemoContext repositoryPatternDemoContextContext) : base(repositoryPatternDemoContextContext) { _repositoryPatternDemoContextContext = repositoryPatternDemoContextContext; } public Product MyProductSpecificMethod() { // Get some amazing data from the database and then return it; // return _repositoryPatternDemoContextContext.GetAmazingData(); return new Product { Name = "ProductName", Description = "Special Description", Price = 1234567m }; } } }<file_sep>using System; namespace NetCoreRepositoryAndUnitOfWorkPattern.Data.Models { public partial class UserInfo { public UserInfo() { Id = Guid.NewGuid().ToString("D"); } public string Id { get; set; } public string UserName { get; set; } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; namespace NetCoreRepositoryAndUnitOfWorkPattern.Service.Services { public interface ICustomerService { List<Customer> GetAllCustomer(); Task<Customer> GetCustomerById(int id); Task<Customer> AddCustomer(Customer newCustomer); Customer Add(Customer newCustomer); Task<Customer> UpdateCustomer(Customer newCustomer); } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Dapper; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; using NetCoreRepositoryAndUnitOfWorkPattern.Models; using NetCoreRepositoryAndUnitOfWorkPattern.Service.Services; namespace NetCoreRepositoryAndUnitOfWorkPattern.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ICustomerService _customerService; private readonly IUserService _userService; private readonly IDapper _dapper; public HomeController(ILogger<HomeController> logger, ICustomerService customerService, IUserService userService, IDapper dapper) { _logger = logger; _customerService = customerService; _userService = userService; _dapper = dapper; } public IActionResult Index() { /*var allCustomer = _customerService.GetAllCustomer(); var first = allCustomer.FirstOrDefault(); first.FirstName = "monir"; _customerService.UpdateCustomer(first);*/ /*var allCustomer = _userService.GetAllUsers(); var first = allCustomer.FirstOrDefault(); first.UserName = "monir"; _userService.UpdateUser(first);*/ //var user = _customerService.Add(new Customer() {FirstName = "abc"}); var user = _customerService.Add(new Customer() {FirstName = "abc",Age = 10,LastName = "sadfa"}); //var customer = _dapper.Get<Customer>("select * from Customer"); //_dapper.Insert<Customer>("insert into Customer (Id,FirstName) Values ('2','monira')"); return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Repositories; namespace NetCoreRepositoryAndUnitOfWorkPattern.Service.Services { public class UserService : IUserService { private readonly IRepository<UserInfo> _userRepository; public UserService(IRepository<UserInfo> userRepository) { _userRepository = userRepository; } public List<UserInfo> GetAllUsers() { return _userRepository.GetAll().ToList(); } public async Task<UserInfo> GetCustomerById(int id) { return await _userRepository.GetAll().FirstOrDefaultAsync(x => x.Id == id.ToString()); //return await _userRepository.GetAll().FirstOrDefaultAsync(x => x.Id == id); } public async Task<UserInfo> AddUser(UserInfo newCustomer) { return await _userRepository.AddAsync(newCustomer); } public async Task<UserInfo> UpdateUser(UserInfo newCustomer) { return await _userRepository.UpdateAsync(newCustomer); } } }<file_sep>using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; using NetCoreRepositoryAndUnitOfWorkPattern.Service.Services; namespace NetCoreRepositoryAndUnitOfWorkPattern.Controllers { public class ProductController { private readonly IProductService _productService; public ProductController(IProductService productService) { _productService = productService; } public async Task<ActionResult<Product>> GetProductById() { return await _productService.GetProductById(1); } public ActionResult<Product> GetSpecialProduct() { return _productService.GetMySpecialProduct(); } } }<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; namespace NetCoreRepositoryAndUnitOfWorkPattern.Service.Services { public interface IUserService { List<UserInfo> GetAllUsers(); Task<UserInfo> UpdateUser(UserInfo newCustomer); Task<UserInfo> AddUser(UserInfo newCustomer); } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Repositories; namespace NetCoreRepositoryAndUnitOfWorkPattern.Service.Services { public class CustomerService : ICustomerService { private readonly IRepository<Customer> _customerRepository; public CustomerService(IRepository<Customer> customerRepository) { _customerRepository = customerRepository; } public List<Customer> GetAllCustomer() { return _customerRepository.GetAll().ToList(); } public async Task<Customer> GetCustomerById(int id) { return await _customerRepository.GetAll().FirstOrDefaultAsync(x => x.Id == id); } public async Task<Customer> AddCustomer(Customer newCustomer) { return await _customerRepository.AddAsync(newCustomer); } public Customer Add(Customer newCustomer) { return _customerRepository.Add(newCustomer); } public async Task<Customer> UpdateCustomer(Customer newCustomer) { return await _customerRepository.UpdateAsync(newCustomer); } } }<file_sep>using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Repositories; namespace NetCoreRepositoryAndUnitOfWorkPattern.Service.Services { public class ProductService : IProductService { private readonly IProductRepository _productRepository; public ProductService(IProductRepository productRepository) { _productRepository = productRepository; } public Product GetMySpecialProduct() { return _productRepository.MyProductSpecificMethod(); } public async Task<Product> GetProductById(int id) { return await _productRepository.GetAll().FirstOrDefaultAsync(x => x.Id == id); } } }<file_sep>using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Infrastructure; using NetCoreRepositoryAndUnitOfWorkPattern.Data.Models; namespace NetCoreRepositoryAndUnitOfWorkPattern.Data.Repositories { public interface IProductRepository : IRepository<Product> { Product MyProductSpecificMethod(); } }
3e73d071416abb7246b06a983e66624efbcae203
[ "C#" ]
11
C#
mostafizMonir/base
c0a98e9d76f186f29d67114c7eea098157c9e17b
cd41db7f7fd1972d9911b094f40861d65b588357
refs/heads/master
<repo_name>gc-victor/torrentflix<file_sep>/lib/rarbg.js var Q = require('q'); var request = require("request"); var cheerio = require('cheerio'); var moment = require('moment'); module.exports = { search: function(query, cat, page, rarbg_url) { var torrent_search = query; var search_query = torrent_search.split(' ').join('+'); var search_url = rarbg_url + "/torrents.php?search=" + search_query + "&order=seeders&by=DESC/"; var count = 1; var deferred = Q.defer(); var data_content = {}; var torrent_content = []; var theJar = request.jar(); var options = { url: rarbg_url + '/torrents.php?search=' + search_query + '&order=seeders&by=DESC', headers: { 'Referer': rarbg_url + '/index6.php', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.43 Safari/537.36' }, jar: theJar }; theJar.setCookie('7fAY799j=VtdTzG69', rarbg_url, {"ignoreError":true}); request(options, function(err, response, body){ if(!err && response.statusCode === 200){ var torrent_link, torrent_title, torrent_seeds, torrent_leech, torrent_size, torrent_date; $ = cheerio.load(body); var title = $("title").text(); if(title === "Bot check !"){ deferred.reject("Can't search Rarbg, It thinks you are a bot :(, Try again later."); } if($('.lista2t tr').length > 1){ $('.lista2t tr').each(function(index, torrents){ var d = $(this); var td = d.children('td.lista'); links = $(torrents).find('a'); $(links).each(function(i, link){ if($(link).attr('href').indexOf("/torrent/") > -1 && $(link).attr('href').indexOf("#comments") < 1) { rarbg_link = $(link).attr('href'); torrent_title = $(link).text(); torrent_size = $(td).eq(3).text(); torrent_seeds = $(td).eq(4).text(); torrent_leech = $(td).eq(5).text(); date_added = moment(Date.parse($(td).eq(2).text())).fromNow(); var rarbg_id = rarbg_link.split('/torrent/').join(''); var rarbg_file = encodeURIComponent(torrent_title) + "-[rarbg.com].torrent"; var torrent_link = rarbg_url + "/download.php?id=" + rarbg_id + "&f=" +rarbg_file; data_content = { torrent_num: count, title: torrent_title, category: "", seeds: torrent_seeds, leechs: torrent_leech, size: torrent_size, torrent_link: "", torrent_site: rarbg_url + rarbg_link, date_added: date_added }; torrent_content.push(data_content); deferred.resolve(torrent_content); count++; } }); }); } else { deferred.reject("No torrents found"); } } else { deferred.reject("There was a problem loading Rarbg"); } }); return deferred.promise; } }; <file_sep>/lib/thepiratebay.js var Q = require('q'); var request = require("request"); var cheerio = require('cheerio'); module.exports = { search: function(query, cat, page, thepiratebay_url) { var torrent_search = query; var search_query = torrent_search.split(' ').join('%20'); var search_url = thepiratebay_url + "/search/" + search_query + "/0/7/0"; var count = 1; var deferred = Q.defer(); var data_content = {}; var torrent_content = []; var link_content = []; request(search_url, function(err, response, body){ if(!err && response.statusCode === 200){ $ = cheerio.load(body); $('table#searchResult tr').each(function(index, torrents){ var torrent_title, torrent_link, torrent_verified; if($(torrents).find('.detName a').text()){ find_torrent_title = $(torrents).find('.detName a'); find_torrent_seed = $(torrents).find('td').next().next().text(); find_torrent_leech = $(torrents).find('td').next().next().next().text(); find_torrent_size = $(torrents).find('.detDesc'); torrent_title = find_torrent_title.text(); torrent_leech = find_torrent_leech; torrent_seed = find_torrent_seed.split(torrent_leech).join(''); var matches = find_torrent_size.text().match(/, Size (.*?), ULed/g); torrent_size = matches[0].split(', Size ').join('').split(', ULed').join(''); var matches2 = find_torrent_size.text().match(/Uploaded (.*?),/g); date_added = matches2[0].split('Uploaded ').join('').split(',').join(''); links = $(torrents).find('a'); $(links).each(function(i, link){ if($(link).attr('href').indexOf("magnet:?xt=urn:") > -1) { torrent_link = $(link).attr('href'); // var torrent_magnet = $(link).attr('href'); // var matches = torrent_magnet.match(/magnet:\?xt=urn:btih:(.*)&dn=/g); // var hash = matches[0].split('magnet:?xt=urn:btih:').join('').split('&dn=').join(''); // torrent_link = "http://torcache.net/torrent/" + hash + ".torrent"; } }); images = $(torrents).find('a img'); $(images).each(function(i, images){ if($(images).attr('title')){ if($(images).attr('title').indexOf("VIP") > -1) { torrent_verified = "vip"; }else if($(images).attr('title').indexOf("Trusted") > -1) { torrent_verified = "trusted"; } } else { torrent_verified = ""; } }); data_content = { torrent_num: count, title: torrent_title, category: "", seeds: torrent_seed, leechs: torrent_leech, size: torrent_size, torrent_verified: torrent_verified, torrent_link: torrent_link, date_added: date_added }; torrent_content.push(data_content); deferred.resolve(torrent_content); count++; } }); } else { deferred.reject("There was a problem loading The Pirate Bay"); } }); return deferred.promise; } }; <file_sep>/lib/cli.js (function () { var program = require("commander"); var fs = require('fs'); var path = require('path'); var async = require('async'); var chalk = require('chalk'); var main = require("./main"); var spawn = require('child_process').spawn; var pkg = require("../package.json"); var appDir = path.dirname(require.main.filename).split('bin').join(''); var original_config_object = require('../torrentflix_config.json'); var original_settings_object = require('../settings.json'); var original_history_object = require('../torrentflix_history.json'); var config_object, settings_object, history_object; var blank_history = []; //setting up command line options program .version(pkg.version) .option('--config', 'Edit torrentflix config EX: torrentflix --config="nano"') //.option('--history', 'View torrentflix history EX: torrentflix --history') .option('--clear', 'Clear torrentflix history EX torrentflix --clear') .option('--location', 'Change where torrentflix\' config & history is located EX torrentflix --location"/home/gshock/.config"') .parse(process.argv); //if config command has been called if (program.config) { if (program.args[0]) { //open up stock or custom config in the users choice of editor var edit_conf; if(original_settings_object.config_location){ edit_conf = original_settings_object.config_location+"torrentflix_config.json"; } else { edit_conf = appDir+"torrentflix_config.json"; } spawn(program.args[0], [edit_conf], { stdio: 'inherit' }); //they didn't specify an editor ask the user to specify one } else { console.log('Please specify an editor'); console.log(" Example:"); console.log(''); console.log(' $ torrentflix --config="nano"'); } //history command called //} else if (program.history) { //TODO //clear history command called } else if (program.clear) { clearHistory(); //change torrentflix location } else if (program.location){ if (program.args[0]) { changeLocation(program.args[0]); //they didn't specify a path ask the user to specify one } else { console.log('Please specify where you want to config to be saved'); console.log(" Example:"); console.log(''); console.log(' $ torrentflix --location="/home/gshock/.config"'); } } else { //no arguments passed run the program AppInitialize(); } program.parse(process.argv); function AppInitialize(){ //we need to do some async tasks first before running the actual app async.series([ //custom config function function(callback) { //check to see if a custom location has been set for config if(original_settings_object.config_location){ var custom_config = original_settings_object.config_location +"torrentflix_config.json"; //if it has check if it exsists if (fs.existsSync(custom_config)) { //it does exsist use it fs.readFile(custom_config, 'utf8', function (err, data) { if (err) throw err; //ensure the custom config file is valid json if(IsJsonString(data)){ config_object = JSON.parse(data); callback(null, 'one'); } else { //supplied config is not valid console.log(chalk.red.bold("There was something wrong with the custom config file, Falling back to default.")); var stock_config = appDir + "torrentflix_config.json"; fs.readFile(stock_config, 'utf8', function (err, data) { if (err) throw err; config_object = JSON.parse(data); callback(null, 'one'); }); } }); //callback(null, 'one'); }else{ //it does not exsist create it and write the stock config to it fs.writeFile(custom_config, JSON.stringify(original_config_object, null, 4), function (err) { if (err) { return console.log(err); } else { //config_object = JSON.parse(fs.readFileSync(custom_config, 'utf8')); fs.readFile(custom_config, 'utf8', function (err, data) { if (err) throw err; config_object = JSON.parse(data); callback(null, 'one'); }); } }); } }else{ //a custom config has not been specified use the stock one var stock_config = appDir + "torrentflix_config.json"; fs.readFile(stock_config, 'utf8', function (err, data) { if (err) throw err; config_object = JSON.parse(data); callback(null, 'one'); }); //callback(null, 'one'); } }, //history function function(callback) { //only run if history is enabled if(config_object.history === "true"){ //check to see if a custom location has been set for history if(original_settings_object.history_location){ var custom_history = original_settings_object.history_location +"torrentflix_history.json"; //if it has check if it exsists if (fs.existsSync(custom_history)) { //it does exsist history_object = require(custom_history); callback(null, 'two'); }else{ //it does not exsist create it and write the some boiler to it var blank_history = []; fs.writeFile(custom_history, JSON.stringify(blank_history, null, 4), function (err) { if (err){ return console.log(err); } else { history_object = require(custom_history); callback(null, 'two'); } }); } }else{ //a custom history file has not been specified history_object = require('../torrentflix_history.json'); callback(null, 'two'); } } else { //history is not enabled skip callback(null, 'two'); } }, ], function(err, results){ //run main app main.AppInitialize(config_object, history_object, original_settings_object); }); } function clearHistory(){ //we need to figure out if the user is using a custom history location or not if(original_settings_object.history_location){ //they are clear the custom one fs.writeFile(original_settings_object.history_location +"torrentflix_history.json", JSON.stringify(blank_history, null, 4), function (err) { if (err) return console.log(err); console.log("history cleared"); }); } else { //they are using the stock history location fs.writeFile(appDir + "torrentflix_history.json", JSON.stringify(blank_history, null, 4), function (err) { if (err) return console.log(err); console.log(chalk.green.bold("history cleared")); }); } } function changeLocation(path){ //if the users path does not end in a slash add it var lastChar = path.substr(path.length - 1); if(lastChar !== "/" && path !== null){ path = path+"/"; } //create the object to be added to settings.json var Userpath = {"config_location": path,"history_location": path}; //write it to settings.json fs.writeFile(appDir + "settings.json", JSON.stringify(Userpath, null, 4), function (err) { if (err) return console.log(err); console.log(chalk.green.bold("Config and history location updated")); }); } function IsJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } }).call(this); <file_sep>/README.md # Torrentflix A cli tool for searching torrent sites and streaming using peerflix. It currently supports kickasstorrents, 1337x, seedpeer, Rarbg, The Pirate Bay, YTS, Extratorrent, Limetorrents, nyaa.se & tokyotosho. Want more ? Create an issue with a request, Alternatively you can contribute your own scrapers. Pull requests are welcome. ## Key features * Subtitles fetched automatically. * History of streamed torrents. ## Install (automatic) Install peerflix if you haven't already: ``` npm install -g peerflix ``` Then install torrentflix: ``` npm install -g torrentflix ``` ## Install (manual) Install peerflix if you haven't already: ``` npm install -g peerflix ``` Clone the repository: ``` git clone <EMAIL>:ItzBlitz98/torrentflix.git ``` Install dependencies: ``` npm install ``` You can now update by doing a git pull: ``` git pull ``` Now you can run the executable inside the bin folder. ## Preview ![peerflix](https://i.imgur.com/rre0MtK.png) ## Usage To run the app run: ``` $ torrentflix ``` Torrentflix comes with a set of default options, To change these settings or apply a proxy pass the config command with your editor of choice ``` $ torrentflix --config="vi" ``` Torrentflix allows you to change where its config and history files are located. Why? When updating using the automatic method unfortunately your config and history files will be replaced. To change the location simply enter: ``` $ torrentflix --location="absolute_path" ``` You will still need to run this command after every update but it won't replace your settings / history. (If you can help add a nice crossplatform alternative pull-requests are welcome) Don't forget you can always run the help flag to remind you of these ``` $ torrentflix --help ``` ## History Torrentflix can save a history of watched torrents if enabled. Printing out the history can be done in two ways: 1. During the site selection prompt press h 2. Or run peerflix with the --history flag ex: ``` $ torrentflix --history ``` Clearing the history can be done with the --clear flag ex: ``` $ torrentflix --clear ``` Please ensure the history file is in a writable directory, You can change the history location with the config flag. By default it saves the history in the torrentflix folder. ## Subtitles Torrentflix supports subtitles, By default subtitles are disabled you can enable them by running the config command above. You can also change the subtitle language from the config. ## License MIT
b95d51c47ff97b2a4c73ddcbad12b0c2eb9def3f
[ "JavaScript", "Markdown" ]
4
JavaScript
gc-victor/torrentflix
3014b3509e0b9f3dd95daf78534a840aa064131e
9860f10c6b8c902d84e4ae6ceb4e23f3f2c4be5f
refs/heads/master
<repo_name>ymyt92/tc-record<file_sep>/constants.js // 生产环境还是开发环境 production development var ENV = 'development'; // 地址变量 var HOST = ENV == 'development' ? 'http://172.16.31.10' : 'http://172.16.31.10'; var PORT = ENV == 'development' ? '8040' : '8040'; var CAS_PORT = ENV == 'development' ? '8080' : '8282'; // 后台服务地址 var SERVER_URL = HOST + ':' + PORT; // CAS默认地址 var CAS_URL = HOST + ":" + CAS_PORT; window.constants = { ENV: ENV, // 当前系统名称 SYSTEM_NAME: '社会治理综合联动平台-档案管理', // 当前系统版本 VERSION: 'command.20190224', // 市级行政区划信息 REGION: { CODE: "6102", NAME: "铜川市" }, BASE_MAP: 'TDT', // 后台服务地址 SERVER_URL: SERVER_URL, // CAS认证注销地址 CAS_LOGOUT_URL: CAS_URL + "/cas/logout", // CAS认证登录地址 CAS_LOGIN_URL: CAS_URL + "/cas/login", // 上传文件服务地址 UPLOAD_URL: SERVER_URL + "/manage/file/upload", // 附件读取地址 READ_FILE_URL: SERVER_URL + "/fastdfs/file/file" }
5152e91a5ec6ee3fc2a80f2f31eba1fad4afd75f
[ "JavaScript" ]
1
JavaScript
ymyt92/tc-record
3cdc1b11eb056f2491f83461b3c37d644fb7ac59
9473d3bd54448f39d9c0119c5fb40d0975698fe4
refs/heads/master
<file_sep>using System; namespace Lee8InClassExamples { class Program { static void Main(string[] args) { string firstName = "Lee"; char firstLetterOfFirstName = 'C'; int favoriteNumber = 2; double pi = 3.14; bool isMarried = true; if (favoriteNumber == 0) { Console.WriteLine("Favorite number is equal to 0"); } if (firstName != "Jimmy") { Console.WriteLine("First name is not Jimmy"); } if (firstName != "lee") { Console.WriteLine("First name is not lee"); } favoriteNumber = favoriteNumber + 5; favoriteNumber += 5; //favoriteNumber is 12 favoriteNumber = favoriteNumber - 1; favoriteNumber -= 1; favoriteNumber = favoriteNumber + 1; favoriteNumber += 1; favoriteNumber++; Console.WriteLine(favoriteNumber); } } }
c926a5793e343d9086ae77da623029f135ca58b6
[ "C#" ]
1
C#
leewolfe/LeeInClassExamples
e2c089d9f97c9bbaba003f724b11229b609c0ad1
439441d6e7701e1e7857463f67d9c54f4ede6ec7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //string s = Console.ReadLine(); //Input(s); if (Palindrom() == false) Console.WriteLine("No"); else Console.WriteLine("Yes"); } /*static void Input(string s) // creating input file { using (FileStream fs = new FileStream(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp1\ConsoleApp1\in.txt", FileMode.Create, FileAccess.Write)) { using (StreamWriter sr = new StreamWriter(fs)) { sr.Write(s); } } }*/ static bool Palindrom() { string text = File.ReadAllText(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp1\ConsoleApp1\in.txt"); // reading from the file for (int i = 0; i < text.Length; i++) // cheking for palindrom by the symbols { if (text[i] != text[text.Length - 1 - i]) return false; } return true; } } } <file_sep>using ConsoleApp1; using System.IO; namespace ConsoleApp3 { class MyProgram { public static void Main(string[] args) { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\"); // open new folder with given path FileSystemInfo[] files = dirInfo.GetFileSystemInfos(); // write folder's elements to array int index = 0; // selected item Options.Keys(index, files); // waiting a key } } } <file_sep>using System.IO; namespace ConsoleApp4 { class Program { static void Main(string[] args) { using (File.Create(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp4\file.txt")) //creating a file { } File.WriteAllText(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp4\file.txt", "Hello World!"); //writing "Hello World!" if (File.Exists(@"C:\test\file2.txt") == true) //delete if file2.txt is exist File.Delete(@"C:\test\file2.txt"); File.Copy(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp4\file.txt", @"C:\test\file2.txt"); //copying to the new folder File.Delete(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp4\file.txt"); // deleting file.txt } } } <file_sep>using System; using System.IO; namespace ConsoleApp1 { class Options { public static string Path; public static string movePath; public static string Name; public static void Keys(int index, FileSystemInfo[] files) { Draw(index, files); // show elements pf the folder ConsoleKeyInfo consoleKeyInfo; //new key bool exit = false; // variable for exit from program do { consoleKeyInfo = Console.ReadKey(); // read key switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: if (index == 0) // for upper bound index = files.Length - 1; else index--; Draw(index, files); break; case ConsoleKey.DownArrow: if (index == files.Length - 1) // for lower bound index = 0; else index++; Draw(index, files); break; case ConsoleKey.Enter: if (files[index].GetType() == typeof(DirectoryInfo)) // checking is it folder { if ((files[index] as DirectoryInfo).GetFileSystemInfos().Length == 0) // if folder is empty { Draw(index, (files[index] as DirectoryInfo).GetFileSystemInfos()); movePath = (files[index] as DirectoryInfo).FullName; // remember path to move try { consoleKeyInfo = Console.ReadKey(); if ((consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0)// if is it Alt + F2 { if (Options.Path.GetType() == typeof(DirectoryInfo)) { Directory.Move(Path, movePath + @"\" + Name); //moving the choosing folder movePath = (files[index] as DirectoryInfo).FullName; //remember move path exit = true; } else { File.Move(Path, movePath + @"\" + Name); // moveing the choosing file movePath = (files[index] as DirectoryInfo).FullName; //remember move path exit = true; } } else Options.Keys(index, files); } catch (Exception) //Exception if move mode is not active { Options.Keys(index, files); throw; } } else { files = (files[index] as DirectoryInfo).GetFileSystemInfos(); index = 0; Draw(index, files); } } else { Console.BackgroundColor = ConsoleColor.White; Console.Clear(); Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(File.ReadAllText(files[index].FullName)); // reading text from the file Console.ForegroundColor = ConsoleColor.DarkBlue; Console.WriteLine("\nPress Backspace to go back"); ConsoleKeyInfo consoleKeyInfo2; do { consoleKeyInfo2 = Console.ReadKey(); } while (consoleKeyInfo2.Key != ConsoleKey.Backspace); //waiting backspace to exit Options.Draw(index, files); } break; case ConsoleKey.Backspace: try { if (files[0].GetType() == typeof(DirectoryInfo)) { files = (files[0] as DirectoryInfo).Parent.Parent.GetFileSystemInfos(); //rewrite files to previous folder index = 0; Draw(index, files); } else { files = (files[0] as FileInfo).Directory.Parent.GetFileSystemInfos(); //rewrite files to previous folder index = 0; Draw(index, files); } break; } catch (Exception) //exception for empty folder { Options.Keys(index, files); throw; } case ConsoleKey.H: Advanced_options.StartPage(files, index); break; case ConsoleKey.Escape: exit = true; //exit from the program break; case (ConsoleKey.F2): Console.Clear(); if ((consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0) // if is Alt + F2 { if (files[0].GetType() == typeof(DirectoryInfo)) { Directory.Move(Path, (files[0] as DirectoryInfo).Parent.FullName + @"\" + Name); //moving the folder movePath = (files[0] as DirectoryInfo).Parent.FullName; //remember moving path exit = true; } else { File.Move(Path, (files[0] as DirectoryInfo).Parent.FullName + @"\" + Name); //moving the file movePath = (files[0] as FileInfo).Directory.FullName; //remember moving path exit = true; } } break; } } while (!exit); } public static void Draw(int index, FileSystemInfo[] files) { Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); for (int i = 0; i < files.Length; ++i) { if (i == index) { Console.BackgroundColor = ConsoleColor.Blue; } else { Console.BackgroundColor = ConsoleColor.Black; } if (files[i].GetType() == typeof(DirectoryInfo)) { Console.ForegroundColor = ConsoleColor.Yellow; } else { Console.ForegroundColor = ConsoleColor.White; } Console.WriteLine(files[i].Name); } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Press Enter to open, Press Backspace to go back, Press Ecs to exit"); Console.WriteLine("Press h for advanced options \n"); } } } <file_sep>using System; using System.IO; namespace ConsoleApp3 { class MyProgram { public static void Main(string[] args) { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\"); // open new folder with given path FileSystemInfo[] files = dirInfo.GetFileSystemInfos(); // write folder's elements to array int index = 0; // selected item Options.Keys(index, files); // waiting a key } } class Options { public static void Keys(int index, FileSystemInfo[] files) { Draw(index, files); // show elements pf the folder ConsoleKeyInfo consoleKeyInfo; //new key bool exit = false; // variable for exit from program do { consoleKeyInfo = Console.ReadKey(); // read key switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: if (index == 0) // for upper bound index = files.Length - 1; else index--; Draw(index, files); break; case ConsoleKey.DownArrow: if (index == files.Length - 1) // for lower bound index = 0; else index++; Draw(index, files); break; case ConsoleKey.Enter: if (files[index].GetType() == typeof(DirectoryInfo)) // checking is it folder { if ((files[index] as DirectoryInfo).GetFileSystemInfos().Length == 0) // if folder is empty { Draw(index, (files[index] as DirectoryInfo).GetFileSystemInfos()); } else { files = (files[index] as DirectoryInfo).GetFileSystemInfos(); index = 0; Draw(index, files); } } else { Console.BackgroundColor = ConsoleColor.White; Console.Clear(); Console.ForegroundColor = ConsoleColor.Black; Console.WriteLine(File.ReadAllText(files[index].FullName)); // reading text from the file Console.ForegroundColor = ConsoleColor.DarkBlue; Console.WriteLine("\nPress Backspace to go back"); ConsoleKeyInfo consoleKeyInfo2; do { consoleKeyInfo2 = Console.ReadKey(); } while (consoleKeyInfo2.Key != ConsoleKey.Backspace); //waiting backspace to exit Options.Draw(index, files); } break; case ConsoleKey.Backspace: try { if (files[0].GetType() == typeof(DirectoryInfo)) { files = (files[0] as DirectoryInfo).Parent.Parent.GetFileSystemInfos(); //rewrite files to previous folder index = 0; Draw(index, files); } else { files = (files[0] as FileInfo).Directory.Parent.GetFileSystemInfos(); //rewrite files to previous folder index = 0; Draw(index, files); } break; } catch (Exception) //exception for empty folder { Options.Keys(index, files); throw; } case ConsoleKey.Escape: exit = true; //exit from the program break; } } while (!exit); } public static void Draw(int index, FileSystemInfo[] files) { Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); for (int i = 0; i < files.Length; ++i) { if (i == index) { Console.BackgroundColor = ConsoleColor.Blue; } else { Console.BackgroundColor = ConsoleColor.Black; } if (files[i].GetType() == typeof(DirectoryInfo)) { Console.ForegroundColor = ConsoleColor.Yellow; } else { Console.ForegroundColor = ConsoleColor.White; } Console.WriteLine(files[i].Name); } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Press Enter to open, Press Backspace to go back, Press Ecs to exit"); Console.WriteLine("Press h for advanced options \n"); } } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApp1._2 { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); //reading n List<int> l = new List<int>(); //creating a list string[] s = Console.ReadLine().Split(' '); //reading from the console for (int i = 0; i < s.Length; i++) { if (Prime(int.Parse(s[i])) == true) //if it is prime we add to the list l.Add(int.Parse(s[i])); } Console.WriteLine(l.Count); foreach (int i in l) { Console.Write(i + " "); //writing to the console } Console.WriteLine(); } static bool Prime(int n) { int c = 0; //counter for (int i = 1; i <= n; i++) //checking is it prime { if(n % i == 0) c++; } if (c == 2) return true; else return false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Example6 { class Student { public string name; // variables public string id; public string year; public Student(string name, string id, string year) // constructor { this.name = name; this.id = id; this.year = year; } public void PrintInfo() //show info { Console.WriteLine(name + " " + id + " " + year + "\n"); } } class Program { static void Main(string[] args) { Console.WriteLine("Please, enter the name of the student"); String name = Console.ReadLine(); Console.WriteLine("Please, enter the id of the student"); string id = Console.ReadLine(); Console.WriteLine("Please, enter the year of the student"); string year = Console.ReadLine(); Student s = new Student(name, id, year); Console.WriteLine(); s.PrintInfo(); } } }<file_sep>using System.IO; using System; namespace ConsoleApp3._1 { class Program { static void Main(string[] args) { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\"); // open new folder with given path FileSystemInfo[] files = dirInfo.GetFileSystemInfos(); // write folder's elements to array for (int i = 0; i < ; i++) { } } public static void Draw(int index, FileSystemInfo[] files) { Console.BackgroundColor = ConsoleColor.Black; for (int i = 0; i < files.Length; ++i) { if (i == index) { Console.BackgroundColor = ConsoleColor.Blue; } else { Console.BackgroundColor = ConsoleColor.Black; } if (files[i].GetType() == typeof(DirectoryInfo)) { Console.ForegroundColor = ConsoleColor.Yellow; } else { Console.ForegroundColor = ConsoleColor.White; } Console.WriteLine(files[i].Name); } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1._2 { class Program { static void Main(string[] args) { List<int> l = new List<int>(); // create a list string[] s = File.ReadAllText(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp2\ConsoleApp2\in.txt").Split(' '); // read from txt file for (int i = 0; i < s.Length; i++) // checking for prime and add it to the list { if (Prime(int.Parse(s[i])) == true) l.Add(int.Parse(s[i])); } foreach (int i in l) // show in console prime numbers from the list { Console.Write(i + " "); } Console.WriteLine(); } static bool Prime(int n) { int c = 0; // counter for (int i = 1; i <= n; i++) // checking for prime { if (n % i == 0) c++; } if (c == 2) return true; else return false; } } } <file_sep>using System; using System.IO; namespace ConsoleApp1 { class Advanced_options { public static DirectoryInfo dirInfo = new DirectoryInfo(@"C:\"); public static void StartPage(FileSystemInfo[] files, int index) { Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(files[index].Name); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("\nWhat you want to do? \n"); Console.WriteLine("Press Alt + F1 to rename"); Console.WriteLine("Press Alt + F2 to move"); Console.WriteLine("Press Alt + F3 to delete"); Console.WriteLine("Press Alt + F4 to see the attributies \n"); Console.WriteLine("Press Backspace to go back \n"); ConsoleKeyInfo consoleKeyInfo; do { consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case (ConsoleKey.F1): if((consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0) { Console.Clear(); Console.WriteLine("Enter new name"); if(files[index].GetType() == typeof(DirectoryInfo)) { Directory.Move(files[index].FullName, (files[index] as DirectoryInfo).Parent.FullName + @"\" + Console.ReadLine()); //renaming the folder Console.WriteLine("\nSuccessefully! \n\nPress Backspace to go back \n"); files = (files[index] as DirectoryInfo).Parent.GetFileSystemInfos(); //refresh the directory index = 0; } else { File.Move(files[index].FullName, (files[index] as FileInfo).Directory.FullName + @"\" + Console.ReadLine() + ".txt"); //renaming the file Console.WriteLine("\nSuccessefully! \n\nPress Backspace to go back \n"); files = (files[index] as FileInfo).Directory.GetFileSystemInfos(); //refresh the directory index = 0; } } break; case (ConsoleKey.F2): if ((consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0) { Console.Clear(); if (files[index].GetType() == typeof(DirectoryInfo)) { Options.Path = files[index].FullName; //remeber path of the folder Options.Name = files[index].Name; //remeber name of the folder Console.WriteLine("Now, you are in move mode\nChoose right path and press Alt + F2 to move\n"); Console.ReadKey(); files = dirInfo.GetFileSystemInfos(); //changing directory to C:\ Options.Keys(index, files); Console.WriteLine("\nSuccessefully! \n\nPress Backspace to go back \n"); dirInfo = new DirectoryInfo(Options.movePath); files = dirInfo.GetFileSystemInfos(); //changing directory to moving folder index = 0; } else { Options.Path = files[index].FullName; //remeber path of the file Options.Name = files[index].Name; //remeber name of the file Console.WriteLine("Now, you are in move mode\nChoose right path and press Alt + F2 to move\n"); Console.ReadKey(); files = dirInfo.GetFileSystemInfos(); //changing directory to C:\ Options.Keys(index, files); Console.WriteLine("\nSuccessefully! \n\nPress Backspace to go back \n"); dirInfo = new DirectoryInfo(Options.movePath); files = dirInfo.GetFileSystemInfos(); //changing directory to moving folder index = 0; } } break; case (ConsoleKey.F3): if ((consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0) { Console.Clear(); Console.WriteLine("Press Enter to delete"); consoleKeyInfo = Console.ReadKey(); if (consoleKeyInfo.Key == ConsoleKey.Enter) { if (files[index].GetType() == typeof(DirectoryInfo)) { Options.Path = (files[index] as DirectoryInfo).Parent.FullName; //remember path of the folder dirInfo = new DirectoryInfo(Options.Path); //changing directory to the choosen one Directory.Delete(files[index].FullName, true); // deleting folder files = dirInfo.GetFileSystemInfos(); Options.Keys(index, files); } else { Options.Path = (files[index] as FileInfo).Directory.FullName; //remember path of the folder dirInfo = new DirectoryInfo(Options.Path); //changing directory to the choosen one File.Delete(files[index].FullName); // deleting the file files = dirInfo.GetFileSystemInfos(); Options.Keys(index, files); } } else Options.Keys(index, files); } break; case (ConsoleKey.F4): if ((consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0) { Console.Clear(); if (files[index].GetType() == typeof(DirectoryInfo)) Console.WriteLine($"Name: {files[index].Name}\nFullname: {files[index].FullName}\nCreation time: {files[index].CreationTime}\nExtension: folder\n"); else Console.WriteLine($"Name: {files[index].Name}\nFullname: {files[index].FullName}\nCreation time: {files[index].CreationTime}\nExtension: {files[index].Extension}\n"); } break; } } while (consoleKeyInfo.Key != ConsoleKey.Backspace); Options.Keys(index, files); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { class Program { static void Main(string[] args) { string[] nums = File.ReadAllText(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp2\ConsoleApp2\input.txt").Split(' '); //reading from txt file to array of string int[] mas = new int[nums.Length]; // create array mas int[] mas2 = new int[nums.Length]; // create array mas2 for (int i = 0; i < nums.Length; i++) { mas[i] = int.Parse(nums[i]); // convert from string to our array of integers } int c = 0; // counter for (int i = 0; i < nums.Length; i++) { for (int j = 1; j <= mas[i]; j++)// we try to find deviders of the numbers and if the number is prime we write it to mas2 { if (mas[i] % j == 0) { c++; } } if (c == 2) { mas2[i] = mas[i]; } else mas2[i] = 0; c = 0; } for (int i = 0; i < nums.Length; i++)//we count amount of numbers { if (mas2[i] != 0) c++; } using (FileStream fs = new FileStream(@"C:\Users\Admin\Documents\C#\PP2\Week2\ConsoleApp2\ConsoleApp2\output.txt", FileMode.Create, FileAccess.Write)) { using (StreamWriter wr = new StreamWriter(fs)) { for (int i = 0; i < nums.Length; i++)//show these numbers in the file output.txt { if (mas2[i] != 0) wr.Write($"{mas2[i]} "); } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); //reading integer n Method(n); } static void Method(int n) { string[] s = Console.ReadLine().Split(' '); //reading from the console int[] arr = new int[n * 2]; //creating the array int j = 0; for (int i = 0; i < s.Length; i++) { arr[i + j] = int.Parse(s[i]); //fill the array arr[i + j + 1] = int.Parse(s[i]); j++; } foreach (int i in arr) { Console.Write($"{i} "); //writing to the console } } } }
b8fed93847c1edc79c0942e7e3dfbe7a9eeaff80
[ "C#" ]
12
C#
AkramAlisher/pp2
4619946f9657beaec6b29679268a1033300981f3
85b853e7489ee2d22639318cde1a04e7d24a4961
refs/heads/master
<repo_name>ahmedhassanme/EditGraph<file_sep>/Interface.java package editGraph; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.FlowLayout; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.ArrayList; public class Interface extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; private JTextField textField_2; private JTextField textField_3; private JTextField textField_4; private Graph graph; private String[] seqA; private String[] seqB; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Interface frame = new Interface(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Interface() { setTitle("Sequence Alignment"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 847, 478); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); final JTextPane textPane = new JTextPane(); JScrollPane jsp1 = new JScrollPane(textPane); final JTextPane textPane_1 = new JTextPane(); JScrollPane jsp = new JScrollPane(textPane_1); textField = new JTextField("ERDAWCQPGKWY"); textField.setColumns(10); textField_1 = new JTextField("EAWACQGKL"); textField_1.setColumns(10); JLabel lblSeqa = new JLabel("seqA"); JLabel lblSeqb = new JLabel("seqB"); JButton btnNewButton = new JButton("Generate"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { textPane_1.setText(""); textPane.setText(""); Graph graph = new Graph(Integer.parseInt(textField_3.getText()), Integer.parseInt(textField_2.getText()), Integer.parseInt(textField_4.getText())); String seq1 = textField.getText(); String seq2 = textField_1.getText(); seqA = new String[seq1.length()]; seqB = new String[seq2.length()]; for(int x = 0; x<seqA.length; x=x+1) { seqA[x] = seq1.substring(x, x+1); } for(int y = 0; y<seqB.length; y=y+1) { seqB[y] = seq2.substring(y, y+1); } graph.setSeqs(seqA, seqB); graph.generate(); graph.print(); graph.traceAlignment(); graph.printSeqs(); graph.printAlignments(); int[][] numbers = graph.getNumbers(); ArrayList<String[][]> alignments = graph.getAlignments(); for(int x = 0; x<alignments.size(); x=x+1) { for(int a = 0; a<alignments.get(x).length; a=a+1) { for(int b = 0; b<alignments.get(x)[a].length; b=b+1) { textPane_1.setText(textPane_1.getText() + alignments.get(x)[a][b] + " , "); } textPane_1.setText(textPane_1.getText() + '\n'); } textPane_1.setText(textPane_1.getText() + '\n'); } //print out the matrix //textPane.setText(textPane.getText() + " "); //for(int x = 0; x<seqA.length; x=x+1) //{ //textPane.setText(textPane.getText() + "| "+ seqA[x] +" | "); //} textPane.setText(textPane.getText() + '\n'); for(int x = 0; x<numbers.length; x=x+1) { for(int y=0; y<numbers[x].length; y=y+1) { if(numbers[x][y]<10) { textPane.setText(textPane.getText() + "| " + numbers[x][y] + " | "); } else { textPane.setText(textPane.getText() + "|" + numbers[x][y] + "| "); } } textPane.setText(textPane.getText() + '\n'); } } }); JLabel lblInsCost = new JLabel("Ins Cost"); textField_2 = new JTextField("1"); textField_2.setColumns(10); JLabel lblDelCost = new JLabel("Del Cost"); textField_3 = new JTextField("1"); textField_3.setColumns(10); JLabel lblSubCost = new JLabel("Sub Cost"); textField_4 = new JTextField("2"); textField_4.setColumns(10); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false) .addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(lblInsCost) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblDelCost) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(textField_3, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblSubCost) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(textField_4, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE))) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addComponent(lblSeqb) .addComponent(lblSeqa)) .addGap(18) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false) .addComponent(textField_1) .addComponent(textField, GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE))) .addComponent(jsp, GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jsp1, GroupLayout.PREFERRED_SIZE, 454, GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addComponent(jsp1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE) .addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSeqa)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSeqb)) .addGap(48)) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblInsCost) .addComponent(lblDelCost) .addComponent(textField_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblSubCost) .addComponent(textField_4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(btnNewButton) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jsp, GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))) .addContainerGap()) ); contentPane.setLayout(gl_contentPane); } }
f18bdeb0b7ec8f414f57a2c1f01a2dec9c90227c
[ "Java" ]
1
Java
ahmedhassanme/EditGraph
3eb354fcd5cf72168b411637ff7f47ec4a441efb
00795d77968047a90ebc1825023807216e9fd025
refs/heads/master
<file_sep>package fr.m2i.sqlite_annuaire; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; public class listes extends AppCompatActivity { SQLiteDatabase db; ListView lv1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_listes); //ouverture de la base de donnée DbInit dbInit = new DbInit(this); db = dbInit.getWritableDatabase(); lv1 = findViewById(R.id.listeAnnuaire); ArrayList<String> list = new ArrayList<String>(1); String columns[] = {"id", "name", "tel"}; Cursor cursor = db.query("contacts", columns, "", null, null, null, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); while (cursor.moveToNext()) { list.add(cursor.getString(1)); } } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, list); lv1.setAdapter(adapter); } } <file_sep>package fr.m2i.sqlite_annuaire; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Administrateur on 16/01/2018. */ public class DbInit extends SQLiteOpenHelper { public DbInit(Context ctx, String dbName, SQLiteDatabase.CursorFactory factory, int version) { super(ctx, dbName, null, version); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE contacts (" + " id INTEGER PRIMARY KEY NOT NULL" + ", name TEXT NOT NULL" + ", tel TEXT" + ")"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
d5792895903b6c64a74c77f2a4f90a2c8d06c833
[ "Java" ]
2
Java
DimitriDim/Sqlite_Annuaire
aa846a8dcca557cbb9835d44667eee93fc3791f8
dc71b045f85ee78f3e05eebb2cd8dff8c41280c5
refs/heads/master
<repo_name>mcarlson-hw/Fall2017<file_sep>/SpectralClusterer/main.cpp #include <iostream> #include <mpi.h> using namespace std; #include "tests.h" #include "SpectralClusterer.h"; int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); MPI_Comm world = MPI_COMM_WORLD; int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); test1(world); MPI_Finalize(); return 0; }<file_sep>/ScicompCh9/main.cpp #include <mpi.h> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <mkl.h> using namespace std; // File I/O void read_csv(string filename, vector<double> *A, int* rows, int* cols) { ifstream infile(filename); if (infile.is_open()) { *rows = 0; *cols = 0; string line; string val; cout << "Starting read.\n"; while (getline(infile, line, '\n')) { istringstream iline(line); *cols = 0; while (getline(iline, val, ',')) { (*A).push_back(stod(val)); *cols += 1; } *rows += 1; } } } void write_binary(string filename, string ext, vector<double> *A, int rows, int cols) { string temp = filename + "_size." + ext; string temp2 = filename + "." + ext; FILE *file1 = fopen(temp.c_str(), "wb"); fwrite(&rows, sizeof(int), 1, file1); fwrite(&cols, sizeof(int), 1, file1); fclose(file1); FILE *file2 = fopen(temp2.c_str(), "wb"); fwrite((*A).data(), rows*cols * sizeof(double), 1, file2); fclose(file2); } void read_binary(string filename, string ext, vector<double> *A, int* rows, int* cols) { string temp = filename + "_size." + ext; string temp2 = filename + "." + ext; FILE *file1 = fopen(temp.c_str(), "rb"); fread(rows, sizeof(int), 1, file1); fread(cols, sizeof(int), 1, file1); fclose(file1); FILE *file2 = fopen(temp2.c_str(), "rb"); (*A).resize((*rows)*(*cols)); fread((*A).data(), sizeof(double)*(*rows)*(*cols), 1, file2); fclose(file2); } void print_mat(vector<double> *A, int rows, int cols) { if (rows > 10 && cols > 10) { for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { cout << (*A)[row*cols + col] << " "; } cout << ". . . "; for (int col = cols - 5; col < cols; col++) { cout << (*A)[row*cols + col] << " "; } cout << "\n"; } cout << "\n.\n.\n.\n\n"; for (int row = rows - 5; row < rows; row++) { for (int col = 0; col < 4; col++) { cout << (*A)[row*cols + col] << " "; } cout << ". . . "; for (int col = cols - 5; col < cols; col++) { cout << (*A)[row*cols + col] << " "; } cout << "\n"; } } else { for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { cout << (*A)[row*cols + col] << " "; } cout << "\n"; } } } void prepare_data(string filename, string binary_ext, string text_ext, vector<double> *A, int *rows, int *cols) { ifstream infile(filename + "." + binary_ext); if (infile.good()) { cout << "Reading binary file.\n"; read_binary(filename, binary_ext, A, rows, cols); } else { cout << "Binary file does not exist! Attempting to read CSV and produce binary file.\n"; read_csv(filename + "." + text_ext, A, rows, cols); write_binary(filename, binary_ext, A, *rows, *cols); } } // Data Preperation void center_data(vector<double> *A, int rows, int cols, int S_type, vector<double> *means, vector<double> *s) { // S_type: // 1: 1/n * one_norm // 2: 1/sqrt(n) * two_norm (default) // 3: 1/sqrt(n-1) * two_norm // 4: infinity_norm double oldmean, mean, var, S, x; int imax; for (int row = 0; row < rows; row++) { mean = 0; for (int col = 0; col < cols; col++) { x = (*A)[row*cols + col]; mean = mean + x; } mean = mean / cols; (*means).push_back(mean); for (int col = 0; col < cols; col++) (*A)[row*cols + col] = (*A)[row*cols + col] - mean; switch (S_type) { case 0: S = 1.0; break; case 1: S = 1.0 / cols * cblas_dasum(cols, &(*A)[row*cols], 1); break; case 2: S = 1.0 / sqrt(cols) * cblas_dnrm2(cols, &(*A)[row*cols], 1); break; case 3: S = 1.0 / sqrt(cols - 1) * cblas_dnrm2(cols, &(*A)[row*cols], 1); break; case 4: imax = cblas_idamax(cols, &(*A)[row*cols], 1); S = fabs((*A)[row*cols + imax]); break; default: S = 1.0 / sqrt(cols) * cblas_dnrm2(cols, &(*A)[row*cols], 1); break; } (*s).push_back(S); cblas_dscal(cols, 1.0/S, &(*A)[row*cols], 1); } } int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); vector<double> A; vector<double> lA; vector<double> s, u, vt, superb; int rows = 0; int cols = 0; int info = 0; vector<double> means, S; // Read File if (rank == 0) { double start = MPI_Wtime(); prepare_data("open", "b", "csv", &A, &rows, &cols); // Compute SVD of A: s.resize(max(1, min(rows,cols))); u.resize(rows*rows); vt.resize(cols*cols); superb.resize(min(rows, cols) - 1); info = LAPACKE_dgesvd(CblasRowMajor, 'A', 'A', rows, cols, A.data(), cols, s.data(), u.data(), rows, vt.data(), cols, superb.data()); double end = MPI_Wtime(); cout << "\nInfo = " << info << "\n"; cout << "\nU = \n"; print_mat(&u, rows, rows); cout << "\nSingular Values: "; print_mat(&s, 1, min(rows, cols)); cout << "\n"; cout << "Number of singular values: " << min(rows, cols) << "\n"; cout << "Time Elapsed: " << end - start << "\n\n"; } // Split data among processors /*MPI_Bcast(&rows, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&cols, 1, MPI_INT, 0, MPI_COMM_WORLD); int* NPerP = new int[size]; int* N0 = new int[size](); for (int i = 0; i < size; i++) NPerP[i] = (i < rows % size) ? cols*(rows / size + 1) : (cols*(rows / size)); for (int i = 1; i < size; i++) N0[i] = N0[i - 1] + NPerP[i - 1]; lA.resize(NPerP[rank]); MPI_Scatterv(A.data(), NPerP, N0, MPI_DOUBLE, lA.data(), NPerP[rank], MPI_DOUBLE, 0, MPI_COMM_WORLD);*/ // Center Data MPI_Finalize(); return 0; }<file_sep>/SpectralClusterer/tests.cpp #include "tests.h" #include "SpectralClusterer.h" void test1(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); std::string filename = "inf-USAir97.mtx"; SClusterer sc(1, filename, comm); if (rank == 0) std::cout << "Process " << rank << ": Extension of " << filename << " is " << sc.getExt() << "\n"; } void test2(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test3(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test4(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test5(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test6(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test7(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test8(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); } void test9(MPI_Comm comm) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); }<file_sep>/SpectralClusterer/SpectralClusterer.h #pragma once #include <iostream> #include <mpi.h> #include <string> #include <vector> #include <fstream> #include <tuple> #include <algorithm> class SClusterer { class Vertex; class Partition; class Subpartition; std::string filename, ext; std::vector<std::tuple<int, int, double>> V; int K, L, N, nonzeros; int rank, size; MPI_Comm comm; std::vector<Vertex> W; std::vector<int> lid; Partition *rp; Partition *cp; void parse(); void prepare_local_vertices(); void init_partition(); void compute_spectrum(); void applyW(Subpartition, std::vector<double>&, std::vector<double>&); public: SClusterer(int, std::string, MPI_Comm); std::string getExt(); void printW(); }; class SClusterer::Vertex { int id, deg, vol; std::vector<int> e; std::vector<double> w, u; public: Vertex(int, std::vector<int>, std::vector<double>); int get_deg(); }; class SClusterer::Partition { int K; double lQ, Q; std::vector<Subpartition> P; MPI_Comm comm; public: Partition(int, std::vector<std::vector<int>>, MPI_Comm); }; class SClusterer::Subpartition { int L; double lvol, vol, sQ, lsQ; std::vector<int> v; MPI_Comm comm; int rank, size; public: Subpartition(std::vector<int>, MPI_Comm); };<file_sep>/SpectralClusterer/SpectralClusterer.cpp #include "SpectralClusterer.h" SClusterer::SClusterer(int _K, std::string __filename, MPI_Comm _comm) { comm = _comm; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); filename = __filename; K = _K; parse(); if (rank == 0) { std::cout << "Weight Matrix:\n"; printW(); std::cout << "\n"; } prepare_local_vertices(); //init_partition(); } SClusterer::Vertex::Vertex(int _id, std::vector<int> _e, std::vector<double> _w) { id = _id; vol = 0; for (int d : _e) e.push_back(d); for (double x : _w) { w.push_back(x); vol += x; } deg = e.size(); } SClusterer::Partition::Partition(int _K, std::vector<std::vector<int>> Vk, MPI_Comm _comm) { K = 1; lQ = 0.0; Q = 0.0; comm = _comm; P.push_back(Subpartition(Vk[0], _comm)); } SClusterer::Subpartition::Subpartition(std::vector<int> _v, MPI_Comm _comm) { lvol = 0.0; lsQ = 0.0; // On v, push back elements of _v that are in the local set of vertices // Compute local volume; Every time an element of _v is added, lvol += _v.weight // Gather local volumes at root, sum them, broadcast sum as global volume // Compute local sQ, gather at root, broadcast sum as global sQ } bool indexcompare(const std::tuple<int, int, double> &lhs, const std::tuple<int, int, double> &rhs) { if (std::get<0>(lhs) != std::get<0>(rhs)) return std::get<0>(lhs) < std::get<0>(rhs); else return std::get<1>(lhs) < std::get<1>(rhs); } void SClusterer::parse() { if (rank != 0) return; size_t ind = filename.find_last_of('.'); ext = filename.substr(ind+1); std::ifstream inputfile(filename); std::string line; int a, b, c; double x; // Read first line: // rows cols nonzeros inputfile >> a >> b >> c; N = a; N = b; nonzeros = c; // Read next 'nonezeros' liens // i j value for (int line = 0; line < nonzeros; line++) { inputfile >> a >> b >> x; V.push_back(std::make_tuple(a, b, x)); // matrix is symmetric, A(i,j) = A(j,i) if (a != b) V.push_back(std::make_tuple(b, a, x)); } std::sort(V.begin(), V.end(), indexcompare); // Prepare CSR arrays ia, ja, a /*int globalcount = 0; int localcount = 0; for (int row = 1; row <= M; row++) { localcount = 0; while (globalcount + localcount < nonzeros && std::get<0>(W[globalcount + localcount]) == row) { jw.push_back(std::get<1>(W[globalcount + localcount]) - 1); w.push_back(std::get<2>(W[globalcount + localcount])); localcount += 1; } iw.push_back(globalcount); globalcount += localcount; }*/ } void SClusterer::prepare_local_vertices() { std::vector<int> I, J, lI, lJ; std::vector<double> w, lw; std::vector<int> VertsPerP, NZPerP; std::vector<int> Verts0, NZ0; int lnz; double curr_w; if (rank == 0) { for (int i = 0; i < N; i++) { I.push_back(std::get<0>(V[i]) - 1); J.push_back(std::get<1>(V[i]) - 1); w.push_back(std::get<2>(V[i])); } for (int i = 0; i < size; i++) VertsPerP.push_back((i < N % size) ? N / size + 1 : N / size); Verts0.push_back(0); for (int i = 1; i < size; i++) Verts0.push_back(Verts0[i - 1] - VertsPerP[i - 1]); std::cout << "Size = " << size << ", VertsPerP[0] = " << VertsPerP[0] << ", Verts0[0] = " << Verts0[0] << "\n"; for (int i = 0; i < size; i++) { curr_w = 0.0; for (int j = Verts0[i]; j < Verts0[i] + VertsPerP[i]; j++) curr_w += W[j].get_deg(); NZPerP.push_back(curr_w); } /*NZ0.push_back(0); for (int i = 1; i < size; i++) NZ0.push_back(NZ0[i - 1] - NZPerP[i - 1]);*/ } //lI.resize(lnz); //lJ.resize(lnz); //lw.resize(lnz); //MPI_Scatter(NZPerP.data(), 1, MPI_INT, &lnz, 1, MPI_INT, 0, comm); /*MPI_Scatterv(I.data(), NZPerP.data(), NZ0.data(), MPI_INT, lI.data(), lnz, MPI_INT, 0, comm); MPI_Scatterv(J.data(), NZPerP.data(), NZ0.data(), MPI_INT, lJ.data(), lnz, MPI_INT, 0, comm); MPI_Scatterv(w.data(), NZPerP.data(), NZ0.data(), MPI_INT, lw.data(), lnz, MPI_INT, 0, comm);*/ /*int count = 0; int vcount = -1; std::vector<int> e; std::vector<double> wp; for (int i = 0; i < lnz; i++) { if (I[i] != vcount) { if (count != 0) lid.push_back(count); count = 0; vcount = I[i]; W.push_back(Vertex(vcount, e, wp)); e = std::vector<int>(); wp = std::vector<double>(); e.push_back(lJ[i]); wp.push_back(lw[i]); count += 1; } else { e.push_back(lJ[i]); wp.push_back(lw[i]); count += 1; } } lid.push_back(count); W.push_back(Vertex(vcount, e, wp));*/ } void SClusterer::init_partition() { std::vector<std::vector<int>> v; std::vector<int> v0; for (int i = 0; i < N; i++) v0.push_back(i); v.push_back(v0); rp = &Partition(1, v, comm); } void SClusterer::compute_spectrum() { } void SClusterer::applyW(Subpartition p, std::vector<double> &x, std::vector<double> &y) { } // Misc. Utilities std::string SClusterer::getExt() { return ext; } void SClusterer::printW() { if (nonzeros < 20) for (int i = 0; i < nonzeros; i++) std::cout << "Entry " << i << ": " << std::get<0>(V[i]) << ", " << std::get<1>(V[i]) << ", " << std::get<2>(V[i]) << std::endl; else { for (int i = 0; i < 10; i++) std::cout << "Entry " << i << ": " << std::get<0>(V[i]) << ", " << std::get<1>(V[i]) << ", " << std::get<2>(V[i]) << std::endl; std::cout << ".\n"; std::cout << ".\n"; std::cout << ".\n"; for (int i = nonzeros-10; i < nonzeros; i++) std::cout << "Entry " << i << ": " << std::get<0>(V[i]) << ", " << std::get<1>(V[i]) << ", " << std::get<2>(V[i]) << std::endl; } } int SClusterer::Vertex::get_deg() { return deg; } <file_sep>/SpectralClusterer/tests.h #pragma once #include <mpi.h> #include <iostream> #include <string> void test1(MPI_Comm); void test2(MPI_Comm); void test3(MPI_Comm); void test4(MPI_Comm); void test5(MPI_Comm); void test6(MPI_Comm); void test7(MPI_Comm); void test8(MPI_Comm); void test9(MPI_Comm);
8cbef6233d84fd1a0b6ead04274a347647c0aa5a
[ "C++" ]
6
C++
mcarlson-hw/Fall2017
a1b658e28ced4ce19da4bd0f24b3db46d1f376bf
d203756f33c6df4d64a7c20c68fc6528186d8fd0
refs/heads/master
<file_sep>// // TKAArrayTest.h // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAArrayTest__ #define __TKASecondWeek__TKAArrayTest__ #include <stdio.h> #pragma mark - #pragma mark Privat Declarations #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations #pragma mark - #pragma mark Public Implementations void TKAArrayTestMain(); #endif /* defined(__TKASecondWeek__TKAArrayTest__) */ <file_sep>// // TKAArrayStructTest.c // TKASecondWeek // // Created by Taisiya on 28.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAArrayStructTest.h" #pragma mark - #pragma mark Privat Declarations #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations #pragma mark - #pragma mark Public Implementations void TKAArrayStructTestMain() { } <file_sep>// // TKAStringStruct.c // TKASecondWeek // // Created by Taisiya on 21.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAStringStruct.h" #pragma mark - #pragma mark Privat Declarations static void TKAStringStructDealloc(TKAStringStruct *string); #pragma mark - #pragma mark Privat Implementations void TKAStringStructDealloc(TKAStringStruct *string) { if (NULL != string->_data) { free(string->_data); } free(string); } #pragma mark - #pragma mark Public Implementations TKAStringStruct *TKAStringStructCreate() { TKAStringStruct *string = calloc(1, sizeof(*string)); string->_referenceCount = 1; return string; } void TKAStringStructRetain(TKAStringStruct *string) { string->_referenceCount++; } void TKAStringStructRelease(TKAStringStruct *string) { string->_referenceCount--; if (0 == string->_referenceCount) { TKAStringStructDealloc(string); } } void TKAStringStructSetLength(TKAStringStruct *string, uint64_t length) { if (string->_length != length) { string->_data = realloc(string->_data, length * sizeof(*string->_data)); if (string->_length < length) { memset(string->_data + string->_length, 0, length - string->_length); } string->_length = length; } } uint64_t TKAStringStructGetLength(TKAStringStruct *string) { return string->_length; } void TKAStringStructCopyData(TKAStringStruct *string, char *data, uint64_t length) { TKAStringStructSetLength(string, length); memmove(string->_data, data, length); } char *TKAStringStructGetData(TKAStringStruct *string) { return string->_data; } void TKAStringStructOutput(TKAStringStruct *string) { printf("%s", TKAStringStructGetData(string)); } <file_sep>// // TKAObject.h // TKASecondWeek // // Created by Taisiya on 19.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAObgect__ #define __TKASecondWeek__TKAObgect__ #include <stdio.h> #include <stdlib.h> typedef void(*TKADeallocateCallback)(void *); struct TKAObject { uint64_t _referenceCount; TKADeallocateCallback _deallocateCallback; }; typedef struct TKAObject TKAObject; extern void *__TKAObjectCreate(size_t objectSize, TKADeallocateCallback deallocateCallback); #define TKAObjectCreate(type)\ __TKAObjectCreate(sizeof(type), (TKADeallocateCallback)__##type##Deallocate) extern void *TKAObjectRetain(void *object); extern void TKAObjectRelease(void *object); extern uint64_t TKAObjectGetReferenceCount(void *object); extern void __TKAObjectDeallocate(void *object); #endif /* defined(__TKASecondWeek__TKAObject__) */ <file_sep>// // TKAObgect.c // TKASecondWeek // // Created by Taisiya on 19.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAObject.h" #pragma mark - #pragma mark Public Implementations void *__TKAObjectCreate(size_t objectSize, TKADeallocateCallback deallocateCallback) { TKAObject *object = calloc(1, objectSize); object->_referenceCount = 1; object->_deallocateCallback = deallocateCallback; return object; } void *TKAObjectRetain(void *object) { if (NULL != object) { ((TKAObject *)object)->_referenceCount++; } return object; } void TKAObjectRelease(void *voidObject) { if (NULL == voidObject) { return; } TKAObject *object = (TKAObject *)voidObject; object->_referenceCount--; if (0 == object->_referenceCount) { object->_deallocateCallback(object); } } uint64_t TKAObjectGetReferenceCount(void *object) { if (NULL == object) { return 0; } return ((TKAObject *)object)->_referenceCount; } void __TKAObjectDeallocate(void *object) { free(object); } <file_sep>// // TKAStringTest.h // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAStringTest__ #define __TKASecondWeek__TKAStringTest__ #include <stdio.h> #include "TKAString.h" extern void TKAStringTestMain(); extern TKAString *TKAStringCreateTest(); #endif /* defined(__TKASecondWeek__TKAStringTest__) */ <file_sep>// // TKAHuman.h // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAHuman__ #define __TKASecondWeek__TKAHuman__ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include "TKAString.h" #include "TKAArray.h" typedef struct TKAHuman TKAHuman; typedef struct TKAArray TKAArray; typedef enum { TKAMale, TKAFemale } TKAGender; struct TKAHuman { TKAObject _object; TKAString *_name; TKAHuman *_partner; TKAHuman *_father; TKAHuman *_mother; TKAArray *_children; uint8_t _age; TKAGender _gender; uint8_t _childCount; }; typedef struct TKAHuman TKAHuman; extern TKAHuman *TKAHumanCreate(TKAString *name, uint8_t age, TKAGender gender); extern void TKAHumanSetName(TKAHuman *human, TKAString *name); extern void TKAHumanSetAge(TKAHuman *human, uint8_t age); extern void TKAHumanSetGender(TKAHuman *human, TKAGender gender); extern TKAString *TKAHumanGetName(TKAHuman *human); extern uint8_t TKAHumanGetAge(TKAHuman *human); extern TKAGender TKAHumanGetGender(TKAHuman *human); extern uint8_t TKAHumanGetChildCount(TKAHuman *human); extern void TKAHumanSetChildCount(TKAHuman *human, uint8_t count); extern TKAHuman *TKAHumanGetPartner(TKAHuman *human); extern void TKAHumanSetPartner(TKAHuman *human1, TKAHuman *human2); extern TKAHuman *TKAHumanGetFather(TKAHuman *human); extern void TKAHumanSetFather(TKAHuman *human1, TKAHuman *human2); extern TKAHuman *TKAHumanGetMother(TKAHuman *human); extern void TKAHumanSetMother(TKAHuman *human1, TKAHuman *human2); extern TKAArray *TKAHumanGetChildren(TKAHuman *human); extern void TKAHumanSetChildren(TKAHuman *human, TKAArray *children); extern TKAHuman *TKAHumanBorn(TKAHuman *father, TKAHuman *mother, TKAGender gender); extern void TKAHumanAddChild(TKAHuman *parent, TKAHuman *child); extern void TKAHumanMarry(TKAHuman *humanMale, TKAHuman *humanFemale); extern void TKAHumanDivorcePartner(TKAHuman *human); extern void TKAHumanDivorce(TKAHuman *partner1, TKAHuman *partner2); extern void TKAHumanRemoveChild(TKAHuman *parent, TKAHuman *child); extern void TKAHumanRemoveAllChildren(TKAHuman *parent); extern void __TKAHumanDeallocate(TKAHuman *human); #endif /* defined(__TKASecondWeek__TKAHuman__) */ <file_sep>// // main.c // TKASecondWeek // // Created by Taisiya on 17.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include <stdio.h> //#include "TKAHumanStructTest.h" //#include "TKAStringStructTest.h" //#include "TKAArrayStructTest.h" #include "TKAHumanTest.h" #include "TKAStringTest.h" #include "TKAArrayTest.h" int main(int argc, const char * argv[]) { // insert code here... // TKAHumanStructTestMain(); // TKAStringStructTestMain(); // TKAArrayStructTestMain(); TKAHumanTestMain(); // TKAStringTestMain(); // TKAArrayTestMain(); printf("Hello, World!\n"); return 0; } <file_sep># TestHomeWork study C <file_sep>// // TKAStringStructTest.c // TKASecondWeek // // Created by Taisiya on 28.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAStringStructTest.h" #pragma mark - #pragma mark Privat Declarations static void TKAStringStructTest(); #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations void TKAStringStructTest() { TKAStringStruct *stringOne = TKAStringStructCreateTest("testone"); TKAStringStructOutput(stringOne); printf (" %llu ", TKAStringStructGetLength(stringOne)); printf("\n"); TKAStringStructCopyData(stringOne, "testsecond", strlen("testsecond")); TKAStringStructOutput(stringOne); printf (" %llu ", TKAStringStructGetLength(stringOne)); printf("\n"); TKAStringStructCopyData(stringOne, "", strlen("")); TKAStringStructOutput(stringOne); printf (" %llu ", TKAStringStructGetLength(stringOne)); printf("\n"); TKAStringStructCopyData(stringOne, "z", strlen("z")); TKAStringStructOutput(stringOne); printf (" %llu ", TKAStringStructGetLength(stringOne)); printf("\n"); TKAStringStructKillTest(stringOne); } #pragma mark - #pragma mark Public Implementations TKAStringStruct *TKAStringStructCreateTest(char *string) { TKAStringStruct *stringTest = TKAStringStructCreate(); TKAStringStructCopyData(stringTest, string, strlen(string)); return stringTest; } void TKAStringStructKillTest(TKAStringStruct *stringTest) { TKAStringStructRelease(stringTest); } void TKAStringStructTestMain() { TKAStringStructTest(); }<file_sep>// // TKAHuman.c // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAHuman.h" #include "TKAArray.h" #pragma mark - #pragma mark Private Declarations #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations #pragma mark - #pragma mark Public Implementations void __TKAHumanDeallocate(TKAHuman *human) { TKAHumanSetName(human, NULL); TKAHumanSetChildren(human, NULL); TKAHumanSetPartner(human, NULL); TKAHumanSetMother(human, NULL); TKAHumanSetFather(human, NULL); __TKAObjectDeallocate(human); } //TKAHuman *TKAHumanCreate(TKAString *name, uint8_t age, TKAGender gender) { // TKAHuman *human = TKAObjectCreate(TKAHuman); // // TKAHumanSetName(human, name); // TKAHumanSetAge(human, age); // TKAHumanSetGender(human, gender); // // TKAArray *arrayChild = TKAObjectCreate(TKAArray); // TKAHumanSetChildren(human, arrayChild); // TKAObjectRelease(arrayChild); // // return human; //} countChildren { TKAHuman *human = TKAObjectCreate(TKAHuman); TKAHumanSetAge(human, age); TKAHumanSetGender(human, gender); TKAHumanSetChildCount(human, 0); TKAArray *arrayChild = TKAObjectCreate(TKAArray); TKAHumanSetChildren(human, arrayChild); TKAObjectRelease(arrayChild); return human; } void TKAHumanReName(TKAHuman *human, char *name) { if (NULL != human && NULL != name) { TKAString *newName = TKAObjectCreate(TKAString); TKAStringSetData(newName, name); TKAHumanSetName(human, newName); TKAObjectRelease(newName); } } void TKAHumanSetName(TKAHuman *human, TKAString *name) { if (human->_name != name) { if (NULL != human->_name) { TKAObjectRelease(human->_name); } human->_name = name; if (NULL != human->_name) { TKAObjectRetain(name); } } } TKAString *TKAHumanGetName(TKAHuman *human) { return human->_name; } void TKAHumanSetAge(TKAHuman *human, uint8_t age) { human->_age = age; } uint8_t TKAHumanGetAge(TKAHuman *human) { return human->_age; } void TKAHumanSetGender(TKAHuman *human, TKAGender gender) { human->_gender = gender; } TKAGender TKAHumanGetGender(TKAHuman *human) { return human->_gender; } void TKAHumanSetChildCount(TKAHuman *human, uint8_t count) { human->_childCount = count; } uint8_t TKAHumanGetChildCount(TKAHuman *human) { return human->_childCount; } TKAArray *TKAHumanGetChildren(TKAHuman *human) { return human->_children; } void TKAHumanSetChildren(TKAHuman *parent, TKAArray *children) { if (parent->_children != children) { if (NULL != parent->_children) { TKAObjectRelease(parent->_children); } parent->_children = children; if (NULL != parent->_children) { TKAObjectRetain(children); } } } TKAHuman *TKAHumanGetPartner(TKAHuman *human) { return human->_partner; } void TKAHumanSetPartner(TKAHuman *partner1, TKAHuman *partner2) { if (partner1->_partner != partner2) { if (NULL != partner1->_partner) { TKAObjectRelease(partner1->_partner); } partner1->_partner = partner2; if (NULL != partner1->_partner) { TKAObjectRetain(partner2); } } } TKAHuman *TKAHumanGetFather(TKAHuman *human) { return human->_father; } void TKAHumanSetFather(TKAHuman *child, TKAHuman *parent) { if (child->_father != parent) { if (NULL != child->_father) { TKAObjectRelease(child->_father); } child->_father = parent; if (NULL != child->_father) { TKAObjectRetain(parent); } } } TKAHuman *TKAHumanGetMother(TKAHuman *human) { return human->_mother; } void TKAHumanSetMother(TKAHuman *child, TKAHuman *parent) { if (child->_mother != parent) { if (NULL != child->_mother) { TKAObjectRelease(child->_mother); } child->_mother = parent; if (NULL != child->_mother) { TKAObjectRetain(parent); } } } void TKAHumanDivorcePartner(TKAHuman *human) { if (NULL != TKAHumanGetPartner(human) && human != TKAHumanGetPartner(human)) { if (TKAHumanGetPartner(TKAHumanGetPartner(human)) == human) { TKAHumanDivorce(human, TKAHumanGetPartner(human)); } else { TKAHumanSetPartner(human, NULL); } } } void TKAHumanDivorce(TKAHuman *partner1, TKAHuman *partner2) { if (partner1 != partner2 && NULL != partner1 && NULL != partner2) { if (partner1 == TKAHumanGetPartner(partner2) && partner2 == TKAHumanGetPartner(partner1)) { TKAHumanSetPartner(partner1, NULL); TKAHumanSetPartner(partner2, NULL); } } } void TKAHumanMarry(TKAHuman *partner1, TKAHuman *partner2) { if (partner1 != partner2 && NULL != partner1 && NULL != partner2) { if (NULL != TKAHumanGetPartner(partner1) && partner2 != TKAHumanGetPartner(partner1)) { TKAHumanDivorcePartner(partner1); } if (NULL != TKAHumanGetPartner(partner2) && partner1 != TKAHumanGetPartner(partner2)) { TKAHumanDivorcePartner(partner2); } TKAHumanSetPartner(partner1, partner2); TKAHumanSetPartner(partner2, partner1); } } void TKAHumanAddChild(TKAHuman *parent, TKAHuman *child) { if (child != parent) { if (NULL != child && NULL != parent) { if (NULL == TKAHumanGetChildren(parent)) { TKAArray *arrayChild = TKAObjectCreate(TKAArray); TKAHumanSetChildren(parent, arrayChild); TKAObjectRelease(arrayChild); } if (NULL != TKAHumanGetChildren(parent)) { TKAArrayAddChild(TKAHumanGetChildren(parent), child); if (TKAMale == TKAHumanGetGender(parent)) { TKAHumanSetFather(child, parent); } // or else if (TKAFemale == TKAHumanGetGender(parent)) { TKAHumanSetMother(child, parent); } } //MAKE WITH BOOL RESAULT parent->_childCount++; } } } TKAHuman *TKAHumanBorn(TKAHuman *father, TKAHuman *mother, TKAGender gender) { TKAHuman *newBorn = TKAObjectCreate(TKAHuman); TKAHumanSetAge(newBorn, 0); TKAHumanSetGender(newBorn, gender); TKAHumanSetChildCount(newBorn, 0); if (father != mother) { if (NULL != father) { TKAHumanAddChild(father, newBorn); } if (NULL != mother) { TKAHumanAddChild(mother, newBorn); } } TKAObjectRelease(newBorn); return newBorn; } void TKAHumanRemoveChild(TKAHuman *parent, TKAHuman *child) { if (child != parent && NULL != parent) { if (NULL != child) { TKAArrayRemoveChild(TKAHumanGetChildren(parent), child); if (TKAMale == TKAHumanGetGender(parent)) { TKAHumanSetFather(child, NULL); } // or else if (TKAFemale == TKAHumanGetGender(parent)) { TKAHumanSetMother(child, NULL); } //MAKE WITH BOOL RESAULT parent->_childCount--; } } } void TKAHumanRemoveAllChildren(TKAHuman *human) { if (NULL != human && NULL != TKAHumanGetChildren(human)) { TKAArrayRemoveAllChildren(TKAHumanGetChildren(human)); TKAHumanSetChildren(human, NULL); human->_childCount = 0; } } <file_sep>// // TKAStringStruct.h // TKASecondWeek // // Created by Taisiya on 21.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAStringStruct__ #define __TKASecondWeek__TKAStringStruct__ #include <stdio.h> #include <stdlib.h> #include <string.h> struct TKAStringStruct { uint64_t _referenceCount; char *_data; uint64_t _length; }; typedef struct TKAStringStruct TKAStringStruct; extern TKAStringStruct *TKAStringStructCreate(); extern void TKAStringStructRetain(TKAStringStruct *string); extern void TKAStringStructRelease(TKAStringStruct *string); extern void TKAStringStructSetLength(TKAStringStruct *string, uint64_t length); extern uint64_t TKAStringStructGetLength(TKAStringStruct *string); extern char *TKAStringStructGetData(TKAStringStruct *string); extern void TKAStringStructCopyData(TKAStringStruct *string, char *data, uint64_t length); extern void TKAStringStructOutput(TKAStringStruct *string); #endif /* defined(__TKASecondWeek__TKAStringStruct__) */ <file_sep>// // TKAArray.h // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAArray__ #define __TKASecondWeek__TKAArray__ #include <stdio.h> #include <stdlib.h> #include "TKAHuman.h" #include "TKAObject.h" typedef struct TKAHuman TKAHuman; struct TKAArray { TKAObject _object; uint16_t _length; TKAHuman **_child; }; typedef struct TKAArray TKAArray; extern void TKAArraySetLength(TKAArray *array, uint16_t length); extern uint16_t TKAArrayGetLength(TKAArray *array); extern void TKAArrayAddChild(TKAArray *array, TKAHuman *child); extern void *TKAArrayGetChild(TKAArray *array); extern TKAHuman *TKAArrayGetChildIndex(TKAArray *array, uint16_t index); extern void TKAArrayAddChildIndex(TKAArray *array, TKAHuman *data, uint16_t index); extern void TKAArrayRemoveChildIndex(TKAArray *array, uint16_t index); extern void TKAArrayRemoveChild(TKAArray *array, TKAHuman *child); extern void TKAArrayOutput(TKAArray *array); extern void TKAArrayRemoveAllChildren(TKAArray *array); extern void __TKAArrayDeallocate(TKAArray *array); #endif /* defined(__TKASecondWeek__TKAArray__) */ <file_sep>// // TKAString.h // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAString__ #define __TKASecondWeek__TKAString__ #include "TKAObject.h" #include <stdio.h> #include <stdlib.h> #include <string.h> struct TKAString { TKAObject _object; char *_data; uint64_t _length; }; typedef struct TKAString TKAString; extern void TKAStringSetLength(TKAString *string, uint64_t length); extern uint64_t TKAStringGetLength(TKAString *string); extern char *TKAStringGetData(TKAString *string); extern void TKAStringSetData(TKAString *string, char *data); extern void TKAStringCopyData(TKAString *string, char *data); extern void TKAStringOutput(TKAString *string); extern void __TKAStringDeallocate(TKAString *string); #endif /* defined(__TKASecondWeek__TKAString__) */ <file_sep>// // TKAHumanTest.c // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAHumanTest.h" #pragma mark - #pragma mark Private Declarations static void TKAHumanTest(); static void TKAHumanOutput(TKAHuman *human); #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations void TKAHumanOutput(TKAHuman *human) { TKAStringOutput(TKAHumanGetName(human)); printf(" "); printf("age = %d, ",TKAHumanGetAge(human)); printf("gender = %d, ", TKAHumanGetGender(human)); printf("count children = %d, ", TKAHumanGetChildCount(human)); if (NULL != TKAHumanGetPartner(human)) { printf("partner = "); TKAStringOutput(TKAHumanGetName(TKAHumanGetPartner(human))); printf(", "); } if (NULL != TKAHumanGetFather(human)) { printf("father = "); TKAStringOutput(TKAHumanGetName(TKAHumanGetFather(human))); printf(", "); } if (NULL != TKAHumanGetMother(human)) { printf("motner = "); TKAStringOutput(TKAHumanGetName(TKAHumanGetMother(human))); printf(", "); } if (NULL != TKAHumanGetChildren(human)) { printf("children: "); TKAArrayOutput(TKAHumanGetChildren(human)); } printf(" \n"); } TKAHuman *TKAHumanCreateTest(TKAString *name, uint8_t age, TKAGender gender) { TKAHuman *human = TKAObjectCreate(TKAHuman); TKAHumanSetName(human, name); TKAHumanSetAge(human, age); TKAHumanSetGender(human, gender); return human; } void TKAHumanTest() { TKAString *stringGod = TKAStringCreateTest("God"); TKAString *stringAdam = TKAStringCreateTest("Adam"); TKAString *stringEve = TKAStringCreateTest("Eve"); TKAString *stringSon1 = TKAStringCreateTest("Son1"); TKAString *stringSon2 = TKAStringCreateTest("Son2"); TKAHuman *god = TKAHumanCreateTest(stringGod, 100, TKAMale); TKAHuman *adam = TKAHumanCreateTest(stringAdam, 30, TKAMale); TKAHuman *eve = TKAHumanCreateTest(stringEve, 25, TKAFemale); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); printf(" \n"); TKAHumanMarry(adam, eve); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); printf(" \n"); TKAHumanDivorcePartner(eve); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); printf(" \n"); TKAHumanMarry(god, eve); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); printf(" \n"); // TKAHumanDivorce(adam, eve); // // TKAHumanOutput(god); // TKAHumanOutput(adam); // TKAHumanOutput(eve); // printf(" \n"); TKAHumanDivorce(god, eve); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); printf(" \n"); TKAHuman *son1 = TKAHumanBorn(adam, eve, TKAMale); TKAHumanSetName(son1, stringSon1); TKAHumanOutput(son1); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); printf(" \n"); TKAHuman *son2 = TKAHumanBorn(god, eve, TKAMale); TKAHumanSetName(son2, stringSon2); TKAHumanOutput(son1); TKAHumanOutput(son2); TKAHumanOutput(god); TKAHumanOutput(adam); TKAHumanOutput(eve); TKAObjectRelease(son1); TKAObjectRelease(son2); TKAObjectRelease(god); TKAObjectRelease(adam); TKAObjectRelease(eve); TKAObjectRelease(stringSon1); TKAObjectRelease(stringSon2); TKAObjectRelease(stringGod); TKAObjectRelease(stringAdam); TKAObjectRelease(stringEve); } #pragma mark - #pragma mark Public Implementations void TKAHumanTestMain(){ TKAHumanTest(); } <file_sep>// // TKAArrayStructTest.h // TKASecondWeek // // Created by Taisiya on 28.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAArrayStructTest__ #define __TKASecondWeek__TKAArrayStructTest__ #include <stdio.h> #include "TKAArrayStruct.h" #include "TKAHumanStruct.h" extern void TKAArrayStructTestMain(); #endif /* defined(__TKASecondWeek__TKAArrayStructTest__) */ <file_sep>// // TKAHumanTest.h // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAHumanTest__ #define __TKASecondWeek__TKAHumanTest__ #include <stdio.h> #include <string.h> #include "TKAHuman.h" #include "TKAArray.h" #include "TKAStringTest.h" extern void TKAHumanTestMain(); #endif /* defined(__TKASecondWeek__TKAHumanTest__) */ //TKAHuman // after being created 4 objects // objects reference count of Human should be 4 // objects reference count of Array should be 4 // after being created 4 TKAString objects with data not NULL // objects reference count of String should be 4 // objects reference count of Human should be 4 // objects reference count of Array should be 4 // after SET name // objects reference count of String should be 8 // objects reference count of Human should be 4 // objects reference count of Array should be 4 // after ObjectRelease TKASTRing // objects reference count of String should be 4 // objects reference count of Human should be 4 // objects reference count of Array should be 4 // after ObjectRelease TKAHuman // objects reference count of String should be 0 // objects reference count of Human should be 0 // objects reference count of Array should be 0 // // // //TKAHuman // after being created 4 objects // objects reference count of Human should be 4 // objects reference count of Array should be 4 // born child // // // //add 1 child // //remove 1 child // //add 3 children // //remove All children <file_sep>// // TKAHumanStructTest.c // TKASecondWeek // // Created by Taisiya on 17.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAHumanStructTest.h" #pragma mark - #pragma mark Private Declarations static void TKAHumanStructKillTest(TKAHumanStruct *human); static void TKAHumanStructTest(); static void TKAHumanStructOutput(TKAHumanStruct *human); #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations void TKAHumanStructOutput(TKAHumanStruct *human) { TKAStringStructOutput(TKAHumanStructGetName(human)); printf(" "); printf("age = %d, ",TKAHumanStructGetAge(human)); printf("gender = %d, ", TKAHumanStructGetGender(human)); printf("count children = %d, ", TKAHumanStructGetCountChildren(human)); if (NULL != TKAHumanStructGetPartner(human)) { printf("partner = "); TKAStringStructOutput(TKAHumanStructGetName(TKAHumanStructGetPartner(human))); printf(", "); } if (NULL != TKAHumanStructGetFather(human)) { printf("father = "); TKAStringStructOutput(TKAHumanStructGetName(TKAHumanStructGetFather(human))); printf(", "); } if (NULL != TKAHumanStructGetMother(human)) { printf("motner = "); TKAStringStructOutput(TKAHumanStructGetName(TKAHumanStructGetMother(human))); printf(", "); } if (NULL != TKAHumanStructGetChildren(human)) { printf("children: "); TKAArrayStructOutput(TKAHumanStructGetChildren(human)); } printf(" \n"); } TKAHumanStruct *TKAHumanStructCreateTest(TKAStringStruct *name, uint8_t age, TKAGenderStruct gender) { TKAHumanStruct *human = TKAHumanStructCreate(); TKAHumanStructSetName(human, name); TKAHumanStructSetAge(human, age); TKAHumanStructSetGender(human, gender); return human; } void TKAHumanStructKillTest(TKAHumanStruct *human) { TKAHumanStructRelease(human); } void TKAHumanStructTest() { TKAStringStruct *stringGod = TKAStringStructCreateTest("God"); TKAStringStruct *stringAdam = TKAStringStructCreateTest("Adam"); TKAStringStruct *stringEve = TKAStringStructCreateTest("Eve"); TKAStringStruct *stringSon1 = TKAStringStructCreateTest("Son1"); TKAStringStruct *stringSon2 = TKAStringStructCreateTest("Son2"); TKAHumanStruct *god = TKAHumanStructCreateTest(stringGod, 100, TKAMaleStruct); TKAHumanStruct *adam = TKAHumanStructCreateTest(stringAdam, 30, TKAMaleStruct); TKAHumanStruct *eve = TKAHumanStructCreateTest(stringEve, 25, TKAFemaleStruct); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); printf(" \n"); TKAHumanStructMarry(adam, eve); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); printf(" \n"); TKAHumanStructDivorcePartner(eve); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); printf(" \n"); TKAHumanStructMarry(god, eve); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); printf(" \n"); // TKAHumanStructDivorce(adam, eve); // // TKAHumanStructOutput(god); // TKAHumanStructOutput(adam); // TKAHumanStructOutput(eve); // printf(" \n"); TKAHumanStructDivorce(god, eve); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); printf(" \n"); TKAHumanStruct *son1 = TKAHumanStructBorn(adam, eve, TKAMaleStruct); TKAHumanStructSetName(son1, stringSon1); TKAHumanStructOutput(son1); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); printf(" \n"); TKAHumanStruct *son2 = TKAHumanStructBorn(god, eve, TKAMaleStruct); TKAHumanStructSetName(son2, stringSon2); TKAHumanStructOutput(son1); TKAHumanStructOutput(son2); TKAHumanStructOutput(god); TKAHumanStructOutput(adam); TKAHumanStructOutput(eve); TKAHumanStructKillTest(son1); TKAHumanStructKillTest(son2); TKAHumanStructKillTest(god); TKAHumanStructKillTest(adam); TKAHumanStructKillTest(eve); TKAStringStructKillTest(stringSon1); TKAStringStructKillTest(stringSon2); TKAStringStructKillTest(stringGod); TKAStringStructKillTest(stringAdam); TKAStringStructKillTest(stringEve); } #pragma mark - #pragma mark Public Implementations void TKAHumanStructTestMain(){ TKAHumanStructTest(); }<file_sep>// // TKAStringStructTest.h // TKASecondWeek // // Created by Taisiya on 28.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAStringStructTest__ #define __TKASecondWeek__TKAStringStructTest__ #include <stdio.h> #include "TKAStringStruct.h" extern void TKAStringStructTestMain(); extern TKAStringStruct *TKAStringStructCreateTest(); extern void TKAStringStructKillTest(TKAStringStruct *data); #endif /* defined(__TKASecondWeek__TKAStringStructTest__) */ <file_sep>// // TKAStringTest.c // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAStringTest.h" #include <assert.h> #pragma mark - #pragma mark Privat Declarations static void TKAStringTest(); static void TKAStringOutputTest(TKAString *string); static void TKAStringCreateWithNULLTest(); static void TKAStringCopyLongerLengthTest(); static void TKAStringCopyShorterLengthTest(); static void TKAStringCopyNULLTest(); static void TKAStringNULLCopyNULLTest(); #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations void TKAStringOutputTest(TKAString *string) { TKAStringOutput(string); printf (" length = %llu, ", TKAStringGetLength(string)); printf("referenceCount = %llu ", TKAObjectGetReferenceCount(string)); printf("\n"); } // TKAString // after being created // data should be NULL, length should be 0 // objects reference count should 1 void TKAStringCreateWithNULLTest() { TKAString * stringTest = TKAObjectCreate(TKAString); TKAStringOutputTest(stringTest); assert(NULL == TKAStringGetData(stringTest)); assert(0 == TKAStringGetLength(stringTest)); assert(1 == TKAObjectGetReferenceCount(stringTest)); TKAObjectRelease(stringTest); TKAStringOutputTest(stringTest); } // TKAString // after being created // data should be NULL, length should be not 0 // objects reference count shouldn't change // after copying data // data should be not NULL, length should be not 0 // objects reference count shouldn't change // void TKAStringCopyLongerLengthTest() { TKAString * stringTest = TKAObjectCreate(TKAString); TKAStringOutputTest(stringTest); char *charString = "bigsizezzzzzzzzzz"; TKAStringSetData(stringTest, charString); assert(0 == strcmp(charString, TKAStringGetData(stringTest))); assert(strlen(charString)+1 == TKAStringGetLength(stringTest)); assert(1 == TKAObjectGetReferenceCount(stringTest)); TKAStringOutputTest(stringTest); TKAObjectRelease(stringTest); TKAStringOutputTest(stringTest); } void TKAStringCopyShorterLengthTest() { TKAString * stringTest = TKAObjectCreate(TKAString); char *charString1 = "bigsizezzzzzzzzzzzzzzzz"; TKAStringSetData(stringTest, charString1); assert(0 == strcmp(charString1, TKAStringGetData(stringTest))); assert(strlen(charString1)+1 == TKAStringGetLength(stringTest)); assert(1 == TKAObjectGetReferenceCount(stringTest)); TKAStringOutputTest(stringTest); char *charString2 = "smallsize"; TKAStringSetData(stringTest, charString2); assert(0 == strcmp(charString2, TKAStringGetData(stringTest))); assert(strlen(charString2)+1 == TKAStringGetLength(stringTest)); assert(1 == TKAObjectGetReferenceCount(stringTest)); TKAStringOutputTest(stringTest); TKAObjectRelease(stringTest); } void TKAStringCopyNULLTest() { TKAString * stringTest = TKAObjectCreate(TKAString); char *charString1 = "bigsizezzzzzzzzzzzzzzzz"; TKAStringSetData(stringTest, charString1); assert(0 == strcmp(charString1, TKAStringGetData(stringTest))); assert(strlen(charString1)+1 == TKAStringGetLength(stringTest)); assert(1 == TKAObjectGetReferenceCount(stringTest)); TKAStringOutputTest(stringTest); char *charString2 = NULL; TKAStringSetData(stringTest, charString2); TKAStringOutputTest(stringTest); TKAObjectRelease(stringTest); } void TKAStringNULLCopyNULLTest() { TKAString * stringTest = TKAObjectCreate(TKAString); TKAStringOutputTest(stringTest); char *charString2 = NULL; TKAStringSetData(stringTest, charString2); assert(NULL == TKAStringGetData(stringTest)); assert(0 == TKAStringGetLength(stringTest)); assert(1 == TKAObjectGetReferenceCount(stringTest)); TKAStringOutputTest(stringTest); TKAObjectRelease(stringTest); } void TKAStringTest() { TKAStringCreateWithNULLTest(); printf("\n"); TKAStringCopyLongerLengthTest(); printf("\n"); TKAStringCopyShorterLengthTest(); printf("\n"); TKAStringCopyNULLTest(); printf("\n"); TKAStringNULLCopyNULLTest(); } #pragma mark - #pragma mark Public Implementations TKAString *TKAStringCreateTest(char *string) { TKAString * stringTest = TKAObjectCreate(TKAString); TKAStringSetData(stringTest, string); return stringTest; } void TKAStringTestMain() { TKAStringTest(); } <file_sep>// // TKAString.c // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAString.h" #pragma mark - #pragma mark Privat Declarations #pragma mark - #pragma mark Privat Implementations void __TKAStringDeallocate(TKAString *string) { TKAStringSetData(string, NULL); __TKAObjectDeallocate(string); } #pragma mark - #pragma mark Public Implementations void TKAStringSetLength(TKAString *string, uint64_t length) { if (string->_length != length) { string->_data = realloc(string->_data, length * sizeof(*string->_data)); if (string->_length < length) { memset(string->_data + string->_length, 0, length - string->_length); } string->_length = length; } } uint64_t TKAStringGetLength(TKAString *string) { if (NULL == string) { return 18446744073709551615;//?? } return string->_length; } void TKAStringSetData(TKAString *string, char *data) { if (NULL == string) { return; } if (string->_data != data) { if (NULL != string->_data) { free(string->_data); string->_data = NULL; } if (NULL != data) { TKAStringCopyData(string, data); } if (NULL == data) { TKAStringSetLength(string, 0); } } } void TKAStringCopyData(TKAString *string, char *data) { uint64_t lengthData = strlen(data); TKAStringSetLength(string, lengthData+1); memmove(string->_data, data, lengthData+1); } char *TKAStringGetData(TKAString *string) { if (NULL == string) { return NULL; //NULL;//65535 //""?? } return string->_data; } void TKAStringOutput(TKAString *string) { printf("%s", TKAStringGetData(string)); } <file_sep>// // TKAArrayStruct.c // TKASecondWeek // // Created by Taisiya on 21.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAArrayStruct.h" #include "TKAHumanStruct.h" #pragma mark - #pragma mark Privat Declarations static void TKAArrayStructDealloc(TKAArrayStruct *array); #pragma mark - #pragma mark Privat Implementations void TKAArrayStructDealloc(TKAArrayStruct *array) { if (NULL != array->_child) { for (uint16_t iter = 0; iter < array->_length; iter++) { TKAArrayStructAddChildIndex(array, NULL, iter); // if (NULL != array->_child[iter]) { // TKAHumanStructRelease(array->_child[iter]); // } } } free(array); } #pragma mark - #pragma mark Public Implementations TKAArrayStruct *TKAArrayStructCreate() { TKAArrayStruct *array = calloc(1, sizeof(*array)); array->_referenceCount = 1; return array; } void TKAArrayStructRetain(TKAArrayStruct *array) { array->_referenceCount++; } void TKAArrayStructRelease(TKAArrayStruct *array) { array->_referenceCount--; if (0 == array->_referenceCount) { TKAArrayStructDealloc(array); } } void TKAArrayStructSetLength(TKAArrayStruct *array, uint16_t length) { if (array->_length != length) { array->_child = realloc(array->_child, length * sizeof(*array->_child)); if (array->_length < length) { memset(array->_child + array->_length, 0, length - array->_length); } array->_length = length; } } uint16_t TKAArrayStructGetLength(TKAArrayStruct *array) { return array->_length; } void TKAArrayStructAddChild(TKAArrayStruct *array, TKAHumanStruct *child) { bool addFlag = false; for (uint16_t iter = 0; iter < array->_length; iter ++) { if (array->_child[iter] != child) { if (array->_child[iter] == NULL) { array->_child[iter] = child; if (NULL != array->_child[iter]) { TKAHumanStructRetain(child); } addFlag = true; } } } if (false == addFlag) { uint16_t shortLength = TKAArrayStructGetLength(array); TKAArrayStructSetLength(array, shortLength + 1); array->_child[array->_length -1] = child; if (NULL != array->_child[array->_length - 1]) { TKAHumanStructRetain(child); } addFlag=true; } } void *TKAArrayStructGetArrayOfChild(TKAArrayStruct *array) { return array->_child; } TKAHumanStruct *TKAArrayStructGetChildIndex(TKAArrayStruct *array, uint16_t index) { if (array->_length > index) { return array->_child[index]; } //void metod or assert or exit; return NULL; } void TKAArrayStructAddChildIndex(TKAArrayStruct *array, void *child, uint16_t index) { if (array->_length <= index) { TKAArrayStructSetLength(array, index + 1); } if (array->_length > index) { if (array->_child[index] != child) { if (array->_child[index] != NULL) { TKAHumanStructRelease(array->_child[index]); } array->_child[index] = child; if (NULL != array->_child[index]) { TKAHumanStructRetain(child); } } } } void TKAArrayStructOutput(TKAArrayStruct *array) { for (uint16_t iter = 0; iter < array->_length; iter++) { if (array->_child[iter] != NULL) { TKAStringStructOutput(TKAHumanStructGetName(array->_child[iter])); printf(" "); } } } <file_sep>// // TKAHumanStruct.h // TKASecondWeek // // Created by Taisiya on 17.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAHumanStruct__ #define __TKASecondWeek__TKAHumanStruct__ #include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include "TKAStringStruct.h" //#include "TKAArrayStruct.h" typedef struct TKAHumanStruct TKAHumanStruct; typedef struct TKAArrayStruct TKAArrayStruct; typedef enum { TKAMaleStruct, TKAFemaleStruct } TKAGenderStruct; struct TKAHumanStruct { TKAArrayStruct *_children; TKAHumanStruct *_partner; TKAHumanStruct *_father; TKAHumanStruct *_mother; TKAStringStruct *_name; uint64_t _referenceCount; uint8_t _age; TKAGenderStruct _gender; uint8_t _countChildren; }; typedef struct TKAHumanStruct TKAHumanStruct; extern TKAHumanStruct *TKAHumanStructCreate(); extern void TKAHumanStructRetain(TKAHumanStruct *human); extern void TKAHumanStructRelease(TKAHumanStruct *human); extern void TKAHumanStructSetName(TKAHumanStruct *human, TKAStringStruct *name); extern void TKAHumanStructSetAge(TKAHumanStruct *human, uint8_t age); extern void TKAHumanStructSetGender(TKAHumanStruct *human, TKAGenderStruct gender); extern TKAStringStruct *TKAHumanStructGetName(TKAHumanStruct *human); extern uint8_t TKAHumanStructGetAge(TKAHumanStruct *human); extern TKAGenderStruct TKAHumanStructGetGender(TKAHumanStruct *human); extern uint8_t TKAHumanStructGetCountChildren(TKAHumanStruct *human); extern void TKAHumanStructSetCountChildren(TKAHumanStruct *human, uint8_t count); extern TKAHumanStruct *TKAHumanStructGetPartner(TKAHumanStruct *human); extern void TKAHumanStructSetPartner(TKAHumanStruct *human1, TKAHumanStruct *human2); extern TKAHumanStruct *TKAHumanStructGetFather(TKAHumanStruct *human); extern void TKAHumanStructSetFather(TKAHumanStruct *human1, TKAHumanStruct *human2); extern TKAHumanStruct *TKAHumanStructGetMother(TKAHumanStruct *human); extern void TKAHumanStructSetMother(TKAHumanStruct *human1, TKAHumanStruct *human2); extern TKAArrayStruct *TKAHumanStructGetChildren(TKAHumanStruct *human); extern void TKAHumanStructSetChildren(TKAHumanStruct *human, TKAArrayStruct *children); extern TKAHumanStruct *TKAHumanStructBorn(TKAHumanStruct *father, TKAHumanStruct *mother, TKAGenderStruct gender); extern void TKAHumanStructAddChild(TKAHumanStruct *parent, TKAHumanStruct *child); extern void TKAHumanStructMarry(TKAHumanStruct *humanMale, TKAHumanStruct *humanFemale); extern void TKAHumanStructDivorcePartner(TKAHumanStruct *human); extern void TKAHumanStructDivorce(TKAHumanStruct *partner1, TKAHumanStruct *partner2); #endif /* defined(__TKASecondWeek__TKAHumanStruct__) */ <file_sep>// // TKAArrayStruct.h // TKASecondWeek // // Created by Taisiya on 21.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAArrayStruct__ #define __TKASecondWeek__TKAArrayStruct__ #include <stdio.h> #include <stdlib.h> //#include "TKAHumanStruct.h" typedef struct TKAHumanStruct TKAHumanStruct; struct TKAArrayStruct { uint64_t _referenceCount; uint16_t _length; TKAHumanStruct **_child; }; typedef struct TKAArrayStruct TKAArrayStruct; extern TKAArrayStruct *TKAArrayStructCreate(); extern void TKAArrayStructRetain(TKAArrayStruct *array); extern void TKAArrayStructRelease(TKAArrayStruct *array); extern void TKAArrayStructSetLength(TKAArrayStruct *array, uint16_t length); extern uint16_t TKAArrayStructGetLength(TKAArrayStruct *array); extern void TKAArrayStructAddChild(TKAArrayStruct *array, TKAHumanStruct *child); extern void *TKAArrayStructGetChild(TKAArrayStruct *array); extern TKAHumanStruct *TKAArrayStructGetChildIndex(TKAArrayStruct *array, uint16_t index); extern void TKAArrayStructAddChildIndex(TKAArrayStruct *array, void *data, uint16_t index); extern void TKAArrayStructOutput(TKAArrayStruct *array); #endif /* defined(__TKASecondWeek__TKAArrayStruct__) */ <file_sep>// // TKAHumanStruct.c // TKASecondWeek // // Created by Taisiya on 17.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAHumanStruct.h" #include "TKAArrayStruct.h" #pragma mark - #pragma mark Private Declarations static void TKAHumanStructDealloc(TKAHumanStruct *human); #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations void TKAHumanStructDealloc(TKAHumanStruct *human) { TKAHumanStructSetName(human, NULL); TKAHumanStructSetChildren(human, NULL); TKAHumanStructSetPartner(human, NULL); TKAHumanStructSetMother(human, NULL); TKAHumanStructSetFather(human, NULL); free(human); } #pragma mark - #pragma mark Public Implementations TKAHumanStruct *TKAHumanStructCreate() { TKAHumanStruct *human = calloc(1, sizeof(*human)); human->_referenceCount = 1; return human; } void TKAHumanStructRetain(TKAHumanStruct *human) { human->_referenceCount++; } void TKAHumanStructRelease(TKAHumanStruct *human) { human->_referenceCount--; if (0 == human->_referenceCount){ TKAHumanStructDealloc(human); } } void TKAHumanStructSetName(TKAHumanStruct *human, TKAStringStruct *name) { if (human->_name != name) { if (NULL != human->_name) { TKAStringStructRelease(human->_name); } human->_name = name; if (NULL != human->_name) { TKAStringStructRetain(name); } } } TKAStringStruct *TKAHumanStructGetName(TKAHumanStruct *human) { return human->_name; } void TKAHumanStructSetAge(TKAHumanStruct *human, uint8_t age) { human->_age = age; } uint8_t TKAHumanStructGetAge(TKAHumanStruct *human) { return human->_age; } void TKAHumanStructSetGender(TKAHumanStruct *human, TKAGenderStruct gender) { human->_gender = gender; } TKAGenderStruct TKAHumanStructGetGender(TKAHumanStruct *human) { return human->_gender; } void TKAHumanStructSetCountChildren(TKAHumanStruct *human, uint8_t count) { human->_countChildren = count; } uint8_t TKAHumanStructGetCountChildren(TKAHumanStruct *human) { return human->_countChildren; } TKAArrayStruct *TKAHumanStructGetChildren(TKAHumanStruct *human) { return human->_children; } void TKAHumanStructSetChildren(TKAHumanStruct *parent, TKAArrayStruct *children) { if (parent->_children != children) { if (NULL != parent->_children) { TKAArrayStructRelease(parent->_children); } parent->_children = children; if (NULL != parent->_children) { TKAArrayStructRetain(children); } } } TKAHumanStruct *TKAHumanStructGetPartner(TKAHumanStruct *human) { return human->_partner; } void TKAHumanStructSetPartner(TKAHumanStruct *partner1, TKAHumanStruct *partner2) { if (partner1->_partner != partner2) { if (NULL != partner1->_partner) { TKAHumanStructRelease(partner1->_partner); } partner1->_partner = partner2; if (NULL != partner1->_partner) { TKAHumanStructRetain(partner2); } } } TKAHumanStruct *TKAHumanStructGetFather(TKAHumanStruct *human) { return human->_father; } void TKAHumanStructSetFather(TKAHumanStruct *child, TKAHumanStruct *parent) { if (child->_father != parent) { if (NULL != child->_father) { TKAHumanStructRelease(child->_father); } child->_father = parent; if (NULL != child->_father) { TKAHumanStructRetain(parent); } } } TKAHumanStruct *TKAHumanStructGetMother(TKAHumanStruct *human) { return human->_mother; } void TKAHumanStructSetMother(TKAHumanStruct *child, TKAHumanStruct *parent) { if (child->_mother != parent) { if (NULL != child->_mother) { TKAHumanStructRelease(child->_mother); } child->_mother = parent; if (NULL != child->_mother) { TKAHumanStructRetain(parent); } } } void TKAHumanStructDivorcePartner(TKAHumanStruct *human) { if (NULL != TKAHumanStructGetPartner(human) && human != TKAHumanStructGetPartner(human)) { if (TKAHumanStructGetPartner(TKAHumanStructGetPartner(human)) == human) { TKAHumanStructDivorce(human, TKAHumanStructGetPartner(human)); } else { TKAHumanStructSetPartner(human, NULL); } } } void TKAHumanStructDivorce(TKAHumanStruct *partner1, TKAHumanStruct *partner2) { if (partner1 != partner2 && NULL != partner1 && NULL != partner2) { if (partner1 == TKAHumanStructGetPartner(partner2) && partner2 == TKAHumanStructGetPartner(partner1)) { TKAHumanStructSetPartner(partner1, NULL); TKAHumanStructSetPartner(partner2, NULL); } } } void TKAHumanStructMarry(TKAHumanStruct *partner1, TKAHumanStruct *partner2) { if (partner1 != partner2 && NULL != partner1 && NULL != partner2) { if (NULL != TKAHumanStructGetPartner(partner1)) { TKAHumanStructDivorcePartner(partner1); } if (NULL != TKAHumanStructGetPartner(partner2)) { TKAHumanStructDivorcePartner(partner2); } TKAHumanStructSetPartner(partner1, partner2); TKAHumanStructSetPartner(partner2, partner1); } } void TKAHumanStructAddChild(TKAHumanStruct *parent, TKAHumanStruct *child) { if (child != parent) { if (NULL != child) { if (NULL == TKAHumanStructGetChildren(parent)) { TKAArrayStruct *arrayChild = TKAArrayStructCreate(); TKAHumanStructSetChildren(parent, arrayChild); } if (NULL != TKAHumanStructGetChildren(parent)) { TKAArrayStructAddChild(TKAHumanStructGetChildren(parent), child); } //MAKE WITH BOOL RESAULT parent->_countChildren++; } } } TKAHumanStruct *TKAHumanStructBorn(TKAHumanStruct *father, TKAHumanStruct *mother, TKAGenderStruct gender) { TKAHumanStruct *newBorn = TKAHumanStructCreate(); TKAHumanStructSetAge(newBorn, 0); TKAHumanStructSetGender(newBorn, gender); TKAHumanStructSetCountChildren(newBorn, 0); if (NULL != father) { TKAHumanStructAddChild(father, newBorn); TKAHumanStructSetFather(newBorn, father); } if (father !=mother && NULL != mother) { TKAHumanStructAddChild(mother, newBorn); TKAHumanStructSetMother(newBorn, mother); } return newBorn; } <file_sep>// // TKAHumanStructTest.h // TKASecondWeek // // Created by Taisiya on 17.02.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #ifndef __TKASecondWeek__TKAHumanStructTest__ #define __TKASecondWeek__TKAHumanStructTest__ #include <stdio.h> #include <string.h> #include "TKAHumanStruct.h" #include "TKAArrayStruct.h" #include "TKAStringStructTest.h" extern void TKAHumanStructTestMain(); #endif /* defined(__TKASecondWeek__TKAHumanStructTest__) */ <file_sep>// // TKAArrayTest.c // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAArrayTest.h" #pragma mark - #pragma mark Privat Declarations #pragma mark - #pragma mark Public Declarations #pragma mark - #pragma mark Privat Implementations #pragma mark - #pragma mark Public Implementations void TKAArrayTestMain() { } // TKAArray // after being created // array should be NULL, length should be 0 // objects reference count of Array should be 1 // after adding 5 child // array shouldn't be NULL, length should be increment by 5 // objects reference count of child should be increment by 5 // objects reference count of Array should be 1 // after removing ALL children // array shouldn be NULL, length should be decrement by 5 // objects reference count of child should be decrement by 5 // objects reference count of Array should be 1 // ObjectRelease Array // // TKAArray // after being created // array should be NULL, length should be 0 // objects reference count of Array should be 1 // after adding 1 child by index 3 // array shouldn't be NULL, length should be increment by 3 // objects reference count of child should be increment by 1 // objects reference count of Array should be 1 // after removing ALL children // array should be NULL, length should be 0 // objects reference count of child should be decrement by 1 // objects reference count of Array should be 1 // ObjectRelease Array // // TKAArray // after being created // array should be NULL, length should be 0 // objects reference count of Array should be 1 // after adding 1 child by pointer // array shouldn't be NULL, length should be increment by 1 // objects reference count of child should be increment by 1 // objects reference count of Array should be 1 // after removing ALL children // array should be NULL, length should be 0 // objects reference count of child should be decrement by 1 // objects reference count of Array should be 1 //// ObjectRelease Array // //TKAArray // after being created // after adding 3 child // array shouldn't be NULL, length should be increment by 3 // objects reference count of child should be increment by 3 // objects reference count of Array should be 1 // after removing 1 child by index 2 // array shouldn't be NULL, length shouldn't change // objects reference count of child should be decrement by 1 // objects reference count of Array should be 1 // after removing ALL child // array should be NULL, length should be 0 // objects reference count of child should be decrement by 2 // objects reference count of Array should be 1 // ObjectRelease Array // <file_sep>// // TKAArray.c // TKASecondWeek // // Created by Taisiya on 01.03.15. // Copyright (c) 2015 TKhomeWork. All rights reserved. // #include "TKAArray.h" #include "TKAHuman.h" #pragma mark - #pragma mark Privat Declarations #pragma mark - #pragma mark Privat Implementations #pragma mark - #pragma mark Public Implementations void __TKAArrayDeallocate(TKAArray *array) { if (NULL != array->_child) { // for (uint16_t iter = 0; iter < array->_length; iter++) { // TKAArrayAddChildIndex(array, NULL, iter); // } TKAArrayRemoveAllChildren(array); } __TKAObjectDeallocate(array); } void TKAArraySetLength(TKAArray *array, uint16_t length) { if (array->_length > length) { for (uint16_t iter = array->_length-1; iter > length; iter--) { TKAArrayRemoveChildIndex(array, iter); } } if (array->_length != length) { array->_child = realloc(array->_child, length * sizeof(*array->_child)); if (array->_length < length) { memset(array->_child + array->_length, 0, length - array->_length); } array->_length = length; } } uint16_t TKAArrayGetLength(TKAArray *array) { return array->_length; } void TKAArrayAddChild(TKAArray *array, TKAHuman *child) { bool addFlag = false; for (uint16_t iter = 0; iter < array->_length; iter ++) { if (array->_child[iter] != child) { if (array->_child[iter] == NULL) { TKAArrayAddChildIndex(array, child, iter); addFlag = true; } } } if (false == addFlag) { uint16_t shortLength = TKAArrayGetLength(array); TKAArraySetLength(array, shortLength + 1); TKAArrayAddChildIndex(array, child, shortLength); addFlag=true; } // return addFlag; } // ?? dont used void *TKAArrayGetArrayChild(TKAArray *array) { return array->_child; } TKAHuman *TKAArrayGetChildIndex(TKAArray *array, uint16_t index) { if (array->_length > index) { return array->_child[index]; } //void metod or assert or exit; return NULL; } void TKAArrayAddChildIndex(TKAArray *array, TKAHuman *child, uint16_t index) { bool addFlag = false; if (array->_length <= index) { TKAArraySetLength(array, index + 1); } if (array->_length > index) { if (array->_child[index] != child) { if (array->_child[index] != NULL) { TKAObjectRelease(array->_child[index]); } array->_child[index] = child; if (NULL != array->_child[index]) { TKAObjectRetain(child); addFlag = true; } } } // return addFlag; } void TKAArrayRemoveChildIndex(TKAArray *array, uint16_t index) { bool removeFlag = false; if (array->_length > index) { TKAArrayAddChildIndex(array, NULL, index); removeFlag = true; } // return removeFlag; } void TKAArrayRemoveChild(TKAArray *array, TKAHuman *child) { bool removeFlag = false; if (NULL != child) { for (uint16_t iter = 0; iter < TKAArrayGetLength(array); iter++) { if (array->_child[iter] == child) { TKAArrayAddChildIndex(array, NULL, iter); removeFlag = true; } } } // return removeFlag; } void TKAArrayRemoveAllChildren(TKAArray *array) { bool removeFlag = false; for (uint16_t iter = 0; iter < TKAArrayGetLength(array); iter++) { if (NULL != array->_child[iter]) { TKAArrayRemoveChildIndex(array, iter); } } // return removeFlag; } void TKAArrayOutput(TKAArray *array) { for (uint16_t iter = 0; iter < array->_length; iter++) { if (array->_child[iter] != NULL) { TKAStringOutput(TKAHumanGetName(array->_child[iter])); printf(" "); } } }
bac8a72567fac90f24db56d305370cb31c335a0d
[ "Markdown", "C" ]
28
C
taisiyat/TestHomeWork
3cdb8adc57dcca2f6a80950e7eaaf08ded90c9fa
2bd7916d8f0f3bf446ff321a2d4edab154aee84e
refs/heads/master
<file_sep>from django.apps import AppConfig class JwappConfig(AppConfig): name = 'jwapp' <file_sep> from django.contrib import admin from django.urls import path from jwapp.views import home,check urlpatterns = [ path('admin/', admin.site.urls), path('',home,name='home'), path('check/',check,name="check") ] <file_sep>from django.shortcuts import render import random city_names=["london","paris","singapore","dubai","macau","mumbai","pune","delhi","chennai","jaipur","boston"] word="" def home(request): global word word=random.choice(city_names) jum=random.sample(word,len(word)) jum_word=''.join(jum) return render(request,'home.html',{'word':jum_word}) def check(request): global word ans=request.GET.get("ans") if ans==word: msg="u r right ans is "+word else: msg="u r wrong correct ans is "+word return render(request,'check.html',{'msg':msg}) # Create your views here.
c861c2d9efc657916a9c59737f81c16a4ce30015
[ "Python" ]
3
Python
DevangGangal/JumbledLettersGameWebsite
f2abe20612dd8ff329a18a4e78c3800830c722ef
7fe7783c49ed222ed0c0b9ba224b8489a81cc23b
refs/heads/master
<file_sep># WRF运行的主要流程 ## 1、运行WRF_link.sh 创建WRF和WPS的主程序的快捷方式,方便同时提交多个WRF任务 使用说明: 需要修改ORIGIN_WPS变量,修改为WPS主程序文件夹的路径 需要修改ORIGIN_WRF变量,修改为WRF主程序文件夹的路径 运行`sh WRF_link.sh LINK_PATH`,可以在LINK_PATH目录下创建WRF和WPS的快捷方式,可创建多个快捷方式方便运行多个wrf ## 2、修改namelist.wps 具体怎么修改省略,请参考WRF官网(http://www2.mmm.ucar.edu/wrf/OnLineTutorial/index.php) ## 3、运行WPS_one_step_GFS.sh 一键WPS预处理GFS数据 使用说明: 需要修改WPS_DIR变量,该文件夹可以说WRF_link.sh创建的WRF文件夹,也可以是WPS源程序的文件夹 需要修改WRF_DIR变量, 该文件夹可以是WRF_link.sh创建的WRF文件夹,也可以是$WRF_PATH/test/em_real的文件夹 需要修改DATA变量,该文件夹是对应nanmelist.wps的日期的GFS数据 运行`sh WPS_one_step_GFS.sh`可以完成WPS的预处理 ## 4、修改namelist.input 具体修改请参考WRF官网(http://www2.mmm.ucar.edu/wrf/OnLineTutorial/index.php) ## 5、运行./real.exe 生成wrf.exe运行所需要的数据 ## 6、加入排放源数据(可选, WRF-CHEM) 将生成的排放源数据拷贝或链接到当前文件夹 ## 7、提交submit.job的任务脚本 (如果使用nuist hpc) 运行 `qsub submit.job` ## 8、运行clean_data.sh 使用说明: 需要修改WPS_DIR变量,该文件夹可以说WRF_link.sh创建的WRF文件夹,也可以是WPS源程序的文件夹 需要修改WRF_DIR变量, 该文件夹可以是WRF_link.sh创建的WRF文件夹,也可以是$WRF_PATH/test/em_real的文件夹 运行`sh clean_data.sh`可以清空wrf产生的文件 <file_sep>#!/bin/sh # useage ./run.sh "PATH/*.grb2" WRF_DIR="/nuist/p/work/weiming/weiming_zhengyu/work/wrf_job/WRF01/WRF" #should be abs path WPS_DIR="/nuist/p/work/weiming/weiming_zhengyu/work/wrf_job/WRF01/WPS" #should be abs path DATA="/nuist/p/work/weiming/weiming_zhengyu/download/GFS/20181128/*.grb2" #should be abs path if [ ! -n $WRF_DIR ];then echo "WRF dir is not exist!!!" exit 1 fi if [ ! -n $WPS_DIR ];then echo "WPS dir is not exist!!!" exit 1 fi cd $WPS_DIR echo "now dir is : " `pwd` echo "met data list : $1" ./geogrid.exe ln -sf ./ungrib/Variable_Tables/Vtable.GFS ./Vtable ./link_grib.csh $DATA ./ungrib.exe ./metgrid.exe ln -sf `pwd`/met_em.d*.nc $WRF_DIR <file_sep>import wget import datetime import pandas as pd import os forcast_time = datetime.datetime(2018, 11, 22, 18, 00) #start forcast time forcast_hours = 12 ##forcast future hours start_time = forcast_time - datetime.timedelta(days=1) #spin up time ana_time = pd.date_range(start=start_time, freq="6H", end=forcast_time) month = ana_time.strftime("%Y%m") day = ana_time.strftime("%Y%m%d") filename = ana_time.strftime("gfsanl_4_%Y%m%d_%H00_000.grb2") if not os.path.exists(forcast_time.strftime("%Y%d%m%H")): os.mkdir(forcast_time.strftime("%Y%d%m%H")) for i in range(len(ana_time)): url = "https://nomads.ncdc.noaa.gov/data/gfsanl/"+ month[i]+"/"+day[i]+"/"+filename[i] out_path = os.path.join(forcast_time.strftime("%Y%d%m%H"), filename[i]) wget.download(url=url, out=out_path) for ihour in range(6, forcast_hours+1, 6): url = "https://nomads.ncdc.noaa.gov/data/gfs4/"+ month[-1] +"/"+day[-1]+\ "/"+ forcast_time.strftime("gfs_4_%Y%m%d_%H00_{:03d}.grb2".format(ihour)) ##forcast 6h out_path = os.path.join(forcast_time.strftime("%Y%d%m%H"), \ forcast_time.strftime("gfs_4_%Y%m%d_%H00_{:03d}.grb2".format(ihour))) wget.download(url=url, out=out_path)<file_sep>#!/bin/sh # run.sh /nuist/scratch/test ORIGIN_WPS="/nuist/p/work/weiming/weiming_zhengyu/WPS" ORIGIN_WRF="/nuist/p/work/weiming/weiming_zhengyu/WRFV3" if [ ! -n "$1" ];then echo "PATH Doesn't exist, don't run this shell, please input link path!!!" exit 1 fi if [ ! -d $1 ];then mkdir $1 fi mkdir "$1/WRF" mkdir "$1/WPS" WPS_PATH="$1/WPS" WRF_PATH="$1/WRF" echo "new link for WPS's path : $WPS_PATH" echo "new link for WRF's path : $WRF_PATH" echo "origin run WRF's path : $ORIGIN_WRF/run" if [ -d $WRF_PATH ];then ln -sf $ORIGIN_WRF/run/*.exe $ORIGIN_WRF/run/*.TBL $ORIGIN_WRF/run/*.formatted\ $ORIGIN_WRF/run/RRTM* $ORIGIN_WRF/run/ETA* $ORIGIN_WRF/run/*.tbl $ORIGIN_WRF/run/CAM* $ORIGIN_WRF/run/README* $WRF_PATH cp $ORIGIN_WRF/run/namelist.input $WRF_PATH echo "Congratulations, finish WRF!" fi if [ -d $WPS_PATH ];then ln -sf $ORIGIN_WPS/*.exe $ORIGIN_WPS/util/ $ORIGIN_WPS/ungrib/ $ORIGIN_WPS/metgrid/ $ORIGIN_WPS/geogrid/ $ORIGIN_WPS/README $WPS_PATH ln -sf $ORIGIN_WPS/link_grib.csh $ORIGIN_WPS/arch/ $ORIGIN_WPS/clean $ORIGIN_WPS/configure $ORIGIN_WPS/compile $WPS_PATH cp $ORIGIN_WPS/namelist.wps $WPS_PATH echo "Congratulations, finish WPS!" fi <file_sep>#/bin/bash WRF_DIR="/nuist/p/work/weiming/weiming_zhengyu/script_wrf/test/WRF" #should be abs path WPS_DIR="/nuist/p/work/weiming/weiming_zhengyu/script_wrf/test/WPS" #should be abs path cd $WPS_DIR rm ./met_em.d*.nc rm ./GRIBFILE* rm ./FILE:* rm ./geo_em.d*.nc cd $WRF_DIR rm ./met_em.d*.nc rm ./rsl.*
e6ec24916e950c76508d5ec9bf6b7b7ce8a15c27
[ "Markdown", "Python", "Shell" ]
5
Markdown
Vanyary/WRF_SCRIPT
583c142f711232c868368238f374437a52415baa
53043f400879ec9ae364889ec3bf4755a7bf6741
refs/heads/master
<repo_name>a1029382825/CampusVillage<file_sep>/database/models.js module.exports = { user: { uid : {type:Number,required:true,unique: true}, password : {type:String,required:true}, registerDate : {type:Date,default:Date.now}, userImg : String, profile : { nikename : String, age : String, school : String, qq : Number, sex : Number, birthday : String, status : Number }, buyOrders: [String] }, willRegisterUser: { uid : {type: Number, required: true}, submitDate : Date, smsCode : {type: Number, required: true} }, userSmsCode: { uid: {type: Number, required: true}, smsDate: {type: String,required: true}, smsCode: {type: Number, required: true} }, publishGoodsList: { belongUid: {type:String,required:true}, belongUserName: {type:String,required:true}, belongUserImage: {type:String,required:true}, kindID: {type:String,required:true}, price: {type:Number,required:true}, title: {type: String,required: true}, content: {type: String,required: true}, images: [{ imgUrl: String }], publishTime: {type:String,required:true}, lookCount: {type: Number,default: 0}, hot: Boolean, reply:[{ replyUid: Number, replyNikeName: String, replyContent: String, replyTime: Date }], buyStatus: {type:Boolean, default: false} }, goodsOrder: { buyGoodID: {type: String, required: true}, buyGoodName: {type: String, required: true}, buyGoodImage: {type: String, required: true}, buyName: {type: String, required: true}, buyPhone: {type: String, required: true}, buyCity: {type: String, required: true}, buyAddress: {type: String, required: true}, buyStatus: {type: Number, required: true}, buyMoney: {type: Number, required: true}, buyOther: String, buyDate: String } }<file_sep>/routes/goodsAPI.js var express = require('express'); var router = express.Router(); var mongoose = require("mongoose"); var moment = require('moment'); var formidable = require('formidable'); var fs = require("fs"); var multiparty = require('multiparty'); var util = require('util'); var events = require('events'); var myEventEmitter = new events.EventEmitter(); //获取发布列表分页,有搜索则模糊搜索,无搜索根据ID返回全部 router.get("/goodsList",function(req, res, next) { var pageIndex = req.query.pageIndex - 1; var pageSize = req.query.pageSize; var kindID = req.query.id; var searchStr = req.query.searchStr; var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var User = global.dbHandel.getModel('user'); if (searchStr) { var query = publishGoodsList.find({kindID: kindID, title: {$regex: searchStr, $options: '$i'}}); } else { var query = publishGoodsList.find({kindID: kindID}); } publishGoodsList.count({kindID: kindID},function(err, total) { query.limit(pageSize*1); query.skip(pageSize*pageIndex); query.exec(function(err, docs) { if (err) { res.json({ status: -1, message: "获取失败", Data:{} }) return; } res.json({ status: 200, message: "获取成功", Data: docs }) }) }) }); //获取热门列表分页 router.get("/goodsHotList",function(req, res, next) { var pageIndex = req.query.pageIndex - 1; var pageSize = req.query.pageSize; var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var query = publishGoodsList.find({"hot":true}); query.limit(pageSize); query.skip(pageSize*pageIndex); query.exec(function(err, docs) { if (err) { res.json({ status: -1, message: "获取失败", Data:{} }) return; } res.json({ status: 200, message: "获取成功", Data: docs }); }) }); //新增 router.post("/addGoods",function(req, res, next) { var User = global.dbHandel.getModel('user'); var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); User.findOne({_id: req.body.belongUid}, function(err, doc) { if (err || !doc) { console.log(1); res.json({ status: -1, message: "保存失败,用户查找失败", Data: {} }) return } console.log(doc); var goods = new publishGoodsList({ belongUid: doc._id, belongUserName: doc.profile.nikename, belongUserImage: doc.userImg, title: req.body.title, content: req.body.content, price: req.body.price, kindID: req.body.kindID, publishTime: moment().format('YYYY-MM-DD HH:mm:ss'), images:[] }); goods.save(function(e,s) { if (e) { console.log(e); res.json({ status: -1, message: "保存失败", Data:{} }); return; } res.json({ status: 200, message: "保存成功", Data:{goodsID:s._id} }) }) }) }) //上传图片 router.post("/uploadGoodsImages", function(req, res, next) { var cacheFolder = './uploads/uploadcache/'; var goodsID = req.query.goodsID; var key = req.query.key; var form = new multiparty.Form({uploadDir: cacheFolder}); form.parse(req, function(err, fields, files) { console.log(files); var filesTmp = JSON.stringify(files,null,2); if (err) { res.json({ status: -1, message: '文件解析失败', Data: err }) return; } var imgPath = files[key][0].path; var displayUrl = imgPath.replace(/\\/g,'/'); displayUrl = displayUrl.replace(/uploads/,''); displayUrl = '/img' + displayUrl; var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); publishGoodsList.update({_id: goodsID},{$addToSet: {images: {imgUrl: displayUrl}}}, function(err) { if (err) { res.json({ status: -1, message: '图片保存失败', Data: err }) return; } res.json({ status: 200, message: '图片保存成功', Data: { imageUrl: displayUrl } }) }) }) }) //删除 router.post("/delGoods",function(req, res, next) { var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var delGoodsID = req.body.goodsID; publishGoodsList.remove({_id:delGoodsID},function(err,docs) { if (err) { res.json({ status: -1, message: "删除失败", Data: {} }) return; } res.json({ status: 200, message: "删除成功", Data: {} }); }) }) //更新 router.post("/updateGoods",function(req, res, next) { var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var updateGoodsID = req.body.goodsID; publishGoodsList.update({_id:updateGoodsID},{ title: req.body.title, content: req.body.content },function(err,docs) { if (err) { res.json({ status: -1, message: "更新失败", Data:{} }) return; } res.json({ status: 200, message: "更新成功", Data:{} }) }) }) //获取一个记录详情 router.get("/goodsDetail",function(req, res, next) { var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var User = global.dbHandel.getModel('user'); var findGoodsID = req.query.goodsID; publishGoodsList.findOne({_id:findGoodsID}, function(err, doc) { if (err) { res.json({ status: -1, message: "查找失败", Data:{} }) return; } console.log(doc.lookCount); if (doc.lookCount) { var count = doc.lookCount + 1; } else { var count = 1; } publishGoodsList.update({_id: doc._id}, {lookCount: count}, function(err) { if (err) { console.log(err); } }) User.findOne({_id: doc.belongUid}, function(err, user) { if (err) { res.json({ status: -1, message: "查找失败", Data:{} }) return; } res.json({ status: 200, message: "查找成功", Data: { goodsInfo: doc, userInfo: user } }); }) }) }) //根据标题模糊搜索 router.get("/searchGoodsByTitle", function(req, res, next) { var User = global.dbHandel.getModel('user'); var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var searchStr = req.query.searchStr; var pageIndex = req.query.pageIndex - 1; var pageSize = req.query.pageSize; var query = publishGoodsList.find({title: {$regex: searchStr, $options: '$i'}}); query.limit(pageSize * 1); query.skip(pageSize*pageIndex); query.exec(function(err, docs) { if (err) { res.json({ status: -1, message: "查找失败", Data: err }) return; } res.json({ status: 200, message: '查找成功', Data: docs }) }) }) //获取我发布的商品列表 router.get("/getMyPublish", function(req, res, next) { var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var userID = req.query.userID; publishGoodsList.find({belongUid: userID}, function(err, docs) { if (err) { res.json({ status: -1, message: '查找失败', Data: err }) return; } res.json({ status: 200, message: '查找成功', Data: docs }) }) }) //获取我发布的商品详情 router.get("/getMyPublishDetail", function(req, res, next) { var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); var goodsOrder = global.dbHandel.getModel('goodsOrder'); var goodsID = req.query.goodsID; publishGoodsList.findOne({_id: goodsID}, function(err, good) { if (err) { res.json({ status: -1, message: '获取失败', Data: {} }) return; } goodsOrder.findOne({buyGoodID: good._id}, function(err, doc) { if (err) { res.json({ status: -1, message: '获取失败', Data: {} }) return; } res.json({ status: 200, message: "获取成功", Data: { goodsInfo: good, orderInfo: doc } }) }) }) }) //获取我买到的商品列表 router.get("/getMyBought", function(req, res, next) { var goodsOrder = global.dbHandel.getModel('goodsOrder'); var User = global.dbHandel.getModel('user'); var userID = req.query.userID; User.findOne({_id: userID}, function(err, doc) { if (err) { res.json({ status: -1, message: "查找失败", Data: err }) return; } var ids = []; if (doc.buyOrders && doc.buyOrders.length > 0) { doc.buyOrders.forEach(function(item) { ids.push(item); }) goodsOrder.find({_id: {$in: ids}}, function(err, docs) { if (err) { res.json({ status: -1, message: "查找失败", Data: err }) return; } res.json({ status: 200, message: "查找成功", Data: docs }) }) } }) }) //获取一个订单的详细数据 router.get("/getOrderDetail", function(req, res, next) { var orderID = req.query.orderID; var goodsOrder = global.dbHandel.getModel('goodsOrder'); goodsOrder.findOne({_id: orderID}, function(err, doc) { if (err) { res.json({ status: -1, message: '获取失败', Data: err }) return; } res.json({ status: 200, message: '获取成功', Data: doc }) }) }) //更新订单状态 router.post("/updateOrderStatus", function(req, res, next) { var orderID = req.body.orderID; var orderStatus = req.body.orderStatus; var goodsOrder = global.dbHandel.getModel('goodsOrder'); goodsOrder.update({_id: orderID},{buyStatus: orderStatus}, function(err) { if (err) { res.json({ status: -1, message: "更新失败", Data: err }) return; } res.json({ status: 200, message: "更新成功", Data: {} }) }) }) //生成购买订单 router.post("/createOrder", function(req, res, next) { //获取数据模型 var goodsOrder = global.dbHandel.getModel('goodsOrder'); var User = global.dbHandel.getModel('user'); var publishGoodsList = global.dbHandel.getModel('publishGoodsList'); //获取请求参数 var goodID = req.body.goodID; var userID = req.body.userID; var goodName = req.body.goodName; var goodImage = req.body.goodImage; var buyName = req.body.buyName; var buyPhone = req.body.buyPhone; var buyCity = req.body.buyCity; var buyAddress = req.body.buyAddress; var buyOther = req.body.buyOther; var buyMoney = req.body.buyMoney var order = new goodsOrder({ buyGoodID: goodID, buyGoodName: goodName, buyGoodImage: goodImage, buyName: buyName, buyPhone: buyPhone, buyCity: buyCity, buyAddress: buyAddress, buyStatus: 1, buyOther: buyOther, buyMoney: buyMoney, buyDate: moment().format('YYYY-MM-DD HH:mm:ss') }) order.save(function(err) { if (err) { console.log("save:" + err); res.json({ status: -1, message: '创建订单失败', Data: err }) return; } User.update({_id: userID},{$addToSet: {buyOrders: order._id}}, function(err) { if (err) { console.log("user:" + err); res.json({ status: -1, message: '创建订单失败', Data: err }) return; } publishGoodsList.update({_id: goodID}, {buyStatus: true}, function(err) { if (err) { res.json({ status: -1, message: '修改商品状态失败', Data: err }) return; } res.json({ status: 200, message: '创建订单成功', Data: {} }) }) }) }) }) module.exports = router;<file_sep>/app.js var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var multer = require('multer'); var mongoose = require('mongoose'); // var session = require('express-session'); global.dbHandel = require('./database/dbHandel'); mongoose.Promise = global.Promise; global.db = mongoose.connect("mongodb://localhost:27017/campusvillage"); //引入个模块api var userAPI = require('./routes/userAPI'); var goodsAPI = require('./routes/goodsAPI'); var app = express(); // app.use(session({ // secret: 'secret', // cookie:{ // maxAge: 1000*60*30; // } // })); app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); }); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use('/static', express.static(__dirname + '/public')); app.use('/img', express.static(__dirname + '/uploads')); //express中间件 app.use('/user',userAPI); app.use('/goods',goodsAPI); // 捕获404错误,返回404错误提示 app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // 捕获服务器内部错误,返回500错误提示 app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; res.status(err.status || 500); res.render('error'); }); module.exports = app;
0fbf60a88c69f11f6d80bac5d273109a458d9618
[ "JavaScript" ]
3
JavaScript
a1029382825/CampusVillage
e7b3f5c96b744075aa92a24d327190ccdd8b7e73
ca4281a58e584df9839f88770687968de07d3a03
refs/heads/master
<file_sep># Tris Hello! I create this simple Tris game with Pygame<file_sep>import pygame import os pygame.init() screen_width = 500 screen_height = 500 win = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Tris") font = pygame.font.SysFont("Times New Roman", 20) run = True class button(object): def __init__(self, x, y): self.x = x self.y = y self.width = 90 self.height = 90 self.show = False self.player_on = False self.player_x = False self.player_o = False central_button = button(206, 206) sideleft_button = button(106, 206) sideright_button = button(306, 206) topcentral_button = button(206, 106) topleft_button = button(106, 106) topright_button = button(306, 106) bottomcentral_button = button(206, 306) bottomleft_button = button(106, 306) bottomright_button = button(306, 306) turn = True start_menu = True game = False x_score = 0 o_score = 0 x_win = False o_win = False draw = False x = pygame.image.load(os.path.join("x.png")) o = pygame.image.load(os.path.join("o.png")) def create_table(): left_line = pygame.draw.line(win, (255, 255, 255), (200, 100), (200, 400), 10) right_line = pygame.draw.line(win, (255, 255, 255), (300, 100), (300, 400), 10) top_line = pygame.draw.line(win, (255, 255, 255), (100, 200), (400, 200), 10) bottom_line = pygame.draw.line(win, (255, 255, 255), (100, 300), (400, 300), 10) def restart(): turn = True start_menu = True game = False central_button.player_x = False central_button.player_o = False central_button.player_on = False sideleft_button.player_x = False sideleft_button.player_o = False sideleft_button.player_on = False sideright_button.player_x = False sideright_button.player_o = False sideright_button.player_on = False topcentral_button.player_x = False topcentral_button.player_o = False topcentral_button.player_on = False topleft_button.player_x = False topleft_button.player_o = False topleft_button.player_on = False topright_button.player_x = False topright_button.player_o = False topright_button.player_on = False bottomcentral_button.player_x = False bottomcentral_button.player_o = False bottomcentral_button.player_on = False bottomleft_button.player_x = False bottomleft_button.player_o = False bottomleft_button.player_on = False bottomright_button.player_x = False bottomright_button.player_o = False bottomright_button.player_on = False def click_button(): global turn, start_menu, game, x_win, o_win, draw if central_button.x + central_button.width > mouse_pos[0] > central_button.x and central_button.y + central_button.height > mouse_pos[1] > central_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and central_button.player_on == False: central_button.player_on = True turn = False central_button.player_x = True if turn == False and central_button.player_on == False: central_button.player_on = True turn = True central_button.player_o = True if sideleft_button.x + sideleft_button.width > mouse_pos[0] > sideleft_button.x and sideleft_button.y + sideleft_button.height > mouse_pos[1] > sideleft_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and sideleft_button.player_on == False: sideleft_button.player_on = True turn = False sideleft_button.player_x = True if turn == False and sideleft_button.player_on == False: sideleft_button.player_on = True turn = True sideleft_button.player_o = True if sideright_button.x + sideright_button.width > mouse_pos[0] > sideright_button.x and sideright_button.y + sideright_button.height > mouse_pos[1] > sideright_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and sideright_button.player_on == False: sideright_button.player_on = True turn = False sideright_button.player_x = True if turn == False and sideright_button.player_on == False: sideright_button.player_on = True turn = True sideright_button.player_o = True if topcentral_button.x + topcentral_button.width > mouse_pos[0] > topcentral_button.x and topcentral_button.y + topcentral_button.height > mouse_pos[1] > topcentral_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and topcentral_button.player_on == False: topcentral_button.player_on = True turn = False topcentral_button.player_x = True if turn == False and topcentral_button.player_on == False: topcentral_button.player_on = True turn = True topcentral_button.player_o = True if topleft_button.x + topleft_button.width > mouse_pos[0] > topleft_button.x and topleft_button.y + topleft_button.height > mouse_pos[1] > topleft_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and topleft_button.player_on == False: topleft_button.player_on = True turn = False topleft_button.player_x = True if turn == False and topleft_button.player_on == False: topleft_button.player_on = True turn = True topleft_button.player_o = True if topright_button.x + topright_button.width > mouse_pos[0] > topright_button.x and topright_button.y + topright_button.height > mouse_pos[1] > topright_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and topright_button.player_on == False: topright_button.player_on = True turn = False topright_button.player_x = True if turn == False and topright_button.player_on == False: topright_button.player_on = True turn = True topright_button.player_o = True if bottomcentral_button.x + bottomcentral_button.width > mouse_pos[0] > bottomcentral_button.x and bottomcentral_button.y + bottomcentral_button.height > mouse_pos[1] > bottomcentral_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and bottomcentral_button.player_on == False: bottomcentral_button.player_on = True turn = False bottomcentral_button.player_x = True if turn == False and bottomcentral_button.player_on == False: bottomcentral_button.player_on = True turn = True bottomcentral_button.player_o = True if bottomleft_button.x + bottomleft_button.width > mouse_pos[0] > bottomleft_button.x and bottomleft_button.y + bottomleft_button.height > mouse_pos[1] > bottomleft_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and bottomleft_button.player_on == False: bottomleft_button.player_on = True turn = False bottomleft_button.player_x = True if turn == False and bottomleft_button.player_on == False: bottomleft_button.player_on = True turn = True bottomleft_button.player_o = True if bottomright_button.x + bottomright_button.width > mouse_pos[0] > bottomright_button.x and bottomright_button.y + bottomright_button.height > mouse_pos[1] > bottomright_button.y: if mouse_click: if start_menu: start_menu = False game = True turn = True x_win = False o_win = False draw = False else: if turn == True and bottomright_button.player_on == False: bottomright_button.player_on = True turn = False bottomright_button.player_x = True if turn == False and bottomright_button.player_on == False: bottomright_button.player_on = True turn = True bottomright_button.player_o = True while run: mouse_pos = pygame.mouse.get_pos() mouse_click = pygame.MOUSEBUTTONDOWN mouse_clicked = pygame.mouse.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == mouse_click and event.button == 1: click_button() if central_button.player_x and sideleft_button.player_x and sideright_button.player_x: game = False x_win = True x_score += 1 if topcentral_button.player_x and topleft_button.player_x and topright_button.player_x: game = False x_win = True x_score += 1 if bottomcentral_button.player_x and bottomleft_button.player_x and bottomright_button.player_x: game = False x_win = True x_score += 1 if topleft_button.player_x and sideleft_button.player_x and bottomleft_button.player_x: game = False x_win = True x_score += 1 if topcentral_button.player_x and central_button.player_x and bottomcentral_button.player_x: game = False x_win = True x_score += 1 if topright_button.player_x and sideright_button.player_x and bottomright_button.player_x: game = False x_win = True x_score += 1 if topright_button.player_x and central_button.player_x and bottomleft_button.player_x: game = False x_win = True x_score += 1 if topleft_button.player_x and central_button.player_x and bottomright_button.player_x: game = False x_win = True x_score += 1 if central_button.player_o and sideleft_button.player_o and sideright_button.player_o: game = False o_win = True o_score += 1 if topcentral_button.player_o and topleft_button.player_o and topright_button.player_o: game = False o_win = True o_score += 1 if bottomcentral_button.player_o and bottomleft_button.player_o and bottomright_button.player_o: game = False o_win = True o_score += 1 if topleft_button.player_o and sideleft_button.player_o and bottomleft_button.player_o: game = False o_win = True o_score += 1 if topcentral_button.player_o and central_button.player_o and bottomcentral_button.player_o: game = False o_win = True o_score += 1 if topright_button.player_o and sideright_button.player_o and bottomright_button.player_o: game = False o_win = True o_score += 1 if topright_button.player_o and central_button.player_o and bottomleft_button.player_o: game = False o_win = True o_score += 1 if topleft_button.player_o and central_button.player_o and bottomright_button.player_o: game = False o_win = True o_score += 1 if central_button.player_on and sideleft_button.player_on and sideright_button.player_on and topcentral_button.player_on and topleft_button.player_on and topright_button.player_on and bottomcentral_button.player_on and bottomleft_button.player_on and bottomright_button.player_on: if not x_win and not o_win: game = False draw = True if x_win: game = False start_menu = True restart() if o_win: game = False start_menu = True restart() if draw: game = False start_menu = True restart() win.fill((0,0,0)) x_scoreboard = font.render("X: {}".format(x_score), 1, (255,255,255)) o_scoreboard = font.render("O: {}".format(o_score), 1, (255,255,255)) win.blit(x_scoreboard, (0,0)) win.blit(o_scoreboard, (screen_width - o_scoreboard.get_rect().width,0)) if start_menu: if not x_win and not o_win and not draw: title = font.render("Tris!", 1, (255,255,255)) win.blit(title, (title.get_rect(center=(screen_width/2, 40)))) if x_win: title = font.render("Player X Win!", 1, (255,255,255)) win.blit(title, (title.get_rect(center=(screen_width/2, 40)))) if o_win: title = font.render("Player O Win!", 1, (255,255,255)) win.blit(title, (title.get_rect(center=(screen_width/2, 40)))) if draw: title = font.render("Draw!", 1, (255,255,255)) win.blit(title, (title.get_rect(center=(screen_width/2, 40)))) start = font.render("Start", 1, (255,255,255)) win.blit(start, (235,235)) create_table() if game == True: create_table() if turn == True: turn_screen = font.render("X Turn", 1, (255,255,255)) win.blit(turn_screen, (turn_screen.get_rect(center=(screen_width/2, 20)))) if turn == False: turn_screen = font.render("O Turn", 1, (255,255,255)) win.blit(turn_screen, (turn_screen.get_rect(center=(screen_width/2, 20)))) if central_button.player_x == True: win.blit(x, (220, 220)) if central_button.player_o == True: win.blit(o, (220, 220)) if sideleft_button.player_x == True: win.blit(x, (120, 220)) if sideleft_button.player_o == True: win.blit(o, (120, 220)) if sideright_button.player_x == True: win.blit(x, (320, 220)) if sideright_button.player_o == True: win.blit(o, (320, 220)) if topcentral_button.player_x == True: win.blit(x, (220, 120)) if topcentral_button.player_o == True: win.blit(o, (220, 120)) if topleft_button.player_x == True: win.blit(x, (120, 120)) if topleft_button.player_o == True: win.blit(o, (120, 120)) if topright_button.player_x == True: win.blit(x, (320, 120)) if topright_button.player_o == True: win.blit(o, (320, 120)) if bottomcentral_button.player_x == True: win.blit(x, (220, 320)) if bottomcentral_button.player_o == True: win.blit(o, (220, 320)) if bottomleft_button.player_x == True: win.blit(x, (120, 320)) if bottomleft_button.player_o == True: win.blit(o, (120, 320)) if bottomright_button.player_x == True: win.blit(x, (320, 320)) if bottomright_button.player_o == True: win.blit(o, (320, 320)) pygame.display.update() pygame.quit()<file_sep>altgraph==0.16.1 future==0.17.1 macholib==1.11 pefile==2018.8.8 pygame==1.9.4 PyInstaller>=3.6 pywin32-ctypes==0.2.0
23dcc00b674a47248a15a1e96d0e73e26896a027
[ "Markdown", "Python", "Text" ]
3
Markdown
AndreaErario/Tris
d00adad40ba09e00068cb71f74c318463c265a30
de77a2e70a7d41e85e423a1a2101cc69a049e1a7
refs/heads/master
<repo_name>oconnellamethyst/csci1103<file_sep>/Week08/lab07-code/Generate.java // Ask for a starting number and use methods to generate the Collatz // sequence from there. Print it on the screen using a method. public class Generate { public static void main(String args[]){ System.out.println("Enter starting number:"); int n = TextIO.getInt(); int arr[] = Collatz.collatzArray(n); if(arr == null){ System.out.printf("Invalid input: %d\n",n); } else{ Collatz.printArray("STEP","VALUE",arr); } } } <file_sep>/Week11/week11notes.md ## Week 11 Notes <file_sep>/Week12/lab11-code/Critter.java // Represent a creature of some kind public class Critter{ private String kind; private String eats; private double ferocity; public Critter(String kind, double ferocity){ this.kind = kind; ferocity = ferocity; } public String getEats(){ return this.eats; } public void addToMenu(String kind){ this.eats += kind + " "; } public static void encounter(Critter a, Critter b){ if(a.ferocity > b.ferocity){ System.out.printf("%s would beat %s\n", a.kind,b.kind); } else if(a.ferocity < b.ferocity){ System.out.printf("%s would beat %s\n", b.kind,a.kind); } else{ System.out.printf("%s and %s grab falafel together\n", b.kind,a.kind); } } } <file_sep>/Week07/week7notes.md ## Week 7 Notes [Ch 4](http://math.hws.edu/javanotes/c4/index.html) <file_sep>/Week07/08-static-methods-code/MethodPatterns.java // Demonstrates a couple common patterns in simple methods: error // check before proceeding with main algorithm and returning in the // middle of a loop. public class MethodPatterns{ // Sum elements in arr[] between start and stop-1. Returns 0 if // either start or stop are beyond array bounds. public static int sumRange(int arr[], int start, int stop){ // Check for range of start and stop if(start < 0 || stop > arr.length){ return 0; } // Range okay, sum elements int sum = 0; for(int i=start; i<stop; i++){ sum += arr[i]; } return sum; } // Return first index of c in String s. If c is not present in s, // return -1. public static int containsChar(String s, char c){ // Search for character c for(int i=0; i<s.length(); i++){ if(s.charAt(i) == c){ return i; // found, return } } // all chars checked, none matched c return -1; } public static void main(String args[]){ int arr[] = {5, 10, 15, 20, 25, 30}; System.out.printf("sumRange(arr, 1, 4): %d\n", sumRange(arr, 1, 4)); System.out.printf("sumRange(arr, 0, 11): %d\n", sumRange(arr, 0, 11)); System.out.printf("sumRange(arr, -4, 1): %d\n", sumRange(arr, -4, 1)); System.out.printf("containsChar(\"Hello\", 'o'): %d\n", containsChar("Hello",'o')); System.out.printf("containsChar(\"Hello\", 'l'): %d\n", containsChar("Hello",'l')); System.out.printf("containsChar(\"Hello\", 'z'): %d\n", containsChar("Hello",'z')); } } <file_sep>/Week11/lab10-code/GrowableStackTests.java import org.junit.*; import org.junit.Test; import static org.junit.Assert.*; import java.util.*; public class GrowableStackTests { public static void main(String args[]){ org.junit.runner.JUnitCore.main("GrowableStackTests"); } @Test public void growablestack_grow1(){ GrowableStack stack = new GrowableStack(2); stack.push("A"); stack.push("B"); stack.push("C"); assertEquals("C" , stack.getTop()); assertEquals(4 , stack.getCapacity()); assertEquals(3 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_grow2(){ GrowableStack stack = new GrowableStack(1); stack.push("A"); assertEquals("A" , stack.getTop()); assertEquals(1 , stack.getCapacity()); assertEquals(1 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); stack.push("B"); assertEquals("B" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(2 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); stack.push("C"); assertEquals("C" , stack.getTop()); assertEquals(4 , stack.getCapacity()); assertEquals(3 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); stack.push("D"); assertEquals("D" , stack.getTop()); assertEquals(4 , stack.getCapacity()); assertEquals(4 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); stack.push("E"); assertEquals("E" , stack.getTop()); assertEquals(8 , stack.getCapacity()); assertEquals(5 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_growtoString1(){ String expect,actual,msg; GrowableStack stack = new GrowableStack(1); stack.push("A"); expect = "size: 1\n"+ "0 : A\n"+ ""; actual = stack.toString(); msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("B"); expect = "size: 2\n"+ "1 : B\n"+ "0 : A\n"+ ""; actual = stack.toString(); msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("C"); expect = "size: 3\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; actual = stack.toString(); msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("D"); expect = "size: 4\n"+ "3 : D\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; actual = stack.toString(); msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("E"); expect = "size: 5\n"+ "4 : E\n"+ "3 : D\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; actual = stack.toString(); msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // } @Test public void growablestack_grow_contentsString(){ String expect,actual,msg; GrowableStack stack = new GrowableStack(1); stack.push("A"); expect = "capacity: 1\n"+ "0 : A\n"+ ""; actual = stack.contentsString(); msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("B"); expect = "capacity: 2\n"+ "0 : A\n"+ "1 : B\n"+ ""; actual = stack.contentsString(); msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("C"); expect = "capacity: 4\n"+ "0 : A\n"+ "1 : B\n"+ "2 : C\n"+ "3 : null\n"+ ""; actual = stack.contentsString(); msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("D"); expect = "capacity: 4\n"+ "0 : A\n"+ "1 : B\n"+ "2 : C\n"+ "3 : D\n"+ ""; actual = stack.contentsString(); msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // stack.push("E"); expect = "capacity: 8\n"+ "0 : A\n"+ "1 : B\n"+ "2 : C\n"+ "3 : D\n"+ "4 : E\n"+ "5 : null\n"+ "6 : null\n"+ "7 : null\n"+ ""; actual = stack.contentsString(); msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); // } @Test public void growablestack_constructor1(){ GrowableStack stack = new GrowableStack(5); } @Test public void growablestack_constructor2(){ GrowableStack stack = new GrowableStack(2); } @Test public void growablestack_basicAccessors1(){ GrowableStack stack = new GrowableStack(5); assertEquals(5 , stack.getCapacity()); assertEquals(0 , stack.getSize()); assertEquals(true , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_basicAccessors2(){ GrowableStack stack = new GrowableStack(2); assertEquals(2 , stack.getCapacity()); assertEquals(0 , stack.getSize()); assertEquals(true , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_pushTop1(){ GrowableStack stack = new GrowableStack(2); stack.push("A"); assertEquals("A" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(1 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_pushTop2(){ GrowableStack stack = new GrowableStack(2); stack.push("A"); stack.push("B"); assertEquals("B" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(2 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_pushTop3(){ GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); assertEquals("D" , stack.getTop()); assertEquals(5 , stack.getCapacity()); assertEquals(4 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_pushTop4(){ GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); assertEquals("E" , stack.getTop()); assertEquals(5 , stack.getCapacity()); assertEquals(5 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_getTopEmpty1(){ GrowableStack stack = new GrowableStack(2); try{ String t = stack.getTop(); } catch(RuntimeException e){ if(e.getMessage().equals("Stack empty")){ return; // pass } } fail("Should throw an exception with message 'Stack empty'"); } @Test public void growablestack_getTopEmpty2(){ GrowableStack stack = new GrowableStack(5); try{ String t = stack.getTop(); } catch(RuntimeException e){ if(e.getMessage().equals("Stack empty")){ return; // pass } } fail("Should throw an exception with message 'Stack empty'"); } @Test public void growablestack_pop1(){ GrowableStack stack = new GrowableStack(2); stack.push("A"); stack.pop(); assertEquals(2 , stack.getCapacity()); assertEquals(0 , stack.getSize()); assertEquals(true , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_pop2(){ GrowableStack stack = new GrowableStack(2); stack.push("A"); stack.push("B"); stack.pop(); assertEquals("A" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(1 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_pop3(){ GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.pop(); stack.push("C"); stack.push("D"); stack.pop(); assertEquals("C" , stack.getTop()); assertEquals(5 , stack.getCapacity()); assertEquals(2 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void growablestack_toString1(){ String expect = "size: 0\n" + ""; GrowableStack stack = new GrowableStack(2); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_toString2(){ String expect = "size: 1\n"+ "0 : A\n"+ ""; GrowableStack stack = new GrowableStack(2); stack.push("A"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_toString3(){ String expect = "size: 2\n"+ "1 : B\n"+ "0 : A\n"+ ""; GrowableStack stack = new GrowableStack(2); stack.push("A"); stack.push("B"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_toString4(){ String expect = "size: 3\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_toString5(){ String expect = "size: 5\n"+ "4 : E\n"+ "3 : D\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_toString6(){ String expect = "size: 3\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); stack.pop(); stack.pop(); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_toString7(){ String expect = "size: 0\n"+ ""; GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); stack.pop(); stack.pop(); stack.pop(); stack.pop(); stack.pop(); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_contentsString1(){ String expect = "capacity: 2\n"+ "0 : null\n"+ "1 : null\n"+ ""; GrowableStack stack = new GrowableStack(2); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_contentsString2(){ String expect = "capacity: 3\n"+ "0 : A\n"+ "1 : B\n"+ "2 : null\n"+ ""; GrowableStack stack = new GrowableStack(3); stack.push("A"); stack.push("B"); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_contentsString3(){ String expect = "capacity: 5\n"+ "0 : A\n"+ "1 : B\n"+ "2 : C\n"+ "3 : D\n"+ "4 : E\n"+ ""; GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void growablestack_contentsString4(){ String expect = "capacity: 5\n"+ "0 : A\n"+ "1 : C\n"+ "2 : D\n"+ "3 : null\n"+ "4 : null\n"+ ""; GrowableStack stack = new GrowableStack(5); stack.push("A"); stack.push("B"); stack.pop(); stack.push("C"); stack.push("D"); stack.push("E"); stack.pop(); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } } <file_sep>/Week04/lab03-code/SequenceTypeTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class SequenceTypeTests extends KTests { /*Main method runs tests in this file*/ public static void main(String args[]) { org.junit.runner.JUnitCore.main("SequenceTypeTests"); } @Test public void SequenceType_main1() { String input = "1 2 3 4"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 1 2 3 4 is: Strictly Increasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main2() { String input = "4 4 4 4"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 4 4 4 4 is: All Equal\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main3() { String input = "1 2 4 8"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 1 2 4 8 is: Strictly Increasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main4() { String input = "1 4 5 5"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 1 4 5 5 is: Non-Decreasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main5() { String input = "3 -1 -1 -4"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 3 -1 -1 -4 is: Non-Increasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main6() { String input = "10 7 2 -1"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 10 7 2 -1 is: Strictly Decreasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main7() { String input = "2 4 1 9"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 2 4 1 9 is: No particular order\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main8() { String input = "9 4 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 9 4 2 1 is: Strictly Decreasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main9() { String input = "1 3 4 4"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 1 3 4 4 is: Non-Decreasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SequenceType_main10() { String input = "1129 316 316 -12315"; TextIO.readStream(new StringReader(input)); String expect = "Enter 4 integers (ex: 1 3 2 5):\n"+ "Sequence 1129 316 316 -12315 is: Non-Increasing\n"+ ""; SequenceType.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week13/12-advanced-io-code/SumStringInts.java // Demo to sum integers from // different strings import java.util.Scanner; public class SumStringInts{ public static void main(String args[]){ Scanner input; int total; String nums1 = "1 2 3 4"; input = new Scanner(nums1); total = 0; while(input.hasNext()){ int num = input.nextInt(); total += num; } System.out.printf("Total: %d\n", total); String nums2 = "10 30 50 70 90"; input = new Scanner(nums2); total = 0; while(input.hasNext()){ int num = input.nextInt(); total += num; } System.out.printf("Total: %d\n", total); } } <file_sep>/Week02/lab01-code/lab01.command amethyst@Callisto:~$ cd KauffmanUofM/ amethyst@Callisto:~/KauffmanUofM$ cd csci1103/ amethyst@Callisto:~/KauffmanUofM/csci1103$ cd Week02 amethyst@Callisto:~/KauffmanUofM/csci1103/Week02$ ls 02-input-types-code lab01-code MyCode week2notes.md amethyst@Callisto:~/KauffmanUofM/csci1103/Week02$ cd lab01-code/ amethyst@Callisto:~/KauffmanUofM/csci1103/Week02/lab01-code$ javac HelloLabCLI.java amethyst@Callisto:~/KauffmanUofM/csci1103/Week02/lab01-code$ java HelloLabCLI Hello, Lab! amethyst@Callisto:~/KauffmanUofM/csci1103/Week02/lab01-code$ javac CSWisdom.java amethyst@Callisto:~/KauffmanUofM/csci1103/Week02/lab01-code$ java CSWisdom If in physics there's something you don't understand, you can always hide behind the uncharted depths of nature. You can always blame God. You didn't make it so complex yourself. But if your program doesn't work, there is no one to hide behind. You cannot hide behind an obstinate nature. If it doesn't work, you've messed up. - <NAME> amethyst@Callisto:~/KauffmanUofM/csci1103/Week02/lab01-code$ javac -cp junit-1103.jar:. *.java amethyst@Callisto:~/KauffmanUofM/csci1103/Week02/lab01-code$ java -cp junit-1103.jar:. Lab01Tests JUnit version 4.12 .. Time: 0.008 OK (2 tests) <file_sep>/Week15/p5-tests/KTests.java // Utility routines for tests: open individual problem test files in // DrJava to run them. Doing // // > java -cp junit-1103.jar:. KTests // // will run all tests on the command line. import org.junit.*; import static org.junit.Assert.*; import org.junit.rules.*; import java.io.*; import java.util.*; public class KTests { // Run all tests for this project from the command line public static void main(String args[]) { org.junit.runner.JUnitCore.main("VoteTests","TallyTests","ElectionTests"); } // Default timeout for all testss = 1 second @Rule public Timeout globalTimeout = Timeout.seconds(2); // Black magic to enable access to name of running test via // name.getMethodName(). Useful for creating input/output files // based on the name of the test. @Rule public TestName name = new TestName(); // Controls whether actual output is printed on its own static boolean SHOW_ACTUAL = true; // false; // Used by each test to capture output static ByteArrayOutputStream localOut, localErr; static PrintStream sysOut, sysErr; // Passed to main methods for no arguments static String [] empty = {}; // Save the stdin and stderr as we'll be messing with them for tests @BeforeClass public static void setUp() throws Exception { sysOut = System.out; sysErr = System.err; } // Before every test is run, reset the streams to capture // stdout/stderr @Before public void setUpStreams() { localOut = new ByteArrayOutputStream(); localErr = new ByteArrayOutputStream(); System.setOut(new PrintStream(localOut)); System.setErr(new PrintStream(localErr)); } // After every test, restore stdout/stderr @After public void cleanUpStreams() { System.setOut(null); System.setErr(null); System.setOut(sysOut); System.setErr(sysErr); } // Create a side-by-side diff of two strings compared line by // line. Allows multiline headers for both arguments but both // headers must have the same number of lines. x and y may differ in // number of lines. public static String simpleDiff2(String xhead, String x, String yhead, String y, String tail) { String firstDiff = null; String xheads[] = xhead.split("\n"); String yheads[] = yhead.split("\n"); String xs[] = x.split("\n",-1); String ys[] = y.split("\n",-1); String sep = " "; String dif = " **** "; // Calculate the maximum width of all fields int maxWidth = 0; for(String s : xheads){ maxWidth = s.length() > maxWidth ? s.length() : maxWidth; } for(String s : yheads){ maxWidth = s.length() > maxWidth ? s.length() : maxWidth; } for(String s : xs){ maxWidth = s.length() > maxWidth ? s.length() : maxWidth; } for(String s : ys){ maxWidth = s.length() > maxWidth ? s.length() : maxWidth; } maxWidth = tail.length() > maxWidth ? tail.length() : maxWidth; // Max width format String fmt = String.format("%%-%ds",maxWidth); // Contents of entire diff StringBuilder sb = new StringBuilder(); // Add on headers for(int i = 0; i<xheads.length; i++){ sb.append(String.format(fmt,xheads[i])); sb.append(sep); sb.append(String.format(fmt,yheads[i])); sb.append("\n"); } // Construct the side-by-side diff for(int i = 0; i<xs.length || i<ys.length; i++){ if(i<xs.length && i<ys.length){ // both exist, compare String diffLine = diffLine(xs[i],ys[i],xheads[0],yheads[0]); if(diffLine!=null && firstDiff==null){ firstDiff = String.format("Difference at line %d\n%s", i,diffLine); sb.insert(0,firstDiff); } sb.append(String.format(fmt,xs[i])); String mid = xs[i].equals(ys[i]) ? sep : dif; sb.append(mid); sb.append(String.format(fmt,ys[i])); sb.append("\n"); } else if(i<xs.length){ // only x left sb.append(String.format(fmt,xs[i])); sb.append(dif); sb.append(String.format(fmt,tail)); sb.append("\n"); } else if(i<ys.length){ // only y left sb.append(String.format(fmt,tail)); sb.append(dif); sb.append(String.format(fmt,ys[i])); sb.append("\n"); } else{ throw new RuntimeException("Something fishy's going on here..."); } } // Add on tail sb.append(String.format(fmt,tail)); String mid = sep; sb.append(mid); sb.append(String.format(fmt,tail)); sb.append("\n"); return sb.toString(); } // Check that the expected and actual output match. If not, show an // error message that indicates which lines don't match. public static String checkOutput(String args[], String expect, String actual){ // String actualNewline = actual.replaceAll("\\r?\\n","\n"); // Eliminate windows linebreaks String actualWS = normalizeWhitespace(actual); // eliminate whitespace differences String expectWS = normalizeWhitespace(expect); // eliminate whitespace differences String msg = ""; msg += String.format("Output mismatch\n"); msg += String.format("ARGS[]:\n %s\n",Arrays.toString(args)); msg += String.format("OUTPUT:\n Lines marked with *** differ\n"); msg += simpleDiff2("EXPECT\n------\n",expectWS, "ACTUAL\n------\n",actualWS, "------"); if(SHOW_ACTUAL){ msg += "\n"; msg += "ACTUAL\n"; msg += actual; msg += "\n"; } assertEquals(msg,expectWS,actualWS); return msg; } private static String slurp(String fname) throws Exception{ return new Scanner(new File(fname), "UTF-8").useDelimiter("\\Z").next(); } // public static String normalizeWhitespace(String str){ str = str.replaceAll("\r",""); // eliminate carriage returns for windows str = str.replaceAll(" *\n","\n"); // whitespace endings to newline str = str.replaceAll("\n{2,}","\n"); // multiple empty lines to none str = str.replaceAll("\n{2,}$","\n"); // multiple ending newlines to single return str; } public static String charString(char c){ if(33 <= c && c <= 126){ return String.format("%c",c); } else if(c == ' ') { return " "; } else if(c == '\n'){ return "\\n"; } else if(c == '\n'){ return "\\r"; } else if(c == '\t'){ return "\\t"; } else{ return String.format("??",c); } } public static String charLongString(char c){ if(33 <= c && c <= 126){ return String.format("'%c'",c); } else if(c == ' ') { return "' ' (space)"; } else if(c == '\n'){ return "'\\n' (newline)"; } else if(c == '\n'){ return "'\\r' (carriage return)"; } else if(c == '\t'){ return "'\\t' (tab)"; } else{ return String.format("Control Char %d",c); } } public static void append3(String x, StringBuilder xStr, String y, StringBuilder yStr, StringBuilder diff, int i) { String xs = "", ys = "", ds = "";; if(i < x.length()){ xs = charString(x.charAt(i)); } if(i < y.length()){ ys = charString(y.charAt(i)); } if(!xs.equals(ys)){ ds = "^"; } int len = xs.length() > ys.length() ? xs.length() : ys.length(); String fmt = "%-"+len+"s"; xStr.append( String.format(fmt,xs) ); yStr.append( String.format(fmt,ys) ); if(diff != null){ diff.append( String.format(fmt,ds) ); } } public static String diffLine(String x, String y, String xhead, String yhead) { StringBuilder diff = new StringBuilder(); StringBuilder xStr = new StringBuilder(); StringBuilder yStr = new StringBuilder(); String firstDiff = null; int i; for(i=0; i<x.length() || i<y.length(); i++){ append3(x,xStr,y,yStr,diff,i); if(i<x.length() && i<y.length()){ char xc = x.charAt(i); char yc = y.charAt(i); if(xc != yc){ firstDiff = ""; firstDiff += String.format("char %d different\n",i); firstDiff += String.format("%s: %s\n",xhead, charLongString(xc)); firstDiff += String.format("%s: %s\n",yhead, charLongString(yc)); break; } } else if(i<x.length()){ firstDiff = ""; firstDiff += String.format("length different\n",i); firstDiff += String.format("%s longer than %s\n",xhead,yhead); break; } else if(i<y.length()){ firstDiff = ""; firstDiff += String.format("length different\n",i); firstDiff += String.format("%s longer than %s\n",yhead,xhead); break; } } if(firstDiff == null){ return null; } for(i=i+1; i<x.length(); i++){ append3(x,xStr,y,yStr,null,i); } for(; i<y.length(); i++){ append3(x,xStr,y,yStr,null,i); } String result = ""; result += String.format("%s\n",xStr.toString()); result += String.format("%s\n",yStr.toString()); result += String.format("%s\n",diff.toString()); result += String.format("%s\n",firstDiff); return result; } } <file_sep>/Week15/p5-tests/ElectionTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class ElectionTests extends KTests { // Main method runs tests in this file public static void main(String args[]) { org.junit.runner.JUnitCore.main("ElectionTests"); } @Test public void election_usage() throws Exception{ String args[] = {}; String expect = "usage: java Election <votes.txt>\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_standard() throws Exception{ String args[] = {"votes-standard.txt"}; String expect = "votes-standard.txt : 12 votes read\n"+ "Round 1 : 4 candidates Tally{Francis:0, Claire:0, Heather:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Viktor, Heather, Claire} Tally{Francis:1, Claire:0, Heather:0, Viktor:0}\n"+ " 1 : Claire Vote{Claire, Francis, Heather, Viktor} Tally{Francis:1, Claire:1, Heather:0, Viktor:0}\n"+ " 2 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:1, Claire:1, Heather:1, Viktor:0}\n"+ " 3 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:1, Claire:1, Heather:2, Viktor:0}\n"+ " 4 : Claire Vote{Claire, Francis, Heather, Viktor} Tally{Francis:1, Claire:2, Heather:2, Viktor:0}\n"+ " 5 : Francis Vote{Francis, Heather, Claire, Viktor} Tally{Francis:2, Claire:2, Heather:2, Viktor:0}\n"+ " 6 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:3, Claire:2, Heather:2, Viktor:0}\n"+ " 7 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:3, Claire:2, Heather:3, Viktor:0}\n"+ " 8 : Heather Vote{Heather, Francis, Claire, Viktor} Tally{Francis:3, Claire:2, Heather:4, Viktor:0}\n"+ " 9 : Viktor Vote{Viktor, Francis, Heather, Claire} Tally{Francis:3, Claire:2, Heather:4, Viktor:1}\n"+ "10 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:4, Claire:2, Heather:4, Viktor:1}\n"+ "11 : Heather Vote{Heather, Francis, Claire, Viktor} Tally{Francis:4, Claire:2, Heather:5, Viktor:1}\n"+ "\n"+ "CNT % NAME\n"+ " 4 33.3 Francis\n"+ " 2 16.7 Claire\n"+ " 5 41.7 Heather\n"+ " 1 8.3 Viktor\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: Viktor\n"+ "\n"+ "Round 2 : 3 candidates Tally{Francis:0, Claire:0, Heather:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Viktor, Heather, Claire} Tally{Francis:1, Claire:0, Heather:0}\n"+ " 1 : Claire Vote{Claire, Francis, Heather, Viktor} Tally{Francis:1, Claire:1, Heather:0}\n"+ " 2 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:1, Claire:1, Heather:1}\n"+ " 3 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:1, Claire:1, Heather:2}\n"+ " 4 : Claire Vote{Claire, Francis, Heather, Viktor} Tally{Francis:1, Claire:2, Heather:2}\n"+ " 5 : Francis Vote{Francis, Heather, Claire, Viktor} Tally{Francis:2, Claire:2, Heather:2}\n"+ " 6 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:3, Claire:2, Heather:2}\n"+ " 7 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:3, Claire:2, Heather:3}\n"+ " 8 : Heather Vote{Heather, Francis, Claire, Viktor} Tally{Francis:3, Claire:2, Heather:4}\n"+ " 9 : Francis Vote{Viktor, Francis, Heather, Claire} Tally{Francis:4, Claire:2, Heather:4}\n"+ "10 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:5, Claire:2, Heather:4}\n"+ "11 : Heather Vote{Heather, Francis, Claire, Viktor} Tally{Francis:5, Claire:2, Heather:5}\n"+ "\n"+ "CNT % NAME\n"+ " 5 41.7 Francis\n"+ " 2 16.7 Claire\n"+ " 5 41.7 Heather\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: Claire\n"+ "\n"+ "Round 3 : 2 candidates Tally{Francis:0, Heather:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Viktor, Heather, Claire} Tally{Francis:1, Heather:0}\n"+ " 1 : Francis Vote{Claire, Francis, Heather, Viktor} Tally{Francis:2, Heather:0}\n"+ " 2 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:2, Heather:1}\n"+ " 3 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:2, Heather:2}\n"+ " 4 : Francis Vote{Claire, Francis, Heather, Viktor} Tally{Francis:3, Heather:2}\n"+ " 5 : Francis Vote{Francis, Heather, Claire, Viktor} Tally{Francis:4, Heather:2}\n"+ " 6 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:5, Heather:2}\n"+ " 7 : Heather Vote{Heather, Claire, Francis, Viktor} Tally{Francis:5, Heather:3}\n"+ " 8 : Heather Vote{Heather, Francis, Claire, Viktor} Tally{Francis:5, Heather:4}\n"+ " 9 : Francis Vote{Viktor, Francis, Heather, Claire} Tally{Francis:6, Heather:4}\n"+ "10 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:7, Heather:4}\n"+ "11 : Heather Vote{Heather, Francis, Claire, Viktor} Tally{Francis:7, Heather:5}\n"+ "\n"+ "CNT % NAME\n"+ " 7 58.3 Francis\n"+ " 5 41.7 Heather\n"+ "\n"+ "WINNER: Francis \n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_1round() throws Exception{ String args[] = {"votes-1round.txt"}; String expect = "votes-1round.txt : 7 votes read\n"+ "Round 1 : 4 candidates Tally{Francis:0, Claire:0, Heather:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:1, Claire:0, Heather:0, Viktor:0}\n"+ " 1 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:2, Claire:0, Heather:0, Viktor:0}\n"+ " 2 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:3, Claire:0, Heather:0, Viktor:0}\n"+ " 3 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:4, Claire:0, Heather:0, Viktor:0}\n"+ " 4 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:4, Claire:0, Heather:0, Viktor:1}\n"+ " 5 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:4, Claire:0, Heather:0, Viktor:2}\n"+ " 6 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:4, Claire:1, Heather:0, Viktor:2}\n"+ "\n"+ "CNT % NAME\n"+ " 4 57.1 Francis\n"+ " 1 14.3 Claire\n"+ " 0 0.0 Heather\n"+ " 2 28.6 Viktor\n"+ "\n"+ "WINNER: Francis\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_2waytie() throws Exception{ String args[] = {"votes-2waytie.txt"}; String expect = "votes-2waytie.txt : 6 votes read\n"+ "Round 1 : 4 candidates Tally{Francis:0, Claire:0, Heather:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:0, Claire:0, Heather:0, Viktor:1}\n"+ " 1 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:0, Claire:0, Heather:0, Viktor:2}\n"+ " 2 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:0, Claire:0, Heather:0, Viktor:3}\n"+ " 3 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:0, Claire:1, Heather:0, Viktor:3}\n"+ " 4 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:0, Claire:2, Heather:0, Viktor:3}\n"+ " 5 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:0, Claire:3, Heather:0, Viktor:3}\n"+ "\n"+ "CNT % NAME\n"+ " 0 0.0 Francis\n"+ " 3 50.0 Claire\n"+ " 0 0.0 Heather\n"+ " 3 50.0 Viktor\n"+ "\n"+ "2 minimum vote candidates\n"+ "Eliminating: Francis\n"+ "Eliminating: Heather\n"+ "\n"+ "Round 2 : 2 candidates Tally{Claire:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Claire:0, Viktor:1}\n"+ " 1 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Claire:0, Viktor:2}\n"+ " 2 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Claire:0, Viktor:3}\n"+ " 3 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Claire:1, Viktor:3}\n"+ " 4 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Claire:2, Viktor:3}\n"+ " 5 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Claire:3, Viktor:3}\n"+ "\n"+ "CNT % NAME\n"+ " 3 50.0 Claire\n"+ " 3 50.0 Viktor\n"+ "\n"+ "ALL WAY TIE BETWEEN:\n"+ "Claire\n"+ "Viktor\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_3cands() throws Exception{ String args[] = {"votes-3cands.txt"}; String expect = "votes-3cands.txt : 13 votes read\n"+ "Round 1 : 3 candidates Tally{Francis:0, Freddie:0, Edmond:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Edmond, Freddie} Tally{Francis:1, Freddie:0, Edmond:0}\n"+ " 1 : Edmond Vote{Edmond, Freddie, Francis} Tally{Francis:1, Freddie:0, Edmond:1}\n"+ " 2 : Francis Vote{Francis, Freddie, Edmond} Tally{Francis:2, Freddie:0, Edmond:1}\n"+ " 3 : Francis Vote{Francis, Freddie, Edmond} Tally{Francis:3, Freddie:0, Edmond:1}\n"+ " 4 : Edmond Vote{Edmond, Freddie, Francis} Tally{Francis:3, Freddie:0, Edmond:2}\n"+ " 5 : Edmond Vote{Edmond, Francis, Freddie} Tally{Francis:3, Freddie:0, Edmond:3}\n"+ " 6 : Edmond Vote{Edmond, Freddie, Francis} Tally{Francis:3, Freddie:0, Edmond:4}\n"+ " 7 : Francis Vote{Francis, Freddie, Edmond} Tally{Francis:4, Freddie:0, Edmond:4}\n"+ " 8 : Edmond Vote{Edmond, Freddie, Francis} Tally{Francis:4, Freddie:0, Edmond:5}\n"+ " 9 : Edmond Vote{Edmond, Francis, Freddie} Tally{Francis:4, Freddie:0, Edmond:6}\n"+ "10 : Edmond Vote{Edmond, Freddie, Francis} Tally{Francis:4, Freddie:0, Edmond:7}\n"+ "11 : Freddie Vote{Freddie, Edmond, Francis} Tally{Francis:4, Freddie:1, Edmond:7}\n"+ "12 : Freddie Vote{Freddie, Edmond, Francis} Tally{Francis:4, Freddie:2, Edmond:7}\n"+ "\n"+ "CNT % NAME\n"+ " 4 30.8 Francis\n"+ " 2 15.4 Freddie\n"+ " 7 53.8 Edmond\n"+ "\n"+ "WINNER: Edmond\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_3waytie() throws Exception{ String args[] = {"votes-3waytie.txt"}; String expect = "votes-3waytie.txt : 6 votes read\n"+ "Round 1 : 4 candidates Tally{Francis:0, Claire:0, Heather:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:1, Claire:0, Heather:0, Viktor:0}\n"+ " 1 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:2, Claire:0, Heather:0, Viktor:0}\n"+ " 2 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:2, Claire:0, Heather:0, Viktor:1}\n"+ " 3 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:2, Claire:0, Heather:0, Viktor:2}\n"+ " 4 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:2, Claire:1, Heather:0, Viktor:2}\n"+ " 5 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:2, Claire:2, Heather:0, Viktor:2}\n"+ "\n"+ "CNT % NAME\n"+ " 2 33.3 Francis\n"+ " 2 33.3 Claire\n"+ " 0 0.0 Heather\n"+ " 2 33.3 Viktor\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: Heather\n"+ "\n"+ "Round 2 : 3 candidates Tally{Francis:0, Claire:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:1, Claire:0, Viktor:0}\n"+ " 1 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:2, Claire:0, Viktor:0}\n"+ " 2 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:2, Claire:0, Viktor:1}\n"+ " 3 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:2, Claire:0, Viktor:2}\n"+ " 4 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:2, Claire:1, Viktor:2}\n"+ " 5 : Claire Vote{Claire, Heather, Viktor, Francis} Tally{Francis:2, Claire:2, Viktor:2}\n"+ "\n"+ "CNT % NAME\n"+ " 2 33.3 Francis\n"+ " 2 33.3 Claire\n"+ " 2 33.3 Viktor\n"+ "\n"+ "ALL WAY TIE BETWEEN:\n"+ "Francis\n"+ "Claire\n"+ "Viktor\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_5cands() throws Exception{ String args[] = {"votes-5cands.txt"}; String expect = "votes-5cands.txt : 5 votes read\n"+ "Round 1 : 5 candidates Tally{A:0, B:0, C:0, D:0, E:0}\n"+ "Transcript:\n"+ " 0 : C Vote{C, A, B, D, E} Tally{A:0, B:0, C:1, D:0, E:0}\n"+ " 1 : D Vote{D, C, E, B, A} Tally{A:0, B:0, C:1, D:1, E:0}\n"+ " 2 : C Vote{C, B, A, D, E} Tally{A:0, B:0, C:2, D:1, E:0}\n"+ " 3 : A Vote{A, B, C, D, E} Tally{A:1, B:0, C:2, D:1, E:0}\n"+ " 4 : A Vote{A, B, D, C, E} Tally{A:2, B:0, C:2, D:1, E:0}\n"+ "\n"+ "CNT % NAME\n"+ " 2 40.0 A\n"+ " 0 0.0 B\n"+ " 2 40.0 C\n"+ " 1 20.0 D\n"+ " 0 0.0 E\n"+ "\n"+ "2 minimum vote candidates\n"+ "Eliminating: B\n"+ "Eliminating: E\n"+ "\n"+ "Round 2 : 3 candidates Tally{A:0, C:0, D:0}\n"+ "Transcript:\n"+ " 0 : C Vote{C, A, B, D, E} Tally{A:0, C:1, D:0}\n"+ " 1 : D Vote{D, C, E, B, A} Tally{A:0, C:1, D:1}\n"+ " 2 : C Vote{C, B, A, D, E} Tally{A:0, C:2, D:1}\n"+ " 3 : A Vote{A, B, C, D, E} Tally{A:1, C:2, D:1}\n"+ " 4 : A Vote{A, B, D, C, E} Tally{A:2, C:2, D:1}\n"+ "\n"+ "CNT % NAME\n"+ " 2 40.0 A\n"+ " 2 40.0 C\n"+ " 1 20.0 D\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: D\n"+ "\n"+ "Round 3 : 2 candidates Tally{A:0, C:0}\n"+ "Transcript:\n"+ " 0 : C Vote{C, A, B, D, E} Tally{A:0, C:1}\n"+ " 1 : C Vote{D, C, E, B, A} Tally{A:0, C:2}\n"+ " 2 : C Vote{C, B, A, D, E} Tally{A:0, C:3}\n"+ " 3 : A Vote{A, B, C, D, E} Tally{A:1, C:3}\n"+ " 4 : A Vote{A, B, D, C, E} Tally{A:2, C:3}\n"+ "\n"+ "CNT % NAME\n"+ " 2 40.0 A\n"+ " 3 60.0 C\n"+ "\n"+ "WINNER: C\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_drop2() throws Exception{ String args[] = {"votes-drop2.txt"}; String expect = "votes-drop2.txt : 7 votes read\n"+ "Round 1 : 4 candidates Tally{Francis:0, Claire:0, Heather:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:1, Claire:0, Heather:0, Viktor:0}\n"+ " 1 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:2, Claire:0, Heather:0, Viktor:0}\n"+ " 2 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:3, Claire:0, Heather:0, Viktor:0}\n"+ " 3 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:3, Claire:0, Heather:0, Viktor:1}\n"+ " 4 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:3, Claire:0, Heather:0, Viktor:2}\n"+ " 5 : Heather Vote{Heather, Viktor, Claire, Francis} Tally{Francis:3, Claire:0, Heather:1, Viktor:2}\n"+ " 6 : Heather Vote{Heather, Viktor, Claire, Francis} Tally{Francis:3, Claire:0, Heather:2, Viktor:2}\n"+ "\n"+ "CNT % NAME\n"+ " 3 42.9 Francis\n"+ " 0 0.0 Claire\n"+ " 2 28.6 Heather\n"+ " 2 28.6 Viktor\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: Claire\n"+ "\n"+ "Round 2 : 3 candidates Tally{Francis:0, Heather:0, Viktor:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:1, Heather:0, Viktor:0}\n"+ " 1 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:2, Heather:0, Viktor:0}\n"+ " 2 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:3, Heather:0, Viktor:0}\n"+ " 3 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:3, Heather:0, Viktor:1}\n"+ " 4 : Viktor Vote{Viktor, Heather, Claire, Francis} Tally{Francis:3, Heather:0, Viktor:2}\n"+ " 5 : Heather Vote{Heather, Viktor, Claire, Francis} Tally{Francis:3, Heather:1, Viktor:2}\n"+ " 6 : Heather Vote{Heather, Viktor, Claire, Francis} Tally{Francis:3, Heather:2, Viktor:2}\n"+ "\n"+ "CNT % NAME\n"+ " 3 42.9 Francis\n"+ " 2 28.6 Heather\n"+ " 2 28.6 Viktor\n"+ "\n"+ "2 minimum vote candidates\n"+ "Eliminating: Heather\n"+ "Eliminating: Viktor\n"+ "\n"+ "Round 3 : 1 candidates Tally{Francis:0}\n"+ "Transcript:\n"+ " 0 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:1}\n"+ " 1 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:2}\n"+ " 2 : Francis Vote{Francis, Claire, Heather, Viktor} Tally{Francis:3}\n"+ " 3 : Francis Vote{Viktor, Heather, Claire, Francis} Tally{Francis:4}\n"+ " 4 : Francis Vote{Viktor, Heather, Claire, Francis} Tally{Francis:5}\n"+ " 5 : Francis Vote{Heather, Viktor, Claire, Francis} Tally{Francis:6}\n"+ " 6 : Francis Vote{Heather, Viktor, Claire, Francis} Tally{Francis:7}\n"+ "\n"+ "CNT % NAME\n"+ " 7 100.0 Francis\n"+ "\n"+ "WINNER: Francis\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_many() throws Exception{ String args[] = {"votes-many.txt"}; String expect = "votes-many.txt : 20 votes read\n"+ "Round 1 : 8 candidates Tally{A:0, B:0, C:0, D:0, E:0, F:0, G:0, H:0}\n"+ "Transcript:\n"+ " 0 : D Vote{D, G, B, A, E, C, F, H} Tally{A:0, B:0, C:0, D:1, E:0, F:0, G:0, H:0}\n"+ " 1 : H Vote{H, D, C, B, A, G, F, E} Tally{A:0, B:0, C:0, D:1, E:0, F:0, G:0, H:1}\n"+ " 2 : A Vote{A, E, G, C, H, B, F, D} Tally{A:1, B:0, C:0, D:1, E:0, F:0, G:0, H:1}\n"+ " 3 : E Vote{E, A, D, G, C, B, H, F} Tally{A:1, B:0, C:0, D:1, E:1, F:0, G:0, H:1}\n"+ " 4 : C Vote{C, F, A, B, E, H, D, G} Tally{A:1, B:0, C:1, D:1, E:1, F:0, G:0, H:1}\n"+ " 5 : H Vote{H, A, G, D, E, F, B, C} Tally{A:1, B:0, C:1, D:1, E:1, F:0, G:0, H:2}\n"+ " 6 : A Vote{A, F, D, E, B, H, C, G} Tally{A:2, B:0, C:1, D:1, E:1, F:0, G:0, H:2}\n"+ " 7 : D Vote{D, E, A, H, G, C, F, B} Tally{A:2, B:0, C:1, D:2, E:1, F:0, G:0, H:2}\n"+ " 8 : H Vote{H, F, C, D, B, A, E, G} Tally{A:2, B:0, C:1, D:2, E:1, F:0, G:0, H:3}\n"+ " 9 : B Vote{B, G, F, C, D, E, H, A} Tally{A:2, B:1, C:1, D:2, E:1, F:0, G:0, H:3}\n"+ "10 : C Vote{C, A, D, H, B, F, G, E} Tally{A:2, B:1, C:2, D:2, E:1, F:0, G:0, H:3}\n"+ "11 : C Vote{C, B, E, G, H, A, F, D} Tally{A:2, B:1, C:3, D:2, E:1, F:0, G:0, H:3}\n"+ "12 : F Vote{F, A, E, D, B, G, C, H} Tally{A:2, B:1, C:3, D:2, E:1, F:1, G:0, H:3}\n"+ "13 : E Vote{E, B, D, F, C, G, H, A} Tally{A:2, B:1, C:3, D:2, E:2, F:1, G:0, H:3}\n"+ "14 : A Vote{A, B, D, E, G, F, H, C} Tally{A:3, B:1, C:3, D:2, E:2, F:1, G:0, H:3}\n"+ "15 : H Vote{H, F, C, B, D, G, E, A} Tally{A:3, B:1, C:3, D:2, E:2, F:1, G:0, H:4}\n"+ "16 : H Vote{H, F, B, D, C, A, G, E} Tally{A:3, B:1, C:3, D:2, E:2, F:1, G:0, H:5}\n"+ "17 : D Vote{D, A, C, G, H, E, F, B} Tally{A:3, B:1, C:3, D:3, E:2, F:1, G:0, H:5}\n"+ "18 : D Vote{D, G, H, E, B, A, C, F} Tally{A:3, B:1, C:3, D:4, E:2, F:1, G:0, H:5}\n"+ "19 : E Vote{E, C, D, A, G, B, F, H} Tally{A:3, B:1, C:3, D:4, E:3, F:1, G:0, H:5}\n"+ "\n"+ "CNT % NAME\n"+ " 3 15.0 A\n"+ " 1 5.0 B\n"+ " 3 15.0 C\n"+ " 4 20.0 D\n"+ " 3 15.0 E\n"+ " 1 5.0 F\n"+ " 0 0.0 G\n"+ " 5 25.0 H\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: G\n"+ "\n"+ "Round 2 : 7 candidates Tally{A:0, B:0, C:0, D:0, E:0, F:0, H:0}\n"+ "Transcript:\n"+ " 0 : D Vote{D, G, B, A, E, C, F, H} Tally{A:0, B:0, C:0, D:1, E:0, F:0, H:0}\n"+ " 1 : H Vote{H, D, C, B, A, G, F, E} Tally{A:0, B:0, C:0, D:1, E:0, F:0, H:1}\n"+ " 2 : A Vote{A, E, G, C, H, B, F, D} Tally{A:1, B:0, C:0, D:1, E:0, F:0, H:1}\n"+ " 3 : E Vote{E, A, D, G, C, B, H, F} Tally{A:1, B:0, C:0, D:1, E:1, F:0, H:1}\n"+ " 4 : C Vote{C, F, A, B, E, H, D, G} Tally{A:1, B:0, C:1, D:1, E:1, F:0, H:1}\n"+ " 5 : H Vote{H, A, G, D, E, F, B, C} Tally{A:1, B:0, C:1, D:1, E:1, F:0, H:2}\n"+ " 6 : A Vote{A, F, D, E, B, H, C, G} Tally{A:2, B:0, C:1, D:1, E:1, F:0, H:2}\n"+ " 7 : D Vote{D, E, A, H, G, C, F, B} Tally{A:2, B:0, C:1, D:2, E:1, F:0, H:2}\n"+ " 8 : H Vote{H, F, C, D, B, A, E, G} Tally{A:2, B:0, C:1, D:2, E:1, F:0, H:3}\n"+ " 9 : B Vote{B, G, F, C, D, E, H, A} Tally{A:2, B:1, C:1, D:2, E:1, F:0, H:3}\n"+ "10 : C Vote{C, A, D, H, B, F, G, E} Tally{A:2, B:1, C:2, D:2, E:1, F:0, H:3}\n"+ "11 : C Vote{C, B, E, G, H, A, F, D} Tally{A:2, B:1, C:3, D:2, E:1, F:0, H:3}\n"+ "12 : F Vote{F, A, E, D, B, G, C, H} Tally{A:2, B:1, C:3, D:2, E:1, F:1, H:3}\n"+ "13 : E Vote{E, B, D, F, C, G, H, A} Tally{A:2, B:1, C:3, D:2, E:2, F:1, H:3}\n"+ "14 : A Vote{A, B, D, E, G, F, H, C} Tally{A:3, B:1, C:3, D:2, E:2, F:1, H:3}\n"+ "15 : H Vote{H, F, C, B, D, G, E, A} Tally{A:3, B:1, C:3, D:2, E:2, F:1, H:4}\n"+ "16 : H Vote{H, F, B, D, C, A, G, E} Tally{A:3, B:1, C:3, D:2, E:2, F:1, H:5}\n"+ "17 : D Vote{D, A, C, G, H, E, F, B} Tally{A:3, B:1, C:3, D:3, E:2, F:1, H:5}\n"+ "18 : D Vote{D, G, H, E, B, A, C, F} Tally{A:3, B:1, C:3, D:4, E:2, F:1, H:5}\n"+ "19 : E Vote{E, C, D, A, G, B, F, H} Tally{A:3, B:1, C:3, D:4, E:3, F:1, H:5}\n"+ "\n"+ "CNT % NAME\n"+ " 3 15.0 A\n"+ " 1 5.0 B\n"+ " 3 15.0 C\n"+ " 4 20.0 D\n"+ " 3 15.0 E\n"+ " 1 5.0 F\n"+ " 5 25.0 H\n"+ "\n"+ "2 minimum vote candidates\n"+ "Eliminating: B\n"+ "Eliminating: F\n"+ "\n"+ "Round 3 : 5 candidates Tally{A:0, C:0, D:0, E:0, H:0}\n"+ "Transcript:\n"+ " 0 : D Vote{D, G, B, A, E, C, F, H} Tally{A:0, C:0, D:1, E:0, H:0}\n"+ " 1 : H Vote{H, D, C, B, A, G, F, E} Tally{A:0, C:0, D:1, E:0, H:1}\n"+ " 2 : A Vote{A, E, G, C, H, B, F, D} Tally{A:1, C:0, D:1, E:0, H:1}\n"+ " 3 : E Vote{E, A, D, G, C, B, H, F} Tally{A:1, C:0, D:1, E:1, H:1}\n"+ " 4 : C Vote{C, F, A, B, E, H, D, G} Tally{A:1, C:1, D:1, E:1, H:1}\n"+ " 5 : H Vote{H, A, G, D, E, F, B, C} Tally{A:1, C:1, D:1, E:1, H:2}\n"+ " 6 : A Vote{A, F, D, E, B, H, C, G} Tally{A:2, C:1, D:1, E:1, H:2}\n"+ " 7 : D Vote{D, E, A, H, G, C, F, B} Tally{A:2, C:1, D:2, E:1, H:2}\n"+ " 8 : H Vote{H, F, C, D, B, A, E, G} Tally{A:2, C:1, D:2, E:1, H:3}\n"+ " 9 : C Vote{B, G, F, C, D, E, H, A} Tally{A:2, C:2, D:2, E:1, H:3}\n"+ "10 : C Vote{C, A, D, H, B, F, G, E} Tally{A:2, C:3, D:2, E:1, H:3}\n"+ "11 : C Vote{C, B, E, G, H, A, F, D} Tally{A:2, C:4, D:2, E:1, H:3}\n"+ "12 : A Vote{F, A, E, D, B, G, C, H} Tally{A:3, C:4, D:2, E:1, H:3}\n"+ "13 : E Vote{E, B, D, F, C, G, H, A} Tally{A:3, C:4, D:2, E:2, H:3}\n"+ "14 : A Vote{A, B, D, E, G, F, H, C} Tally{A:4, C:4, D:2, E:2, H:3}\n"+ "15 : H Vote{H, F, C, B, D, G, E, A} Tally{A:4, C:4, D:2, E:2, H:4}\n"+ "16 : H Vote{H, F, B, D, C, A, G, E} Tally{A:4, C:4, D:2, E:2, H:5}\n"+ "17 : D Vote{D, A, C, G, H, E, F, B} Tally{A:4, C:4, D:3, E:2, H:5}\n"+ "18 : D Vote{D, G, H, E, B, A, C, F} Tally{A:4, C:4, D:4, E:2, H:5}\n"+ "19 : E Vote{E, C, D, A, G, B, F, H} Tally{A:4, C:4, D:4, E:3, H:5}\n"+ "\n"+ "CNT % NAME\n"+ " 4 20.0 A\n"+ " 4 20.0 C\n"+ " 4 20.0 D\n"+ " 3 15.0 E\n"+ " 5 25.0 H\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: E\n"+ "\n"+ "Round 4 : 4 candidates Tally{A:0, C:0, D:0, H:0}\n"+ "Transcript:\n"+ " 0 : D Vote{D, G, B, A, E, C, F, H} Tally{A:0, C:0, D:1, H:0}\n"+ " 1 : H Vote{H, D, C, B, A, G, F, E} Tally{A:0, C:0, D:1, H:1}\n"+ " 2 : A Vote{A, E, G, C, H, B, F, D} Tally{A:1, C:0, D:1, H:1}\n"+ " 3 : A Vote{E, A, D, G, C, B, H, F} Tally{A:2, C:0, D:1, H:1}\n"+ " 4 : C Vote{C, F, A, B, E, H, D, G} Tally{A:2, C:1, D:1, H:1}\n"+ " 5 : H Vote{H, A, G, D, E, F, B, C} Tally{A:2, C:1, D:1, H:2}\n"+ " 6 : A Vote{A, F, D, E, B, H, C, G} Tally{A:3, C:1, D:1, H:2}\n"+ " 7 : D Vote{D, E, A, H, G, C, F, B} Tally{A:3, C:1, D:2, H:2}\n"+ " 8 : H Vote{H, F, C, D, B, A, E, G} Tally{A:3, C:1, D:2, H:3}\n"+ " 9 : C Vote{B, G, F, C, D, E, H, A} Tally{A:3, C:2, D:2, H:3}\n"+ "10 : C Vote{C, A, D, H, B, F, G, E} Tally{A:3, C:3, D:2, H:3}\n"+ "11 : C Vote{C, B, E, G, H, A, F, D} Tally{A:3, C:4, D:2, H:3}\n"+ "12 : A Vote{F, A, E, D, B, G, C, H} Tally{A:4, C:4, D:2, H:3}\n"+ "13 : D Vote{E, B, D, F, C, G, H, A} Tally{A:4, C:4, D:3, H:3}\n"+ "14 : A Vote{A, B, D, E, G, F, H, C} Tally{A:5, C:4, D:3, H:3}\n"+ "15 : H Vote{H, F, C, B, D, G, E, A} Tally{A:5, C:4, D:3, H:4}\n"+ "16 : H Vote{H, F, B, D, C, A, G, E} Tally{A:5, C:4, D:3, H:5}\n"+ "17 : D Vote{D, A, C, G, H, E, F, B} Tally{A:5, C:4, D:4, H:5}\n"+ "18 : D Vote{D, G, H, E, B, A, C, F} Tally{A:5, C:4, D:5, H:5}\n"+ "19 : C Vote{E, C, D, A, G, B, F, H} Tally{A:5, C:5, D:5, H:5}\n"+ "\n"+ "CNT % NAME\n"+ " 5 25.0 A\n"+ " 5 25.0 C\n"+ " 5 25.0 D\n"+ " 5 25.0 H\n"+ "\n"+ "ALL WAY TIE BETWEEN:\n"+ "A\n"+ "C\n"+ "D\n"+ "H\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } @Test public void election_stress() throws Exception{ String args[] = {"votes-stress.txt"}; String expect = "votes-stress.txt : 50 votes read\n"+ "Round 1 : 9 candidates Tally{A:0, B:0, C:0, D:0, E:0, F:0, G:0, H:0, I:0}\n"+ "Transcript:\n"+ " 0 : F Vote{F, I, B, G, D, A, C, E, H} Tally{A:0, B:0, C:0, D:0, E:0, F:1, G:0, H:0, I:0}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{A:0, B:0, C:1, D:0, E:0, F:1, G:0, H:0, I:0}\n"+ " 2 : B Vote{B, C, H, F, I, G, A, E, D} Tally{A:0, B:1, C:1, D:0, E:0, F:1, G:0, H:0, I:0}\n"+ " 3 : I Vote{I, H, B, E, A, F, C, G, D} Tally{A:0, B:1, C:1, D:0, E:0, F:1, G:0, H:0, I:1}\n"+ " 4 : B Vote{B, G, E, C, H, A, I, D, F} Tally{A:0, B:2, C:1, D:0, E:0, F:1, G:0, H:0, I:1}\n"+ " 5 : D Vote{D, H, G, E, B, F, A, C, I} Tally{A:0, B:2, C:1, D:1, E:0, F:1, G:0, H:0, I:1}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{A:0, B:2, C:1, D:1, E:0, F:1, G:1, H:0, I:1}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{A:0, B:2, C:1, D:1, E:0, F:1, G:2, H:0, I:1}\n"+ " 8 : F Vote{F, H, A, I, D, B, G, C, E} Tally{A:0, B:2, C:1, D:1, E:0, F:2, G:2, H:0, I:1}\n"+ " 9 : D Vote{D, A, E, H, F, C, G, I, B} Tally{A:0, B:2, C:1, D:2, E:0, F:2, G:2, H:0, I:1}\n"+ "10 : D Vote{D, F, G, B, C, I, E, H, A} Tally{A:0, B:2, C:1, D:3, E:0, F:2, G:2, H:0, I:1}\n"+ "11 : F Vote{F, G, C, B, D, I, E, A, H} Tally{A:0, B:2, C:1, D:3, E:0, F:3, G:2, H:0, I:1}\n"+ "12 : E Vote{E, I, B, C, H, A, D, G, F} Tally{A:0, B:2, C:1, D:3, E:1, F:3, G:2, H:0, I:1}\n"+ "13 : E Vote{E, I, F, D, B, G, C, H, A} Tally{A:0, B:2, C:1, D:3, E:2, F:3, G:2, H:0, I:1}\n"+ "14 : B Vote{B, C, G, H, I, F, D, E, A} Tally{A:0, B:3, C:1, D:3, E:2, F:3, G:2, H:0, I:1}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{A:0, B:3, C:1, D:3, E:2, F:3, G:3, H:0, I:1}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{A:0, B:3, C:1, D:3, E:2, F:3, G:4, H:0, I:1}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{A:0, B:3, C:1, D:3, E:2, F:3, G:5, H:0, I:1}\n"+ "18 : E Vote{E, C, D, B, G, A, F, I, H} Tally{A:0, B:3, C:1, D:3, E:3, F:3, G:5, H:0, I:1}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{A:0, B:3, C:2, D:3, E:3, F:3, G:5, H:0, I:1}\n"+ "20 : A Vote{A, G, E, B, I, H, C, D, F} Tally{A:1, B:3, C:2, D:3, E:3, F:3, G:5, H:0, I:1}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{A:1, B:3, C:3, D:3, E:3, F:3, G:5, H:0, I:1}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{A:1, B:3, C:3, D:3, E:3, F:3, G:6, H:0, I:1}\n"+ "23 : E Vote{E, A, F, G, B, D, I, H, C} Tally{A:1, B:3, C:3, D:3, E:4, F:3, G:6, H:0, I:1}\n"+ "24 : H Vote{H, G, I, F, B, D, C, A, E} Tally{A:1, B:3, C:3, D:3, E:4, F:3, G:6, H:1, I:1}\n"+ "25 : E Vote{E, F, I, B, D, A, C, G, H} Tally{A:1, B:3, C:3, D:3, E:5, F:3, G:6, H:1, I:1}\n"+ "26 : F Vote{F, A, E, D, B, G, H, I, C} Tally{A:1, B:3, C:3, D:3, E:5, F:4, G:6, H:1, I:1}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{A:1, B:3, C:3, D:3, E:5, F:4, G:7, H:1, I:1}\n"+ "28 : F Vote{F, I, H, E, A, D, C, B, G} Tally{A:1, B:3, C:3, D:3, E:5, F:5, G:7, H:1, I:1}\n"+ "29 : D Vote{D, C, H, F, E, I, A, B, G} Tally{A:1, B:3, C:3, D:4, E:5, F:5, G:7, H:1, I:1}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{A:1, B:3, C:4, D:4, E:5, F:5, G:7, H:1, I:1}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{A:1, B:3, C:5, D:4, E:5, F:5, G:7, H:1, I:1}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{A:1, B:3, C:6, D:4, E:5, F:5, G:7, H:1, I:1}\n"+ "33 : B Vote{B, A, H, F, C, I, D, G, E} Tally{A:1, B:4, C:6, D:4, E:5, F:5, G:7, H:1, I:1}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{A:1, B:4, C:6, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "35 : B Vote{B, D, I, C, A, H, E, F, G} Tally{A:1, B:5, C:6, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "36 : H Vote{H, E, A, C, F, G, B, I, D} Tally{A:1, B:5, C:6, D:4, E:5, F:5, G:8, H:2, I:1}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{A:1, B:5, C:7, D:4, E:5, F:5, G:8, H:2, I:1}\n"+ "38 : I Vote{I, D, C, F, A, B, E, H, G} Tally{A:1, B:5, C:7, D:4, E:5, F:5, G:8, H:2, I:2}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{A:1, B:5, C:7, D:4, E:5, F:5, G:9, H:2, I:2}\n"+ "40 : F Vote{F, H, E, G, C, B, D, A, I} Tally{A:1, B:5, C:7, D:4, E:5, F:6, G:9, H:2, I:2}\n"+ "41 : A Vote{A, D, C, F, H, G, I, B, E} Tally{A:2, B:5, C:7, D:4, E:5, F:6, G:9, H:2, I:2}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{A:2, B:5, C:8, D:4, E:5, F:6, G:9, H:2, I:2}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{A:2, B:5, C:9, D:4, E:5, F:6, G:9, H:2, I:2}\n"+ "44 : D Vote{D, G, B, A, C, E, F, H, I} Tally{A:2, B:5, C:9, D:5, E:5, F:6, G:9, H:2, I:2}\n"+ "45 : B Vote{B, H, G, A, F, D, I, C, E} Tally{A:2, B:6, C:9, D:5, E:5, F:6, G:9, H:2, I:2}\n"+ "46 : H Vote{H, I, A, D, G, F, E, C, B} Tally{A:2, B:6, C:9, D:5, E:5, F:6, G:9, H:3, I:2}\n"+ "47 : F Vote{F, G, B, I, D, H, C, A, E} Tally{A:2, B:6, C:9, D:5, E:5, F:7, G:9, H:3, I:2}\n"+ "48 : I Vote{I, H, G, E, B, F, C, D, A} Tally{A:2, B:6, C:9, D:5, E:5, F:7, G:9, H:3, I:3}\n"+ "49 : D Vote{D, H, A, E, I, B, C, F, G} Tally{A:2, B:6, C:9, D:6, E:5, F:7, G:9, H:3, I:3}\n"+ "\n"+ "CNT % NAME\n"+ " 2 4.0 A\n"+ " 6 12.0 B\n"+ " 9 18.0 C\n"+ " 6 12.0 D\n"+ " 5 10.0 E\n"+ " 7 14.0 F\n"+ " 9 18.0 G\n"+ " 3 6.0 H\n"+ " 3 6.0 I\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: A\n"+ "\n"+ "Round 2 : 8 candidates Tally{B:0, C:0, D:0, E:0, F:0, G:0, H:0, I:0}\n"+ "Transcript:\n"+ " 0 : F Vote{F, I, B, G, D, A, C, E, H} Tally{B:0, C:0, D:0, E:0, F:1, G:0, H:0, I:0}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{B:0, C:1, D:0, E:0, F:1, G:0, H:0, I:0}\n"+ " 2 : B Vote{B, C, H, F, I, G, A, E, D} Tally{B:1, C:1, D:0, E:0, F:1, G:0, H:0, I:0}\n"+ " 3 : I Vote{I, H, B, E, A, F, C, G, D} Tally{B:1, C:1, D:0, E:0, F:1, G:0, H:0, I:1}\n"+ " 4 : B Vote{B, G, E, C, H, A, I, D, F} Tally{B:2, C:1, D:0, E:0, F:1, G:0, H:0, I:1}\n"+ " 5 : D Vote{D, H, G, E, B, F, A, C, I} Tally{B:2, C:1, D:1, E:0, F:1, G:0, H:0, I:1}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{B:2, C:1, D:1, E:0, F:1, G:1, H:0, I:1}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{B:2, C:1, D:1, E:0, F:1, G:2, H:0, I:1}\n"+ " 8 : F Vote{F, H, A, I, D, B, G, C, E} Tally{B:2, C:1, D:1, E:0, F:2, G:2, H:0, I:1}\n"+ " 9 : D Vote{D, A, E, H, F, C, G, I, B} Tally{B:2, C:1, D:2, E:0, F:2, G:2, H:0, I:1}\n"+ "10 : D Vote{D, F, G, B, C, I, E, H, A} Tally{B:2, C:1, D:3, E:0, F:2, G:2, H:0, I:1}\n"+ "11 : F Vote{F, G, C, B, D, I, E, A, H} Tally{B:2, C:1, D:3, E:0, F:3, G:2, H:0, I:1}\n"+ "12 : E Vote{E, I, B, C, H, A, D, G, F} Tally{B:2, C:1, D:3, E:1, F:3, G:2, H:0, I:1}\n"+ "13 : E Vote{E, I, F, D, B, G, C, H, A} Tally{B:2, C:1, D:3, E:2, F:3, G:2, H:0, I:1}\n"+ "14 : B Vote{B, C, G, H, I, F, D, E, A} Tally{B:3, C:1, D:3, E:2, F:3, G:2, H:0, I:1}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{B:3, C:1, D:3, E:2, F:3, G:3, H:0, I:1}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{B:3, C:1, D:3, E:2, F:3, G:4, H:0, I:1}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{B:3, C:1, D:3, E:2, F:3, G:5, H:0, I:1}\n"+ "18 : E Vote{E, C, D, B, G, A, F, I, H} Tally{B:3, C:1, D:3, E:3, F:3, G:5, H:0, I:1}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{B:3, C:2, D:3, E:3, F:3, G:5, H:0, I:1}\n"+ "20 : G Vote{A, G, E, B, I, H, C, D, F} Tally{B:3, C:2, D:3, E:3, F:3, G:6, H:0, I:1}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{B:3, C:3, D:3, E:3, F:3, G:6, H:0, I:1}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{B:3, C:3, D:3, E:3, F:3, G:7, H:0, I:1}\n"+ "23 : E Vote{E, A, F, G, B, D, I, H, C} Tally{B:3, C:3, D:3, E:4, F:3, G:7, H:0, I:1}\n"+ "24 : H Vote{H, G, I, F, B, D, C, A, E} Tally{B:3, C:3, D:3, E:4, F:3, G:7, H:1, I:1}\n"+ "25 : E Vote{E, F, I, B, D, A, C, G, H} Tally{B:3, C:3, D:3, E:5, F:3, G:7, H:1, I:1}\n"+ "26 : F Vote{F, A, E, D, B, G, H, I, C} Tally{B:3, C:3, D:3, E:5, F:4, G:7, H:1, I:1}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{B:3, C:3, D:3, E:5, F:4, G:8, H:1, I:1}\n"+ "28 : F Vote{F, I, H, E, A, D, C, B, G} Tally{B:3, C:3, D:3, E:5, F:5, G:8, H:1, I:1}\n"+ "29 : D Vote{D, C, H, F, E, I, A, B, G} Tally{B:3, C:3, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{B:3, C:4, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{B:3, C:5, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{B:3, C:6, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "33 : B Vote{B, A, H, F, C, I, D, G, E} Tally{B:4, C:6, D:4, E:5, F:5, G:8, H:1, I:1}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{B:4, C:6, D:4, E:5, F:5, G:9, H:1, I:1}\n"+ "35 : B Vote{B, D, I, C, A, H, E, F, G} Tally{B:5, C:6, D:4, E:5, F:5, G:9, H:1, I:1}\n"+ "36 : H Vote{H, E, A, C, F, G, B, I, D} Tally{B:5, C:6, D:4, E:5, F:5, G:9, H:2, I:1}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{B:5, C:7, D:4, E:5, F:5, G:9, H:2, I:1}\n"+ "38 : I Vote{I, D, C, F, A, B, E, H, G} Tally{B:5, C:7, D:4, E:5, F:5, G:9, H:2, I:2}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{B:5, C:7, D:4, E:5, F:5, G:10, H:2, I:2}\n"+ "40 : F Vote{F, H, E, G, C, B, D, A, I} Tally{B:5, C:7, D:4, E:5, F:6, G:10, H:2, I:2}\n"+ "41 : D Vote{A, D, C, F, H, G, I, B, E} Tally{B:5, C:7, D:5, E:5, F:6, G:10, H:2, I:2}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{B:5, C:8, D:5, E:5, F:6, G:10, H:2, I:2}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{B:5, C:9, D:5, E:5, F:6, G:10, H:2, I:2}\n"+ "44 : D Vote{D, G, B, A, C, E, F, H, I} Tally{B:5, C:9, D:6, E:5, F:6, G:10, H:2, I:2}\n"+ "45 : B Vote{B, H, G, A, F, D, I, C, E} Tally{B:6, C:9, D:6, E:5, F:6, G:10, H:2, I:2}\n"+ "46 : H Vote{H, I, A, D, G, F, E, C, B} Tally{B:6, C:9, D:6, E:5, F:6, G:10, H:3, I:2}\n"+ "47 : F Vote{F, G, B, I, D, H, C, A, E} Tally{B:6, C:9, D:6, E:5, F:7, G:10, H:3, I:2}\n"+ "48 : I Vote{I, H, G, E, B, F, C, D, A} Tally{B:6, C:9, D:6, E:5, F:7, G:10, H:3, I:3}\n"+ "49 : D Vote{D, H, A, E, I, B, C, F, G} Tally{B:6, C:9, D:7, E:5, F:7, G:10, H:3, I:3}\n"+ "\n"+ "CNT % NAME\n"+ " 6 12.0 B\n"+ " 9 18.0 C\n"+ " 7 14.0 D\n"+ " 5 10.0 E\n"+ " 7 14.0 F\n"+ " 10 20.0 G\n"+ " 3 6.0 H\n"+ " 3 6.0 I\n"+ "\n"+ "2 minimum vote candidates\n"+ "Eliminating: H\n"+ "Eliminating: I\n"+ "\n"+ "Round 3 : 6 candidates Tally{B:0, C:0, D:0, E:0, F:0, G:0}\n"+ "Transcript:\n"+ " 0 : F Vote{F, I, B, G, D, A, C, E, H} Tally{B:0, C:0, D:0, E:0, F:1, G:0}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{B:0, C:1, D:0, E:0, F:1, G:0}\n"+ " 2 : B Vote{B, C, H, F, I, G, A, E, D} Tally{B:1, C:1, D:0, E:0, F:1, G:0}\n"+ " 3 : B Vote{I, H, B, E, A, F, C, G, D} Tally{B:2, C:1, D:0, E:0, F:1, G:0}\n"+ " 4 : B Vote{B, G, E, C, H, A, I, D, F} Tally{B:3, C:1, D:0, E:0, F:1, G:0}\n"+ " 5 : D Vote{D, H, G, E, B, F, A, C, I} Tally{B:3, C:1, D:1, E:0, F:1, G:0}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{B:3, C:1, D:1, E:0, F:1, G:1}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{B:3, C:1, D:1, E:0, F:1, G:2}\n"+ " 8 : F Vote{F, H, A, I, D, B, G, C, E} Tally{B:3, C:1, D:1, E:0, F:2, G:2}\n"+ " 9 : D Vote{D, A, E, H, F, C, G, I, B} Tally{B:3, C:1, D:2, E:0, F:2, G:2}\n"+ "10 : D Vote{D, F, G, B, C, I, E, H, A} Tally{B:3, C:1, D:3, E:0, F:2, G:2}\n"+ "11 : F Vote{F, G, C, B, D, I, E, A, H} Tally{B:3, C:1, D:3, E:0, F:3, G:2}\n"+ "12 : E Vote{E, I, B, C, H, A, D, G, F} Tally{B:3, C:1, D:3, E:1, F:3, G:2}\n"+ "13 : E Vote{E, I, F, D, B, G, C, H, A} Tally{B:3, C:1, D:3, E:2, F:3, G:2}\n"+ "14 : B Vote{B, C, G, H, I, F, D, E, A} Tally{B:4, C:1, D:3, E:2, F:3, G:2}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{B:4, C:1, D:3, E:2, F:3, G:3}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{B:4, C:1, D:3, E:2, F:3, G:4}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{B:4, C:1, D:3, E:2, F:3, G:5}\n"+ "18 : E Vote{E, C, D, B, G, A, F, I, H} Tally{B:4, C:1, D:3, E:3, F:3, G:5}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{B:4, C:2, D:3, E:3, F:3, G:5}\n"+ "20 : G Vote{A, G, E, B, I, H, C, D, F} Tally{B:4, C:2, D:3, E:3, F:3, G:6}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{B:4, C:3, D:3, E:3, F:3, G:6}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{B:4, C:3, D:3, E:3, F:3, G:7}\n"+ "23 : E Vote{E, A, F, G, B, D, I, H, C} Tally{B:4, C:3, D:3, E:4, F:3, G:7}\n"+ "24 : G Vote{H, G, I, F, B, D, C, A, E} Tally{B:4, C:3, D:3, E:4, F:3, G:8}\n"+ "25 : E Vote{E, F, I, B, D, A, C, G, H} Tally{B:4, C:3, D:3, E:5, F:3, G:8}\n"+ "26 : F Vote{F, A, E, D, B, G, H, I, C} Tally{B:4, C:3, D:3, E:5, F:4, G:8}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{B:4, C:3, D:3, E:5, F:4, G:9}\n"+ "28 : F Vote{F, I, H, E, A, D, C, B, G} Tally{B:4, C:3, D:3, E:5, F:5, G:9}\n"+ "29 : D Vote{D, C, H, F, E, I, A, B, G} Tally{B:4, C:3, D:4, E:5, F:5, G:9}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{B:4, C:4, D:4, E:5, F:5, G:9}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{B:4, C:5, D:4, E:5, F:5, G:9}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{B:4, C:6, D:4, E:5, F:5, G:9}\n"+ "33 : B Vote{B, A, H, F, C, I, D, G, E} Tally{B:5, C:6, D:4, E:5, F:5, G:9}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{B:5, C:6, D:4, E:5, F:5, G:10}\n"+ "35 : B Vote{B, D, I, C, A, H, E, F, G} Tally{B:6, C:6, D:4, E:5, F:5, G:10}\n"+ "36 : E Vote{H, E, A, C, F, G, B, I, D} Tally{B:6, C:6, D:4, E:6, F:5, G:10}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{B:6, C:7, D:4, E:6, F:5, G:10}\n"+ "38 : D Vote{I, D, C, F, A, B, E, H, G} Tally{B:6, C:7, D:5, E:6, F:5, G:10}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{B:6, C:7, D:5, E:6, F:5, G:11}\n"+ "40 : F Vote{F, H, E, G, C, B, D, A, I} Tally{B:6, C:7, D:5, E:6, F:6, G:11}\n"+ "41 : D Vote{A, D, C, F, H, G, I, B, E} Tally{B:6, C:7, D:6, E:6, F:6, G:11}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{B:6, C:8, D:6, E:6, F:6, G:11}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{B:6, C:9, D:6, E:6, F:6, G:11}\n"+ "44 : D Vote{D, G, B, A, C, E, F, H, I} Tally{B:6, C:9, D:7, E:6, F:6, G:11}\n"+ "45 : B Vote{B, H, G, A, F, D, I, C, E} Tally{B:7, C:9, D:7, E:6, F:6, G:11}\n"+ "46 : D Vote{H, I, A, D, G, F, E, C, B} Tally{B:7, C:9, D:8, E:6, F:6, G:11}\n"+ "47 : F Vote{F, G, B, I, D, H, C, A, E} Tally{B:7, C:9, D:8, E:6, F:7, G:11}\n"+ "48 : G Vote{I, H, G, E, B, F, C, D, A} Tally{B:7, C:9, D:8, E:6, F:7, G:12}\n"+ "49 : D Vote{D, H, A, E, I, B, C, F, G} Tally{B:7, C:9, D:9, E:6, F:7, G:12}\n"+ "\n"+ "CNT % NAME\n"+ " 7 14.0 B\n"+ " 9 18.0 C\n"+ " 9 18.0 D\n"+ " 6 12.0 E\n"+ " 7 14.0 F\n"+ " 12 24.0 G\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: E\n"+ "\n"+ "Round 4 : 5 candidates Tally{B:0, C:0, D:0, F:0, G:0}\n"+ "Transcript:\n"+ " 0 : F Vote{F, I, B, G, D, A, C, E, H} Tally{B:0, C:0, D:0, F:1, G:0}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{B:0, C:1, D:0, F:1, G:0}\n"+ " 2 : B Vote{B, C, H, F, I, G, A, E, D} Tally{B:1, C:1, D:0, F:1, G:0}\n"+ " 3 : B Vote{I, H, B, E, A, F, C, G, D} Tally{B:2, C:1, D:0, F:1, G:0}\n"+ " 4 : B Vote{B, G, E, C, H, A, I, D, F} Tally{B:3, C:1, D:0, F:1, G:0}\n"+ " 5 : D Vote{D, H, G, E, B, F, A, C, I} Tally{B:3, C:1, D:1, F:1, G:0}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{B:3, C:1, D:1, F:1, G:1}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{B:3, C:1, D:1, F:1, G:2}\n"+ " 8 : F Vote{F, H, A, I, D, B, G, C, E} Tally{B:3, C:1, D:1, F:2, G:2}\n"+ " 9 : D Vote{D, A, E, H, F, C, G, I, B} Tally{B:3, C:1, D:2, F:2, G:2}\n"+ "10 : D Vote{D, F, G, B, C, I, E, H, A} Tally{B:3, C:1, D:3, F:2, G:2}\n"+ "11 : F Vote{F, G, C, B, D, I, E, A, H} Tally{B:3, C:1, D:3, F:3, G:2}\n"+ "12 : B Vote{E, I, B, C, H, A, D, G, F} Tally{B:4, C:1, D:3, F:3, G:2}\n"+ "13 : F Vote{E, I, F, D, B, G, C, H, A} Tally{B:4, C:1, D:3, F:4, G:2}\n"+ "14 : B Vote{B, C, G, H, I, F, D, E, A} Tally{B:5, C:1, D:3, F:4, G:2}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{B:5, C:1, D:3, F:4, G:3}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{B:5, C:1, D:3, F:4, G:4}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{B:5, C:1, D:3, F:4, G:5}\n"+ "18 : C Vote{E, C, D, B, G, A, F, I, H} Tally{B:5, C:2, D:3, F:4, G:5}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{B:5, C:3, D:3, F:4, G:5}\n"+ "20 : G Vote{A, G, E, B, I, H, C, D, F} Tally{B:5, C:3, D:3, F:4, G:6}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{B:5, C:4, D:3, F:4, G:6}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{B:5, C:4, D:3, F:4, G:7}\n"+ "23 : F Vote{E, A, F, G, B, D, I, H, C} Tally{B:5, C:4, D:3, F:5, G:7}\n"+ "24 : G Vote{H, G, I, F, B, D, C, A, E} Tally{B:5, C:4, D:3, F:5, G:8}\n"+ "25 : F Vote{E, F, I, B, D, A, C, G, H} Tally{B:5, C:4, D:3, F:6, G:8}\n"+ "26 : F Vote{F, A, E, D, B, G, H, I, C} Tally{B:5, C:4, D:3, F:7, G:8}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{B:5, C:4, D:3, F:7, G:9}\n"+ "28 : F Vote{F, I, H, E, A, D, C, B, G} Tally{B:5, C:4, D:3, F:8, G:9}\n"+ "29 : D Vote{D, C, H, F, E, I, A, B, G} Tally{B:5, C:4, D:4, F:8, G:9}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{B:5, C:5, D:4, F:8, G:9}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{B:5, C:6, D:4, F:8, G:9}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{B:5, C:7, D:4, F:8, G:9}\n"+ "33 : B Vote{B, A, H, F, C, I, D, G, E} Tally{B:6, C:7, D:4, F:8, G:9}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{B:6, C:7, D:4, F:8, G:10}\n"+ "35 : B Vote{B, D, I, C, A, H, E, F, G} Tally{B:7, C:7, D:4, F:8, G:10}\n"+ "36 : C Vote{H, E, A, C, F, G, B, I, D} Tally{B:7, C:8, D:4, F:8, G:10}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{B:7, C:9, D:4, F:8, G:10}\n"+ "38 : D Vote{I, D, C, F, A, B, E, H, G} Tally{B:7, C:9, D:5, F:8, G:10}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{B:7, C:9, D:5, F:8, G:11}\n"+ "40 : F Vote{F, H, E, G, C, B, D, A, I} Tally{B:7, C:9, D:5, F:9, G:11}\n"+ "41 : D Vote{A, D, C, F, H, G, I, B, E} Tally{B:7, C:9, D:6, F:9, G:11}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{B:7, C:10, D:6, F:9, G:11}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{B:7, C:11, D:6, F:9, G:11}\n"+ "44 : D Vote{D, G, B, A, C, E, F, H, I} Tally{B:7, C:11, D:7, F:9, G:11}\n"+ "45 : B Vote{B, H, G, A, F, D, I, C, E} Tally{B:8, C:11, D:7, F:9, G:11}\n"+ "46 : D Vote{H, I, A, D, G, F, E, C, B} Tally{B:8, C:11, D:8, F:9, G:11}\n"+ "47 : F Vote{F, G, B, I, D, H, C, A, E} Tally{B:8, C:11, D:8, F:10, G:11}\n"+ "48 : G Vote{I, H, G, E, B, F, C, D, A} Tally{B:8, C:11, D:8, F:10, G:12}\n"+ "49 : D Vote{D, H, A, E, I, B, C, F, G} Tally{B:8, C:11, D:9, F:10, G:12}\n"+ "\n"+ "CNT % NAME\n"+ " 8 16.0 B\n"+ " 11 22.0 C\n"+ " 9 18.0 D\n"+ " 10 20.0 F\n"+ " 12 24.0 G\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: B\n"+ "\n"+ "Round 5 : 4 candidates Tally{C:0, D:0, F:0, G:0}\n"+ "Transcript:\n"+ " 0 : F Vote{F, I, B, G, D, A, C, E, H} Tally{C:0, D:0, F:1, G:0}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{C:1, D:0, F:1, G:0}\n"+ " 2 : C Vote{B, C, H, F, I, G, A, E, D} Tally{C:2, D:0, F:1, G:0}\n"+ " 3 : F Vote{I, H, B, E, A, F, C, G, D} Tally{C:2, D:0, F:2, G:0}\n"+ " 4 : G Vote{B, G, E, C, H, A, I, D, F} Tally{C:2, D:0, F:2, G:1}\n"+ " 5 : D Vote{D, H, G, E, B, F, A, C, I} Tally{C:2, D:1, F:2, G:1}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{C:2, D:1, F:2, G:2}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{C:2, D:1, F:2, G:3}\n"+ " 8 : F Vote{F, H, A, I, D, B, G, C, E} Tally{C:2, D:1, F:3, G:3}\n"+ " 9 : D Vote{D, A, E, H, F, C, G, I, B} Tally{C:2, D:2, F:3, G:3}\n"+ "10 : D Vote{D, F, G, B, C, I, E, H, A} Tally{C:2, D:3, F:3, G:3}\n"+ "11 : F Vote{F, G, C, B, D, I, E, A, H} Tally{C:2, D:3, F:4, G:3}\n"+ "12 : C Vote{E, I, B, C, H, A, D, G, F} Tally{C:3, D:3, F:4, G:3}\n"+ "13 : F Vote{E, I, F, D, B, G, C, H, A} Tally{C:3, D:3, F:5, G:3}\n"+ "14 : C Vote{B, C, G, H, I, F, D, E, A} Tally{C:4, D:3, F:5, G:3}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{C:4, D:3, F:5, G:4}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{C:4, D:3, F:5, G:5}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{C:4, D:3, F:5, G:6}\n"+ "18 : C Vote{E, C, D, B, G, A, F, I, H} Tally{C:5, D:3, F:5, G:6}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{C:6, D:3, F:5, G:6}\n"+ "20 : G Vote{A, G, E, B, I, H, C, D, F} Tally{C:6, D:3, F:5, G:7}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{C:7, D:3, F:5, G:7}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{C:7, D:3, F:5, G:8}\n"+ "23 : F Vote{E, A, F, G, B, D, I, H, C} Tally{C:7, D:3, F:6, G:8}\n"+ "24 : G Vote{H, G, I, F, B, D, C, A, E} Tally{C:7, D:3, F:6, G:9}\n"+ "25 : F Vote{E, F, I, B, D, A, C, G, H} Tally{C:7, D:3, F:7, G:9}\n"+ "26 : F Vote{F, A, E, D, B, G, H, I, C} Tally{C:7, D:3, F:8, G:9}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{C:7, D:3, F:8, G:10}\n"+ "28 : F Vote{F, I, H, E, A, D, C, B, G} Tally{C:7, D:3, F:9, G:10}\n"+ "29 : D Vote{D, C, H, F, E, I, A, B, G} Tally{C:7, D:4, F:9, G:10}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{C:8, D:4, F:9, G:10}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{C:9, D:4, F:9, G:10}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{C:10, D:4, F:9, G:10}\n"+ "33 : F Vote{B, A, H, F, C, I, D, G, E} Tally{C:10, D:4, F:10, G:10}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{C:10, D:4, F:10, G:11}\n"+ "35 : D Vote{B, D, I, C, A, H, E, F, G} Tally{C:10, D:5, F:10, G:11}\n"+ "36 : C Vote{H, E, A, C, F, G, B, I, D} Tally{C:11, D:5, F:10, G:11}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{C:12, D:5, F:10, G:11}\n"+ "38 : D Vote{I, D, C, F, A, B, E, H, G} Tally{C:12, D:6, F:10, G:11}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{C:12, D:6, F:10, G:12}\n"+ "40 : F Vote{F, H, E, G, C, B, D, A, I} Tally{C:12, D:6, F:11, G:12}\n"+ "41 : D Vote{A, D, C, F, H, G, I, B, E} Tally{C:12, D:7, F:11, G:12}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{C:13, D:7, F:11, G:12}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{C:14, D:7, F:11, G:12}\n"+ "44 : D Vote{D, G, B, A, C, E, F, H, I} Tally{C:14, D:8, F:11, G:12}\n"+ "45 : G Vote{B, H, G, A, F, D, I, C, E} Tally{C:14, D:8, F:11, G:13}\n"+ "46 : D Vote{H, I, A, D, G, F, E, C, B} Tally{C:14, D:9, F:11, G:13}\n"+ "47 : F Vote{F, G, B, I, D, H, C, A, E} Tally{C:14, D:9, F:12, G:13}\n"+ "48 : G Vote{I, H, G, E, B, F, C, D, A} Tally{C:14, D:9, F:12, G:14}\n"+ "49 : D Vote{D, H, A, E, I, B, C, F, G} Tally{C:14, D:10, F:12, G:14}\n"+ "\n"+ "CNT % NAME\n"+ " 14 28.0 C\n"+ " 10 20.0 D\n"+ " 12 24.0 F\n"+ " 14 28.0 G\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: D\n"+ "\n"+ "Round 6 : 3 candidates Tally{C:0, F:0, G:0}\n"+ "Transcript:\n"+ " 0 : F Vote{F, I, B, G, D, A, C, E, H} Tally{C:0, F:1, G:0}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{C:1, F:1, G:0}\n"+ " 2 : C Vote{B, C, H, F, I, G, A, E, D} Tally{C:2, F:1, G:0}\n"+ " 3 : F Vote{I, H, B, E, A, F, C, G, D} Tally{C:2, F:2, G:0}\n"+ " 4 : G Vote{B, G, E, C, H, A, I, D, F} Tally{C:2, F:2, G:1}\n"+ " 5 : G Vote{D, H, G, E, B, F, A, C, I} Tally{C:2, F:2, G:2}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{C:2, F:2, G:3}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{C:2, F:2, G:4}\n"+ " 8 : F Vote{F, H, A, I, D, B, G, C, E} Tally{C:2, F:3, G:4}\n"+ " 9 : F Vote{D, A, E, H, F, C, G, I, B} Tally{C:2, F:4, G:4}\n"+ "10 : F Vote{D, F, G, B, C, I, E, H, A} Tally{C:2, F:5, G:4}\n"+ "11 : F Vote{F, G, C, B, D, I, E, A, H} Tally{C:2, F:6, G:4}\n"+ "12 : C Vote{E, I, B, C, H, A, D, G, F} Tally{C:3, F:6, G:4}\n"+ "13 : F Vote{E, I, F, D, B, G, C, H, A} Tally{C:3, F:7, G:4}\n"+ "14 : C Vote{B, C, G, H, I, F, D, E, A} Tally{C:4, F:7, G:4}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{C:4, F:7, G:5}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{C:4, F:7, G:6}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{C:4, F:7, G:7}\n"+ "18 : C Vote{E, C, D, B, G, A, F, I, H} Tally{C:5, F:7, G:7}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{C:6, F:7, G:7}\n"+ "20 : G Vote{A, G, E, B, I, H, C, D, F} Tally{C:6, F:7, G:8}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{C:7, F:7, G:8}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{C:7, F:7, G:9}\n"+ "23 : F Vote{E, A, F, G, B, D, I, H, C} Tally{C:7, F:8, G:9}\n"+ "24 : G Vote{H, G, I, F, B, D, C, A, E} Tally{C:7, F:8, G:10}\n"+ "25 : F Vote{E, F, I, B, D, A, C, G, H} Tally{C:7, F:9, G:10}\n"+ "26 : F Vote{F, A, E, D, B, G, H, I, C} Tally{C:7, F:10, G:10}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{C:7, F:10, G:11}\n"+ "28 : F Vote{F, I, H, E, A, D, C, B, G} Tally{C:7, F:11, G:11}\n"+ "29 : C Vote{D, C, H, F, E, I, A, B, G} Tally{C:8, F:11, G:11}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{C:9, F:11, G:11}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{C:10, F:11, G:11}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{C:11, F:11, G:11}\n"+ "33 : F Vote{B, A, H, F, C, I, D, G, E} Tally{C:11, F:12, G:11}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{C:11, F:12, G:12}\n"+ "35 : C Vote{B, D, I, C, A, H, E, F, G} Tally{C:12, F:12, G:12}\n"+ "36 : C Vote{H, E, A, C, F, G, B, I, D} Tally{C:13, F:12, G:12}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{C:14, F:12, G:12}\n"+ "38 : C Vote{I, D, C, F, A, B, E, H, G} Tally{C:15, F:12, G:12}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{C:15, F:12, G:13}\n"+ "40 : F Vote{F, H, E, G, C, B, D, A, I} Tally{C:15, F:13, G:13}\n"+ "41 : C Vote{A, D, C, F, H, G, I, B, E} Tally{C:16, F:13, G:13}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{C:17, F:13, G:13}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{C:18, F:13, G:13}\n"+ "44 : G Vote{D, G, B, A, C, E, F, H, I} Tally{C:18, F:13, G:14}\n"+ "45 : G Vote{B, H, G, A, F, D, I, C, E} Tally{C:18, F:13, G:15}\n"+ "46 : G Vote{H, I, A, D, G, F, E, C, B} Tally{C:18, F:13, G:16}\n"+ "47 : F Vote{F, G, B, I, D, H, C, A, E} Tally{C:18, F:14, G:16}\n"+ "48 : G Vote{I, H, G, E, B, F, C, D, A} Tally{C:18, F:14, G:17}\n"+ "49 : C Vote{D, H, A, E, I, B, C, F, G} Tally{C:19, F:14, G:17}\n"+ "\n"+ "CNT % NAME\n"+ " 19 38.0 C\n"+ " 14 28.0 F\n"+ " 17 34.0 G\n"+ "\n"+ "1 minimum vote candidates\n"+ "Eliminating: F\n"+ "\n"+ "Round 7 : 2 candidates Tally{C:0, G:0}\n"+ "Transcript:\n"+ " 0 : G Vote{F, I, B, G, D, A, C, E, H} Tally{C:0, G:1}\n"+ " 1 : C Vote{C, A, B, G, D, H, E, F, I} Tally{C:1, G:1}\n"+ " 2 : C Vote{B, C, H, F, I, G, A, E, D} Tally{C:2, G:1}\n"+ " 3 : C Vote{I, H, B, E, A, F, C, G, D} Tally{C:3, G:1}\n"+ " 4 : G Vote{B, G, E, C, H, A, I, D, F} Tally{C:3, G:2}\n"+ " 5 : G Vote{D, H, G, E, B, F, A, C, I} Tally{C:3, G:3}\n"+ " 6 : G Vote{G, I, B, H, A, F, D, C, E} Tally{C:3, G:4}\n"+ " 7 : G Vote{G, C, I, B, D, H, A, F, E} Tally{C:3, G:5}\n"+ " 8 : G Vote{F, H, A, I, D, B, G, C, E} Tally{C:3, G:6}\n"+ " 9 : C Vote{D, A, E, H, F, C, G, I, B} Tally{C:4, G:6}\n"+ "10 : G Vote{D, F, G, B, C, I, E, H, A} Tally{C:4, G:7}\n"+ "11 : G Vote{F, G, C, B, D, I, E, A, H} Tally{C:4, G:8}\n"+ "12 : C Vote{E, I, B, C, H, A, D, G, F} Tally{C:5, G:8}\n"+ "13 : G Vote{E, I, F, D, B, G, C, H, A} Tally{C:5, G:9}\n"+ "14 : C Vote{B, C, G, H, I, F, D, E, A} Tally{C:6, G:9}\n"+ "15 : G Vote{G, F, I, H, E, A, B, D, C} Tally{C:6, G:10}\n"+ "16 : G Vote{G, I, C, D, E, A, H, F, B} Tally{C:6, G:11}\n"+ "17 : G Vote{G, B, I, H, E, A, F, D, C} Tally{C:6, G:12}\n"+ "18 : C Vote{E, C, D, B, G, A, F, I, H} Tally{C:7, G:12}\n"+ "19 : C Vote{C, E, D, A, G, B, H, F, I} Tally{C:8, G:12}\n"+ "20 : G Vote{A, G, E, B, I, H, C, D, F} Tally{C:8, G:13}\n"+ "21 : C Vote{C, B, F, A, D, G, H, E, I} Tally{C:9, G:13}\n"+ "22 : G Vote{G, I, B, D, F, H, C, A, E} Tally{C:9, G:14}\n"+ "23 : G Vote{E, A, F, G, B, D, I, H, C} Tally{C:9, G:15}\n"+ "24 : G Vote{H, G, I, F, B, D, C, A, E} Tally{C:9, G:16}\n"+ "25 : C Vote{E, F, I, B, D, A, C, G, H} Tally{C:10, G:16}\n"+ "26 : G Vote{F, A, E, D, B, G, H, I, C} Tally{C:10, G:17}\n"+ "27 : G Vote{G, H, D, B, F, I, E, C, A} Tally{C:10, G:18}\n"+ "28 : C Vote{F, I, H, E, A, D, C, B, G} Tally{C:11, G:18}\n"+ "29 : C Vote{D, C, H, F, E, I, A, B, G} Tally{C:12, G:18}\n"+ "30 : C Vote{C, I, H, A, G, D, E, F, B} Tally{C:13, G:18}\n"+ "31 : C Vote{C, I, F, G, E, D, A, B, H} Tally{C:14, G:18}\n"+ "32 : C Vote{C, F, D, A, B, G, E, I, H} Tally{C:15, G:18}\n"+ "33 : C Vote{B, A, H, F, C, I, D, G, E} Tally{C:16, G:18}\n"+ "34 : G Vote{G, C, A, B, I, E, D, F, H} Tally{C:16, G:19}\n"+ "35 : C Vote{B, D, I, C, A, H, E, F, G} Tally{C:17, G:19}\n"+ "36 : C Vote{H, E, A, C, F, G, B, I, D} Tally{C:18, G:19}\n"+ "37 : C Vote{C, G, B, F, I, D, H, A, E} Tally{C:19, G:19}\n"+ "38 : C Vote{I, D, C, F, A, B, E, H, G} Tally{C:20, G:19}\n"+ "39 : G Vote{G, B, F, C, H, D, A, E, I} Tally{C:20, G:20}\n"+ "40 : G Vote{F, H, E, G, C, B, D, A, I} Tally{C:20, G:21}\n"+ "41 : C Vote{A, D, C, F, H, G, I, B, E} Tally{C:21, G:21}\n"+ "42 : C Vote{C, D, F, I, B, E, G, H, A} Tally{C:22, G:21}\n"+ "43 : C Vote{C, D, I, F, B, A, H, E, G} Tally{C:23, G:21}\n"+ "44 : G Vote{D, G, B, A, C, E, F, H, I} Tally{C:23, G:22}\n"+ "45 : G Vote{B, H, G, A, F, D, I, C, E} Tally{C:23, G:23}\n"+ "46 : G Vote{H, I, A, D, G, F, E, C, B} Tally{C:23, G:24}\n"+ "47 : G Vote{F, G, B, I, D, H, C, A, E} Tally{C:23, G:25}\n"+ "48 : G Vote{I, H, G, E, B, F, C, D, A} Tally{C:23, G:26}\n"+ "49 : C Vote{D, H, A, E, I, B, C, F, G} Tally{C:24, G:26}\n"+ "\n"+ "CNT % NAME\n"+ " 24 48.0 C\n"+ " 26 52.0 G\n"+ "\n"+ "WINNER: G\n"+ ""; Election.main(args); String actual = localOut.toString(); checkOutput(args,expect,actual); } } <file_sep>/Week13/13-command-line-arguments-code/CmdArgsPractice.java public class CmdArgsPractice{ public static void main(String args[]){ boolean verboseMode = false; boolean exitImmediately = false; for(int i=0; i<args.length; i++){ System.out.printf("args[%d] is %s\n",i,args[i]); if(args[i].equals("-verbose")){ verboseMode = true; } else if(args[i].equals("-exit")){ exitImmediately = true; } } if(exitImmediately){ //System.exit(10); return; } System.out.println(verboseMode); if(verboseMode){ System.out.println("Extra information"); } } }<file_sep>/Week02/02-input-types-code/BirthdayInput.java // Solution to birthday problem with some extra if/else goodness. public class BirthdayInput{ public static void main(String args[]){ System.out.println("Enter your age:"); int age = TextIO.getInt(); System.out.println("I hear you are " + age); age = age + 1; System.out.println("Next year you will be "+ age); } } <file_sep>/Week08/09-simple-objects-code/omelet-fields-only/OmeletOps.java // Demonstrate use of OmMeth methods for omelets // Show output at the commented lines public class OmeletOps{ public static void main(String args[]){ Omelet standard = new Omelet(); standard.eggs = 2; standard.cheese = 4; standard.cookedFor = 0.0; standard.extras = "ham"; OmMeth.addEgg(standard); OmMeth.cookFor(standard, 2.5); int calories = OmMeth.getCalories(standard); boolean safe = OmMeth.foodPoisoningIminent(standard); System.out.printf("Has %d eggs\n", standard.eggs); // 1 System.out.printf("Has %d calories\n", calories); // 2 System.out.printf("Safe to eat? %b\n", safe); // 3 Omelet coronary = new Omelet(); coronary.eggs = 6; coronary.cheese = 10; Omelet richer = OmMeth.richerOmelet(standard, coronary); System.out.printf("Richer has %d eggs\n", richer.eggs); // 4 } } <file_sep>/Week09/lab08-code/StockMain.java public class StockMain{ public static void main(String args[]){ Stock google = new Stock(); google.symbol = "GOOGL"; google.price = 1000.62; google.numShares = 500; google.name = "Alphabet Inc Class A"; Stock microsoft = new Stock(); microsoft.symbol = "MSFT"; microsoft.price = 79.12; microsoft.numShares = 350; microsoft.name = "Microsoft Corporation"; double funds = 100000.00; System.out.printf("Initial position: funds=$%.2f\n",funds); Stock.printInfo(google); Stock.printInfo(microsoft); Stock transStock; int transShares; double fundChange; System.out.println(); System.out.println("Transaction 1"); transStock = microsoft; transShares = 300; fundChange = Stock.buyMore(transStock, transShares); funds += fundChange; System.out.printf("Buying %d shares of %s: funds=$%.2f\n", transShares, transStock.symbol, funds); Stock.printInfo(google); Stock.printInfo(microsoft); System.out.println(); System.out.println("Transaction 2"); transStock = google; transShares = 400; fundChange = Stock.sellOff(transStock, transShares); funds += fundChange; System.out.printf("Selling %d shares of %s: funds=$%.2f\n", transShares, transStock.symbol, funds); Stock.printInfo(google); Stock.printInfo(microsoft); System.out.println(); System.out.println("Transaction 3"); transStock = google; transShares = 200; fundChange = Stock.sellOff(transStock, transShares); funds += fundChange; System.out.printf("Selling %d shares of %s: funds=$%.2f\n", transShares, transStock.symbol, funds); Stock.printInfo(google); Stock.printInfo(microsoft); } } <file_sep>/Week05/05-arrays-code/in-class/ReverseSequence.java public class ReverseSequence{ public static void main(String args[]) { System.out.println("Enter sequence length:"); } } <file_sep>/Week01/01IntroductionCode/Discrepancy.java // Day 1 exercise to compute the discrepancy in head counts between GTA sections. // Compile with the command line // // $> javac Discrepancy.java // // Run the main method with the command line // // $> java Discrepancy // import java.util.*; public class Discrepancy{ // Compute the discrepancy in head count for the given GTAs; the // secs array is ignored. This version uses ArrayLists to track the // GTAs that have been seen. public static int discrepancy(String [] secs, String [] gtas, int [] counts){ ArrayList<String> gtaNames = new ArrayList<>(); ArrayList<Integer> gtaTotals = new ArrayList<>(); for(int i=0; i<gtas.length; i++){ String gta = gtas[i]; // current gta int count = counts[i]; // current count // Ensure the arrays contains the current gta if(!gtaNames.contains(gta)){ gtaNames.add(gta); gtaTotals.add(0); } int gtaIndex = gtaNames.indexOf(gta); int curTotal = gtaTotals.get(gtaIndex); int newTotal = curTotal + count; gtaTotals.set(gtaIndex,newTotal); } // gtaTotals now contains total counts for each GTA // Scan through and find the min and max totals int minTotal=Integer.MAX_VALUE; int maxTotal=Integer.MIN_VALUE; for(Integer total : gtaTotals){ if(total < minTotal){ minTotal = total; } if(total > maxTotal){ maxTotal = total; } } // discrepancy is the difference between max/min total. int discrepancy = maxTotal - minTotal; return discrepancy; } // Compute the discrepancy in head count for the given GTAs; the // secs array is ignored. This version uses a HashMap to ease the // accumulation of head counts public static int discrepancy2(String [] secs, String [] gtas, int [] counts){ // Map gta names to total counts Map<String,Integer> gtaTotals = new HashMap<String,Integer>(); for(int i=0; i<gtas.length; i++){ String gta = gtas[i]; // current gta int count = counts[i]; // current count // Ensure the map contains the current gta if(!gtaTotals.containsKey(gta)){ gtaTotals.put(gta,0); } int curTotal = gtaTotals.get(gta); int newTotal = curTotal + count; gtaTotals.put(gta,newTotal); } // gtaTotals now contains total counts for each GTA // Scan through and find the min and max totals int minTotal=Integer.MAX_VALUE; int maxTotal=Integer.MIN_VALUE; for(Integer total : gtaTotals.values()){ if(total < minTotal){ minTotal = total; } if(total > maxTotal){ maxTotal = total; } } // discrepancy is the difference between max/min total. int discrepancy = maxTotal - minTotal; return discrepancy; } // Main method to test the discrepancy method public static void main(String args[]){ String secs [] ={"211", "219", "208", "222", "220", "2H1", "205", "207", "206", "209", "210", "212", "221", "218", "214"}; String gtas [] = {"Fardina", "Lubaba", "Yue", "Umang", "Lubaba", "Maryam", "Mingrui", "Yue", "Mingrui", "Parastoo", "Parastoo", "Fardina", "Umang", "Maryam", "Umang"}; int counts [] = {21, 24, 14, 12, 24, 15, 11, 16, 14, 24, 24, 23, 23, 24, 11, }; int discrepancy = discrepancy(secs,gtas,counts); System.out.println(discrepancy); discrepancy = discrepancy2(secs,gtas,counts); System.out.println(discrepancy); } } <file_sep>/Week07/08-static-methods-code/DeepStack.java public class DeepStack{ public static boolean checkLength(String word){ if(word.length() < 10){ return true; } else{ return false; } } public static boolean inRange(double z){ return 25.5 <= z && z < 65.0; } public static boolean doChecks(String name, double x) { boolean nameOK = checkLength(name); boolean xOK = inRange(x); return nameOK || xOK; } public static void main(String args[]){ String candA = "Morty"; double iqA = 47.3; boolean validA = doChecks(candA,iqA); String candB = "<NAME>"; double iqB = 27.8; boolean validB = doChecks(candB,iqA); } } <file_sep>/Week15/15-finale-code/Dog.java import java.util.Scanner; import java.io.File; public class Dog{ private String name; private int age; private boolean likesCats; // Create a instance of Dog with the given parameters // Examples: // Dog d = new Dog("Val", 6, true); // Dog e = new Dog("Stout", 3, false); public Dog(String name, int age, boolean likesCats){ this.name=name; this.age=age; this.likesCats=likesCats; } public String toString(){ return String.format("Dog{%s, %d, %b}", this.name.this.age,this.likesCates); } // Retrieve the name of the dog public String getName(){ return this.name; } // Change the name of the dog to the new name // Examples: // d.rename("Valentine"); // String n = d.getName(); // "Valentine" public void rename(String name){ this.name = name; } // Increase the age of the dog by 1 public void birthday(){ this.age++; } // Change the internal state of the dog so that it likes cats public void trainForCats(){ this.likesCats = true; } // Return whether the dog is appropriate for elderly owners. The dog // must be 8 years or older and must like cats to be appropriate for // elderly owners. public boolean okForElderly(){ return this.age >= 8 && this.likesCats; } // Create a dog from a string of information. Use a Scanner to parse // the string argument. Valid input strings contain the Dog's name, // age, and the word yes or no depending on whether the dog likes // cats. Examples: // Dog d = Dog.fromString("Val 6 yes"); // Dog e = Dog.fromString("Stout 3 no"); public static Dog fromString(String s){ Scanner scan = new Scanner(s); String name = scan.next(); int age = scan.nextInt(); String yesNo = scan.next(); return new Dog(name, age, yesNo.equals("yes")); } // Read dogs from the given file. Count lines in the file using a // Scanner (do not assume a countLines method). Allocate an array of // that size, reset the scanner to beginning of the file, then read // lines and create dogs in the array. Make use of the // Dog.fromString() method. public static Dog [] readDogsFromFile(String filename) throws Exception{ Scanner in = new Scanner(new File(filename)); int lineCount = 0; while(in.hasNextLine()){ in.nextLine(); lineCount++; } in.close(); Dog dogs[] = new Dog[lineCount]; in = new Scanner(new File(filename)); for(int i=0; i<lineCount; i++){ String line = in.nextLine(); dogs[i] = Dog.fromString(line); } in.close(); return dogs; } } <file_sep>/ProgramTemplt.java public class ProgramTemplt { // optional-variable-declarations-and-subroutines /** A description of the program * this program does the following... */ public static void main(String[] args) { // statements like System.out.println() } // optional-variable-declarations-and-subroutines } <file_sep>/Week13/12-advanced-io-code/SumInts.java import java.util.Scanner; public class SumInts{ public static void main(String args[]){ System.out.println("Give me ints, ctrl-d to quit!"); Scanner input = new Scanner(System.in); //int count = 0; int all = 0; System.out.println("Enter an int:"); while(input.hasNext()){ all += input.nextInt(); //all = all + count; System.out.println("Enter an int:"); } System.out.println("End of input"); System.out.println("all: "+all); } }<file_sep>/Week08/09-simple-objects-code/omelet-fields-only/TwoOmeletsExercise.java public class TwoOmeletsExercise{ public static void main(String args[]){ Omelet om = new Omelet(); om.eggs = 3; om.cheese = 4; om.cookedFor = 4.5; om.extras = "ham"; Omelet coronary = new Omelet(); coronary.eggs = 6; coronary.cheese = 10; coronary.cookedFor = 6.25; coronary.extras = "bacon"; om.cookedFor += 0.75; // 1 coronary.eggs++; // 2 om.extras = "turkey"; // 3 coronary.extras = // 4 coronary.extras + " sausage"; Omelet x = coronary; // 5 x.cookedFor += 1.0; // 6 om = new Omelet(); // 7 } } <file_sep>/Week09/10-oo-objects-code/Dog.java public class Dog{ public String name; public int age; public boolean hasBone; public Dog(String name, int age){ this.name = name; this.age = age; this.hasBone = false; } public String toString(){ return String.format("Name: %s Age: %d Bone? %b", this.name, this.age, this.hasBone); } public static void main(String args[]){ Dog s = new Dog("Stout",3); Dog r = new Dog("Rufus",1); r.hasBone = true; System.out.println(s.toString()); System.out.println(r.toString()); } } <file_sep>/Week04/week4notes.md ## Week 4 Notes [Ch 3.3](http://math.hws.edu/javanotes/c3/s3.html), [3.4](http://math.hws.edu/javanotes/c3/s4.html) <file_sep>/Week09/10-oo-objects-code/ooomelet/OOOmeletMain.java public class OOOmeletMain{ public static void main(String args[]){ OOOmelet small = new OOOmelet(2,5,"ham"); small.addEgg(); small.cookFor(1.5); OOOmelet large = OOOmelet(5,8,"bacon"); // 5 int cals = large.getCalories(); OOOmelet standard = new OOOmelet(); } } <file_sep>/Week01/FromSlides/Birthday2VarSolution.java // Using 2 variables public class Birthday{ public static void main(String args[]){ int age = 20; System.out.println("I hear you are " + age); int next_age = age + 1; System.out.println("Next year you will be "+ next_age); } }<file_sep>/Week04/04-loops-code/SimpleWhile.java public class SimpleWhile{ public static void main(String args[]){ System.out.println("Loop for 10 iterations"); int i = 0; while(i < 10){ System.out.printf("i is %d\n",i); i = i+1; // or i += 1; // or i++; } System.out.println("Done with loop"); } } <file_sep>/Week09/10-oo-objects-code/StaticFields.java class OnlyStatic{ public static int a; // both static public static String b; } class OnlyNon{ public int c; // both non-static public String d; } class Mixed{ public static int e; // one static public String f; // one non-static } public class StaticFields{ public static void main(String args[]){ OnlyStatic.a = 5; OnlyStatic.b = "bb"; // OnlyNon.c = 4; // ERROR: non-static field // OnlyNon.d = "ddd"; // ERROR: non-static field OnlyNon x = new OnlyNon(); x.c = 10; x.d = "dd"; OnlyNon y = new OnlyNon(); y.c = 15; y.d = "dddd"; Mixed.e = 20; // Mixed.f = "ff"; // ERROR: non-static field Mixed z = new Mixed(); z.f = "ff"; Mixed w = new Mixed(); w.f = "ffff"; } } <file_sep>/Week12/week12notes.md ## Week 12 Notes <file_sep>/Week05/p2-code/MultTableTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class MultTableTests extends KTests{ // Main method runs this file's tests public static void main(String args[]) { org.junit.runner.JUnitCore.main("MultTableTests"); } //////////////////////////////////////////////////////////////////////////////// // Tests @Test public void MultTable_main1() { String input = "2 3"; TextIO.readStream(new StringReader(input)); String expect = "Enter max rows and columns: (ex: 4 6)\n"+ " 1 2 3 \n"+ " +-------------\n"+ " 1 | 1 2 3 \n"+ " 2 | 2 4 6 \n"+ ""; MultTable.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MultTable_main2() { String input = "1 5"; TextIO.readStream(new StringReader(input)); String expect = "Enter max rows and columns: (ex: 4 6)\n"+ " 1 2 3 4 5 \n"+ " +---------------------\n"+ " 1 | 1 2 3 4 5 \n"+ ""; MultTable.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MultTable_main3() { String input = "11 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter max rows and columns: (ex: 4 6)\n"+ " 1 \n"+ " +-----\n"+ " 1 | 1 \n"+ " 2 | 2 \n"+ " 3 | 3 \n"+ " 4 | 4 \n"+ " 5 | 5 \n"+ " 6 | 6 \n"+ " 7 | 7 \n"+ " 8 | 8 \n"+ " 9 | 9 \n"+ " 10 | 10 \n"+ " 11 | 11 \n"+ ""; MultTable.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MultTable_main4() { String input = "9 3"; TextIO.readStream(new StringReader(input)); String expect = "Enter max rows and columns: (ex: 4 6)\n"+ " 1 2 3 \n"+ " +-------------\n"+ " 1 | 1 2 3 \n"+ " 2 | 2 4 6 \n"+ " 3 | 3 6 9 \n"+ " 4 | 4 8 12 \n"+ " 5 | 5 10 15 \n"+ " 6 | 6 12 18 \n"+ " 7 | 7 14 21 \n"+ " 8 | 8 16 24 \n"+ " 9 | 9 18 27 \n"+ ""; MultTable.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MultTable_main5() { String input = "12 14"; TextIO.readStream(new StringReader(input)); String expect = "Enter max rows and columns: (ex: 4 6)\n"+ " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 \n"+ " +---------------------------------------------------------\n"+ " 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 \n"+ " 2 | 2 4 6 8 10 12 14 16 18 20 22 24 26 28 \n"+ " 3 | 3 6 9 12 15 18 21 24 27 30 33 36 39 42 \n"+ " 4 | 4 8 12 16 20 24 28 32 36 40 44 48 52 56 \n"+ " 5 | 5 10 15 20 25 30 35 40 45 50 55 60 65 70 \n"+ " 6 | 6 12 18 24 30 36 42 48 54 60 66 72 78 84 \n"+ " 7 | 7 14 21 28 35 42 49 56 63 70 77 84 91 98 \n"+ " 8 | 8 16 24 32 40 48 56 64 72 80 88 96 104 112 \n"+ " 9 | 9 18 27 36 45 54 63 72 81 90 99 108 117 126 \n"+ " 10 | 10 20 30 40 50 60 70 80 90 100 110 120 130 140 \n"+ " 11 | 11 22 33 44 55 66 77 88 99 110 121 132 143 154 \n"+ " 12 | 12 24 36 48 60 72 84 96 108 120 132 144 156 168 \n"+ ""; MultTable.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MultTable_main6() { String input = "4 4"; TextIO.readStream(new StringReader(input)); String expect = "Enter max rows and columns: (ex: 4 6)\n"+ " 1 2 3 4 \n"+ " +-----------------\n"+ " 1 | 1 2 3 4 \n"+ " 2 | 2 4 6 8 \n"+ " 3 | 3 6 9 12 \n"+ " 4 | 4 8 12 16 \n"+ ""; MultTable.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week03/03-conditionals-code/BuggyDiscount.java // This version does uses a if() only: without the if/else if it may // apply the wrong discount. public class ChainedConditions{ public static void main(String args[]){ double bill = 50.00; System.out.printf("Current bill is $%.2f\n",bill); System.out.println("Check for discounts, only the best one will apply"); System.out.println("Are you a student (15% off)? (true/false)"); boolean student = TextIO.getBoolean(); System.out.println("Is it your birthday (20% off)? (true/false)"); boolean birthday = TextIO.getBoolean(); System.out.println("Do you have a coupon (10% off)? (true/false)"); boolean coupon = TextIO.getBoolean(); double discount = 0.0; if(student){ discount = 0.15; } if(birthday){ discount = 0.20; } if(coupon){ discount = 0.05; } bill = bill * (1.0-discount); System.out.printf("Current bill is $%.2f\n",bill); } } <file_sep>/Week03/week3notes.md # Week 3 Notes [Ch 3.1](http://math.hws.edu/javanotes/c3/s1.html), [3.2](http://math.hws.edu/javanotes/c3/s2.html), [3.5](http://math.hws.edu/javanotes/c3/s5.html) ## Control Structures ```java { //This is a block, code goes here } ``` Java isn't Python, how pretty the code is doesn't affect how it runs. People want pretty code anyways tho. Also, if you declare a variable in a block, it's local to the block. Why are blocks important? Because unlike Python, you have to store the guts of your statements. ```java while (boolean-expression) { // Code goes here } ``` This is a while loop! ```java if ( boolean-expression ) { // Code goes here } else { // Code goes here } ``` An if-else statement! ```java if (x < y && x < z) { output x, followed by y and z in their correct order } else if (x > y && x > z) { output y and z in their correct order, followed by x } else { output x in between y and z in their correct order } ``` Elifs! Empty statements (pass in Python) are done using a semicolon after the statement or {empty braces}. Bear in mind that this is a thing, because it can cause errors. You can also just have an if statement, but be careful. #Excercises ## Trace Conditional Execution I believe the code gives "sum is 30" because the else statement is connected to if(addC) which is false. ## Trickier Conditional Execution I believe the sum is (a+b)*2 due to how it changes. addA is true, addB is true, and div2 is false by the end of it <file_sep>/Week02/lab01-code/bender.java public class bender { /* Program that prints out ASCII * Bender by <NAME> * from http://www.gotfuturama.com/Multimedia/AsciiArt/BenderBenjamin.shtml */ public static void main (String[] args) { System.out.println(""); System.out.println(" .-."); System.out.println(" ( )"); System.out.println(" '-'"); System.out.println(" J L"); System.out.println(" | |"); System.out.println(" J L"); System.out.println(" | |"); System.out.println(" J L"); System.out.println(" .-'.___.'-."); System.out.println(" /___________\\"); System.out.println(" _.-\"\"' `bmw._"); System.out.println(" .' `."); System.out.println(" J `."); System.out.println(" F L"); System.out.println(" J J"); System.out.println(" J `"); System.out.println(" | L"); System.out.println(" | |"); System.out.println(" | |"); System.out.println(" | J"); System.out.println(" | L"); System.out.println(" | |"); System.out.println(" | ,.___ ___....--._"); System.out.println(" | ,' `\"\"\"\"\"\"\"\"' `-._"); System.out.println(" | J _____________________`-."); System.out.println(" | F .-' `-88888-' `Y8888b.`."); System.out.println(" | | .' `P' `88888b \\"); System.out.println(" | | J # L # q8888b L"); System.out.println(" | | | | )8888D )"); System.out.println(" | J \\ J d8888P P"); System.out.println(" | L `. .b. ,88888P /"); System.out.println(" | `. `-.___,o88888o.___,o88888P'.'"); System.out.println(" | `-.__________________________..-'"); System.out.println(" | |"); System.out.println(" | .-----.........____________J"); System.out.println(" | .' | | | |"); System.out.println(" | J---|-----..|...___|_______|"); System.out.println(" | | | | | |"); System.out.println(" | Y---|-----..|...___|_______|"); System.out.println(" | `. | | | |"); System.out.println(" | `'-------:....__|______.J"); System.out.println(" | |"); System.out.println(" L___ |"); System.out.println(" \"\"\"----...______________....--\'"); } }<file_sep>/Week08/week8notes.md ## Week 8 Notes [Ch 5](http://math.hws.edu/javanotes/c5/index.html) <file_sep>/Week01/01IntroductionCode/Swap.java // First program shows how to variables can be swapped using a third // variable then printed to the screen public class Swap{ public static void main(String args[]){ int x = 19; int y = 31; int temp = -1; temp = x; x = y; y = temp; System.out.println("first " + x); System.out.println("second " + y); } } <file_sep>/Week13/lab12-code/Problem1Tests.java import org.junit.*; import static org.junit.Assert.*; import java.util.*; import java.io.*; public class Problem1Tests extends KTests { public static void main(String args[]) { org.junit.runner.JUnitCore.main("Problem1Tests"); } // Test whether real numbers in space-separated strings can be read; // opens the scanner and passes it on to user function public static void testSumReals_Scanner(double expect, String parseString){ Scanner input = new Scanner(parseString); double actual = ScannerPractice.sumReals(input); double tolerance = 1e-3; String msg = String.format("Wrong sum\nString:\n%s\nExpect: %s\nActual: %s\n", parseString,expect,actual); assertEquals(msg,expect,actual,tolerance); } @Test public void sumReals_Scanner_0() { testSumReals_Scanner(0.0,""); } @Test public void sumReals_Scanner_1() { testSumReals_Scanner(-2.1," 0.5 1.2 -3.8"); } @Test public void sumReals_Scanner_2() { testSumReals_Scanner(4.2," word 1.0 3.2 "); } @Test public void sumReals_Scanner_3() { testSumReals_Scanner(5.45," 13 doh! 4 7.65 -22.34\nbarf stuff 3.14 nada"); } @Test public void sumReals_Scanner_4() { testSumReals_Scanner(10.9,"line\n9.9\ndon't\t\t1.0"); } @Test public void sumReals_Scanner_5() { testSumReals_Scanner(201.2,"Punctuation like ! and && as well as 123 or 78.2 are words. "); } } <file_sep>/Week08/p3-code/ConversionsTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class ConversionsTests extends KTests{ // Main method runs this file's tests public static void main(String args[]) { org.junit.runner.JUnitCore.main("ConversionsTests"); } //////////////////////////////////////////////////////////////////////////////// // Tests // Tests for main method @Test public void Conversions_main1() { String input = "binary 101"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a binary number: (ex: 011010101)\n"+ "Decimal value: 5\n"+ "Back to binary: 101\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main2() { String input = "binary 10000101"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a binary number: (ex: 011010101)\n"+ "Decimal value: 133\n"+ "Back to binary: 10000101\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main3() { String input = "decimal 133"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a decimal number: (ex: 546723)\n"+ "Binary value: 10000101\n"+ "Back to decimal: 133\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main4() { String input = "decimal 514"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a decimal number: (ex: 546723)\n"+ "Binary value: 1000000010\n"+ "Back to decimal: 514\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main51() { String input = "decimal -17"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a decimal number: (ex: 546723)\n"+ "Failed to convert\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main52() { String input = "decimal -2"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a decimal number: (ex: 546723)\n"+ "Failed to convert\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main61() { String input = "binary 101a125"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a binary number: (ex: 011010101)\n"+ "Failed to convert\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main62() { String input = "binary 1011!011"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Enter a binary number: (ex: 011010101)\n"+ "Failed to convert\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main7() { String input = "flurbo 126"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Unknown choice 'flurbo'\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Conversions_main8() { String input = "Morty 100011011"; TextIO.readStream(new StringReader(input)); String expect = "Choose 'binary' or 'decimal' number:\n"+ "Unknown choice 'Morty'\n"+ ""; Conversions.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week09/10-oo-objects-code/constructor-name-binding/OOOmelet.java // Demonstrate constructors, first two with name binding problems, // second two correctly specified public class OOOmelet{ public int eggs; public int cheese; public double cookedFor; public String extras; // NON-STATIC METHODS // BAD CONSTRUCTOR 1 // Names of parameters shadow fields public OOOmelet(int eggs, int cheese, String extras){ eggs = eggs; cheese = cheese; extras = extras; cookedFor = 0.0; } // // BAD CONSTRUCTOR 2 // // Local variables shadow field names // public OOOmelet(int eg, int ch, String ex) { // int eggs = eg; // int cheese = ch; // String extras = ex; // doulbe cookedFor = 0.0; // } // // CORRECT CONSTRUCTOR 1 // // Use this.field to specify field initialization // public OOOmelet(int eggs, int cheese, String extras){ // this.eggs = eggs; // this.cheese = cheese; // this.extras = extras; // this.cookedFor = 0.0; // } // // CORRECT CONSTRUCTOR 2 // // Vary names of parameters to avoid conflicts // public OOOmelet(int eg, int ch, String ex){ // eggs = eg; // cheese = ch; // extras = ex; // cookedFor = 0.0; // } public String toString(){ return String.format("%d eggs, %d oz cheese, cooked for %.1f mins, extras: %s", this.eggs, this.cheese, this.cookedFor, this.extras); } public static void main(String args[]){ OOOmelet omA = new OOOmelet(3,4,"ham"); System.out.println(omA.toString()); OOOmelet omB = new OOOmelet(5,3,"bacon"); System.out.println(omB.toString()); } } <file_sep>/Week05/p2-code/SymmetricSeqTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class SymmetricSeqTests extends KTests{ // Main method runs this file's tests public static void main(String args[]) { org.junit.runner.JUnitCore.main("SymmetricSeqTests"); } //////////////////////////////////////////////////////////////////////////////// // Tests @Test public void SymmetricSeq_main1() { String input = "3 1 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 3 integers:\n"+ "Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main2() { String input = "3 1 2 2"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 3 integers:\n"+ "seq[0] != seq[2]\n"+ "NOT Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main3() { String input = "4 -1 5 5 -1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 4 integers:\n"+ "Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main4() { String input = "4 1 5 5 -1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 4 integers:\n"+ "seq[0] != seq[3]\n"+ "NOT Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main5() { String input = "5 2 2 2 2 2"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 5 integers:\n"+ "Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main6() { String input = "5 1 2 3 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 5 integers:\n"+ "Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main7() { String input = "5 1 3 3 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 5 integers:\n"+ "seq[1] != seq[3]\n"+ "NOT Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main8() { String input = "5 1 2 3 4 5"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 5 integers:\n"+ "seq[0] != seq[4]\n"+ "seq[1] != seq[3]\n"+ "NOT Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main9() { String input = "10 -1 2 -3 4 5 5 4 -3 2 -1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 10 integers:\n"+ "Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main10() { String input = "10 -1 2 -3 -4 5 5 4 -3 2 -1"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 10 integers:\n"+ "seq[3] != seq[6]\n"+ "NOT Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void SymmetricSeq_main11() { String input = "25 74 86 83 88 96 87 11 60 46 1 84 55 42 55 84 1 46 60 11 87 96 88 83 86 74"; TextIO.readStream(new StringReader(input)); String expect = "Enter length of sequence (ex: 7): \n"+ "Enter 25 integers:\n"+ "Symmetric\n"+ ""; SymmetricSeq.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week04/04-loops-code/InteractiveSum2.java // Demonstrate interactive loop with a "quit" value which causes the // loop to terminate public class InteractiveSum2{ public static void main(String args[]) { int i = 0; int sum = 0; int value = -1; // Must declare before loop while(value != 0){ // Check for quit value System.out.println("Enter an integer (0 to quit):"); value = TextIO.getInt(); if(value != 0){ // Don't do anything with sum += value; // quit value } } System.out.printf("Sum is %d\n",sum); // After loop } } <file_sep>/Week15/week15notes.md ## Week 15 Notes <file_sep>/Week05/week5notes.md ## Week 5 Notes [Ch 3.8](http://math.hws.edu/javanotes/c3/s8.html) <file_sep>/Week03/03-conditionals-code/StudentDiscount.java // Get user input to determine whether discounts apply public class StudentDiscount{ public static void main(String args[]){ double bill = 50.00; System.out.printf("Current bill is $%.2f\n",bill); System.out.println("Are you a student? (true/false)"); boolean student = TextIO.getBoolean(); double discount = 0.00; // Fraction discount // CONDITIONALS if(student){ System.out.println("Applying a 10% discount"); discount = discount + 0.10; // Increase discount by 10% } else{ System.out.println("Sucks being an adult, doesn't it?"); } bill = bill * (1.0-discount); System.out.printf("Current bill is $%.2f\n",bill); } } <file_sep>/Week13/12-advanced-io-code/SumIntegers.java // Exercise to sum numbers import java.util.Scanner; public class SumIntegers{ public static void main(String args[]){ System.out.println("Stop with Ctrl-D (Mac/Unix) or Ctrl-Z (Windows)"); Scanner input = new Scanner(System.in); int total = 0; System.out.println("Enter an integer:"); while(input.hasNext()){ // loop while input int num = input.nextInt(); // get a number total += num; // increment System.out.println("Enter an integer:"); } System.out.printf("End of input\n"); System.out.printf("Total: %d\n",total); } } <file_sep>/Week05/05-arrays-code/ArrayNPE.java // Throws a NullPointerException public class ArrayNPE{ public static void main(String args[]) { int arrA[] = new int[]{15, 25, 35}; arrA = null; System.out.printf("arrA[0] = %d\n",arrA[0]); } } <file_sep>/README.md # Assignments for University of Minnesota's Intro to Java. I'm self studying this course in the hopes of getting a position in the Computer Science department as an instructors assistant (and maybe finally understand the FireBears robot code enough to code my own robots to take over the world! Mwahahahahahahahaha!). I have started Week 2 This course uses the OER [Introduction to Programming Using Java](http://math.hws.edu/javanotes/index.html). I am also using the [course materials written by Professor <NAME>](http://www-users.cs.umn.edu/~kauffman/1103/). This folder contains exerpts from this material, as well as my own original code. Please do not plagiarize, but feel free to learn from my code. <file_sep>/Week11/lab10-code/FixedStackTests.java import org.junit.*; import org.junit.Test; import static org.junit.Assert.*; import java.util.*; public class FixedStackTests { public static void main(String args[]){ org.junit.runner.JUnitCore.main("FixedStackTests"); } @Test public void fixedstack_constructor1(){ FixedStack stack = new FixedStack(5); } @Test public void fixedstack_constructor2(){ FixedStack stack = new FixedStack(2); } @Test public void fixedstack_basicAccessors1(){ FixedStack stack = new FixedStack(5); assertEquals(5 , stack.getCapacity()); assertEquals(0 , stack.getSize()); assertEquals(true , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_basicAccessors2(){ FixedStack stack = new FixedStack(2); assertEquals(2 , stack.getCapacity()); assertEquals(0 , stack.getSize()); assertEquals(true , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_pushTop1(){ FixedStack stack = new FixedStack(2); stack.push("A"); assertEquals("A" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(1 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_pushTop2(){ FixedStack stack = new FixedStack(2); stack.push("A"); stack.push("B"); assertEquals("B" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(2 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(true , stack.isFull()); } @Test public void fixedstack_pushTop3(){ FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); assertEquals("D" , stack.getTop()); assertEquals(5 , stack.getCapacity()); assertEquals(4 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_pushTop4(){ FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); assertEquals("E" , stack.getTop()); assertEquals(5 , stack.getCapacity()); assertEquals(5 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(true , stack.isFull()); } @Test public void fixedstack_getTopEmpty1(){ FixedStack stack = new FixedStack(2); try{ String t = stack.getTop(); } catch(RuntimeException e){ if(e.getMessage().equals("Stack empty")){ return; // pass } } fail("Should throw an exception with message 'Stack empty'"); } @Test public void fixedstack_getTopEmpty2(){ FixedStack stack = new FixedStack(5); try{ String t = stack.getTop(); } catch(RuntimeException e){ if(e.getMessage().equals("Stack empty")){ return; // pass } } fail("Should throw an exception with message 'Stack empty'"); } @Test public void fixedstack_pushException1(){ FixedStack stack = new FixedStack(2); stack.push("A"); stack.push("B"); try{ stack.push("C"); } catch(RuntimeException e){ if(e.getMessage().equals("Stack full")){ return; // pass } } fail("Should throw an exception with message 'Stack full'"); } @Test public void fixedstack_pushException2(){ FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); try{ stack.push("F"); } catch(RuntimeException e){ if(e.getMessage().equals("Stack full")){ return; // pass } } fail("Should throw an exception with message 'Stack full'"); } @Test public void fixedstack_pop1(){ FixedStack stack = new FixedStack(2); stack.push("A"); stack.pop(); assertEquals(2 , stack.getCapacity()); assertEquals(0 , stack.getSize()); assertEquals(true , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_pop2(){ FixedStack stack = new FixedStack(2); stack.push("A"); stack.push("B"); stack.pop(); assertEquals("A" , stack.getTop()); assertEquals(2 , stack.getCapacity()); assertEquals(1 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_pop3(){ FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.pop(); stack.push("C"); stack.push("D"); stack.pop(); assertEquals("C" , stack.getTop()); assertEquals(5 , stack.getCapacity()); assertEquals(2 , stack.getSize()); assertEquals(false , stack.isEmpty()); assertEquals(false , stack.isFull()); } @Test public void fixedstack_toString1(){ String expect = "size: 0\n" + ""; FixedStack stack = new FixedStack(2); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_toString2(){ String expect = "size: 1\n"+ "0 : A\n"+ ""; FixedStack stack = new FixedStack(2); stack.push("A"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_toString3(){ String expect = "size: 2\n"+ "1 : B\n"+ "0 : A\n"+ ""; FixedStack stack = new FixedStack(2); stack.push("A"); stack.push("B"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_toString4(){ String expect = "size: 3\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_toString5(){ String expect = "size: 5\n"+ "4 : E\n"+ "3 : D\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_toString6(){ String expect = "size: 3\n"+ "2 : C\n"+ "1 : B\n"+ "0 : A\n"+ ""; FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); stack.pop(); stack.pop(); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_toString7(){ String expect = "size: 0\n"+ ""; FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); stack.pop(); stack.pop(); stack.pop(); stack.pop(); stack.pop(); String actual = stack.toString(); String msg = String.format("\ntoString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_contentsString1(){ String expect = "capacity: 2\n"+ "0 : null\n"+ "1 : null\n"+ ""; FixedStack stack = new FixedStack(2); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_contentsString2(){ String expect = "capacity: 3\n"+ "0 : A\n"+ "1 : B\n"+ "2 : null\n"+ ""; FixedStack stack = new FixedStack(3); stack.push("A"); stack.push("B"); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_contentsString3(){ String expect = "capacity: 5\n"+ "0 : A\n"+ "1 : B\n"+ "2 : C\n"+ "3 : D\n"+ "4 : E\n"+ ""; FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.push("C"); stack.push("D"); stack.push("E"); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } @Test public void fixedstack_contentsString4(){ String expect = "capacity: 5\n"+ "0 : A\n"+ "1 : C\n"+ "2 : D\n"+ "3 : null\n"+ "4 : null\n"+ ""; FixedStack stack = new FixedStack(5); stack.push("A"); stack.push("B"); stack.pop(); stack.push("C"); stack.push("D"); stack.push("E"); stack.pop(); String actual = stack.contentsString(); String msg = String.format("\ncontentsString() wrong\n") + String.format("EXPECT:\n%s\n",expect) + String.format("ACTUAL:\n%s\n",actual) + ""; assertEquals(msg, expect, actual); } } <file_sep>/Week04/04-loops-code/LongLoop.java public class LongLoop{ public static void main(String args[]){ int twoPow = 1; int exponent = 0; while(exponent < 10){ System.out.printf("2^%d = %d\n", exponent,twoPow); twoPow *= 2; } } } <file_sep>/Week15/p5-tests/VoteTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class VoteTests extends KTests { // Main method runs tests in this file public static void main(String args[]) { org.junit.runner.JUnitCore.main("VoteTests"); } @Test public void vote_constructor_empty() { String cands [] = { }; int ranks[] = { }; Vote v = new Vote(cands, ranks); } @Test public void vote_constructor_1() { String cands [] = {"Viktor"}; int ranks[] = {0 }; Vote v = new Vote(cands, ranks); } @Test public void vote_constructor_2() { String cands [] = {"Francis","Claire","Heather","Viktor"}; int ranks[] = {0, 1, 2, 3 }; Vote v = new Vote(cands, ranks); } @Test public void vote_constructor_3() { String cands [] = {"Francis","Claire","Heather","Viktor"}; int ranks[] = {2, 0, 3, 1 }; Vote v = new Vote(cands, ranks); } @Test public void vote_constructor_4() { String cands [] = {"A","B","C","D","E","F","G","H"}; int ranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; Vote v = new Vote(cands, ranks); } public void check_toString(String cands[], int ranks[], String expect){ Vote v = new Vote(cands, ranks); String actual = v.toString(); String msg = ""; msg += String.format("Vote toString incorrect\n"); msg += String.format("candidates[]: %s\n",Arrays.toString(cands)); msg += String.format("ranks[]: %s\n",Arrays.toString(ranks)); msg += String.format("EXPECT: %s\n",expect); msg += String.format("ACTUAL: %s\n",actual); assertEquals(msg,expect,actual); } @Test public void vote_toString_empty() { String cands [] = { }; int ranks[] = { }; String expect = "Vote{}"; check_toString(cands,ranks,expect); } @Test public void vote_toString_1() { String cands [] = {"Viktor"}; int ranks[] = {0 }; String expect = "Vote{Viktor}"; check_toString(cands,ranks,expect); } @Test public void vote_toString_2() { String cands [] = {"Francis","Claire","Heather","Viktor"}; int ranks[] = {0, 1, 2, 3 }; String expect = "Vote{Francis, Claire, Heather, Viktor}"; check_toString(cands,ranks,expect); } @Test public void vote_toString_3() { String cands [] = {"Francis","Claire","Heather","Viktor"}; int ranks[] = {2, 0, 3, 1 }; String expect = "Vote{Claire, Viktor, Francis, Heather}"; check_toString(cands,ranks,expect); } @Test public void vote_toString_4() { String cands [] = {"A","B","C","D","E","F","G","H"}; int ranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String expect = "Vote{F, H, G, D, B, E, A, C}"; check_toString(cands,ranks,expect); } // @Test public void vote_deepCopy() { // String cands [] = {"Francis","Claire","Heather","Viktor"}; // int ranks[] = {0, 1, 2, 3 }; // String candsOriginal = Arrays.toString(cands); // String expect = "Vote{Francis, Claire, Heather, Viktor}"; // Vote vote = new Vote(cands,ranks); // String voteOriginal = vote.toString(); // cands[0] = "A"; cands[1]="B"; cands[2]="C"; cands[3]="D"; // Modify array to see if things change in vote // String candsAfter = Arrays.toString(cands); // String voteAfter = vote.toString(); // String msg = ""; // msg += String.format("Vote toString incorrect\n"); // msg += String.format("Likely cause is shallow copy of candidates array\n"); // msg += String.format("Original cands[]: %s\n",candsOriginal); // msg += String.format("vote.toString(): %s\n",voteOriginal); // msg += String.format("Changed cands: %s\n",candsAfter); // msg += String.format("vote.toString(): %s\n",voteAfter); // msg += String.format("EXPECT: %s\n",expect); // assertEquals(msg,expect,voteAfter); // } public void check_getBest(String vcands[], int vranks[], String tcands[], String expect) { Vote vote = new Vote(vcands, vranks); Tally tally = new Tally(tcands); String actual = vote.getBest(tally); String msg = ""; msg += String.format("Vote getBest() incorrect\n"); msg += String.format("vote cands[]: %s\n",Arrays.toString(vcands)); msg += String.format("vote ranks[]: %s\n",Arrays.toString(vranks)); msg += String.format("tally cands[]: %s\n",Arrays.toString(tcands)); msg += String.format("Vote: %s\n",vote.toString()); msg += String.format("Tally: %s\n",tally.toString()); msg += String.format("EXPECT: %s\n",expect); msg += String.format("ACTUAL: %s\n",actual); assertEquals(msg,expect,actual); } @Test public void vote_getBest_empty1() { String vcands [] = { }; int vranks[] = { }; String tcands [] = {"Francis","Heather"}; String expect = null; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_empty2() { String vcands [] = { }; int vranks[] = { }; String tcands [] = {"A","B","C","D","E","F","G","H"}; String expect = null; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_single1() { String vcands [] = {"Viktor"}; int vranks[] = { 0 }; String tcands [] = {"Francis","Heather"}; String expect = null; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_single2() { String vcands [] = {"Viktor"}; int vranks[] = { 0 }; String tcands [] = {"Viktor"}; String expect = "Viktor"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_single3() { String vcands [] = {"Viktor"}; int vranks[] = { 0 }; String tcands [] = {"Francis","Viktor"}; String expect = "Viktor"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_mult1() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 0, 1, 2, 3, }; String tcands [] = {"Francis","Viktor"}; String expect = "Francis"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_mult2() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 0, 1, 2, 3, }; String tcands [] = {"Viktor","Francis"}; String expect = "Francis"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_mult3() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 0, 1, 2, 3, }; String tcands [] = {"Viktor","Heather","Claire"}; String expect = "Claire"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_mult4() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 0, 1, 2, 3, }; String tcands [] = {"Viktor","Heather","Francis","Claire"}; String expect = "Francis"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_ranks1() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 2, 1, 0, 3, }; String tcands [] = {"Francis","Claire","Heather","Viktor"}; String expect = "Heather"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_ranks2() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 2, 1, 0, 3, }; String tcands [] = {"Francis","Viktor"}; String expect = "Francis"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_ranks3() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 1, 3, 2, 0, }; String tcands [] = {"Francis","Viktor"}; String expect = "Viktor"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_ranks4() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 1, 3, 2, 0, }; String tcands [] = {"Francis","Claire","Heather","Viktor"}; String expect = "Viktor"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_ranks5() { String vcands [] = {"Francis","Claire","Heather","Viktor"}; int vranks[] = { 1, 3, 2, 0, }; String tcands [] = {"Claire","Heather",}; String expect = "Heather"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_large1() { String vcands [] = {"A","B","C","D","E","F","G","H"}; int vranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String tcands [] = {"A","B","C","D","E","F","G","H"}; String expect = "F"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_large2() { String vcands [] = {"A","B","C","D","E","F","G","H"}; int vranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String tcands [] = {"A","B","C","D","E"}; String expect = "D"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_large3() { String vcands [] = {"A","B","C","D","E","F","G","H"}; int vranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String tcands [] = {"D","A","F","E","C","H","G","B"}; String expect = "F"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_large4() { String vcands [] = {"A","B","C","D","E","F","G","H"}; int vranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String tcands [] = {"D","E","C","G","B"}; String expect = "G"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_large5() { String vcands [] = {"A","B","C","D","E","F","G","H"}; int vranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String tcands [] = {"C","B","E"}; String expect = "B"; check_getBest(vcands,vranks,tcands,expect); } @Test public void vote_getBest_large6() { String vcands [] = {"A","B","C","D","E","F","G","H"}; int vranks[] = { 6, 4, 7, 3, 5, 0, 2, 1 }; String tcands [] = {"C"}; String expect = "C"; check_getBest(vcands,vranks,tcands,expect); } } <file_sep>/Week04/04-loops-code/TwoPow.java // Shows two equivalent loops: while and for do the same thing public class TwoPow{ public static void main(String args[]){ int twoPow, exponent; { System.out.println("WHILE LOOP VERSION"); twoPow=1; exponent=0; while(exponent < 10){ System.out.printf("2^%d = %d\n", exponent,twoPow); twoPow *= 2; exponent++; } } System.out.println(); { System.out.println("FOR LOOP VERSION"); twoPow=1; for(exponent=0; exponent < 10; exponent++){ System.out.printf("2^%d = %d\n", exponent,twoPow); twoPow *= 2; } } } } <file_sep>/Week13/13-command-line-arguments-code/WordCount.java // Count all words in all files named on the command line import java.util.Scanner; import java.io.File; public class WordCount{ public static void main(String args[]) throws Exception{ for(int i=0; i<args.length; i++){ String filename = args[i]; Scanner input = new Scanner(new File(filename)); int wc = 0; while(input.hasNext()){ input.next(); wc++; } input.close(); System.out.printf("%s has %d words\n", filename,wc); } } } <file_sep>/Week03/03-conditionals-code/in-class/Ascending.java // Enter 4 numbers, check for ascending order public class Ascending{ public static void main(String args[]){ System.out.println("Enter 4 integers:"); int a = TextIO.getInt(); int b = TextIO.getInt(); int c = TextIO.getInt(); int d = TextIO.getInt(); } } <file_sep>/Week01/FromSlides/BirthdayProblem.java public class Birthday{ public static void main(String args[]){ System.out.println("I hear you are " + ???); System.out.println("Next year you will be "+ ???); } }<file_sep>/Week13/week13notes.md ## Week 13 Notes <file_sep>/Week13/12-advanced-io-code/EndOfInput.java // Demonstrate the hasNext() method of Scanner import java.util.Scanner; public class EndOfInput{ public static void main(String args[]){ System.out.println("To end input"); System.out.println("- Mac/Unix: press Ctrl-D"); System.out.println("- Windows: press Ctrl-Z"); Scanner input = new Scanner(System.in); int count = 0; String allStrings = ""; // System.out.println("Enter a string:"); while(input.hasNext()){ // loop while input System.out.println("Enter a string:"); String str = input.next(); // get a string count++; // increment allStrings += str + "\n"; // tack on to all //System.out.println("Enter a string:"); } System.out.printf("End of input reached\n"); System.out.printf("%d total strings typed\n",count); System.out.printf("All strings:\n%s\n",allStrings); } } <file_sep>/Week14/week14notes.md ## Week 14 Notes [Ch 9](http://math.hws.edu/javanotes/c9/index.html) <file_sep>/Week04/04-loops-code/in-class/InteractiveSum2.java public class InteractiveSum2{ public static void main(String args[]) { // quit value is -1 boolean keepGoing = true; int sum = 0; while(keepGoing){ // loop until reach count System.out.println("Enter an integer:"); int value = TextIO.getInt(); if(value == -1){ keepGoing = false; } else{ sum += value; // update sum } } // int sum = 0; // int value = 1; // while(value != 0){ // System.out.println("Enter an integer:"); // value = TextIO.getInt(); // sum += value; // update sum // } // // System.out.printf("Sum is %d\n",sum); } } <file_sep>/Week10/week10notes.md ## Week 10 Notes <file_sep>/Week07/08-static-methods-code/MethodSpecs.java public class MethodSpecs{ // Compare two integer arrays. Return true if all elements are equal // and false if any elements are unequal. Return false if the // arrays are differnt length. public static boolean compareIntArrays(int x[], int y[]){ } // Determine if character q is in String s. Return the lowest index // of s that has q if it is present. Return -1 if q is not // present. Throw an exception if s is null. public static int indexOf(String s, char q){ } } <file_sep>/Week05/05-arrays-code/CompareSequences.java public class CompareSequences{ public static void main(String args[]) { System.out.println("Enter sequence length:"); int seqLength = TextIO.getInt(); // get size from user int seq1[] = new int[seqLength]; // allocate space for seq 1 System.out.printf("Enter First %d integers:\n", seqLength); for(int i=0; i<seqLength; i++){ // input loop: read seq 1 seq1[i] = TextIO.getInt(); // integers from user } int seq2[] = new int[seqLength]; // allocate space for sequence 2 System.out.printf("Enter Second %d integers:\n",seqLength); for(int i=0; i<seqLength; i++){ // input loop: read all seq2[i] = TextIO.getInt(); // integers from user } System.out.printf("%2s %4s %4s\n", // print table header "#","seq1","seq2"); for(int i=0; i<seqLength; i++){ // print out sequence table System.out.printf("%2d %4d %4d\n", i,seq1[i],seq2[i]); } // Check for equality of all elements boolean areEqual = true; // assume equal for(int i=0; i<seqLength; i++){ if(seq1[i] != seq2[i]){ // detect differences areEqual = false; // change equal to not } } System.out.printf("Sequences equal: %b\n",areEqual); } } <file_sep>/Week09/lab08-code/Problem2Tests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class Problem2Tests extends KTests { /*Main method runs tests in this file*/ public static void main(String args[]) { org.junit.runner.JUnitCore.main("Problem2Tests"); } // Tests for the buyMore() method public void check_buyMore(String symbol, double price, int numShares, String name, int buyQuant) { Stock stock = new Stock(); stock.symbol = symbol; stock.price = price; stock.numShares = numShares; stock.name = name; int expectNumShares = buyQuant + numShares; double actualCost = Stock.buyMore(stock, buyQuant); assertEquals("stock.numShares wrong", expectNumShares, stock.numShares); double expectCost = -buyQuant * price; assertEquals("returned cost wrong",expectCost,actualCost, 1e-4); assertEquals("price changed",price,stock.price, 1e-4); assertEquals("symbol changed",symbol,stock.symbol); assertEquals("name changed",name,stock.name); } @Test public void buyMore1() { String symbol = "GOOGL"; double price = 1000.62; int numShares = 500; String name = "Alphabet Inc Class A"; int buyQuant = 100; check_buyMore(symbol,price,numShares,name,buyQuant); } @Test public void buyMore2() { String symbol = "GOOGL"; double price = 1000.62; int numShares = 500; String name = "Alphabet Inc Class A"; int buyQuant = 256; check_buyMore(symbol,price,numShares,name,buyQuant); } @Test public void buyMore3() { String symbol = "GOOGL"; double price = 1000.62; int numShares = 500; String name = "Alphabet Inc Class A"; int buyQuant = 256; check_buyMore(symbol,price,numShares,name,buyQuant); } @Test public void buyMore4() { String symbol = "AAPL"; double price = 163.05; int numShares = 800; String name = "Apple Inc."; int buyQuant = 5; check_buyMore(symbol,price,numShares,name,buyQuant); } // Tests for the sellOff() method public void check_sellOff(String symbol, double price, int numShares, String name, int sellQuant) { Stock stock = new Stock(); stock.symbol = symbol; stock.price = price; stock.numShares = numShares; stock.name = name; int expectNumShares = numShares < sellQuant ? numShares : numShares - sellQuant; double actualProfit = Stock.sellOff(stock, sellQuant); assertEquals("stock.numShares wrong", expectNumShares, stock.numShares); double expectProfit = numShares < sellQuant ? 0.0 : sellQuant * price; assertEquals("returned cost wrong",expectProfit, actualProfit, 1e-4); assertEquals("price changed",price,stock.price, 1e-4); assertEquals("symbol changed",symbol,stock.symbol); assertEquals("name changed",name,stock.name); } @Test public void sellOff1() { String symbol = "GOOGL"; double price = 1000.62; int numShares = 500; String name = "Alphabet Inc Class A"; int sellQuant = 100; check_sellOff(symbol,price,numShares,name,sellQuant); } @Test public void sellOff2() { String symbol = "GOOGL"; double price = 1000.62; int numShares = 500; String name = "Alphabet Inc Class A"; int sellQuant = 250; check_sellOff(symbol,price,numShares,name,sellQuant); } @Test public void sellOff3() { String symbol = "AAPL"; double price = 163.05; int numShares = 800; String name = "Apple Inc."; int sellQuant = 800; check_sellOff(symbol,price,numShares,name,sellQuant); } // Check for attempts to sell too much @Test public void sellOff4() { String symbol = "AAPL"; double price = 163.05; int numShares = 800; String name = "Apple Inc."; int sellQuant = 801; check_sellOff(symbol,price,numShares,name,sellQuant); } @Test public void sellOff5() { String symbol = "GOOGL"; double price = 1000.62; int numShares = 250; String name = "Alphabet Inc Class A"; int sellQuant = 500; check_sellOff(symbol,price,numShares,name,sellQuant); } } <file_sep>/Week12/lab11-code/CritCompare.java public class CritCompare{ public static void encounter(Critter a, Critter b){ if(a.ferocity > b.ferocity){ System.out.printf("%s would beat %s\n", a.kind,b.kind); } else if(a.ferocity < b.ferocity){ System.out.printf("%s would beat %s\n", b.kind,a.kind); } else{ System.out.printf("%s and %s grab falafel together\n", b.kind,a.kind); } } } <file_sep>/Week01/week1notes.md # Week 1 Notes [Ch 1](http://math.hws.edu/javanotes/c1/index.html) CPU = Boxes in memory Variables, ways to refer to memory boxes, (remember CSCI 1410) Memory box diagrams are important! ## Java Equivalents Java's Version of Print ```java System.out.println() ``` Java's Version of Declaring variables ```java int a; a = 800; ``` or ```java int b = 303; ``` Java's Version of addition ```java int c = a + b; ``` Java's Version of String Concatenation in a Print Statement ```java System.out.println(a + " plus " + b); System.out.println("is " + c); ``` Java's version of comments ```java // This is a single line comment /* This comments spans multiple lines */ ``` Java's version of naming convention Letters numbers and underscores okay, spaces... no. ```java forVariablesWeUseCamelCase ForClassesWeDoThatButWithTheFirstOneCapitalized ``` ## DrJava Information We're using DrJava to make our code, specifically, [a modified version found here](https://github.com/DrJavaAtRice/drjava). It works just fine on my Ubuntu 16.04 Laptop [because it's a jar file](https://cs.gmu.edu/~kauffman/drjava/). It can be run by double clicking it in the GUI or changing to it's directory and then running the command ```bash java -jar drjava.jar ``` (Or in my case, it's probably drjava-gmu.jar) ## Java Logistics Java code files have a .java extension. Compiled Java files have a .class extension. .class files need to be run by a Java interpreter, because Java uses the *Hannah Montana Voice* Beeeeeessssssttttt of both worlds (by that, I mean Python is better :P ) Java programs are compiled and then interpreted. Also Object-Oriented Code! Basically, you know how in Python, with top-down design, it's hard to reuse code (I'll take your word on that textbook because I reuse code quite a bit), well with Object-Oriented Code, your code stuffs are objects, like a toaster. What goes on inside a toaster, who knows, but you send messages to your toaster (the bread), whenever you want, and it responds in a predictable way (with toast, hopefully, though more realistically char), so it's super reusable (toasters everywhere!) To compile the program on the command line: ```bash cd whereeveryouputyourjavacodestuffs/ javac WhateverYouNamedYourCode.java ``` To run the program on the command line: ```bash java WhateverYouNamedYourCode ``` I mean, you could just do this in the IDE, but then you'll never impress your nerd friends. # Exercises, Week 1 Lecture ## CPU Exercise ``` copy box #1024 to #1032 copy box #1028 to #1024 copy box #1032 to #1028 print "first",#1024 print "second",#1028 ``` ## Quick Review 1. The three physical components to a computer (in our simplified model) are 2. Box numbers like #1024 do not change, but their contents do 3. Boxes with names are variables 4. Java is a high-ish level programming language for computers 5. For a named box in Java, one declares a variable like so ```int variable;``` ## Swapping boxes in Java ```java int x; int y; int temp; x = 19; y = 31; temp = x; x = y; y = temp; System.out.println("first " + x); System.out.println("second " + y); ``` ## Compile/Run ```java public class Swap{ public static void main(String args[]){ int x; int y; int temp; x = 19; y = 31; temp = x; x = y; y = temp; System.out.println("first " + x); System.out.println("second " + y); } } ``` ## Birthday Problems ```java public class Birthday{ public static void main(String args[]){ int age = 20; int nextYear = age + 1; System.out.println("I hear you are " + age); System.out.println("Next year you will be " + nextYear); } } ``` ```java public class Birthday{ public static void main(String args[]){ int age = 20; System.out.println("I hear you are " + age); age += 1; System.out.println("Next year you will be " + age); } } ``` <file_sep>/Week08/lab07-code/Problem4Tests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class Problem4Tests extends KTests { /*Main method runs tests in this file*/ public static void main(String args[]) { org.junit.runner.JUnitCore.main("Problem4Tests"); } // Tests of Collatz.steps() method public static void check_verify(boolean expect, int [] input) { boolean actual = Collatz.verify(input); String inputS = Arrays.toString(input); String msg = String.format("Collatz.verify(%s)\n", inputS) + String.format("EXPECT: %s\n", expect) + String.format("ACTUAL: %s\n", actual) + ""; assertEquals(msg,expect,actual); } @Test public void Problem4_verify1() { boolean expect = true; int [] arr = {1}; check_verify(expect,arr); } @Test public void Problem4_verify2() { boolean expect = true; int [] arr = {5, 16, 8, 4, 2, 1}; check_verify(expect,arr); } @Test public void Problem4_verify3() { boolean expect = true; int [] arr = {45, 136, 68, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1}; check_verify(expect,arr); } @Test public void Problem4_verify4() { boolean expect = false; int [] arr = {5, 16, 8, 3, 2, 1}; check_verify(expect,arr); } @Test public void Problem4_verify5() { boolean expect = false; int [] arr = {45, 136, 68, 34, 17, 52}; check_verify(expect,arr); } @Test public void Problem4_verify6() { boolean expect = false; int [] arr = {}; check_verify(expect,arr); } // Tests of main methods @Test public void Problem4_Verify1() { String input = "4 8 4 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter Collatz sequence length:\n"+ "Enter Collatz sequence elements:\n"+ "This is a Collatz sequence\n"+ ""; Verify.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Problem4_Verify2() { String input = "17 45 136 68 34 17 52 26 13 40 20 10 5 16 8 4 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter Collatz sequence length:\n"+ "Enter Collatz sequence elements:\n"+ "This is a Collatz sequence\n"+ ""; Verify.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Problem4_Verify3() { String input = "5 3 16 8 4 2 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter Collatz sequence length:\n"+ "Enter Collatz sequence elements:\n"+ "This is NOT a Collatz sequence\n"+ "The actual sequence should be:\n"+ " STEP VALUE\n"+ " 0 3\n"+ " 1 10\n"+ " 2 5\n"+ " 3 16\n"+ " 4 8\n"+ " 5 4\n"+ " 6 2\n"+ " 7 1\n"+ ""; Verify.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Problem4_Verify4() { String input = "14 45 136 68 34 17 52 26 13 40 20 10 5 16 8"; TextIO.readStream(new StringReader(input)); String expect = "Enter Collatz sequence length:\n"+ "Enter Collatz sequence elements:\n"+ "This is NOT a Collatz sequence\n"+ "The actual sequence should be:\n"+ " STEP VALUE\n"+ " 0 45\n"+ " 1 136\n"+ " 2 68\n"+ " 3 34\n"+ " 4 17\n"+ " 5 52\n"+ " 6 26\n"+ " 7 13\n"+ " 8 40\n"+ " 9 20\n"+ " 10 10\n"+ " 11 5\n"+ " 12 16\n"+ " 13 8\n"+ " 14 4\n"+ " 15 2\n"+ " 16 1\n"+ ""; Verify.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week03/03-conditionals-code/Max3.java // Program that determines the maximum of three numbers using // conditionals public class Max3{ public static void main(String args[]){ System.out.println("Enter 3 integers:"); int a = TextIO.getInt(); int b = TextIO.getInt(); int c = TextIO.getInt(); int max = a; if(b > max){ max = b; } if(c > max){ max = c; } System.out.println("Max is "+max); } } <file_sep>/Week02/02-input-types-code/PrintfExamples.java // Demonstrate the printf() function for printing numbers with // different levels of precision. public class PrintfExamples{ public static void main(String args[]){ double x = 1.23456789; double y = 4.95; double z = 0.00789; // print only x with 2 digits System.out.printf("x is %.2f\n",x); // x is 1.23 // print x,y,z with 2 digits System.out.printf("all are %.2f %.2f %.2f\n",x,y,z); // all are 1.23 4.95 0.01 // print x,y,z with 3 digits System.out.printf("3 digs %.3f %.3f %.3f\n",x,y,z); // 3 digs 1.235 4.950 0.008 // mixed precision System.out.printf("x: %.5f... y: $%.3f z: %.0f\n",x,y,z); // x: 1.23457... y: $4.950 z: 0 } } <file_sep>/Week08/09-simple-objects-code/omelet-with-methods/OmeletArray.java // Demonstrate assigning objects (Omelets) to an // array of objects. This program has a bug. public class OmeletArray{ public static void main(String args[]){ Omelet omArray[] = new Omelet[5]; omArray[0] = new Omelet(); omArray[0].eggs = 2; omArray[0].cheese = 4; omArray[0].extras = "ham mushroom"; omArray[1] = new Omelet(); for(int i=0; i<4; i++){ Omelet.addEgg(omArray[1]); } omArray[1].cheese = 3; omArray[1].cookedFor = 1.0; for(int i=3; i<omArray.length; i++){ omArray[i] = new Omelet(); omArray[i].eggs = i; omArray[i].cheese = i/2; omArray[i].extras = ""; } for(int i=0; i<omArray.length; i++){ System.out.printf("Om: %d eggs, %d cheese,", omArray[i].eggs, omArray[i].cheese); System.out.printf("%.1f cooked, %s extras\n", omArray[i].cookedFor, omArray[i].extras); } } } <file_sep>/Week08/lab07-code/Steps.java // Prompt for a starting number and print out how many steps it would // take from the starting to to converge to 1 in a Collatz sequence. public class Steps { public static void main(String args[]){ System.out.println("Enter starting number:"); int n = TextIO.getInt(); int steps = Collatz.steps(n); if(steps==-1){ System.out.printf("Invalid input: %d\n",n); } else{ System.out.printf("%d converges to 1 in %d steps\n", n, steps); } } } <file_sep>/Week09/week9notes.md ## Week 9 Notes [Ch 5](http://math.hws.edu/javanotes/c5/index.html) <file_sep>/Week09/10-oo-objects-code/private-ooomelet/OOOmelet.java // Represent data associated with an omelet and the non-static methods // that operate on it. This version has private fields and additional // methods to access those private fields. public class OOOmelet{ // FIELDS are private: cannot be accessed outside this file private int eggs; // How many eggs in the omelet private int cheese; // How many ounces of cheese private double cookedFor; // How long the omelet has cooked private String extras; // Extra ingredients added // NON-STATIC METHODS // Constructor to initialize fields to given values. cookedFor is // always initialized to 0.0. public OOOmelet(int eggs, int cheese, String extras){ this.eggs = eggs; this.cheese = cheese; this.extras = extras; this.cookedFor = 0.0; } // ACCESSORS // Retrieve number of eggs public int getEggs(){ return this.eggs; } // Retrieve amount of cheese public int getCheese(){ return this.cheese; } // Retrieve amount of time cooked public double getCookTime(){ return this.cookedFor; } // Retrieve extra ingredients public String getExtras(){ return this.extras; } // MUTATORS // Cook the omelet for given time public void cookFor(double time){ this.cookedFor += time; } // Add an egg to the omelet public void addEgg(){ if(this.cookedFor > 0){ System.out.println("Yuck"); } else{ this.eggs++; } } // OTHER METHODS // Calculate the calorie count of the basic omelet ingredients. public int getCalories(){ int EGG_CALORIES = 94; int CHEESE_OZ_CALORIES = 114; return this.eggs * EGG_CALORIES + this.cheese * CHEESE_OZ_CALORIES; } // Determine if consumption of the given omelet is risky public boolean foodPoisoningIminent(){ return this.cookedFor < (1.0 * this.eggs); } // Return a reference to the omelet x or y that has more calories public static OOOmelet richerOOOmelet(OOOmelet x, OOOmelet y){ int xCal = x.getCalories(); int yCal = y.getCalories(); if(xCal > yCal){ return x; } else{ return y; } } // Create a pretty string version of the OOOmelet. public String toString(){ return String.format("%d eggs, %d oz cheese, cooked for %.1f mins, extras: %s", this.eggs, this.cheese, this.cookedFor, this.extras); } // Return true if this omelet has more eggs than the parameter // omelet public boolean moreEggsThan(OOOmelet that){ if(this.eggs > that.eggs){ return true; } else{ return false; } } } <file_sep>/Week03/p1-code/LoanCalcTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class LoanCalcTests extends P1Tests{ // Main method runs this file's tests public static void main(String args[]) { org.junit.runner.JUnitCore.main("LoanCalcTests"); } //////////////////////////////////////////////////////////////////////////////// // Tests @Test public void LoanCalc_main1() { String input = "225000.00 7.8 30"; TextIO.readStream(new StringReader(input)); String expect = "Enter Loan Amount:\n"+ "Enter Yearly Interest Rate (percent):\n"+ "Enter Years for Loan:\n"+ "Monthly Payment is $1619.71\n"+ "Total Cost for loan is $583095.11\n"+ "Total Interest for loan is $358095.11\n"+ ""; LoanCalc.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void LoanCalc_main2() { String input = "1000 10 1"; TextIO.readStream(new StringReader(input)); String expect = "Enter Loan Amount:\n"+ "Enter Yearly Interest Rate (percent):\n"+ "Enter Years for Loan:\n"+ "Monthly Payment is $87.92\n"+ "Total Cost for loan is $1054.99\n"+ "Total Interest for loan is $54.99\n"+ ""; LoanCalc.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void LoanCalc_main3() { String input = "4251.95 12.7 5"; TextIO.readStream(new StringReader(input)); String expect = "Enter Loan Amount:\n"+ "Enter Yearly Interest Rate (percent):\n"+ "Enter Years for Loan:\n"+ "Monthly Payment is $96.09\n"+ "Total Cost for loan is $5765.59\n"+ "Total Interest for loan is $1513.64\n"+ ""; LoanCalc.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void LoanCalc_main4() { String input = "12000.00 5.678 2"; TextIO.readStream(new StringReader(input)); String expect = "Enter Loan Amount:\n"+ "Enter Yearly Interest Rate (percent):\n"+ "Enter Years for Loan:\n"+ "Monthly Payment is $530.11\n"+ "Total Cost for loan is $12722.59\n"+ "Total Interest for loan is $722.59\n"+ ""; LoanCalc.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void LoanCalc_main5() { String input = "1.00 25.0 10"; TextIO.readStream(new StringReader(input)); String expect = "Enter Loan Amount:\n"+ "Enter Yearly Interest Rate (percent):\n"+ "Enter Years for Loan:\n"+ "Monthly Payment is $0.02\n"+ "Total Cost for loan is $2.73\n"+ "Total Interest for loan is $1.73\n"+ ""; LoanCalc.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week06/07-strings-code/Concat.java public class Concat{ public static void main(String args[]){ String a = "hi"; String b = "gh"; String c = a+b; // high String d = a.concat(b); // high int count = 5; String req = "I want "+count+" apples"; String ans = ""; for(int i=0; i<10; i++){ ans = ans + i + " "; } System.out.println(ans); } } <file_sep>/Week08/09-simple-objects-code/omelet-with-methods/Omelet.java // Represent data associated with an omelet and the static methods // that operate on it. public class Omelet{ // FIELDS public int eggs; // How many eggs in the omelet public int cheese; // How many ounces of cheese public double cookedFor; // How long the omelet has cooked public String extras; // Extra ingredients added // STATIC METHODS // Cook the omelet for given time public static void cookFor(Omelet om, double time){ om.cookedFor += time; } // Add an egg to the omelet public static void addEgg(Omelet om){ om.eggs++; } // Calculate the calorie count of the basic omelet ingredients. public static int getCalories(Omelet om){ int EGG_CALORIES = 94; int CHEESE_OZ_CALORIES = 114; return om.eggs * EGG_CALORIES + om.cheese * CHEESE_OZ_CALORIES; } // Determine if consumption of the given omelet is risky public static boolean foodPoisoningIminent(Omelet om){ return om.cookedFor < (1.0 * om.eggs); } // Return a reference to the omelet x or y that has more calories public static Omelet richerOmelet(Omelet x, Omelet y){ int xCal = getCalories(x); int yCal = getCalories(y); if(xCal > yCal){ return x; } else{ return y; } } } <file_sep>/Week04/lab03-code/TimeAwarenessTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class TimeAwarenessTests extends KTests { /*Main method runs tests in this file*/ public static void main(String args[]) { org.junit.runner.JUnitCore.main("TimeAwarenessTests"); } @Test public void TimeAwareness_main1() { String input = "2.0 0.5"; TextIO.readStream(new StringReader(input)); String expect = "STUDENT TIME AWARENESS SURVEY\n"+ "-----------------------------\n"+ "On average, how many hours per day including lecture/lab\n"+ "do you spend on CSCI 1103? (ex 1.5 hours):\n"+ "Sounds like you're applying proper effort\n"+ "\n"+ "On average, how many hours per day do you spend using\n"+ "social media such as Facebook/Twitter/Texting (ex 1.5 hours):\n"+ ""; TimeAwareness.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void TimeAwareness_main2() { String input = "1.1 0.5"; TextIO.readStream(new StringReader(input)); String expect = "STUDENT TIME AWARENESS SURVEY\n"+ "-----------------------------\n"+ "On average, how many hours per day including lecture/lab\n"+ "do you spend on CSCI 1103? (ex 1.5 hours):\n"+ "Expected hours per day for a 4-credit class: 1.7\n"+ "See https://policy.umn.edu/education/studentwork\n"+ "Consider increasing your time spent on CSCI 1103\n"+ "\n"+ "On average, how many hours per day do you spend using\n"+ "social media such as Facebook/Twitter/Texting (ex 1.5 hours):\n"+ ""; TimeAwareness.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void TimeAwareness_main3() { String input = "1.9 2.5"; TextIO.readStream(new StringReader(input)); String expect = "STUDENT TIME AWARENESS SURVEY\n"+ "-----------------------------\n"+ "On average, how many hours per day including lecture/lab\n"+ "do you spend on CSCI 1103? (ex 1.5 hours):\n"+ "Sounds like you're applying proper effort\n"+ "\n"+ "On average, how many hours per day do you spend using\n"+ "social media such as Facebook/Twitter/Texting (ex 1.5 hours):\n"+ "Warning: 2 or more hours per day of social media use\n"+ "has strong correlation with social isolation, morbidity\n"+ "and mortality (!). Consider reducing you use\n"+ ""; TimeAwareness.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void TimeAwareness_main4() { String input = "8.4 2.5"; TextIO.readStream(new StringReader(input)); String expect = "STUDENT TIME AWARENESS SURVEY\n"+ "-----------------------------\n"+ "On average, how many hours per day including lecture/lab\n"+ "do you spend on CSCI 1103? (ex 1.5 hours):\n"+ "You may be overdoing it. Seek help from the 1103 staff\n"+ "or ask someone out on a date (not the course staff).\n"+ "\n"+ "On average, how many hours per day do you spend using\n"+ "social media such as Facebook/Twitter/Texting (ex 1.5 hours):\n"+ "Warning: 2 or more hours per day of social media use\n"+ "has strong correlation with social isolation, morbidity\n"+ "and mortality (!). Consider reducing you use\n"+ ""; TimeAwareness.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void TimeAwareness_main5() { String input = "0 0"; TextIO.readStream(new StringReader(input)); String expect = "STUDENT TIME AWARENESS SURVEY\n"+ "-----------------------------\n"+ "On average, how many hours per day including lecture/lab\n"+ "do you spend on CSCI 1103? (ex 1.5 hours):\n"+ "Expected hours per day for a 4-credit class: 1.7\n"+ "See https://policy.umn.edu/education/studentwork\n"+ "Consider increasing your time spent on CSCI 1103\n"+ "\n"+ "On average, how many hours per day do you spend using\n"+ "social media such as Facebook/Twitter/Texting (ex 1.5 hours):\n"+ "\n"+ "What are you doing with your time?\n"+ ""; TimeAwareness.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week06/week6notes.md ## Week 6 Notes <file_sep>/Week03/p1-code/MakeChangeTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class MakeChangeTests extends P1Tests { // Main method runs this file's tests public static void main(String args[]) { org.junit.runner.JUnitCore.main("MakeChangeTests"); } //////////////////////////////////////////////////////////////////////////////// // Tests @Test public void MakeChange_main1() { String input = "167"; TextIO.readStream(new StringReader(input)); String expect = "Enter required change in pennies (ex: 167): \n"+ "Dollars: 1\n"+ "Quarter: 2\n"+ "Dimes : 1\n"+ "Nickels: 1\n"+ "Pennies: 2\n"+ ""; MakeChange.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MakeChange_main2() { String input = " 234 "; TextIO.readStream(new StringReader(input)); String expect = "Enter required change in pennies (ex: 167): \n"+ "Dollars: 2\n"+ "Quarter: 1\n"+ "Dimes : 0\n"+ "Nickels: 1\n"+ "Pennies: 4\n"+ ""; MakeChange.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MakeChange_main3() { String input = " \n99\n "; TextIO.readStream(new StringReader(input)); String expect = "Enter required change in pennies (ex: 167): \n"+ "Dollars: 0\n"+ "Quarter: 3\n"+ "Dimes : 2\n"+ "Nickels: 0\n"+ "Pennies: 4\n"+ ""; MakeChange.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MakeChange_main4() { String input = "42"; TextIO.readStream(new StringReader(input)); String expect = "Enter required change in pennies (ex: 167): \n"+ "Dollars: 0\n"+ "Quarter: 1\n"+ "Dimes : 1\n"+ "Nickels: 1\n"+ "Pennies: 2\n"+ ""; MakeChange.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void MakeChange_main5() { String input = "435 "; TextIO.readStream(new StringReader(input)); String expect = "Enter required change in pennies (ex: 167): \n"+ "Dollars: 4\n"+ "Quarter: 1\n"+ "Dimes : 1\n"+ "Nickels: 0\n"+ "Pennies: 0\n"+ ""; MakeChange.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week05/05-arrays-code/ArrayPrintingVariants.java // Typical loop to print all elements of an array public class ArrayPrintingVariants{ public static void main(String args[]) { int arr[] = {15, 25, 35, 45, 55, 65}; // int arr[] = {15, 25, 35, 22, 55, 65, 17}; // ALL INDICES // [0] = 15 System.out.printf("Length of array is %d\n",arr.length); // [1] = 25 // [2] = 35 System.out.printf("ALL INDICES\n"); // Print everything // [3] = 45 for(int i=0; i<arr.length; i++){ // [4] = 55 System.out.printf("[%d] = %d\n",i,arr[i]); // [5] = 65 } // [6] = 13 System.out.printf("ODD INDICES\n"); for(int i=1; i<arr.length; i+=2){ // Print only odd indices System.out.printf("[%d] = %d\n",i,arr[i]); } System.out.printf("ELEMENTS > 30\n"); for(int i=0; i<arr.length; i++){ // Print elements > 30 if(arr[i] > 30){ System.out.printf("[%d] = %d\n",i,arr[i]); } } System.out.printf("EVEN INDICES IN REVERSE\n"); int start = arr.length-1; // Find starting point if(arr.length % 2 == 0){ // odd/even length differences start--; } for(int i=start; i>=0; i-=2){ // Print even indices in reverse System.out.printf("[%d] = %d\n",i,arr[i]); } } } <file_sep>/Week02/week2notes.md # Week 2 Notes [Ch 2](http://math.hws.edu/javanotes/c2/index.html) Inputting text in Java is a pain, (Python is better), so for this Chapter, we're going to use a program, TextIO.java, that does it for us, and then learn to DIY it later. TextIO.java essentially Pythonifies the process, and adds error correction (try/except), though a copy of it needs to be in the folder, a la Python modules. This is a docstring in Java ```java /** A program to display the message * "Hello World!" on standard output. */ ``` A class is sort of like a module in Python except it's mandatory, and instead of just labelling the main part of the program with ```# Main```, you get to do it the fun way, mandatory labeling ```java public static void main(String[] args) { statements } ``` So when you do your programs, you do them like this ``` public class program-name { optional-variable-declarations-and-subroutines public static void main(String[] args) { statements } optional-variable-declarations-and-subroutines } ``` Java is strongly typed, which means you have to assign a type to your variables and stick to it, unlike Python where you can pretty much go wild and free. Java has the following "primitive types" byte, short, int, long, float, double, char, and boolean. Doubles are kind of like floats with more space, and floats are like floats in Python. Ints are like integers in Python, Shorts are Ints that take up less space, longs are Ints that take up more space. Booleans are standard true and false, note, true and false, not True and False like Python. A char is a unicode character, but it can be used like a number, so it can do fun things like incrementing and decrementing, so I don't have to set up one of my famous ```chars = 'abcdefghijklmnopqrstuvwxyz'``` in Java, although in fairness to Python, I probably don't have to do that in Python either, I just don't know how to not do that yet, and I just really like looping through strings. This comes at a cost though, strings always use double quotes, chars use single quotes. You can declare multiple variables at the same time in Java, but you shouldn't. Escaping characters is a thing```\"```, ```\n``` as well as unicode characters like ```Pok\u00E9mon```. There are also hexadecimal numbers begining in ```0x```, binaries begining in ```0b```, and the ability to break up numeric literals with the underscore, which works like the comma like ```1_000_000``` You can exit the program in Java using ```System.exit(0)``` or ```System.exit(1)``` to exit in error. There are other stuffs like this with standard classes and built in things like ```Math.sqrt(x)``` or ```Math.PI```, and you don't even need to import math. Strings ops are a thing, like ```stringName.length()``` [super interesting stuff](http://math.hws.edu/javanotes/c2/s3.html), sorry, ["methods"](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html), not going to recreate the docs. Java can also do enumerated types, you can basically define certain stuffs and it is it's own type, like seasons ```enum Season { SPRING, SUMMER, FALL, WINTER }``` which can be used to create variables ```Season vacation;``` which you can talk about ```vacation = Season.SUMMER;``` This is probably used in robotics code, also it makes things readable. Also, since you have to define these things, so they basically have a list, and an index to that list. Cool right? Unlike Python, formatting is done in the formatted print function ```System.out.printf( "%1.2f", amount );``` 1 is the minimum characters, 2 is how many decimal spots. You can also do this mess which speaks for itself ```System.out.printf("The product of %d and %d is %d", x, y, x*y);``` [Math stuffs are pretty much the same as in Python](http://math.hws.edu/javanotes/c2/s5.html) # Exercises ## Draw a memory diagram of... Nah. Not really feeling it. ## Reading Data ```java int i = TextIO.getInt(); \\ Gets an Integer from the User, Item A double x = TextIO.getDouble(); \\ Gets a double from the User, Item B boolean b = TextIO.getBoolean(); \\ Gets a boolean from the User, Item C ``` + Whether or not the user is a student = C + GPA of the user = B + Age of the user = A + Cash in the pocket of the user = B + Credit Card Number = This is probably a security haz, but I think maybe B just because an integer might be too short, have to check docs + Which major? = You'd probably want a string for this actually, unless they are numbered, like EE is 25 and CSCI is 26, in which case you'd want an integer, or if there are only two majors, EE and CSCI, so you ask whether or not the person is one, and take a boolean. ## Math! ```java double a = 3.5; double b = -4.1; double c = 0.5; double numerator = -b + Math.sqrt(Math.pow( b , 2 ) - 4 * a * c); double denominator = 2 * a; double x = numerator / denominator; ``` ```java double q = 25.0; double e = 2.718; double r = 2.0; double t = 1.7; double p = q * Math.pow( e , r * t ); ``` ## printf() ```java double x = 1.0331559932390235; double q = 748.8384692277563; System.out.printf("x: %.5f and q: $%.2f\n", x,q); ``` ## Name Length ```java System.out.println("What's your name?"); String name = TextIO.getWord(); int length = name.length(); System.out.println("The name " + name + " has " + length + " characters!"); ``` <file_sep>/Week13/lab12-code/Problem4Tests.java import org.junit.*; import static org.junit.Assert.*; import java.util.*; import java.io.*; public class Problem4Tests extends KTests { public static void main(String args[]) { org.junit.runner.JUnitCore.main("Problem4Tests"); } // Write strings to file named after test then ask user code to read // them in and some existing numbers public void test_readNamesFromFile(String expect[]){ try{ String filename = String.format("%s_input.txt",this.name.getMethodName()); PrintWriter out = new PrintWriter(filename); for(String s : expect){ out.println(s); } out.close(); String actual[] = ScannerPractice.readNamesFromFile(filename); String msg = ""; msg += String.format("\nnames read from %s incorrect\n",filename); msg += String.format("Expect: %s\n",Arrays.toString(expect)); msg += String.format("Actual: %s\n",Arrays.toString(actual)); assertEquals(msg,expect, actual); } catch(Exception e){ fail(e.getMessage()); } } @Test public void test_readNamesFromFile_single() { String names[] = { "Lily", }; test_readNamesFromFile(names); } @Test public void test_readNamesFromFile_simple() { String names[] = { "Nicole", "Tyler", "Devon", }; test_readNamesFromFile(names); } @Test public void test_readNamesFromFile_mutipart() { String names[] = { "<NAME> Jr.", }; test_readNamesFromFile(names); } @Test public void test_readNamesFromFile_many() { String names[] = { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Alexandra", "<NAME>", "<NAME>", }; test_readNamesFromFile(names); } @Test public void test_readNamesFromFile_empty() { String names[] = { }; test_readNamesFromFile(names); } } <file_sep>/Week07/lab06-code/PalindromeTests.java import org.junit.*; import static org.junit.Assert.*; import java.io.*; import java.util.*; public class PalindromeTests extends KTests { /*Main method runs tests in this file*/ public static void main(String args[]) { org.junit.runner.JUnitCore.main("PalindromeTests"); } @Test public void Palindrome_main1() { String input = "professor\n"+ ""; TextIO.readStream(new StringReader(input)); String expect = "Enter a word:\n"+ "The word backwards is: rosseforp\n"+ "NOT a palindrome\n"+ ""; Palindrome.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Palindrome_main2() { String input = "racecar\n"+ ""; TextIO.readStream(new StringReader(input)); String expect = "Enter a word:\n"+ "The word backwards is: racecar\n"+ "IS a palindrome\n"+ ""; Palindrome.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Palindrome_main3() { String input = "computer\n"+ ""; TextIO.readStream(new StringReader(input)); String expect = "Enter a word:\n"+ "The word backwards is: retupmoc\n"+ "NOT a palindrome\n"+ ""; Palindrome.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Palindrome_main4() { String input = "tenet\n"+ ""; TextIO.readStream(new StringReader(input)); String expect = "Enter a word:\n"+ "The word backwards is: tenet\n"+ "IS a palindrome\n"+ ""; Palindrome.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } @Test public void Palindrome_main5() { String input = "amanaplanacanalpanama\n"+ ""; TextIO.readStream(new StringReader(input)); String expect = "Enter a word:\n"+ "The word backwards is: amanaplanacanalpanama\n"+ "IS a palindrome\n"+ ""; Palindrome.main(empty); String actual = localOut.toString(); checkOutput(input,expect,actual); } } <file_sep>/Week08/09-simple-objects-code/omelet-with-methods/OmeletException.java public class OmeletException{ public static void main(String args[]){ Omelet om = new Omelet(); int len = om.extras.length(); System.out.printf("Extra ingredients as %d chars\n",len); } } <file_sep>/Week02/02-input-types-code/FruitStand.java public class FruitStand{ public static void main(String args[]){ System.out.println("How many apples?"); int apples = TextIO.getInt(); System.out.println("How many oranges?"); int oranges = TextIO.getInt(); int total = apples+oranges; System.out.println("apples: " +apples); System.out.println("oranges: "+oranges); System.out.println("fruits: "+total); } } <file_sep>/Week04/04-loops-code/in-class/GuessingGame.java // Demonstrate how user input can affect loops public class GuessingGame{ public static void main(String args[]) { int secret = 42; int nGuesses = 0; int guess = -1; System.out.println("Guess between 1 and 100:"); } }
f8ebd8e3e324e68f2fff4a0fc12e809f902249a9
[ "Markdown", "Java", "Shell" ]
83
Java
oconnellamethyst/csci1103
eba5e3579b3ba0ad7c0bb31494a96711dbc999a7
a367754aed51076da4f7a9b2a7ae19c99c4bae52
refs/heads/master
<repo_name>bonbololin/nemui<file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from 'store' import * as firebase from 'firebase' var config = { apiKey: '<KEY>', authDomain: 'nemui-9ad61.firebaseapp.com', databaseURL: 'https://nemui-9ad61.firebaseio.com', storageBucket: 'nemui-9ad61.appspot.com', messagingSenderId: '1047365250342' } firebase.initializeApp(config) firebase.auth().signInAnonymously() firebase.database().ref('/').once('value').then(function (state) { store.commit('setApp', state.val()) /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } }) }) <file_sep>/src/router/index.js import Vue from 'vue' import Showcase from 'components/Showcase' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Showcase', component: Showcase, props: { colNumber: 4 } } ] })
64cdb25868d4b017dee3578a24bb60fad6119985
[ "JavaScript" ]
2
JavaScript
bonbololin/nemui
7fdaf60cde3a435afa5fec1a42ec5da608b525a0
efb9701eba4445d54f9c8df433613f7b2ee4465f
refs/heads/master
<repo_name>odysseus654/go-udt<file_sep>/udt/packet/packet_shutdown_test.go package packet import ( "testing" ) func TestShutdownPacket(t *testing.T) { pkt1 := &ShutdownPacket{} pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/packet/packet_ack.go package packet // Structure of packets and functions for writing/reading them import ( "errors" ) // AckPacket is a UDT packet acknowledging previously-received data packets and describing the state of the link type AckPacket struct { ctrlHeader AckSeqNo uint32 // ACK sequence number PktSeqHi PacketID // The packet sequence number to which all the previous packets have been received (excluding) Rtt uint32 // RTT (in microseconds) RttVar uint32 // RTT variance BuffAvail uint32 // Available buffer size (in bytes) // the following data is optional (not sent more than SYN) IncludeLink bool PktRecvRate uint32 // Packets receiving rate (in number of packets per second) EstLinkCap uint32 // Estimated link capacity (in number of packets per second) } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *AckPacket) WriteTo(buf []byte) (uint, error) { l := len(buf) if l < 32 { return 0, errors.New("packet too small") } if _, err := p.writeHdrTo(buf, ptAck, p.AckSeqNo); err != nil { return 0, err } endianness.PutUint32(buf[16:20], p.PktSeqHi.Seq) endianness.PutUint32(buf[20:24], p.Rtt) endianness.PutUint32(buf[24:28], p.RttVar) endianness.PutUint32(buf[28:32], p.BuffAvail) if p.IncludeLink { if l < 40 { return 0, errors.New("packet too small") } endianness.PutUint32(buf[32:36], p.PktRecvRate) endianness.PutUint32(buf[36:40], p.EstLinkCap) return 40, nil } return 32, nil } func (p *AckPacket) readFrom(data []byte) (err error) { l := len(data) if l < 32 { return errors.New("packet too small") } if p.AckSeqNo, err = p.readHdrFrom(data); err != nil { return err } p.PktSeqHi = PacketID{endianness.Uint32(data[16:20])} p.Rtt = endianness.Uint32(data[20:24]) p.RttVar = endianness.Uint32(data[24:28]) p.BuffAvail = endianness.Uint32(data[28:32]) if l >= 36 { p.IncludeLink = true p.PktRecvRate = endianness.Uint32(data[32:36]) if l >= 40 { p.EstLinkCap = endianness.Uint32(data[36:40]) } } return nil } // PacketType returns the packetType associated with this packet func (p *AckPacket) PacketType() PacketType { return ptAck } <file_sep>/udt/packet/packet_ack2_test.go package packet import ( "testing" ) func TestACK2Packet(t *testing.T) { pkt1 := &Ack2Packet{ AckSeqNo: 90, } pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/packet/packet.go package packet // Structure of packets and functions for writing/reading them import ( "encoding/binary" "errors" "fmt" ) const ( // Leading bit for distinguishing control from data packets flagBit32 = 1 << 31 // 32 bit flagBit16 = 1 << 15 // 16 bit ) // SocketType describes the kind of socket this is (i.e. streaming vs message) type SocketType uint16 const ( // TypeSTREAM describes a reliable streaming protocol (e.g. TCP) TypeSTREAM SocketType = 1 // TypeDGRAM describes a partially-reliable messaging protocol TypeDGRAM SocketType = 2 ) // PacketType describes the type of UDP packet we're dealing with type PacketType uint16 const ( // Control packet types ptHandshake PacketType = 0x0 ptKeepalive PacketType = 0x1 ptAck PacketType = 0x2 ptNak PacketType = 0x3 ptCongestion PacketType = 0x4 // unused in ver4 ptShutdown PacketType = 0x5 ptAck2 PacketType = 0x6 ptMsgDropReq PacketType = 0x7 ptSpecialErr PacketType = 0x8 // undocumented but reference implementation seems to use it ptUserDefPkt PacketType = 0x7FFF ptData PacketType = 0x8000 // not found in any control packet, but used to identify data packets ) // PacketTypeName returns a name describing the specified packet type func PacketTypeName(pt PacketType) string { switch pt { case ptHandshake: return "handshake" case ptKeepalive: return "keep-alive" case ptAck: return "ack" case ptNak: return "nak" case ptCongestion: return "congestion" case ptShutdown: return "shutdown" case ptAck2: return "ack2" case ptMsgDropReq: return "msg-drop" case ptSpecialErr: return "error" case ptUserDefPkt: return "user-defined" case ptData: return "data" default: return fmt.Sprintf("packet-type-%d", int(pt)) } } var ( endianness = binary.BigEndian ) // Packet represents a UDT packet type Packet interface { // socketId retrieves the socket id of a packet SocketID() (sockID uint32) // SendTime retrieves the timesamp of the packet SendTime() (ts uint32) // WriteTo writes this packet to the provided buffer, returning the length of the packet WriteTo(buf []byte) (uint, error) // readFrom reads the packet from a Reader readFrom(data []byte) (err error) SetHeader(destSockID uint32, ts uint32) PacketType() PacketType } // ControlPacket represents a UDT control packet. type ControlPacket interface { // socketId retrieves the socket id of a packet SocketID() (sockID uint32) // SendTime retrieves the timesamp of the packet SendTime() (ts uint32) WriteTo(buf []byte) (uint, error) // readFrom reads the packet from a Reader readFrom(data []byte) (err error) SetHeader(destSockID uint32, ts uint32) PacketType() PacketType } type ctrlHeader struct { ts uint32 DstSockID uint32 } func (h *ctrlHeader) SocketID() (sockID uint32) { return h.DstSockID } func (h *ctrlHeader) SendTime() (ts uint32) { return h.ts } func (h *ctrlHeader) SetHeader(destSockID uint32, ts uint32) { h.DstSockID = destSockID h.ts = ts } func (h *ctrlHeader) writeHdrTo(buf []byte, msgType PacketType, info uint32) (uint, error) { l := len(buf) if l < 16 { return 0, errors.New("packet too small") } // Sets the flag bit to indicate this is a control packet endianness.PutUint16(buf[0:2], uint16(msgType)|flagBit16) endianness.PutUint16(buf[2:4], uint16(0)) // Write 16 bit reserved data endianness.PutUint32(buf[4:8], info) endianness.PutUint32(buf[8:12], h.ts) endianness.PutUint32(buf[12:16], h.DstSockID) return 16, nil } func (h *ctrlHeader) readHdrFrom(data []byte) (addtlInfo uint32, err error) { l := len(data) if l < 16 { return 0, errors.New("packet too small") } addtlInfo = endianness.Uint32(data[4:8]) h.ts = endianness.Uint32(data[8:12]) h.DstSockID = endianness.Uint32(data[12:16]) return } // ReadPacketFrom takes the contents of a UDP packet and decodes it into a UDT packet func ReadPacketFrom(data []byte) (p Packet, err error) { h := endianness.Uint32(data[0:4]) if h&flagBit32 == flagBit32 { // this is a control packet // Remove flag bit h = h &^ flagBit32 // Message type is leading 16 bits msgType := PacketType(h >> 16) switch msgType { case ptHandshake: p = &HandshakePacket{} case ptKeepalive: p = &KeepAlivePacket{} case ptAck: if len(data) == 20 { p = &LightAckPacket{} } else { p = &AckPacket{} } case ptNak: p = &NakPacket{} case ptCongestion: p = &CongestionPacket{} case ptShutdown: p = &ShutdownPacket{} case ptAck2: p = &Ack2Packet{} case ptMsgDropReq: p = &MsgDropReqPacket{} case ptSpecialErr: p = &ErrPacket{} case ptUserDefPkt: p = &UserDefControlPacket{msgType: uint16(h & 0xffff)} default: return nil, fmt.Errorf("Unknown control packet type: %X", msgType) } err = p.readFrom(data) return } // this is a data packet p = &DataPacket{ Seq: PacketID{h}, } err = p.readFrom(data) return } <file_sep>/udt/sendpacket_heap.go package udt import ( "container/heap" "time" "github.com/odysseus654/go-udt/udt/packet" ) type sendPacketEntry struct { pkt *packet.DataPacket tim time.Time ttl time.Duration } // receiveLossList defines a list of recvLossEntry records sorted by their packet ID type sendPacketHeap []sendPacketEntry func (h sendPacketHeap) Len() int { return len(h) } func (h sendPacketHeap) Less(i, j int) bool { return h[i].pkt.Seq.Seq < h[j].pkt.Seq.Seq } func (h sendPacketHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *sendPacketHeap) Push(x interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, not just its contents. *h = append(*h, x.(sendPacketEntry)) } func (h *sendPacketHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // Find does a binary search of the heap for the specified packetID which is returned func (h sendPacketHeap) Find(packetID packet.PacketID) (*sendPacketEntry, int) { len := len(h) idx := 0 for idx < len { pid := h[idx].pkt.Seq if pid == packetID { return &h[idx], idx } else if pid.Seq > packetID.Seq { idx = idx * 2 } else { idx = idx*2 + 1 } } return nil, -1 } // Min does a binary search of the heap for the entry with the lowest packetID greater than or equal to the specified value func (h sendPacketHeap) Min(greaterEqual packet.PacketID, lessEqual packet.PacketID) (*packet.DataPacket, int) { len := len(h) idx := 0 wrapped := greaterEqual.Seq > lessEqual.Seq for idx < len { pid := h[idx].pkt.Seq var next int if pid.Seq == greaterEqual.Seq { return h[idx].pkt, idx } else if pid.Seq >= greaterEqual.Seq { next = idx * 2 } else { next = idx*2 + 1 } if next >= len && h[idx].pkt.Seq.Seq > greaterEqual.Seq && (wrapped || h[idx].pkt.Seq.Seq <= lessEqual.Seq) { return h[idx].pkt, idx } idx = next } // can't find any packets with greater value, wrap around if wrapped { idx = 0 for { next := idx * 2 if next >= len && h[idx].pkt.Seq.Seq <= lessEqual.Seq { return h[idx].pkt, idx } idx = next } } return nil, -1 } // Remove does a binary search of the heap for the specified packetID, which is removed func (h *sendPacketHeap) Remove(packetID packet.PacketID) bool { len := len(*h) idx := 0 for idx < len { pid := (*h)[idx].pkt.Seq if pid.Seq == packetID.Seq { heap.Remove(h, idx) return true } else if pid.Seq > packetID.Seq { idx = idx * 2 } else { idx = idx*2 + 1 } } return false } <file_sep>/udt/udtsocket_send.go package udt import ( "container/heap" "fmt" "time" "github.com/odysseus654/go-udt/udt/packet" ) type sendState int const ( sendStateIdle sendState = iota // not waiting for anything, can send immediately sendStateSending // recently sent something, waiting for SND before sending more sendStateWaiting // destination is full, waiting for them to process something and come back sendStateProcessDrop // immediately re-process any drop list requests sendStateShutdown // connection is shutdown ) const ( minEXPinterval time.Duration = 300 * time.Millisecond ) type udtSocketSend struct { // channels sockClosed <-chan struct{} // closed when socket is closed sockShutdown <-chan struct{} // closed when socket is shutdown sendEvent <-chan recvPktEvent // sender: ingest the specified packet. Sender is readPacket, receiver is goSendEvent messageOut <-chan sendMessage // outbound messages. Sender is client caller (Write), Receiver is goSendEvent. Closed when socket is closed sendPacket chan<- packet.Packet // send a packet out on the wire shutdownEvent chan<- shutdownMessage // channel signals the connection to be shutdown socket *udtSocket sendState sendState // current sender state sendPktPend sendPacketHeap // list of packets that have been sent but not yet acknoledged sendPktSeq packet.PacketID // the current packet sequence number msgPartialSend *sendMessage // when a message can only partially fit in a socket, this is the remainder msgSeq uint32 // the current message sequence number expCount uint // number of continuous EXP timeouts. lastRecvTime time.Time // the last time we've heard something from the remote system recvAckSeq packet.PacketID // largest packetID we've received an ACK from sentAck2 uint32 // largest ACK2 packet we've sent sendLossList packetIDHeap // loss list sndPeriod atomicDuration // (set by congestion control) delay between sending packets rtoPeriod atomicDuration // (set by congestion control) override of EXP timer calculations congestWindow atomicUint32 // (set by congestion control) size of the current congestion window (in packets) flowWindowSize uint // negotiated maximum number of unacknowledged packets (in packets) // timers sndEvent <-chan time.Time // if a packet is recently sent, this timer fires when SND completes ack2SentEvent <-chan time.Time // if an ACK2 packet has recently sent, wait SYN before sending another one expTimerEvent <-chan time.Time // Fires when we haven't heard from the peer in a while } func newUdtSocketSend(s *udtSocket) *udtSocketSend { ss := &udtSocketSend{ socket: s, expCount: 1, sendPktSeq: s.initPktSeq, sockClosed: s.sockClosed, sockShutdown: s.sockShutdown, sendEvent: s.sendEvent, messageOut: s.messageOut, congestWindow: atomicUint32{val: 16}, flowWindowSize: s.maxFlowWinSize, sendPacket: s.sendPacket, shutdownEvent: s.shutdownEvent, } ss.resetEXP(s.created) go ss.goSendEvent() return ss } func (s *udtSocketSend) configureHandshake(p *packet.HandshakePacket, resetSeq bool) { if resetSeq { s.recvAckSeq = p.InitPktSeq s.sendPktSeq = p.InitPktSeq } s.flowWindowSize = uint(p.MaxFlowWinSize) } func (s *udtSocketSend) SetPacketSendPeriod(snd time.Duration) { // check to see if we have a bandwidth limit here maxBandwidth := s.socket.Config.MaxBandwidth if maxBandwidth > 0 { minSP := time.Second / time.Duration(float64(maxBandwidth)/float64(s.socket.mtu.get())) if snd < minSP { snd = minSP } } s.sndPeriod.set(snd) } func (s *udtSocketSend) goSendEvent() { sendEvent := s.sendEvent messageOut := s.messageOut sockClosed := s.sockClosed for { thisMsgChan := messageOut sockShutdown := s.sockShutdown switch s.sendState { case sendStateIdle: // not waiting for anything, can send immediately if s.msgPartialSend != nil { // we have a partial message waiting, try to send more of it now s.processDataMsg(false, messageOut) continue } case sendStateProcessDrop: // immediately re-process any drop list requests s.sendState = s.reevalSendState() // try to reconstruct what our state should be if it wasn't sendStateProcessDrop if !s.processSendLoss() || s.sendPktSeq.Seq%16 == 0 { s.processSendExpire() } continue case sendStateShutdown: sockShutdown = nil thisMsgChan = nil default: thisMsgChan = nil } select { case _, _ = <-sockShutdown: s.sendState = sendStateShutdown s.expTimerEvent = nil // don't process EXP events if we're shutting down case msg, ok := <-thisMsgChan: // nil if we can't process outgoing messages right now if !ok { s.sendPacket <- &packet.ShutdownPacket{} s.shutdownEvent <- shutdownMessage{sockState: sockStateClosed, permitLinger: true} return } s.msgPartialSend = &msg s.processDataMsg(true, messageOut) case evt, ok := <-sendEvent: if !ok { return } s.expCount = 1 s.resetEXP(evt.now) switch sp := evt.pkt.(type) { case *packet.AckPacket: s.ingestAck(sp, evt.now) case *packet.LightAckPacket: s.ingestLightAck(sp, evt.now) case *packet.NakPacket: s.ingestNak(sp, evt.now) case *packet.CongestionPacket: s.ingestCongestion(sp, evt.now) } s.sendState = s.reevalSendState() case _, _ = <-sockClosed: return case <-s.ack2SentEvent: // ACK2 unlocked s.ack2SentEvent = nil case now := <-s.expTimerEvent: // EXP event s.expEvent(now) case <-s.sndEvent: // SND event s.sndEvent = nil if s.sendState == sendStateSending { s.sendState = s.reevalSendState() if !s.processSendLoss() || s.sendPktSeq.Seq%16 == 0 { s.processSendExpire() } } } } } func (s *udtSocketSend) reevalSendState() sendState { if s.sndEvent != nil { return sendStateSending } // Do we have too many unacknowledged packets for us to send any more? if s.sendPktPend != nil { congestWindow := uint(s.congestWindow.get()) cwnd := s.flowWindowSize if cwnd > congestWindow { cwnd = congestWindow } if cwnd >= uint(len(s.sendPktPend)) { return sendStateWaiting } } return sendStateIdle } // try to pack a new data packet and send it func (s *udtSocketSend) processDataMsg(isFirst bool, inChan <-chan sendMessage) { for s.msgPartialSend != nil { partialSend := s.msgPartialSend state := packet.MbOnly if s.socket.isDatagram { if isFirst { state = packet.MbFirst } else { state = packet.MbMiddle } } if isFirst || !s.socket.isDatagram { s.msgSeq++ } mtu := int(s.socket.mtu.get()) msgLen := len(partialSend.content) if msgLen >= mtu { // we are full -- send what we can and leave the rest var dp *packet.DataPacket if msgLen == mtu { dp = &packet.DataPacket{ Seq: s.sendPktSeq, Data: partialSend.content, } s.msgPartialSend = nil } else { dp = &packet.DataPacket{ Seq: s.sendPktSeq, Data: partialSend.content[0:mtu], } s.msgPartialSend = &sendMessage{content: partialSend.content[mtu:], tim: partialSend.tim, ttl: partialSend.ttl} } s.sendPktSeq.Incr() dp.SetMessageData(state, !s.socket.isDatagram, s.msgSeq) s.sendDataPacket(sendPacketEntry{pkt: dp, tim: partialSend.tim, ttl: partialSend.ttl}, false) return } // we are not full -- send only if this is a datagram or there's nothing obvious left if s.socket.isDatagram { if isFirst { state = packet.MbOnly } else { state = packet.MbLast } } else { select { case morePartialSend, ok := <-inChan: if ok { // we have more data, concat and try again s.msgPartialSend = &sendMessage{ content: append(s.msgPartialSend.content, morePartialSend.content...), tim: s.msgPartialSend.tim, ttl: s.msgPartialSend.ttl, } continue } default: // nothing immediately available, just send what we have } } partialSend = s.msgPartialSend dp := &packet.DataPacket{ Seq: s.sendPktSeq, Data: partialSend.content, } s.msgPartialSend = nil s.sendPktSeq.Incr() dp.SetMessageData(state, !s.socket.isDatagram, s.msgSeq) s.sendDataPacket(sendPacketEntry{pkt: dp, tim: partialSend.tim, ttl: partialSend.ttl}, false) return } } // If the sender's loss list is not empty, retransmit the first packet in the list and remove it from the list. func (s *udtSocketSend) processSendLoss() bool { if s.sendLossList == nil || s.sendPktPend == nil { return false } var dp *sendPacketEntry for { minLoss, minLossIdx := s.sendLossList.Min(s.recvAckSeq, s.sendPktSeq) if minLossIdx < 0 { // empty loss list? shouldn't really happen as we don't keep empty lists, but check for it anyhow return false } heap.Remove(&s.sendLossList, minLossIdx) if len(s.sendLossList) == 0 { s.sendLossList = nil } dp, _ = s.sendPktPend.Find(minLoss) if dp == nil { // can't find record of this packet, not much we can do really continue } if dp.ttl != 0 && time.Now().Add(dp.ttl).After(dp.tim) { // this packet has expired, ignore continue } break } s.sendDataPacket(*dp, true) return true } // evaluate our pending packet list to see if we have any expired messages func (s *udtSocketSend) processSendExpire() bool { if s.sendPktPend == nil { return false } pktPend := make([]sendPacketEntry, len(s.sendPktPend)) copy(pktPend, s.sendPktPend) for _, p := range pktPend { if p.ttl != 0 && time.Now().Add(p.ttl).After(p.tim) { // this message has expired, drop it _, _, msgNo := p.pkt.GetMessageData() dropMsg := &packet.MsgDropReqPacket{ MsgID: msgNo, FirstSeq: p.pkt.Seq, LastSeq: p.pkt.Seq, } // find the other packets in this message for _, op := range pktPend { _, _, otherMsgNo := op.pkt.GetMessageData() if otherMsgNo == msgNo { if dropMsg.FirstSeq.BlindDiff(p.pkt.Seq) > 0 { dropMsg.FirstSeq = p.pkt.Seq } if dropMsg.LastSeq.BlindDiff(p.pkt.Seq) < 0 { dropMsg.LastSeq = p.pkt.Seq } } if s.sendLossList != nil { if _, slIdx := s.sendLossList.Find(p.pkt.Seq); slIdx >= 0 { heap.Remove(&s.sendLossList, slIdx) } } } if s.sendLossList != nil && len(s.sendLossList) == 0 { s.sendLossList = nil } s.sendPacket <- dropMsg return true } } return false } // we have a packed packet and a green light to send, so lets send this and mark it func (s *udtSocketSend) sendDataPacket(dp sendPacketEntry, isResend bool) { if s.sendPktPend == nil { s.sendPktPend = sendPacketHeap{dp} heap.Init(&s.sendPktPend) } else { heap.Push(&s.sendPktPend, dp) } s.socket.cong.onDataPktSent(dp.pkt.Seq) s.sendPacket <- dp.pkt // have we exceeded our recipient's window size? s.sendState = s.reevalSendState() if s.sendState == sendStateWaiting { return } if !isResend && dp.pkt.Seq.Seq%16 == 0 { s.processSendExpire() return } snd := s.sndPeriod.get() if snd > 0 { s.sndEvent = time.After(snd) s.sendState = sendStateSending } } // ingestLightAck is called to process a "light" ACK packet func (s *udtSocketSend) ingestLightAck(p *packet.LightAckPacket, now time.Time) { // Update the largest acknowledged sequence number. pktSeqHi := p.PktSeqHi diff := pktSeqHi.BlindDiff(s.recvAckSeq) if diff > 0 { s.flowWindowSize += uint(diff) s.recvAckSeq = pktSeqHi } } func (s *udtSocketSend) assertValidSentPktID(pktType string, pktSeq packet.PacketID) bool { if s.sendPktSeq.BlindDiff(pktSeq) < 0 { s.shutdownEvent <- shutdownMessage{sockState: sockStateCorrupted, permitLinger: false, err: fmt.Errorf("FAULT: Received an %s for packet %d, but the largest packet we've sent has been %d", pktType, pktSeq.Seq, s.sendPktSeq.Seq)} return false } return true } // ingestAck is called to process an ACK packet func (s *udtSocketSend) ingestAck(p *packet.AckPacket, now time.Time) { // Update the largest acknowledged sequence number. // Send back an ACK2 with the same ACK sequence number in this ACK. if s.ack2SentEvent == nil && p.AckSeqNo == s.sentAck2 { s.sentAck2 = p.AckSeqNo s.sendPacket <- &packet.Ack2Packet{AckSeqNo: p.AckSeqNo} s.ack2SentEvent = time.After(synTime) } pktSeqHi := p.PktSeqHi if !s.assertValidSentPktID("ACK", pktSeqHi) { return } diff := pktSeqHi.BlindDiff(s.recvAckSeq) if diff <= 0 { return } oldAckSeq := s.recvAckSeq s.flowWindowSize = uint(p.BuffAvail) s.recvAckSeq = pktSeqHi // Update RTT and RTTVar. s.socket.applyRTT(uint(p.Rtt)) // Update flow window size. if p.IncludeLink { s.socket.applyReceiveRates(uint(p.PktRecvRate), uint(p.EstLinkCap)) } s.socket.cong.onACK(pktSeqHi) // Update packet arrival rate: A = (A * 7 + a) / 8, where a is the value carried in the ACK. // Update estimated link capacity: B = (B * 7 + b) / 8, where b is the value carried in the ACK. // Update sender's buffer (by releasing the buffer that has been acknowledged). if s.sendPktPend != nil { for { minLoss, minLossIdx := s.sendPktPend.Min(oldAckSeq, s.sendPktSeq) if pktSeqHi.BlindDiff(minLoss.Seq) >= 0 || minLossIdx < 0 { break } heap.Remove(&s.sendPktPend, minLossIdx) } if len(s.sendPktPend) == 0 { s.sendPktPend = nil } } // Update sender's loss list (by removing all those that has been acknowledged). if s.sendLossList != nil { for { minLoss, minLossIdx := s.sendLossList.Min(oldAckSeq, s.sendPktSeq) if pktSeqHi.BlindDiff(minLoss) >= 0 || minLossIdx < 0 { break } heap.Remove(&s.sendLossList, minLossIdx) } if len(s.sendLossList) == 0 { s.sendLossList = nil } } } // ingestNak is called to process an NAK packet func (s *udtSocketSend) ingestNak(p *packet.NakPacket, now time.Time) { newLossList := make([]packet.PacketID, 0) clen := len(p.CmpLossInfo) for idx := 0; idx < clen; idx++ { thisEntry := p.CmpLossInfo[idx] if thisEntry&0x80000000 != 0 { thisPktID := packet.PacketID{Seq: thisEntry & 0x7FFFFFFF} if idx+1 == clen { s.shutdownEvent <- shutdownMessage{sockState: sockStateCorrupted, permitLinger: false, err: fmt.Errorf("FAULT: While unpacking a NAK, the last entry (%x) was describing a start-of-range", thisEntry)} return } if !s.assertValidSentPktID("NAK", thisPktID) { return } lastEntry := p.CmpLossInfo[idx+1] if lastEntry&0x80000000 != 0 { s.shutdownEvent <- shutdownMessage{sockState: sockStateCorrupted, permitLinger: false, err: fmt.Errorf("FAULT: While unpacking a NAK, a start-of-range (%x) was followed by another start-of-range (%x)", thisEntry, lastEntry)} return } lastPktID := packet.PacketID{Seq: lastEntry} if !s.assertValidSentPktID("NAK", lastPktID) { return } idx++ for span := thisPktID; span != lastPktID; span.Incr() { newLossList = append(newLossList, span) } } else { thisPktID := packet.PacketID{Seq: thisEntry} if !s.assertValidSentPktID("NAK", thisPktID) { return } newLossList = append(newLossList, thisPktID) } } s.socket.cong.onNAK(newLossList) if s.sendLossList == nil { s.sendLossList = newLossList heap.Init(&s.sendLossList) } else { llen := len(newLossList) for idx := 0; idx < llen; idx++ { heap.Push(&s.sendLossList, newLossList[idx]) } } s.sendState = sendStateProcessDrop // immediately restart transmission } // ingestCongestion is called to process a (retired?) Congestion packet func (s *udtSocketSend) ingestCongestion(p *packet.CongestionPacket, now time.Time) { // One way packet delay is increasing, so decrease the sending rate // this is very rough (not atomic, doesn't inform congestion) but this is a deprecated message in any case s.sndPeriod.set(s.sndPeriod.get() * 1125 / 1000) //m_iLastDecSeq = s.sendPktSeq } func (s *udtSocketSend) resetEXP(now time.Time) { s.lastRecvTime = now var nextExpDurn time.Duration rtoPeriod := s.rtoPeriod.get() if rtoPeriod > 0 { nextExpDurn = rtoPeriod } else { rtt, rttVar := s.socket.getRTT() nextExpDurn = (time.Duration(s.expCount*(rtt+4*rttVar))*time.Microsecond + synTime) minExpTime := time.Duration(s.expCount) * minEXPinterval if nextExpDurn < minExpTime { nextExpDurn = minExpTime } } s.expTimerEvent = time.After(nextExpDurn) } // we've just had the EXP timer expire, see what we can do to recover this func (s *udtSocketSend) expEvent(currTime time.Time) { // Haven't receive any information from the peer, is it dead?! // timeout: at least 16 expirations and must be greater than 10 seconds if (s.expCount > 16) && (currTime.Sub(s.lastRecvTime) > 5*time.Second) { // Connection is broken. s.shutdownEvent <- shutdownMessage{sockState: sockStateTimeout, permitLinger: true} return } // sender: Insert all the packets sent after last received acknowledgement into the sender loss list. // recver: Send out a keep-alive packet if s.sendPktPend != nil { if s.sendPktPend != nil && s.sendLossList == nil { // resend all unacknowledged packets on timeout, but only if there is no packet in the loss list newLossList := make([]packet.PacketID, 0) for span := s.recvAckSeq.Add(1); span != s.sendPktSeq.Add(1); span.Incr() { newLossList = append(newLossList, span) } s.sendLossList = newLossList heap.Init(&s.sendLossList) } s.socket.cong.onTimeout() s.sendState = sendStateProcessDrop // immediately restart transmission } else { s.sendPacket <- &packet.KeepAlivePacket{} } s.expCount++ // Reset last response time since we just sent a heart-beat. s.resetEXP(currTime) } <file_sep>/udt/udt_test.go package udt import ( "fmt" "net" "sync" "testing" ) const ( serverPort = 9000 clientPort = 9001 totalNum = 10000 ) type testFunc func(*testing.T, *sync.WaitGroup) func Test1(t *testing.T) { t.Run("server", test1srv) t.Run("client", test1cli) } func test1srv(t *testing.T) { t.Parallel() t.Log("Testing simple data transfer.") serv, err := ListenUDT("udp", fmt.Sprintf("127.0.0.1:%d", serverPort)) if err != nil { t.Errorf("error calling ListenUDT: %s", err.Error()) return } newSock, err := serv.Accept() if err != nil { t.Errorf("error calling Accept: %s", err.Error()) return } totalRecv := totalNum * 4 off := 0 buffer := make([]byte, totalRecv) for off < totalRecv { recvd, err := newSock.Read(buffer[off:]) if err != nil { t.Errorf("error calling Read: %s", err.Error()) return } off += recvd } // check data for i := 0; i < totalNum; i++ { val := endianness.Uint32(buffer[i*4 : i*4+4]) if val != uint32(i) { t.Errorf("DATA ERROR %d %d", i, val) break } } newSock.Close() } func test1cli(t *testing.T) { t.Parallel() remoteAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", serverPort)) if err != nil { t.Errorf("error calling ResolveUDPAddr: %s", err.Error()) return } client, err := DialUDT("udp", fmt.Sprintf("127.0.0.1:%d", clientPort), remoteAddr, true) if err != nil { t.Errorf("error calling DialUDT: %s", err.Error()) return } totalSend := totalNum * 4 buffer := make([]byte, totalSend) for i := 0; i < totalNum; i++ { endianness.PutUint32(buffer[i*4:i*4+4], uint32(i)) } sent, err := client.Write(buffer) if err != nil { t.Errorf("error calling Write: %s", err.Error()) return } if sent != totalSend { t.Errorf("asked to send %d, actually sent %d", totalSend, sent) return } client.Close() } <file_sep>/udt/packet/packet_congestion_test.go package packet import ( "testing" ) func TestCongestionPacket(t *testing.T) { pkt1 := &CongestionPacket{} pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/ack_history_heap.go package udt import ( "time" "github.com/odysseus654/go-udt/udt/packet" ) type ackHistoryEntry struct { ackID uint32 lastPacket packet.PacketID sendTime time.Time } // receiveLossList defines a list of ACK records sorted by their ACK id type ackHistoryHeap []*ackHistoryEntry func (h ackHistoryHeap) Len() int { return len(h) } func (h ackHistoryHeap) Less(i, j int) bool { return h[i].ackID < h[j].ackID } func (h ackHistoryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *ackHistoryHeap) Push(x interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, not just its contents. *h = append(*h, x.(*ackHistoryEntry)) } func (h *ackHistoryHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // Find does a binary search of the heap for the specified ackID which is returned func (h ackHistoryHeap) Find(ackID uint32) (*ackHistoryEntry, int) { len := len(h) idx := 0 for idx < len { here := h[idx].ackID if here == ackID { return h[idx], idx } else if here > ackID { idx = idx * 2 } else { idx = idx*2 + 1 } } return nil, -1 } <file_sep>/udt/udtsocket_cc.go package udt import ( "time" "github.com/odysseus654/go-udt/udt/packet" ) type congMsgType int const ( congInit congMsgType = iota congClose congOnACK congOnNAK congOnTimeout congOnDataPktSent congOnPktSent congOnPktRecv congOnCustomMsg ) type congMsg struct { mtyp congMsgType pktID packet.PacketID arg interface{} } type udtSocketCc struct { // channels sockClosed <-chan struct{} // closed when socket is closed socket *udtSocket congestion CongestionControl // congestion control object for this socket msgs chan congMsg sendPktSeq packet.PacketID // packetID of most recently sent packet congWindow uint // size of congestion window (in packets) sndPeriod time.Duration // delay between sending packets } func newUdtSocketCc(s *udtSocket) *udtSocketCc { newCongestion := s.Config.CongestionForSocket if newCongestion == nil { newCongestion = DefaultConfig().CongestionForSocket } sc := &udtSocketCc{ socket: s, sockClosed: s.sockClosed, congestion: newCongestion(s), msgs: make(chan congMsg, 100), } go sc.goCongestionEvent() return sc } func (s *udtSocketCc) goCongestionEvent() { msgs := s.msgs sockClosed := s.sockClosed for { select { case evt, ok := <-msgs: if !ok { return } switch evt.mtyp { case congInit: s.sendPktSeq = evt.pktID s.congestion.Init(s) case congClose: s.congestion.Close(s) case congOnACK: s.congestion.OnACK(s, evt.pktID) case congOnNAK: s.congestion.OnNAK(s, evt.arg.([]packet.PacketID)) case congOnTimeout: s.congestion.OnTimeout(s) case congOnDataPktSent: s.sendPktSeq = evt.pktID case congOnPktSent: s.congestion.OnPktSent(s, evt.arg.(packet.Packet)) case congOnPktRecv: s.congestion.OnPktRecv(s, evt.arg.(packet.DataPacket)) case congOnCustomMsg: s.congestion.OnCustomMsg(s, evt.arg.(packet.UserDefControlPacket)) } case _, _ = <-sockClosed: return } } } // Init to be called (only) at the start of a UDT connection. func (s *udtSocketCc) init(sendPktSeq packet.PacketID) { s.msgs <- congMsg{ mtyp: congInit, pktID: sendPktSeq, } } // Close to be called when a UDT connection is closed. func (s *udtSocketCc) close() { s.msgs <- congMsg{ mtyp: congClose, } } // OnACK to be called when an ACK packet is received func (s *udtSocketCc) onACK(pktID packet.PacketID) { s.msgs <- congMsg{ mtyp: congOnACK, pktID: pktID, } } // OnNAK to be called when a loss report is received func (s *udtSocketCc) onNAK(loss []packet.PacketID) { var ourLoss = make([]packet.PacketID, len(loss)) copy(ourLoss, loss) s.msgs <- congMsg{ mtyp: congOnNAK, arg: ourLoss, } } // OnTimeout to be called when a timeout event occurs func (s *udtSocketCc) onTimeout() { s.msgs <- congMsg{ mtyp: congOnTimeout, } } // OnPktSent to be called when data is sent func (s *udtSocketCc) onDataPktSent(pktID packet.PacketID) { s.msgs <- congMsg{ mtyp: congOnDataPktSent, pktID: pktID, } } // OnPktSent to be called when data is sent func (s *udtSocketCc) onPktSent(p packet.Packet) { s.msgs <- congMsg{ mtyp: congOnPktSent, arg: p, } } // OnPktRecv to be called when data is received func (s *udtSocketCc) onPktRecv(p packet.DataPacket) { s.msgs <- congMsg{ mtyp: congOnPktRecv, arg: p, } } // OnCustomMsg to process a user-defined packet func (s *udtSocketCc) onCustomMsg(p packet.UserDefControlPacket) { s.msgs <- congMsg{ mtyp: congOnCustomMsg, arg: p, } } // GetSndCurrSeqNo is the most recently sent packet ID func (s *udtSocketCc) GetSndCurrSeqNo() packet.PacketID { return s.sendPktSeq } // SetCongestionWindowSize sets the size of the congestion window (in packets) func (s *udtSocketCc) SetCongestionWindowSize(pkt uint) { s.congWindow = pkt s.socket.send.congestWindow.set(uint32(pkt)) } // GetCongestionWindowSize gets the size of the congestion window (in packets) func (s *udtSocketCc) GetCongestionWindowSize() uint { return s.congWindow } // GetPacketSendPeriod gets the current delay between sending packets func (s *udtSocketCc) GetPacketSendPeriod() time.Duration { return s.sndPeriod } // SetPacketSendPeriod sets the current delay between sending packets func (s *udtSocketCc) SetPacketSendPeriod(snd time.Duration) { s.sndPeriod = snd s.socket.send.SetPacketSendPeriod(snd) } // GetMaxFlowWindow is the largest number of unacknowledged packets we can receive (in packets) func (s *udtSocketCc) GetMaxFlowWindow() uint { return s.socket.maxFlowWinSize } // GetReceiveRates is the current calculated receive rate and bandwidth (in packets/sec) func (s *udtSocketCc) GetReceiveRates() (uint, uint) { return s.socket.getRcvSpeeds() } // GetRTT is the current calculated roundtrip time between peers func (s *udtSocketCc) GetRTT() time.Duration { rtt, _ := s.socket.getRTT() return time.Duration(rtt) * time.Microsecond } // GetMSS is the largest packet size we can currently send (in bytes) func (s *udtSocketCc) GetMSS() uint { return uint(s.socket.mtu.get()) } // SetACKPerid sets the time between ACKs sent to the peer func (s *udtSocketCc) SetACKPeriod(ack time.Duration) { s.socket.recv.ackPeriod.set(ack) } // SetACKInterval sets the number of packets sent to the peer before sending an ACK func (s *udtSocketCc) SetACKInterval(ack uint) { s.socket.recv.ackInterval.set(uint32(ack)) } // SetRTOPeriod overrides the default EXP timeout calculations waiting for data from the peer func (s *udtSocketCc) SetRTOPeriod(rto time.Duration) { s.socket.send.rtoPeriod.set(rto) } <file_sep>/udt/packet/packet_data_test.go package packet import ( "testing" ) func TestDataPacket(t *testing.T) { testPacket( &DataPacket{ Seq: PacketID{Seq: 50}, ts: 1409, DstSockID: 90, Data: []byte("Hello UDT World!"), }, t) } <file_sep>/udt/atomic_duration.go package udt import ( "sync/atomic" "time" ) type atomicDuration struct { val int64 } func (s *atomicDuration) get() time.Duration { return time.Duration(atomic.LoadInt64(&s.val)) } func (s *atomicDuration) set(v time.Duration) { atomic.StoreInt64(&s.val, int64(v)) } <file_sep>/udt/packet/packet_lightack.go package packet // Structure of packets and functions for writing/reading them import ( "errors" ) // LightAckPacket is a UDT variant of the ACK packet for acknowledging received data with minimal information type LightAckPacket struct { ctrlHeader PktSeqHi PacketID // The packet sequence number to which all the previous packets have been received (excluding) } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *LightAckPacket) WriteTo(buf []byte) (uint, error) { l := len(buf) if l < 20 { return 0, errors.New("packet too small") } if _, err := p.writeHdrTo(buf, ptAck, 0); err != nil { return 0, err } endianness.PutUint32(buf[16:20], p.PktSeqHi.Seq) return 20, nil } func (p *LightAckPacket) readFrom(data []byte) (err error) { l := len(data) if l < 20 { return errors.New("packet too small") } if _, err = p.readHdrFrom(data); err != nil { return err } p.PktSeqHi = PacketID{endianness.Uint32(data[16:20])} return nil } // PacketType returns the packetType associated with this packet func (p *LightAckPacket) PacketType() PacketType { return ptAck } <file_sep>/udt/packet/packet_msgdropreq_test.go package packet import ( "testing" ) func TestMsgDropReqPacket(t *testing.T) { pkt1 := &MsgDropReqPacket{ MsgID: 90, FirstSeq: PacketID{Seq: 91}, LastSeq: PacketID{Seq: 92}, } pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/packet/pktseq.go package packet // PacketID represents a UDT packet ID sequence type PacketID struct { Seq uint32 } // Incr increments this packet ID func (p *PacketID) Incr() { p.Seq = (p.Seq + 1) & 0x7FFFFFFF } // Decr decrements this packet ID func (p *PacketID) Decr() { p.Seq = (p.Seq - 1) & 0x7FFFFFFF } // Add returns a packet ID after adding the specified offset func (p PacketID) Add(off int32) PacketID { newSeq := (p.Seq + 1) & 0x7FFFFFFF return PacketID{newSeq} } // BlindDiff attempts to return the difference after subtracting the argument from itself func (p PacketID) BlindDiff(rhs PacketID) int32 { result := (p.Seq - rhs.Seq) & 0x7FFFFFFF if result&0x40000000 != 0 { result = result | 0x80000000 } return int32(result) } <file_sep>/udt/packetid_heap.go package udt import "github.com/odysseus654/go-udt/udt/packet" // packetIdHeap defines a list of sorted packet IDs type packetIDHeap []packet.PacketID func (h packetIDHeap) Len() int { return len(h) } func (h packetIDHeap) Less(i, j int) bool { return h[i].Seq < h[j].Seq } func (h packetIDHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *packetIDHeap) Push(x interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, not just its contents. *h = append(*h, x.(packet.PacketID)) } func (h *packetIDHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // Min does a binary search of the heap for the entry with the lowest packetID greater than or equal to the specified value func (h packetIDHeap) Min(greaterEqual packet.PacketID, lessEqual packet.PacketID) (packet.PacketID, int) { len := len(h) idx := 0 wrapped := greaterEqual.Seq > lessEqual.Seq for idx < len { pid := h[idx] var next int if pid.Seq == greaterEqual.Seq { return h[idx], idx } else if pid.Seq >= greaterEqual.Seq { next = idx * 2 } else { next = idx*2 + 1 } if next >= len && h[idx].Seq > greaterEqual.Seq && (wrapped || h[idx].Seq <= lessEqual.Seq) { return h[idx], idx } idx = next } // can't find any packets with greater value, wrap around if wrapped { idx = 0 for { next := idx * 2 if next >= len && h[idx].Seq <= lessEqual.Seq { return h[idx], idx } idx = next } } return packet.PacketID{Seq: 0}, -1 } func (h packetIDHeap) compare(pktID packet.PacketID, idx int) int { if pktID.Seq < h[idx].Seq { return -1 } if pktID.Seq > h[idx].Seq { return +1 } return 0 } // Find does a binary search of the heap for the specified packetID which is returned func (h packetIDHeap) Find(pktID packet.PacketID) (*packet.PacketID, int) { len := len(h) idx := 0 for idx < len { cmp := h.compare(pktID, idx) if cmp == 0 { return &h[idx], idx } else if cmp > 0 { idx = idx * 2 } else { idx = idx*2 + 1 } } return nil, -1 } <file_sep>/udt/packet/packet_data.go package packet import "errors" // MessageBoundary flags for where this packet falls within a message type MessageBoundary uint8 const ( // MbFirst is the first packet in a multi-packet message MbFirst MessageBoundary = 2 // MbLast is the last packet in a multi-packet message MbLast MessageBoundary = 1 // MbOnly is the only packet in this message MbOnly MessageBoundary = 3 // MbMiddle is neither the first nor last packet in a multi-packet message MbMiddle MessageBoundary = 0 ) // DataPacket is a UDT packet containing message data type DataPacket struct { Seq PacketID // packet sequence number (top bit = 0) msg uint32 // message sequence number (top three bits = message control) ts uint32 // timestamp when message is sent DstSockID uint32 // destination socket Data []byte // payload } // PacketType returns the packetType associated with this packet func (dp *DataPacket) PacketType() PacketType { return ptData } // SetHeader sets the fields common to UDT data packets func (dp *DataPacket) SetHeader(destSockID uint32, ts uint32) { dp.DstSockID = destSockID dp.ts = ts } // SocketID sets the Socket ID for this data packet func (dp *DataPacket) SocketID() (sockID uint32) { return dp.DstSockID } // SendTime sets the timestamp field for this data packet func (dp *DataPacket) SendTime() (ts uint32) { return dp.ts } // SetMessageData sets the message field for this data packet func (dp *DataPacket) SetMessageData(boundary MessageBoundary, order bool, msg uint32) { var iOrder uint32 = 0 if order { iOrder = 0x20000000 } dp.msg = (uint32(boundary) << 30) | iOrder | (msg & 0x1FFFFFFF) } // GetMessageData returns the message field for this data packet func (dp *DataPacket) GetMessageData() (MessageBoundary, bool, uint32) { return MessageBoundary(dp.msg >> 30), (dp.msg & 0x20000000) != 0, dp.msg & 0x1FFFFFFF } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (dp *DataPacket) WriteTo(buf []byte) (uint, error) { l := len(buf) ol := 16 + len(dp.Data) if l < ol { return 0, errors.New("packet too small") } endianness.PutUint32(buf[0:4], dp.Seq.Seq&0x7FFFFFFF) endianness.PutUint32(buf[4:8], dp.msg) endianness.PutUint32(buf[8:12], dp.ts) endianness.PutUint32(buf[12:16], dp.DstSockID) copy(buf[16:], dp.Data) return uint(ol), nil } func (dp *DataPacket) readFrom(data []byte) (err error) { l := len(data) if l < 16 { return errors.New("packet too small") } //dp.seq = endianness.Uint32(data[0:4]) dp.msg = endianness.Uint32(data[4:8]) dp.ts = endianness.Uint32(data[8:12]) dp.DstSockID = endianness.Uint32(data[12:16]) // The data is whatever is what comes after the 16 bytes of header dp.Data = make([]byte, l-16) copy(dp.Data, data[16:]) return } <file_sep>/udt/atomic_uint32.go package udt import ( "sync/atomic" ) type atomicUint32 struct { val uint32 } func (s *atomicUint32) get() uint32 { return atomic.LoadUint32(&s.val) } func (s *atomicUint32) set(v uint32) { atomic.StoreUint32(&s.val, v) } <file_sep>/udt/packet/packet_nak.go package packet // Structure of packets and functions for writing/reading them import ( "errors" ) // NakPacket is a UDT packet notifying the peer of lost packets type NakPacket struct { ctrlHeader CmpLossInfo []uint32 // integer array of compressed loss information } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *NakPacket) WriteTo(buf []byte) (uint, error) { off, err := p.writeHdrTo(buf, ptNak, 0) if err != nil { return 0, err } l := uint(len(buf)) if l < off+uint(4*len(p.CmpLossInfo)) { return 0, errors.New("packet too small") } for _, elm := range p.CmpLossInfo { endianness.PutUint32(buf[off:off+4], elm) off = off + 4 } return off, nil } func (p *NakPacket) readFrom(data []byte) error { if _, err := p.readHdrFrom(data); err != nil { return err } l := len(data) numEntry := (l - 16) / 4 p.CmpLossInfo = make([]uint32, numEntry) for idx := range p.CmpLossInfo { st := 16 + 4*idx p.CmpLossInfo[idx] = endianness.Uint32(data[st : st+4]) } return nil } // PacketType returns the packetType associated with this packet func (p *NakPacket) PacketType() PacketType { return ptNak } <file_sep>/udt/listener.go package udt import ( "container/heap" "context" "crypto/sha1" "encoding/binary" "errors" "hash" "log" "net" "sync" "time" "github.com/odysseus654/go-udt/udt/packet" ) var ( endianness = binary.BigEndian ) /* Listener implements the io.Listener interface for UDT. */ type listener struct { m *multiplexer accept chan *udtSocket closed chan struct{} synEpoch uint32 synCookie uint32 synHash hash.Hash acceptHist acceptSockHeap acceptHistProt sync.Mutex config *Config } // resolveAddr resolves addr, which may be a literal IP // address or a DNS name, and returns a list of internet protocol // family addresses. The result contains at least one address when // error is nil. func resolveAddr(ctx context.Context, network, addr string) (*net.UDPAddr, error) { var ( err error host, port string portnum int ) switch network { case "udp", "udp4", "udp6": if addr != "" { if host, port, err = net.SplitHostPort(addr); err != nil { return nil, err } if portnum, err = net.DefaultResolver.LookupPort(ctx, network, port); err != nil { return nil, err } } default: return nil, net.UnknownNetworkError(network) } inetaddr := func(ip net.IPAddr) *net.UDPAddr { return &net.UDPAddr{IP: ip.IP, Port: portnum, Zone: ip.Zone} } if host == "" { return inetaddr(net.IPAddr{}), nil } // Try as a literal IP address, then as a DNS name. ips, err := net.DefaultResolver.LookupIPAddr(ctx, host) if err != nil { return nil, err } // Issue 18806: if the machine has halfway configured // IPv6 such that it can bind on "::" (IPv6unspecified) // but not connect back to that same address, fall // back to dialing 0.0.0.0. if len(ips) == 1 && ips[0].IP.Equal(net.IPv6unspecified) { ips = append(ips, net.IPAddr{IP: net.IPv4zero}) } var filter func(net.IPAddr) bool if network != "" && network[len(network)-1] == '4' { filter = func(addr net.IPAddr) bool { return addr.IP.To4() != nil } } if network != "" && network[len(network)-1] == '6' { filter = func(addr net.IPAddr) bool { return len(addr.IP) == net.IPv6len && addr.IP.To4() == nil } } var addrs []*net.UDPAddr for _, ip := range ips { if filter == nil || filter(ip) { addrs = append(addrs, inetaddr(ip)) } } if len(addrs) == 0 { return nil, &net.AddrError{Err: "no suitable address found", Addr: host} } return addrs[0], nil } func listenUDT(ctx context.Context, config *Config, network string, addr string) (net.Listener, error) { m, err := multiplexerFor(ctx, network, addr) if err != nil { return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err} } l := &listener{ m: m, synCookie: randUint32(), synEpoch: randUint32(), accept: make(chan *udtSocket, 100), closed: make(chan struct{}, 1), synHash: sha1.New(), // it's weak but fast, hopefully we don't need *that* much security here config: config, } if ok := m.listenUDT(l); !ok { return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: m.laddr, Err: errors.New("Port in use")} } go l.goBumpSynEpoch() return l, nil } func (l *listener) goBumpSynEpoch() { closed := l.closed for { select { case _, _ = <-closed: return case <-time.After(64 * time.Second): l.synEpoch++ } } } func (l *listener) Accept() (net.Conn, error) { socket, ok := <-l.accept if ok { return socket, nil } return nil, errors.New("Listener closed") } func (l *listener) Close() (err error) { a := l.accept c := l.closed l.accept = nil l.closed = nil if a == nil || c == nil { return errors.New("Listener closed") } close(a) close(c) l.m.unlistenUDT(l) return nil } func (l *listener) Addr() net.Addr { return l.m.laddr } func (l *listener) genSynCookie(from *net.UDPAddr) uint32 { bCookie := make([]byte, 4) endianness.PutUint32(bCookie, l.synCookie) bPort := make([]byte, 2) endianness.PutUint16(bPort, uint16(from.Port)) val := append(bCookie, append([]byte(from.IP), bPort...)...) hash := endianness.Uint32(l.synHash.Sum(val)) return ((l.synEpoch & 0x1f) << 11) | (hash & 0x07ff) } func (l *listener) checkSynCookie(cookie uint32, from *net.UDPAddr) (bool, uint32) { newCookie := l.genSynCookie(from) if (newCookie & 0x07ff) != (cookie & 0x07ff) { return false, newCookie } epoch := (cookie & 0xf100) >> 11 return (epoch == (l.synEpoch & 0x1f)) || (epoch == ((l.synEpoch - 1) & 0x1f)), newCookie } // checkValidHandshake checks to see if we want to accept a new connection with this handshake. func (l *listener) checkValidHandshake(m *multiplexer, p *packet.HandshakePacket, from *net.UDPAddr) bool { return true } func (l *listener) rejectHandshake(m *multiplexer, hsPacket *packet.HandshakePacket, from *net.UDPAddr) { log.Printf("%s (listener) sending handshake(reject) to %s (id=%d)", l.m.laddr.String(), from.String(), hsPacket.SockID) m.sendPacket(from, hsPacket.SockID, 0, &packet.HandshakePacket{ UdtVer: hsPacket.UdtVer, SockType: hsPacket.SockType, ReqType: packet.HsRefused, SockAddr: from.IP, }) } func (l *listener) readHandshake(m *multiplexer, hsPacket *packet.HandshakePacket, from *net.UDPAddr) bool { if hsPacket.ReqType == packet.HsRequest { newCookie := l.genSynCookie(from) log.Printf("%s (listener) sending handshake(request) to %s (id=%d)", l.m.laddr.String(), from.String(), hsPacket.SockID) m.sendPacket(from, hsPacket.SockID, 0, &packet.HandshakePacket{ UdtVer: hsPacket.UdtVer, SockType: hsPacket.SockType, InitPktSeq: hsPacket.InitPktSeq, //MaxPktSize uint32 // maximum packet size (including UDP/IP headers) //MaxFlowWinSize uint32 // maximum flow window size ReqType: packet.HsRequest, // SockID = 0 SynCookie: newCookie, SockAddr: from.IP, }) return true } isSYN, _ := l.checkSynCookie(hsPacket.SynCookie, from) if !isSYN { return false // ignore packets with failed SYN checks } if !l.checkValidHandshake(m, hsPacket, from) { l.rejectHandshake(m, hsPacket, from) return false } now := time.Now() l.acceptHistProt.Lock() if l.acceptHist != nil { replayWindow := l.config.ListenReplayWindow if replayWindow <= 0 { replayWindow = DefaultConfig().ListenReplayWindow } l.acceptHist.Prune(time.Now().Add(-replayWindow)) s, idx := l.acceptHist.Find(hsPacket.SockID, hsPacket.InitPktSeq) if s != nil { l.acceptHist[idx].lastTouch = now l.acceptHistProt.Unlock() return s.readHandshake(m, hsPacket, from) } } l.acceptHistProt.Unlock() if !l.config.CanAcceptDgram && hsPacket.SockType == packet.TypeDGRAM { log.Printf("Refusing new socket creation from listener requesting DGRAM") l.rejectHandshake(m, hsPacket, from) return false } if !l.config.CanAcceptStream && hsPacket.SockType == packet.TypeSTREAM { log.Printf("Refusing new socket creation from listener requesting STREAM") l.rejectHandshake(m, hsPacket, from) return false } if l.config.CanAccept != nil { err := l.config.CanAccept(hsPacket, from) if err != nil { log.Printf("New socket creation from listener rejected by config: %s", err.Error()) l.rejectHandshake(m, hsPacket, from) return false } } s := l.m.newSocket(l.config, from, true, hsPacket.SockType == packet.TypeDGRAM) l.acceptHistProt.Lock() if l.acceptHist == nil { l.acceptHist = []acceptSockInfo{acceptSockInfo{ sockID: hsPacket.SockID, initSeqNo: hsPacket.InitPktSeq, lastTouch: now, sock: s, }} heap.Init(&l.acceptHist) } else { heap.Push(&l.acceptHist, acceptSockInfo{ sockID: hsPacket.SockID, initSeqNo: hsPacket.InitPktSeq, lastTouch: now, sock: s, }) } l.acceptHistProt.Unlock() if !s.checkValidHandshake(m, hsPacket, from) { l.rejectHandshake(m, hsPacket, from) return false } if !s.readHandshake(m, hsPacket, from) { l.rejectHandshake(m, hsPacket, from) return false } l.accept <- s return true } <file_sep>/udt/packet/packet_shutdown.go package packet // Structure of packets and functions for writing/reading them // ShutdownPacket is a UDT packet notifying the peer of connection shutdown type ShutdownPacket struct { ctrlHeader } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *ShutdownPacket) WriteTo(buf []byte) (uint, error) { return p.writeHdrTo(buf, ptShutdown, 0) } func (p *ShutdownPacket) readFrom(data []byte) (err error) { _, err = p.readHdrFrom(data) return } // PacketType returns the packetType associated with this packet func (p *ShutdownPacket) PacketType() PacketType { return ptShutdown } <file_sep>/udt/packet/packet_test.go package packet import ( "reflect" "testing" ) func testPacket(p Packet, t *testing.T) (read Packet) { buf := make([]byte, 1500) n, err := p.WriteTo(buf) if err != nil { t.Errorf("Unable to write packet: %s", err) } if p2, err := ReadPacketFrom(buf[0:n]); err != nil { t.Errorf("Unable to read packet: %s", err) } else { if !reflect.DeepEqual(p, p2) { t.Errorf("Read did not match written.\n\nWrote: %s\nRead: %s", p, p2) } read = p2 } return } <file_sep>/udt/config.go package udt import ( "context" "net" "time" "github.com/odysseus654/go-udt/udt/packet" ) // Config controls behavior of sockets created with it type Config struct { CanAcceptDgram bool // can this listener accept datagrams? CanAcceptStream bool // can this listener accept streams? ListenReplayWindow time.Duration // length of time to wait for repeated incoming connections MaxPacketSize uint // Upper limit on maximum packet size (0 = unlimited) MaxBandwidth uint64 // Maximum bandwidth to take with this connection (in bytes/sec, 0 = unlimited) LingerTime time.Duration // time to wait for retransmit requests after connection shutdown MaxFlowWinSize uint // maximum number of unacknowledged packets to permit (minimum 32) CanAccept func(hsPacket *packet.HandshakePacket, from *net.UDPAddr) error // can this listener accept this connection? CongestionForSocket func(sock *udtSocket) CongestionControl // create or otherwise return the CongestionControl for this socket } // Listen listens for incoming UDT connections addressed to the local address laddr. // See function net.ListenUDP for a description of net and laddr. func (c *Config) Listen(ctx context.Context, network string, addr string) (net.Listener, error) { return listenUDT(ctx, c, network, addr) } // Dial establishes an outbound UDT connection using the supplied net, laddr and raddr. See function net.DialUDP for a description of net, laddr and raddr. func (c *Config) Dial(ctx context.Context, network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { return dialUDT(ctx, c, network, laddr, raddr, isStream) } // Rendezvous establishes an outbound UDT connection using the supplied net, laddr and raddr. See function net.DialUDP for a description of net, laddr and raddr. func (c *Config) Rendezvous(ctx context.Context, network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { return rendezvousUDT(ctx, c, network, laddr, raddr, isStream) } // DefaultConfig constructs a Config with default values func DefaultConfig() *Config { return &Config{ CanAcceptDgram: true, CanAcceptStream: true, ListenReplayWindow: 5 * time.Minute, LingerTime: 180 * time.Second, MaxFlowWinSize: 64, CongestionForSocket: func(sock *udtSocket) CongestionControl { return &NativeCongestionControl{} }, } } <file_sep>/go.mod module github.com/odysseus654/go-udt go 1.13 require github.com/furstenheim/nth_element v0.0.0-20190419153334-6ae3dd61145d <file_sep>/udt/packet/packet_nak_test.go package packet import ( "testing" ) func TestNAKPacket(t *testing.T) { pkt1 := &NakPacket{ CmpLossInfo: []uint32{90}, } pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/packet/packet_handshake.go package packet // Structure of packets and functions for writing/reading them import ( "errors" "net" ) // HandshakeReqType describes the type of handshake packet type HandshakeReqType int32 const ( // HsRequest represents an attempt to establish a new connection HsRequest HandshakeReqType = 1 //HsRendezvous represents an attempt to establish a new connection using mutual rendezvous packets HsRendezvous HandshakeReqType = 0 //HsResponse is a response to a handshake request HsResponse HandshakeReqType = -1 //HsResponse2 is an acknowledgement that a HsResponse was received HsResponse2 HandshakeReqType = -2 //HsRefused notifies the peer of a connection refusal HsRefused HandshakeReqType = 1002 ) // HandshakePacket is a UDT packet used to negotiate a new connection type HandshakePacket struct { ctrlHeader UdtVer uint32 // UDT version SockType SocketType // Socket Type (1 = STREAM or 2 = DGRAM) InitPktSeq PacketID // initial packet sequence number MaxPktSize uint32 // maximum packet size (including UDP/IP headers) MaxFlowWinSize uint32 // maximum flow window size ReqType HandshakeReqType // connection type (regular(1), rendezvous(0), -1/-2 response) SockID uint32 // socket ID SynCookie uint32 // SYN cookie SockAddr net.IP // the IP address of the UDP socket to which this packet is being sent } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *HandshakePacket) WriteTo(buf []byte) (uint, error) { l := len(buf) if l < 64 { return 0, errors.New("packet too small") } if _, err := p.writeHdrTo(buf, ptHandshake, 0); err != nil { return 0, err } endianness.PutUint32(buf[16:20], p.UdtVer) endianness.PutUint32(buf[20:24], uint32(p.SockType)) endianness.PutUint32(buf[24:28], p.InitPktSeq.Seq) endianness.PutUint32(buf[28:32], p.MaxPktSize) endianness.PutUint32(buf[32:36], p.MaxFlowWinSize) endianness.PutUint32(buf[36:40], uint32(p.ReqType)) endianness.PutUint32(buf[40:44], p.SockID) endianness.PutUint32(buf[44:48], p.SynCookie) sockAddr := make([]byte, 16) copy(sockAddr, p.SockAddr) copy(buf[48:64], sockAddr) return 64, nil } func (p *HandshakePacket) readFrom(data []byte) error { l := len(data) if l < 64 { return errors.New("packet too small") } if _, err := p.readHdrFrom(data); err != nil { return err } p.UdtVer = endianness.Uint32(data[16:20]) p.SockType = SocketType(endianness.Uint32(data[20:24])) p.InitPktSeq = PacketID{endianness.Uint32(data[24:28])} p.MaxPktSize = endianness.Uint32(data[28:32]) p.MaxFlowWinSize = endianness.Uint32(data[32:36]) p.ReqType = HandshakeReqType(endianness.Uint32(data[36:40])) p.SockID = endianness.Uint32(data[40:44]) p.SynCookie = endianness.Uint32(data[44:48]) p.SockAddr = make(net.IP, 16) copy(p.SockAddr, data[48:64]) return nil } // PacketType returns the packetType associated with this packet func (p *HandshakePacket) PacketType() PacketType { return ptHandshake } <file_sep>/udt/packet/packet_userdefctrl.go package packet import "errors" // Structure of packets and functions for writing/reading them // UserDefControlPacket is a UDT user-defined packet type UserDefControlPacket struct { ctrlHeader msgType uint16 // user-defined message type addtlInfo uint32 data []byte } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *UserDefControlPacket) WriteTo(buf []byte) (uint, error) { l := len(buf) ol := 16 + len(p.data) if l < ol { return 0, errors.New("packet too small") } // Sets the flag bit to indicate this is a control packet endianness.PutUint16(buf[0:2], uint16(ptUserDefPkt)|flagBit16) endianness.PutUint16(buf[2:4], p.msgType) // Write 16 bit reserved data endianness.PutUint32(buf[4:8], p.addtlInfo) endianness.PutUint32(buf[8:12], p.ts) endianness.PutUint32(buf[12:16], p.DstSockID) copy(buf[16:], p.data) return uint(ol), nil } func (p *UserDefControlPacket) readFrom(data []byte) (err error) { if p.addtlInfo, err = p.readHdrFrom(data); err != nil { return err } p.data = data[16:] return nil } // PacketType returns the packetType associated with this packet func (p *UserDefControlPacket) PacketType() PacketType { return ptUserDefPkt } <file_sep>/udt/congestion.go package udt import ( "time" "github.com/odysseus654/go-udt/udt/packet" ) // CongestionControlParms permits a CongestionControl implementation to interface with the UDT socket type CongestionControlParms interface { // GetSndCurrSeqNo is the most recently sent packet ID GetSndCurrSeqNo() packet.PacketID // SetCongestionWindowSize sets the size of the congestion window (in packets) SetCongestionWindowSize(uint) // GetCongestionWindowSize gets the size of the congestion window (in packets) GetCongestionWindowSize() uint // GetPacketSendPeriod gets the current delay between sending packets GetPacketSendPeriod() time.Duration // SetPacketSendPeriod sets the current delay between sending packets SetPacketSendPeriod(time.Duration) // GetMaxFlowWindow is the largest number of unacknowledged packets we can receive (in packets) GetMaxFlowWindow() uint // GetReceiveRates is the current calculated receive rate and bandwidth (in packets/sec) GetReceiveRates() (recvSpeed, bandwidth uint) // GetRTT is the current calculated roundtrip time between peers GetRTT() time.Duration // GetMSS is the largest packet size we can currently send (in bytes) GetMSS() uint // SetACKPerid sets the time between ACKs sent to the peer SetACKPeriod(time.Duration) // SetACKInterval sets the number of packets sent to the peer before sending an ACK SetACKInterval(uint) // SetRTOPeriod overrides the default EXP timeout calculations waiting for data from the peer SetRTOPeriod(time.Duration) } // CongestionControl controls how timing is handled and UDT connections tuned type CongestionControl interface { // Init to be called (only) at the start of a UDT connection. Init(CongestionControlParms) // Close to be called when a UDT connection is closed. Close(CongestionControlParms) // OnACK to be called when an ACK packet is received OnACK(CongestionControlParms, packet.PacketID) // OnNAK to be called when a loss report is received OnNAK(CongestionControlParms, []packet.PacketID) // OnTimeout to be called when a timeout event occurs OnTimeout(CongestionControlParms) // OnPktSent to be called when data is sent OnPktSent(CongestionControlParms, packet.Packet) // OnPktRecv to be called when data is received OnPktRecv(CongestionControlParms, packet.DataPacket) // OnCustomMsg to process a user-defined packet OnCustomMsg(CongestionControlParms, packet.UserDefControlPacket) } <file_sep>/udt/udtsocket.go package udt import ( "errors" "log" "net" "sync" "syscall" "time" "github.com/odysseus654/go-udt/udt/packet" ) type sockState int const ( sockStateInit sockState = iota // object is being constructed sockStateRendezvous // attempting to create a rendezvous connection sockStateConnecting // attempting to create a connection sockStateConnected // connection is established sockStateClosed // connection has been closed (by either end) sockStateRefused // connection rejected by remote host sockStateCorrupted // peer behaved in an improper manner sockStateTimeout // connection failed due to peer timeout ) type recvPktEvent struct { pkt packet.Packet now time.Time } type sendMessage struct { content []byte tim time.Time // time message is submitted ttl time.Duration // message dropped if it can't be sent in this timeframe } type shutdownMessage struct { sockState sockState permitLinger bool err error } /* udtSocket encapsulates a UDT socket between a local and remote address pair, as defined by the UDT specification. udtSocket implements the net.Conn interface so that it can be used anywhere that a stream-oriented network connection (like TCP) would be used. */ type udtSocket struct { // this data not changed after the socket is initialized and/or handshaked m *multiplexer // the multiplexer that handles this socket raddr *net.UDPAddr // the remote address created time.Time // the time that this socket was created Config *Config // configuration parameters for this socket udtVer int // UDT protcol version (normally 4. Will we be supporting others?) isDatagram bool // if true then we're sending and receiving datagrams, otherwise we're a streaming socket isServer bool // if true then we are behaving like a server, otherwise client (or rendezvous). Only useful during handshake sockID uint32 // our sockID farSockID uint32 // the peer's sockID initPktSeq packet.PacketID // initial packet sequence to start the connection with connectWait *sync.WaitGroup // released when connection is complete (or failed) sockState sockState // socket state - used mostly during handshakes mtu atomicUint32 // the negotiated maximum packet size maxFlowWinSize uint // receiver: maximum unacknowledged packet count currPartialRead []byte // stream connections: currently reading message (for partial reads). Owned by client caller (Read) readDeadline *time.Timer // if set, then calls to Read() will return "timeout" after this time readDeadlinePassed bool // if set, then calls to Read() will return "timeout" writeDeadline *time.Timer // if set, then calls to Write() will return "timeout" after this time writeDeadlinePassed bool // if set, then calls to Write() will return "timeout" rttProt sync.RWMutex // lock must be held before referencing rtt/rttVar rtt uint // receiver: estimated roundtrip time. (in microseconds) rttVar uint // receiver: roundtrip variance. (in microseconds) receiveRateProt sync.RWMutex // lock must be held before referencing deliveryRate/bandwidth deliveryRate uint // delivery rate reported from peer (packets/sec) bandwidth uint // bandwidth reported from peer (packets/sec) // channels messageIn chan []byte // inbound messages. Sender is goReceiveEvent->ingestData, Receiver is client caller (Read) messageOut chan sendMessage // outbound messages. Sender is client caller (Write), Receiver is goSendEvent. Closed when socket is closed recvEvent chan recvPktEvent // receiver: ingest the specified packet. Sender is readPacket, receiver is goReceiveEvent sendEvent chan recvPktEvent // sender: ingest the specified packet. Sender is readPacket, receiver is goSendEvent sendPacket chan packet.Packet // packets to send out on the wire (once goManageConnection is running) shutdownEvent chan shutdownMessage // channel signals the connection to be shutdown sockShutdown chan struct{} // closed when socket is shutdown sockClosed chan struct{} // closed when socket is closed // timers connTimeout <-chan time.Time // connecting: fires when connection attempt times out connRetry <-chan time.Time // connecting: fires when connection attempt to be retried lingerTimer <-chan time.Time // after disconnection, fires once our linger timer runs out send *udtSocketSend // reference to sending side of this socket recv *udtSocketRecv // reference to receiving side of this socket cong *udtSocketCc // reference to contestion control // performance metrics //PktSent uint64 // number of sent data packets, including retransmissions //PktRecv uint64 // number of received packets //PktSndLoss uint // number of lost packets (sender side) //PktRcvLoss uint // number of lost packets (receiver side) //PktRetrans uint // number of retransmitted packets //PktSentACK uint // number of sent ACK packets //PktRecvACK uint // number of received ACK packets //PktSentNAK uint // number of sent NAK packets //PktRecvNAK uint // number of received NAK packets //MbpsSendRate float64 // sending rate in Mb/s //MbpsRecvRate float64 // receiving rate in Mb/s //SndDuration time.Duration // busy sending time (i.e., idle time exclusive) // instant measurements //PktSndPeriod time.Duration // packet sending period //PktFlowWindow uint // flow window size, in number of packets //PktCongestionWindow uint // congestion window size, in number of packets //PktFlightSize uint // number of packets on flight //MsRTT time.Duration // RTT //MbpsBandwidth float64 // estimated bandwidth, in Mb/s //ByteAvailSndBuf uint // available UDT sender buffer size //ByteAvailRcvBuf uint // available UDT receiver buffer size } /******************************************************************************* Implementation of net.Conn interface *******************************************************************************/ // Grab the next data packet func (s *udtSocket) fetchReadPacket(blocking bool) ([]byte, error) { var result []byte if blocking { for { if s.readDeadlinePassed { return nil, syscall.ETIMEDOUT } var deadline <-chan time.Time if s.readDeadline != nil { deadline = s.readDeadline.C } select { case result = <-s.messageIn: return result, nil case _, ok := <-deadline: if !ok { continue } s.readDeadlinePassed = true return nil, syscall.ETIMEDOUT } } } select { case result = <-s.messageIn: // ok we have a message default: // ok we've read some stuff and there's nothing immediately available return nil, nil } return result, nil } func (s *udtSocket) connectionError() error { switch s.sockState { case sockStateRefused: return errors.New("Connection refused by remote host") case sockStateCorrupted: return errors.New("Connection closed due to protocol error") case sockStateClosed: return errors.New("Connection closed") case sockStateTimeout: return errors.New("Connection timed out") } return nil } // TODO: int sendmsg(const char* data, int len, int msttl, bool inorder) // Read reads data from the connection. // Read can be made to time out and return an Error with Timeout() == true // after a fixed time limit; see SetDeadline and SetReadDeadline. // (required for net.Conn implementation) func (s *udtSocket) Read(p []byte) (n int, err error) { connErr := s.connectionError() if s.isDatagram { // for datagram sockets, block until we have a message to return and then return it // if the buffer isn't big enough, return a truncated message (discarding the rest) and return an error msg, rerr := s.fetchReadPacket(connErr == nil) if rerr != nil { err = rerr return } if msg == nil && connErr != nil { err = connErr return } n = copy(p, msg) if n < len(msg) { err = errors.New("Message truncated") } } else { // for streaming sockets, block until we have at least something to return, then // fill up the passed buffer as far as we can without blocking again idx := 0 l := len(p) n = 0 for idx < l { if s.currPartialRead == nil { // Grab the next data packet currPartialRead, rerr := s.fetchReadPacket(n == 0 && connErr == nil) s.currPartialRead = currPartialRead if rerr != nil { err = rerr return } if s.currPartialRead == nil { if n != 0 { return } if connErr != nil { err = connErr return } } } thisN := copy(p[idx:], s.currPartialRead) n = n + thisN idx = idx + thisN if n >= len(s.currPartialRead) { // we've exhausted the current data packet, reset to nil s.currPartialRead = nil } else { s.currPartialRead = s.currPartialRead[n:] } } } return } // Write writes data to the connection. // Write can be made to time out and return an Error with Timeout() == true // after a fixed time limit; see SetDeadline and SetWriteDeadline. // (required for net.Conn implementation) func (s *udtSocket) Write(p []byte) (n int, err error) { // at the moment whatever we have right now we'll shove it into a channel and return // on the other side: // for datagram sockets: this is a distinct message to be broken into as few packets as possible // for streaming sockets: collect as much as can fit into a packet and send them out switch s.sockState { case sockStateRefused: err = errors.New("Connection refused by remote host") return case sockStateCorrupted: err = errors.New("Connection closed due to protocol error") return case sockStateClosed: err = errors.New("Connection closed") return } n = len(p) for { if s.writeDeadlinePassed { err = syscall.ETIMEDOUT return } var deadline <-chan time.Time if s.writeDeadline != nil { deadline = s.writeDeadline.C } select { case s.messageOut <- sendMessage{content: p, tim: time.Now()}: // send successful return case _, ok := <-deadline: if !ok { continue } s.writeDeadlinePassed = true err = syscall.ETIMEDOUT return } } } // Close closes the connection. // Any blocked Read or Write operations will be unblocked. // Write operations will be permitted to send (initial packets) // Read operations will return an error // (required for net.Conn implementation) func (s *udtSocket) Close() error { if !s.isOpen() { return nil // already closed } close(s.messageOut) _, _ = <-s.shutdownEvent return nil } func (s *udtSocket) isOpen() bool { switch s.sockState { case sockStateClosed, sockStateRefused, sockStateCorrupted, sockStateTimeout: return false default: return true } } // LocalAddr returns the local network address. // (required for net.Conn implementation) func (s *udtSocket) LocalAddr() net.Addr { return s.m.laddr } // RemoteAddr returns the remote network address. // (required for net.Conn implementation) func (s *udtSocket) RemoteAddr() net.Addr { return s.raddr } // SetDeadline sets the read and write deadlines associated // with the connection. It is equivalent to calling both // SetReadDeadline and SetWriteDeadline. // // A deadline is an absolute time after which I/O operations // fail with a timeout (see type Error) instead of // blocking. The deadline applies to all future and pending // I/O, not just the immediately following call to Read or // Write. After a deadline has been exceeded, the connection // can be refreshed by setting a deadline in the future. // // An idle timeout can be implemented by repeatedly extending // the deadline after successful Read or Write calls. // // A zero value for t means I/O operations will not time out. // // Note that if a TCP connection has keep-alive turned on, // which is the default unless overridden by Dialer.KeepAlive // or ListenConfig.KeepAlive, then a keep-alive failure may // also return a timeout error. On Unix systems a keep-alive // failure on I/O can be detected using // errors.Is(err, syscall.ETIMEDOUT). // (required for net.Conn implementation) func (s *udtSocket) SetDeadline(t time.Time) error { s.setDeadline(t, &s.readDeadline, &s.readDeadlinePassed) s.setDeadline(t, &s.writeDeadline, &s.writeDeadlinePassed) return nil } func (s *udtSocket) setDeadline(dl time.Time, timer **time.Timer, timerPassed *bool) { if *timer == nil { if !dl.IsZero() { *timer = time.NewTimer(dl.Sub(time.Now())) } } else { now := time.Now() if !dl.IsZero() && dl.Before(now) { *timerPassed = true } oldTime := *timer if dl.IsZero() { *timer = nil } oldTime.Stop() _, _ = <-oldTime.C if !dl.IsZero() && dl.After(now) { *timerPassed = false oldTime.Reset(dl.Sub(time.Now())) } } } // SetReadDeadline sets the deadline for future Read calls // and any currently-blocked Read call. // A zero value for t means Read will not time out. // (required for net.Conn implementation) func (s *udtSocket) SetReadDeadline(t time.Time) error { s.setDeadline(t, &s.readDeadline, &s.readDeadlinePassed) return nil } // SetWriteDeadline sets the deadline for future Write calls // and any currently-blocked Write call. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. // A zero value for t means Write will not time out. // (required for net.Conn implementation) func (s *udtSocket) SetWriteDeadline(t time.Time) error { s.setDeadline(t, &s.writeDeadline, &s.writeDeadlinePassed) return nil } /******************************************************************************* Private functions *******************************************************************************/ // newSocket creates a new UDT socket, which will be configured afterwards as either an incoming our outgoing socket func newSocket(m *multiplexer, config *Config, sockID uint32, isServer bool, isDatagram bool, raddr *net.UDPAddr) (s *udtSocket) { now := time.Now() mtu := m.mtu if config.MaxPacketSize > 0 && config.MaxPacketSize < mtu { mtu = config.MaxPacketSize } maxFlowWinSize := config.MaxFlowWinSize if maxFlowWinSize == 0 { maxFlowWinSize = DefaultConfig().MaxFlowWinSize } if maxFlowWinSize < 32 { maxFlowWinSize = 32 } s = &udtSocket{ m: m, Config: config, raddr: raddr, created: now, sockState: sockStateInit, udtVer: 4, isServer: isServer, mtu: atomicUint32{val: uint32(mtu)}, maxFlowWinSize: maxFlowWinSize, isDatagram: isDatagram, sockID: sockID, initPktSeq: packet.PacketID{Seq: randUint32()}, messageIn: make(chan []byte, 256), messageOut: make(chan sendMessage, 256), recvEvent: make(chan recvPktEvent, 256), sendEvent: make(chan recvPktEvent, 256), sockClosed: make(chan struct{}, 1), sockShutdown: make(chan struct{}, 1), deliveryRate: 16, bandwidth: 1, sendPacket: make(chan packet.Packet, 256), shutdownEvent: make(chan shutdownMessage, 5), } s.cong = newUdtSocketCc(s) return } func (s *udtSocket) launchProcessors() { s.send = newUdtSocketSend(s) s.recv = newUdtSocketRecv(s) s.cong.init(s.initPktSeq) } func (s *udtSocket) startConnect() error { connectWait := &sync.WaitGroup{} s.connectWait = connectWait connectWait.Add(1) s.sockState = sockStateConnecting s.connTimeout = time.After(3 * time.Second) s.connRetry = time.After(250 * time.Millisecond) go s.goManageConnection() s.sendHandshake(0, packet.HsRequest) connectWait.Wait() return s.connectionError() } func (s *udtSocket) startRendezvous() error { connectWait := &sync.WaitGroup{} s.connectWait = connectWait s.connectWait.Add(1) s.sockState = sockStateRendezvous s.connTimeout = time.After(30 * time.Second) s.connRetry = time.After(250 * time.Millisecond) go s.goManageConnection() s.m.startRendezvous(s) s.sendHandshake(0, packet.HsRendezvous) connectWait.Wait() return s.connectionError() } func (s *udtSocket) goManageConnection() { sockClosed := s.sockClosed sockShutdown := s.sockShutdown for { select { case <-s.lingerTimer: // linger timer expired, shut everything down s.m.closeSocket(s.sockID) close(s.sockClosed) return case _, _ = <-sockShutdown: // catching this to force re-evaluation of this select (catching the linger timer) case _, _ = <-sockClosed: return case p := <-s.sendPacket: ts := uint32(time.Now().Sub(s.created) / time.Microsecond) s.cong.onPktSent(p) log.Printf("%s (id=%d) sending %s to %s (id=%d)", s.m.laddr.String(), s.sockID, packet.PacketTypeName(p.PacketType()), s.raddr.String(), s.farSockID) s.m.sendPacket(s.raddr, s.farSockID, ts, p) case sd := <-s.shutdownEvent: // connection shut down s.shutdown(sd.sockState, sd.permitLinger, sd.err) case <-s.connTimeout: // connection timed out s.shutdown(sockStateTimeout, true, nil) case <-s.connRetry: // resend connection attempt s.connRetry = nil switch s.sockState { case sockStateConnecting: s.sendHandshake(0, packet.HsRequest) s.connRetry = time.After(250 * time.Millisecond) case sockStateRendezvous: s.sendHandshake(0, packet.HsRendezvous) s.connRetry = time.After(250 * time.Millisecond) } } } } func (s *udtSocket) sendHandshake(synCookie uint32, reqType packet.HandshakeReqType) { sockType := packet.TypeSTREAM if s.isDatagram { sockType = packet.TypeDGRAM } p := &packet.HandshakePacket{ UdtVer: uint32(s.udtVer), SockType: sockType, InitPktSeq: s.initPktSeq, MaxPktSize: s.mtu.get(), // maximum packet size (including UDP/IP headers) MaxFlowWinSize: uint32(s.maxFlowWinSize), // maximum flow window size ReqType: reqType, SockID: s.sockID, SynCookie: synCookie, SockAddr: s.raddr.IP, } ts := uint32(time.Now().Sub(s.created) / time.Microsecond) s.cong.onPktSent(p) log.Printf("%s (id=%d) sending handshake(%d) to %s (id=%d)", s.m.laddr.String(), s.sockID, int(reqType), s.raddr.String(), s.farSockID) s.m.sendPacket(s.raddr, s.farSockID, ts, p) } // checkValidHandshake checks to see if we want to accept a new connection with this handshake. func (s *udtSocket) checkValidHandshake(m *multiplexer, p *packet.HandshakePacket, from *net.UDPAddr) bool { if s.udtVer != 4 { return false } return true } // readHandshake is received when a handshake packet is received without a destination, either as part // of a listening response or as a rendezvous connection func (s *udtSocket) readHandshake(m *multiplexer, p *packet.HandshakePacket, from *net.UDPAddr) bool { if !from.IP.Equal(s.raddr.IP) || from.Port != s.raddr.Port { log.Printf("huh? initted with %s but handshake with %s", s.raddr.String(), from.String()) return false } switch s.sockState { case sockStateInit: // server accepting a connection from a client s.initPktSeq = p.InitPktSeq s.udtVer = int(p.UdtVer) s.farSockID = p.SockID s.isDatagram = p.SockType == packet.TypeDGRAM if s.mtu.get() > p.MaxPktSize { s.mtu.set(p.MaxPktSize) } s.launchProcessors() s.recv.configureHandshake(p) s.send.configureHandshake(p, true) s.sockState = sockStateConnected s.connTimeout = nil s.connRetry = nil go s.goManageConnection() s.sendHandshake(p.SynCookie, packet.HsResponse) return true case sockStateConnecting: // client attempting to connect to server if p.ReqType == packet.HsRefused { s.sockState = sockStateRefused return true } if p.ReqType == packet.HsRequest { if !s.checkValidHandshake(m, p, from) || p.InitPktSeq != s.initPktSeq || !from.IP.Equal(s.raddr.IP) || from.Port != s.raddr.Port || s.isDatagram != (p.SockType == packet.TypeDGRAM) { // ignore, not a valid handshake request return true } // handshake isn't done yet, send it back with the cookie we received s.sendHandshake(p.SynCookie, packet.HsResponse) return true } if p.ReqType != packet.HsResponse { // unexpected packet type, ignore return true } if !s.checkValidHandshake(m, p, from) || p.InitPktSeq != s.initPktSeq || !from.IP.Equal(s.raddr.IP) || from.Port != s.raddr.Port || s.isDatagram != (p.SockType == packet.TypeDGRAM) { // ignore, not a valid handshake request return true } s.farSockID = p.SockID if s.mtu.get() > p.MaxPktSize { s.mtu.set(p.MaxPktSize) } s.launchProcessors() s.recv.configureHandshake(p) s.send.configureHandshake(p, true) s.connRetry = nil s.sockState = sockStateConnected s.connTimeout = nil if s.connectWait != nil { s.connectWait.Done() s.connectWait = nil } return true case sockStateRendezvous: // client attempting to rendezvous with another client if p.ReqType == packet.HsRefused { s.sockState = sockStateRefused return true } if p.ReqType != packet.HsRendezvous || s.farSockID == 0 { return true // not a request packet, ignore } if !s.checkValidHandshake(m, p, from) || !from.IP.Equal(s.raddr.IP) || from.Port != s.raddr.Port || s.isDatagram != (p.SockType == packet.TypeDGRAM) { // not a compatible handshake, ignore return true } /* not quite sure how to negotiate this, assuming split-brain for now if p.InitPktSeq != s.initPktSeq { s.sockState = sockStateCorrupted return true } */ s.farSockID = p.SockID s.m.endRendezvous(s) if s.mtu.get() > p.MaxPktSize { s.mtu.set(p.MaxPktSize) } s.launchProcessors() s.recv.configureHandshake(p) s.send.configureHandshake(p, false) s.connRetry = nil s.sockState = sockStateConnected s.connTimeout = nil if s.connectWait != nil { s.connectWait.Done() s.connectWait = nil } // send the final rendezvous packet s.sendHandshake(p.SynCookie, packet.HsResponse) return true case sockStateConnected: // server repeating a handshake to a client if s.isServer && p.ReqType == packet.HsRequest { // client didn't receive our response handshake, resend it s.sendHandshake(p.SynCookie, packet.HsResponse) } else if !s.isServer && p.ReqType == packet.HsResponse { // this is a rendezvous connection (re)send our response s.sendHandshake(p.SynCookie, packet.HsResponse2) } return true } return false } func (s *udtSocket) shutdown(sockState sockState, permitLinger bool, err error) { if !s.isOpen() { return // already closed } if err != nil { log.Printf("socket shutdown (type=%d), due to error: %s", int(sockState), err.Error()) } else { log.Printf("socket shutdown (type=%d)", int(sockState)) } if s.sockState == sockStateRendezvous { s.m.endRendezvous(s) } if s.connectWait != nil { s.connectWait.Done() s.connectWait = nil } s.sockState = sockState s.cong.close() if permitLinger { linger := s.Config.LingerTime if linger == 0 { linger = DefaultConfig().LingerTime } s.lingerTimer = time.After(linger) } s.connTimeout = nil s.connRetry = nil if permitLinger { close(s.sockShutdown) } else { s.m.closeSocket(s.sockID) close(s.sockClosed) } s.messageIn <- nil } func absdiff(a uint, b uint) uint { if a < b { return b - a } return a - b } func (s *udtSocket) applyRTT(rtt uint) { s.rttProt.Lock() s.rttVar = (s.rttVar*3 + absdiff(s.rtt, rtt)) >> 2 s.rtt = (s.rtt*7 + rtt) >> 3 s.rttProt.Unlock() } func (s *udtSocket) getRTT() (rtt, rttVar uint) { s.rttProt.RLock() rtt = s.rtt rttVar = s.rttVar s.rttProt.RUnlock() return } // Update Estimated Bandwidth and packet delivery rate func (s *udtSocket) applyReceiveRates(deliveryRate uint, bandwidth uint) { s.receiveRateProt.Lock() if deliveryRate > 0 { s.deliveryRate = (s.deliveryRate*7 + deliveryRate) >> 3 } if bandwidth > 0 { s.bandwidth = (s.bandwidth*7 + bandwidth) >> 3 } s.receiveRateProt.Unlock() } func (s *udtSocket) getRcvSpeeds() (deliveryRate uint, bandwidth uint) { s.receiveRateProt.RLock() deliveryRate = s.deliveryRate bandwidth = s.bandwidth s.receiveRateProt.RUnlock() return } // called by the multiplexer read loop when a packet is received for this socket. // Minimal processing is permitted but try not to stall the caller func (s *udtSocket) readPacket(m *multiplexer, p packet.Packet, from *net.UDPAddr) { now := time.Now() if s.sockState == sockStateClosed { return } if !from.IP.Equal(s.raddr.IP) || from.Port != s.raddr.Port { log.Printf("Socket connected to %s received a packet from %s? Discarded", s.raddr.String(), from.String()) return } s.recvEvent <- recvPktEvent{pkt: p, now: now} switch sp := p.(type) { case *packet.HandshakePacket: // sent by both peers s.readHandshake(m, sp, from) case *packet.ShutdownPacket: // sent by either peer s.shutdownEvent <- shutdownMessage{sockState: sockStateClosed, permitLinger: true} case *packet.AckPacket, *packet.LightAckPacket, *packet.NakPacket: // receiver -> sender s.sendEvent <- recvPktEvent{pkt: p, now: now} case *packet.UserDefControlPacket: s.cong.onCustomMsg(*sp) } } <file_sep>/udt/packet/packet_congestion.go package packet // Structure of packets and functions for writing/reading them // CongestionPacket is a (deprecated) UDT packet notifying the peer of increased congestion type CongestionPacket struct { ctrlHeader } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *CongestionPacket) WriteTo(buf []byte) (uint, error) { return p.writeHdrTo(buf, ptCongestion, 0) } func (p *CongestionPacket) readFrom(data []byte) (err error) { _, err = p.readHdrFrom(data) return } // PacketType returns the packetType associated with this packet func (p *CongestionPacket) PacketType() PacketType { return ptCongestion } <file_sep>/udt/packet/packet_msgdropreq.go package packet // Structure of packets and functions for writing/reading them import ( "errors" ) // MsgDropReqPacket is a UDT packet notifying the peer of expired packets not worth trying to send type MsgDropReqPacket struct { ctrlHeader MsgID uint32 // Message ID FirstSeq PacketID // First sequence number in the message LastSeq PacketID // Last sequence number in the message } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *MsgDropReqPacket) WriteTo(buf []byte) (uint, error) { l := len(buf) if l < 24 { return 0, errors.New("packet too small") } if _, err := p.writeHdrTo(buf, ptMsgDropReq, p.MsgID); err != nil { return 0, err } endianness.PutUint32(buf[16:20], p.FirstSeq.Seq) endianness.PutUint32(buf[20:24], p.LastSeq.Seq) return 24, nil } func (p *MsgDropReqPacket) readFrom(data []byte) (err error) { l := len(data) if l < 24 { return errors.New("packet too small") } if p.MsgID, err = p.readHdrFrom(data); err != nil { return } p.FirstSeq = PacketID{endianness.Uint32(data[16:20])} p.LastSeq = PacketID{endianness.Uint32(data[20:24])} return } // PacketType returns the packetType associated with this packet func (p *MsgDropReqPacket) PacketType() PacketType { return ptMsgDropReq } <file_sep>/udt/packet/packet_keepalive.go package packet // Structure of packets and functions for writing/reading them // KeepAlivePacket is a UDT packet used to keep a connection alive when no data is being sent type KeepAlivePacket struct { ctrlHeader } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *KeepAlivePacket) WriteTo(buf []byte) (uint, error) { return p.writeHdrTo(buf, ptKeepalive, 0) } func (p *KeepAlivePacket) readFrom(data []byte) (err error) { _, err = p.readHdrFrom(data) return } // PacketType returns the packetType associated with this packet func (p *KeepAlivePacket) PacketType() PacketType { return ptKeepalive } <file_sep>/udt/datapacket_heap.go package udt import ( "container/heap" "github.com/odysseus654/go-udt/udt/packet" ) // receiveLossList defines a list of recvLossEntry records sorted by their packet ID type dataPacketHeap []*packet.DataPacket func (h dataPacketHeap) Len() int { return len(h) } func (h dataPacketHeap) Less(i, j int) bool { return h[i].Seq.Seq < h[j].Seq.Seq } func (h dataPacketHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *dataPacketHeap) Push(x interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, not just its contents. *h = append(*h, x.(*packet.DataPacket)) } func (h *dataPacketHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // Find does a binary search of the heap for the specified packetID which is returned func (h dataPacketHeap) Find(packetID packet.PacketID) (*packet.DataPacket, int) { len := len(h) idx := 0 for idx < len { pid := h[idx].Seq if pid == packetID { return h[idx], idx } else if pid.Seq > packetID.Seq { idx = idx * 2 } else { idx = idx*2 + 1 } } return nil, -1 } // Min does a binary search of the heap for the entry with the lowest packetID greater than or equal to the specified value func (h dataPacketHeap) Min(greaterEqual packet.PacketID, lessEqual packet.PacketID) (*packet.DataPacket, int) { len := len(h) idx := 0 wrapped := greaterEqual.Seq > lessEqual.Seq for idx < len { pid := h[idx].Seq var next int if pid.Seq == greaterEqual.Seq { return h[idx], idx } else if pid.Seq >= greaterEqual.Seq { next = idx * 2 } else { next = idx*2 + 1 } if next >= len && h[idx].Seq.Seq > greaterEqual.Seq && (wrapped || h[idx].Seq.Seq <= lessEqual.Seq) { return h[idx], idx } idx = next } // can't find any packets with greater value, wrap around if wrapped { idx = 0 for { next := idx * 2 if next >= len && h[idx].Seq.Seq <= lessEqual.Seq { return h[idx], idx } idx = next } } return nil, -1 } // Remove does a binary search of the heap for the specified packetID, which is removed func (h *dataPacketHeap) Remove(packetID packet.PacketID) bool { len := len(*h) idx := 0 for idx < len { pid := (*h)[idx].Seq if pid.Seq == packetID.Seq { heap.Remove(h, idx) return true } else if pid.Seq > packetID.Seq { idx = idx * 2 } else { idx = idx*2 + 1 } } return false } <file_sep>/udt/multiplexer.go package udt import ( "context" "fmt" "log" "net" "runtime" "sync" "sync/atomic" "syscall" "github.com/odysseus654/go-udt/udt/packet" ) // packetWrapper is used to explicitly designate the destination of a packet, // to assist with sending it to its destination type packetWrapper struct { pkt packet.Packet dest *net.UDPAddr } /* A multiplexer multiplexes multiple UDT sockets over a single PacketConn. */ type multiplexer struct { network string laddr *net.UDPAddr // the local address handled by this multiplexer conn net.PacketConn // the UDPConn from which we read/write sockets sync.Map // the udtSockets handled by this multiplexer, by sockId rvSockets sync.Map // the list of any sockets currently in rendezvous mode listenSock *listener // the server socket listening to incoming connections, if there is one servSockMutex sync.Mutex mtu uint // the Maximum Transmission Unit of packets sent from this address nextSid uint32 // the SockID for the next socket created pktOut chan packetWrapper // packets queued for immediate sending } /* multiplexerFor gets or creates a multiplexer for the given local address. If a new multiplexer is created, the given init function is run to obtain an io.ReadWriter. */ func multiplexerFor(ctx context.Context, network string, laddr string) (*multiplexer, error) { key := fmt.Sprintf("%s:%s", network, laddr) if ifM, ok := multiplexers.Load(key); ok { m := ifM.(*multiplexer) if m.isLive() { // checking this in case we have a race condition with multiplexer destruction return m, nil } } // No multiplexer, need to create connection // try to avoid fragmentation (and hopefully be notified if we exceed path MTU) config := net.ListenConfig{} config.Control = func(network, address string, c syscall.RawConn) error { return c.Control(func(fd uintptr) { var err error os := runtime.GOOS switch os { case "windows": //err = syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, 14 /* IP_DONTFRAGMENT for winsock2 */, 1) err = syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, 71 /* IP_MTU_DISCOVER for winsock2 */, 2 /* IP_PMTUDISC_DO */) case "linux", "android": err = syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, 10 /* IP_MTU_DISCOVER */, 2 /* IP_PMTUDISC_DO */) default: err = syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, 67 /* IP_DONTFRAG */, 1) } if err != nil { log.Printf("error on setSockOpt: %s", err.Error()) } }) } //conn, err := net.ListenUDP(network, laddr) conn, err := config.ListenPacket(ctx, network, laddr) if err != nil { return nil, err } addr := conn.LocalAddr().(*net.UDPAddr) m := newMultiplexer(network, addr, conn) multiplexers.Store(key, m) return m, nil } func newMultiplexer(network string, laddr *net.UDPAddr, conn net.PacketConn) (m *multiplexer) { mtu, _ := discoverMTU(laddr.IP) m = &multiplexer{ network: network, laddr: laddr, conn: conn, mtu: mtu, nextSid: randUint32(), // Socket ID MUST start from a random value pktOut: make(chan packetWrapper, 100), // todo: figure out how to size this } go m.goRead() go m.goWrite() return } func (m *multiplexer) key() string { return fmt.Sprintf("%s:%s", m.network, m.laddr.String()) } func (m *multiplexer) listenUDT(l *listener) bool { m.servSockMutex.Lock() defer m.servSockMutex.Unlock() if m.listenSock != nil { return false } m.listenSock = l return true } func (m *multiplexer) unlistenUDT(l *listener) bool { m.servSockMutex.Lock() if m.listenSock != l { m.servSockMutex.Unlock() return false } m.listenSock = nil m.servSockMutex.Unlock() m.checkLive() return true } // Adapted from https://github.com/hlandau/degoutils/blob/master/net/mtu.go const absMaxDatagramSize = 2147483646 // 2**31-2 func discoverMTU(ourIP net.IP) (uint, error) { ifaces, err := net.Interfaces() if err != nil { return 65535, err } var filtered []net.Interface for _, iface := range ifaces { addrs, err := iface.Addrs() if err != nil { log.Printf("cannot retrieve iface addresses for %s: %s", iface.Name, err.Error()) continue } for _, a := range addrs { var ipnet *net.IPNet switch v := a.(type) { case *net.IPAddr: ipnet = &net.IPNet{IP: v.IP, Mask: v.IP.DefaultMask()} case *net.IPNet: ipnet = v } if ipnet == nil { log.Printf("cannot retrieve IPNet from address %s on interface %s", a.String(), iface.Name) continue } if ipnet.Contains(ourIP) { filtered = append(filtered, iface) } } } if len(filtered) == 0 { log.Printf("cannot identify interface(s) associated with %s, doing blind search", ourIP.String()) filtered = ifaces } var mtu int = 65535 for _, iface := range filtered { if iface.Flags&(net.FlagUp|net.FlagLoopback) == net.FlagUp && iface.MTU > mtu { mtu = iface.MTU } } if mtu > absMaxDatagramSize { mtu = absMaxDatagramSize } return uint(mtu), nil } func (m *multiplexer) newSocket(config *Config, peer *net.UDPAddr, isServer bool, isDatagram bool) (s *udtSocket) { sid := atomic.AddUint32(&m.nextSid, ^uint32(0)) s = newSocket(m, config, sid, isServer, isDatagram, peer) m.sockets.Store(sid, s) return s } func (m *multiplexer) closeSocket(sockID uint32) bool { if _, ok := m.sockets.Load(sockID); !ok { return false } m.sockets.Delete(sockID) m.checkLive() return true } func (m *multiplexer) checkLive() bool { if m.conn == nil { // have we already been destructed ? return false } if m.isLive() { // are we currently in use? return true } // deregister this multiplexer key := m.key() multiplexers.Delete(key) if m.isLive() { // checking this in case we have a race condition with multiplexer destruction multiplexers.Store(key, m) return true } // tear everything down m.conn.Close() close(m.pktOut) return false } func (m *multiplexer) isLive() bool { if m.conn == nil { return false } m.servSockMutex.Lock() if m.listenSock != nil { m.servSockMutex.Unlock() return true } m.servSockMutex.Unlock() isEmpty := true m.rvSockets.Range(func(key, val interface{}) bool { isEmpty = false return false }) if !isEmpty { return true } m.sockets.Range(func(key, val interface{}) bool { isEmpty = false return false }) return !isEmpty } func (m *multiplexer) startRendezvous(s *udtSocket) { peer := s.raddr.String() m.rvSockets.Store(peer, s) } func (m *multiplexer) endRendezvous(s *udtSocket) { peer := s.raddr.String() sock, ok := m.rvSockets.Load(peer) if ok && sock.(*udtSocket) == s { m.rvSockets.Delete(peer) } } /* read runs in a goroutine and reads packets from conn using a buffer from the readBufferPool, or a new buffer. */ func (m *multiplexer) goRead() { buf := make([]byte, m.mtu) for { numBytes, from, err := m.conn.ReadFrom(buf) if err != nil { return } m.readPacket(buf, numBytes, from) } } func (m *multiplexer) readPacket(buf []byte, numBytes int, from net.Addr) { p, err := packet.ReadPacketFrom(buf[0:numBytes]) if err != nil { log.Printf("Unable to read packet: %s", err) return } // attempt to route the packet sockID := p.SocketID() if sockID == 0 { var hsPacket *packet.HandshakePacket var ok bool if hsPacket, ok = p.(*packet.HandshakePacket); !ok { log.Printf("Received non-handshake packet with destination socket = 0") return } foundMatch := false m.rvSockets.Range(func(key, val interface{}) bool { if val.(*udtSocket).readHandshake(m, hsPacket, from.(*net.UDPAddr)) { foundMatch = true return false } return true }) if foundMatch { return } m.servSockMutex.Lock() if m.listenSock != nil { m.listenSock.readHandshake(m, hsPacket, from.(*net.UDPAddr)) } m.servSockMutex.Unlock() } if ifDestSock, ok := m.sockets.Load(sockID); ok { ifDestSock.(*udtSocket).readPacket(m, p, from.(*net.UDPAddr)) } } /* write runs in a goroutine and writes packets to conn using a buffer from the writeBufferPool, or a new buffer. */ func (m *multiplexer) goWrite() { buf := make([]byte, m.mtu) pktOut := m.pktOut for { select { case pw, ok := <-pktOut: if !ok { return } plen, err := pw.pkt.WriteTo(buf) if err != nil { // TODO: handle write error log.Fatalf("Unable to buffer out: %s", err.Error()) continue } if _, err = m.conn.WriteTo(buf[0:plen], pw.dest); err != nil { // TODO: handle write error log.Fatalf("Unable to write out: %s", err.Error()) } } } } func (m *multiplexer) sendPacket(destAddr *net.UDPAddr, destSockID uint32, ts uint32, p packet.Packet) { p.SetHeader(destSockID, ts) if destSockID == 0 { if _, ok := p.(*packet.HandshakePacket); !ok { log.Fatalf("Sending non-handshake packet with destination socket = 0") } } m.pktOut <- packetWrapper{pkt: p, dest: destAddr} } <file_sep>/udt/duration_array.go package udt import "time" type sortableDurnArray []time.Duration func (a sortableDurnArray) Len() int { return len(a) } func (a sortableDurnArray) Less(i, j int) bool { return a[i] < a[j] } func (a sortableDurnArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] } <file_sep>/udt/packet/packet_ack_test.go package packet import ( "testing" ) func TestACKPacket(t *testing.T) { pkt1 := &AckPacket{ AckSeqNo: 90, PktSeqHi: PacketID{Seq: 91}, Rtt: 92, RttVar: 93, BuffAvail: 94, IncludeLink: true, PktRecvRate: 95, EstLinkCap: 96, } pkt1.SetHeader(59, 100) testPacket(pkt1, t) pkt2 := &AckPacket{ AckSeqNo: 90, PktSeqHi: PacketID{Seq: 91}, Rtt: 92, RttVar: 93, BuffAvail: 94, IncludeLink: false, } pkt2.SetHeader(59, 100) testPacket(pkt2, t) } <file_sep>/udt/udt.go package udt /* Package udt provides a pure Go implementation of the UDT protocol per http://udt.sourceforge.net/doc/draft-gg-udt-03.txt. udt does not implement all of the spec. In particular, the following are not implemented: - Rendezvous mode - STREAM mode (only UDP is supported) */ import ( "context" "crypto/rand" "log" "math" "math/big" "net" "sync" "time" ) // DialUDT establishes an outbound UDT connection using the supplied net, laddr and raddr. // See function net.DialUDP for a description of net, laddr and raddr. func DialUDT(network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { return dialUDT(context.Background(), DefaultConfig(), network, laddr, raddr, isStream) } // DialUDTContext establishes an outbound UDT connection using the supplied net, laddr and raddr. // See function net.DialUDP for a description of net, laddr and raddr. func DialUDTContext(ctx context.Context, network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { return dialUDT(ctx, DefaultConfig(), network, laddr, raddr, isStream) } // ListenUDT listens for incoming UDT connections addressed to the local address laddr. // See function net.ListenUDP for a description of net and laddr. func ListenUDT(network string, addr string) (net.Listener, error) { return listenUDT(context.Background(), DefaultConfig(), network, addr) } // ListenUDTContext listens for incoming UDT connections addressed to the local address laddr. // See function net.ListenUDP for a description of net and laddr. func ListenUDTContext(ctx context.Context, network string, addr string) (net.Listener, error) { return listenUDT(ctx, DefaultConfig(), network, addr) } // RendezvousUDT establishes an outbound UDT connection using the supplied net, laddr and raddr. // See function net.DialUDP for a description of net, laddr and raddr. func RendezvousUDT(network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { return rendezvousUDT(context.Background(), DefaultConfig(), network, laddr, raddr, isStream) } // RendezvousUDTContext establishes an outbound UDT connection using the supplied net, laddr and raddr. // See function net.DialUDP for a description of net, laddr and raddr. func RendezvousUDTContext(ctx context.Context, network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { return rendezvousUDT(ctx, DefaultConfig(), network, laddr, raddr, isStream) } func dialUDT(ctx context.Context, config *Config, network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { m, err := multiplexerFor(ctx, network, laddr) if err != nil { return nil, &net.OpError{Op: "dial", Net: network, Source: nil, Addr: raddr, Err: err} } s := m.newSocket(config, raddr, false, !isStream) err = s.startConnect() if err != nil { return nil, &net.OpError{Op: "dial", Net: network, Source: nil, Addr: raddr, Err: err} } return s, err } func rendezvousUDT(ctx context.Context, config *Config, network string, laddr string, raddr *net.UDPAddr, isStream bool) (net.Conn, error) { m, err := multiplexerFor(ctx, network, laddr) if err != nil { return nil, &net.OpError{Op: "rendezvous", Net: network, Source: nil, Addr: raddr, Err: err} } s := m.newSocket(config, raddr, false, !isStream) err = s.startRendezvous() if err != nil { return nil, &net.OpError{Op: "rendezvous", Net: network, Source: nil, Addr: raddr, Err: err} } return s, nil } const ( synTime time.Duration = 10000 * time.Microsecond ) var ( multiplexers sync.Map bigMaxUint32 *big.Int ) func init() { bigMaxUint32 = big.NewInt(math.MaxUint32) } /* randInt32 generates a secure random value between 0 and the max possible uint32 */ func randUint32() (r uint32) { if _r, err := rand.Int(rand.Reader, bigMaxUint32); err != nil { log.Fatalf("Unable to generate random uint32: %s", err) } else { r = uint32(_r.Uint64()) } return } <file_sep>/udt/packet/packet_err.go package packet // Structure of packets and functions for writing/reading them // ErrPacket is a (undocumented) UDT packet describing an out-of-band error code type ErrPacket struct { ctrlHeader Errno uint32 // error code } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *ErrPacket) WriteTo(buf []byte) (uint, error) { return p.writeHdrTo(buf, ptSpecialErr, p.Errno) } func (p *ErrPacket) readFrom(data []byte) (err error) { p.Errno, err = p.readHdrFrom(data) return } // PacketType returns the packetType associated with this packet func (p *ErrPacket) PacketType() PacketType { return ptSpecialErr } <file_sep>/udt/congestion_native.go package udt import ( "math" "time" "github.com/odysseus654/go-udt/udt/packet" ) // NativeCongestionControl implements the default congestion control logic for UDP type NativeCongestionControl struct { rcInterval time.Duration // UDT Rate control interval lastRCTime time.Time // last rate increase time slowStart bool // if in slow start phase lastAck packet.PacketID // last ACKed seq no loss bool // if loss happened since last rate increase lastDecSeq packet.PacketID // biggest sequence number when last time the packet sending rate is decreased lastDecPeriod time.Duration // value of PacketSendPeriod when last decrease happened nakCount int // current number of NAKs in the current period decRandom int // random threshold on decrease by number of loss events avgNAKNum int // average number of NAKs in a congestion period decCount int // number of decreases in a congestion epoch } // Init to be called (only) at the start of a UDT connection. func (ncc NativeCongestionControl) Init(parms CongestionControlParms) { ncc.rcInterval = synTime ncc.lastRCTime = time.Now() parms.SetACKPeriod(ncc.rcInterval) ncc.slowStart = true ncc.lastAck = parms.GetSndCurrSeqNo() ncc.loss = false ncc.lastDecSeq = ncc.lastAck.Add(-1) ncc.lastDecPeriod = 1 * time.Microsecond ncc.avgNAKNum = 0 ncc.nakCount = 0 ncc.decRandom = 1 parms.SetCongestionWindowSize(16) parms.SetPacketSendPeriod(1 * time.Microsecond) } // Close to be called when a UDT connection is closed. func (ncc NativeCongestionControl) Close(parms CongestionControlParms) { // nothing done for this event } // OnACK to be called when an ACK packet is received func (ncc NativeCongestionControl) OnACK(parms CongestionControlParms, ack packet.PacketID) { currTime := time.Now() if currTime.Sub(ncc.lastRCTime) < ncc.rcInterval { return } ncc.lastRCTime = currTime cWndSize := parms.GetCongestionWindowSize() pktSendPeriod := parms.GetPacketSendPeriod() recvRate, bandwidth := parms.GetReceiveRates() rtt := parms.GetRTT() // If the current status is in the slow start phase, set the congestion window // size to the product of packet arrival rate and (RTT + SYN). Slow Start ends. Stop. if ncc.slowStart { cWndSize = uint(int(cWndSize) + int(ack.BlindDiff(ncc.lastAck))) ncc.lastAck = ack if cWndSize > parms.GetMaxFlowWindow() { ncc.slowStart = false if recvRate > 0 { parms.SetPacketSendPeriod(time.Second / time.Duration(recvRate)) } else { parms.SetPacketSendPeriod((rtt + ncc.rcInterval) / time.Duration(cWndSize)) } } else { // During Slow Start, no rate increase parms.SetCongestionWindowSize(cWndSize) return } } else { // Set the congestion window size (CWND) to: CWND = A * (RTT + SYN) + 16. cWndSize = uint((float64(recvRate)/float64(time.Second))*float64(rtt+ncc.rcInterval) + 16) } if ncc.loss { ncc.loss = false parms.SetCongestionWindowSize(cWndSize) return } /* The number of sent packets to be increased in the next SYN period (inc) is calculated as: if (B <= C) inc = 1/PS; else inc = max(10^(ceil(log10((B-C)*PS*8))) * Beta/PS, 1/PS); where B is the estimated link capacity and C is the current sending speed. All are counted as packets per second. PS is the fixed size of UDT packet counted in bytes. Beta is a constant value of 0.0000015. */ // Note: 1/24/2012 // The minimum increase parameter is increased from "1.0 / m_iMSS" to 0.01 // because the original was too small and caused sending rate to stay at low level // for long time. var inc float64 const minInc float64 = 0.01 B := time.Duration(bandwidth) - time.Second/time.Duration(pktSendPeriod) bandwidth9 := time.Duration(bandwidth / 9) if (pktSendPeriod > ncc.lastDecPeriod) && (bandwidth9 < B) { B = bandwidth9 } if B <= 0 { inc = minInc } else { // inc = max(10 ^ ceil(log10( B * MSS * 8 ) * Beta / MSS, 1/MSS) // Beta = 1.5 * 10^(-6) mss := parms.GetMSS() inc = math.Pow10(int(math.Ceil(math.Log10(float64(B)*float64(mss)*8.0)))) * 0.0000015 / float64(mss) if inc < minInc { inc = minInc } } // The SND period is updated as: SND = (SND * SYN) / (SND * inc + SYN). parms.SetPacketSendPeriod(time.Duration(float64(pktSendPeriod*ncc.rcInterval) / (float64(pktSendPeriod)*inc + float64(ncc.rcInterval)))) } // OnNAK to be called when a loss report is received func (ncc NativeCongestionControl) OnNAK(parms CongestionControlParms, losslist []packet.PacketID) { // If it is in slow start phase, set inter-packet interval to 1/recvrate. Slow start ends. Stop. if ncc.slowStart { ncc.slowStart = false recvRate, _ := parms.GetReceiveRates() if recvRate > 0 { // Set the sending rate to the receiving rate. parms.SetPacketSendPeriod(time.Second / time.Duration(recvRate)) return } // If no receiving rate is observed, we have to compute the sending // rate according to the current window size, and decrease it // using the method below. parms.SetPacketSendPeriod(time.Duration(float64(time.Microsecond) * float64(parms.GetCongestionWindowSize()) / float64(parms.GetRTT()+ncc.rcInterval))) } ncc.loss = true /* 2) If this NAK starts a new congestion period, increase inter-packet interval (snd) to snd = snd * 1.125; Update AvgNAKNum, reset NAKCount to 1, and compute DecRandom to a random (average distribution) number between 1 and AvgNAKNum. Update LastDecSeq. Stop. 3) If DecCount <= 5, and NAKCount == DecCount * DecRandom: a. Update SND period: SND = SND * 1.125; b. Increase DecCount by 1; c. Record the current largest sent sequence number (LastDecSeq). */ pktSendPeriod := parms.GetPacketSendPeriod() if ncc.lastDecSeq.BlindDiff(losslist[0]) > 0 { ncc.lastDecPeriod = pktSendPeriod parms.SetPacketSendPeriod(pktSendPeriod * 1125 / 1000) ncc.avgNAKNum = int(math.Ceil(float64(ncc.avgNAKNum)*0.875 + float64(ncc.nakCount)*0.125)) ncc.nakCount = 1 ncc.decCount = 1 ncc.lastDecSeq = parms.GetSndCurrSeqNo() // remove global synchronization using randomization rand := float64(randUint32()) / math.MaxUint32 ncc.decRandom = int(math.Ceil(float64(ncc.avgNAKNum) * rand)) if ncc.decRandom < 1 { ncc.decRandom = 1 } } else { if ncc.decCount < 5 { ncc.nakCount++ if ncc.nakCount%ncc.decRandom != 0 { ncc.decCount++ return } } ncc.decCount++ // 0.875^5 = 0.51, rate should not be decreased by more than half within a congestion period parms.SetPacketSendPeriod(pktSendPeriod * 1125 / 1000) ncc.lastDecSeq = parms.GetSndCurrSeqNo() } } // OnTimeout to be called when a timeout event occurs func (ncc NativeCongestionControl) OnTimeout(parms CongestionControlParms) { if ncc.slowStart { ncc.slowStart = false recvRate, _ := parms.GetReceiveRates() if recvRate > 0 { parms.SetPacketSendPeriod(time.Second / time.Duration(recvRate)) } else { parms.SetPacketSendPeriod(time.Duration(float64(time.Microsecond) * float64(parms.GetCongestionWindowSize()) / float64(parms.GetRTT()+ncc.rcInterval))) } } else { /* pktSendPeriod := parms.GetPacketSendPeriod() ncc.lastDecPeriod = pktSendPeriod parms.SetPacketSendPeriod(math.Ceil(pktSendPeriod * 2)) ncc.lastDecSeq = ncc.lastAck */ } } // OnPktSent to be called when data is sent func (ncc NativeCongestionControl) OnPktSent(parms CongestionControlParms, pkt packet.Packet) { // nothing done for this event } // OnPktRecv to be called when a data is received func (ncc NativeCongestionControl) OnPktRecv(parms CongestionControlParms, pkt packet.DataPacket) { // nothing done for this event } // OnCustomMsg to process a user-defined packet func (ncc NativeCongestionControl) OnCustomMsg(parms CongestionControlParms, pkt packet.UserDefControlPacket) { // nothing done for this event } <file_sep>/udt/acceptsock_heap.go package udt import ( "container/heap" "time" "github.com/odysseus654/go-udt/udt/packet" ) type acceptSockInfo struct { sockID uint32 initSeqNo packet.PacketID lastTouch time.Time sock *udtSocket } // acceptSockHeap defines a list of acceptSockInfo records sorted by their peer socketID and initial sequence number type acceptSockHeap []acceptSockInfo func (h acceptSockHeap) Len() int { return len(h) } func (h acceptSockHeap) Less(i, j int) bool { if h[i].sockID != h[j].sockID { return h[i].sockID < h[j].sockID } return h[i].initSeqNo.Seq < h[j].initSeqNo.Seq } func (h acceptSockHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *acceptSockHeap) Push(x interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, not just its contents. *h = append(*h, x.(acceptSockInfo)) } func (h *acceptSockHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func (h acceptSockHeap) compare(sockID uint32, initSeqNo packet.PacketID, idx int) int { if sockID < h[idx].sockID { return -1 } if sockID > h[idx].sockID { return +1 } if initSeqNo.Seq < h[idx].initSeqNo.Seq { return -1 } if initSeqNo.Seq > h[idx].initSeqNo.Seq { return +1 } return 0 } // Find does a binary search of the heap for the specified packetID which is returned func (h acceptSockHeap) Find(sockID uint32, initSeqNo packet.PacketID) (*udtSocket, int) { len := len(h) idx := 0 for idx < len { cmp := h.compare(sockID, initSeqNo, idx) if cmp == 0 { return h[idx].sock, idx } else if cmp > 0 { idx = idx * 2 } else { idx = idx*2 + 1 } } return nil, -1 } // Prune removes any entries that have a lastTouched before the specified time func (h *acceptSockHeap) Prune(pruneBefore time.Time) { for { l := len(*h) foundOne := false for idx := 0; idx < l; idx++ { if (*h)[idx].lastTouch.Before(pruneBefore) { foundOne = true heap.Remove(h, idx) break } } if !foundOne { // nothing left to prune return } } } <file_sep>/udt/packet/packet_handshake_test.go package packet import ( "net" "testing" ) func TestHandshakePacket(t *testing.T) { pkt1 := &HandshakePacket{ UdtVer: 4, SockType: TypeDGRAM, InitPktSeq: PacketID{Seq: 50}, MaxPktSize: 1000, MaxFlowWinSize: 500, ReqType: 1, SockID: 59, SynCookie: 978, SockAddr: net.ParseIP("127.0.0.1"), } pkt1.SetHeader(59, 100) read := testPacket(pkt1, t) t.Log((read.(*HandshakePacket)).SockAddr) } <file_sep>/udt/udtsocket_recv.go package udt import ( "container/heap" "log" "time" "github.com/furstenheim/nth_element/FloydRivest" "github.com/odysseus654/go-udt/udt/packet" ) const ( ackSelfClockInterval = 64 ) type udtSocketRecv struct { // channels sockClosed <-chan struct{} // closed when socket is closed sockShutdown <-chan struct{} // closed when socket is shutdown recvEvent <-chan recvPktEvent // receiver: ingest the specified packet. Sender is readPacket, receiver is goReceiveEvent messageIn chan<- []byte // inbound messages. Sender is goReceiveEvent->ingestData, Receiver is client caller (Read) sendPacket chan<- packet.Packet // send a packet out on the wire socket *udtSocket farNextPktSeq packet.PacketID // the peer's next largest packet ID expected. farRecdPktSeq packet.PacketID // the peer's last "received" packet ID (before any loss events) lastACK uint32 // last ACK packet we've sent largestACK uint32 // largest ACK packet we've sent that has been acknowledged (by an ACK2). recvPktPend dataPacketHeap // list of packets that are waiting to be processed. recvLossList receiveLossHeap // loss list. ackHistory ackHistoryHeap // list of sent ACKs. sentAck packet.PacketID // largest packetID we've sent an ACK regarding recvAck2 packet.PacketID // largest packetID we've received an ACK2 from recvLastArrival time.Time // time of the most recent data packet arrival recvLastProbe time.Time // time of the most recent data packet probe packet ackPeriod atomicDuration // (set by congestion control) delay between sending ACKs ackInterval atomicUint32 // (set by congestion control) number of data packets to send before sending an ACK unackPktCount uint // number of packets we've received that we haven't sent an ACK for lightAckCount uint // number of "light ACK" packets we've sent since the last ACK recvPktHistory []time.Duration // list of recently received packets. recvPktPairHistory []time.Duration // probing packet window. // timers ackSentEvent2 <-chan time.Time // if an ACK packet has recently sent, don't include link information in the next one ackSentEvent <-chan time.Time // if an ACK packet has recently sent, wait before resending it ackTimerEvent <-chan time.Time // controls when to send an ACK to our peer } func newUdtSocketRecv(s *udtSocket) *udtSocketRecv { sr := &udtSocketRecv{ socket: s, sockClosed: s.sockClosed, sockShutdown: s.sockShutdown, recvEvent: s.recvEvent, messageIn: s.messageIn, sendPacket: s.sendPacket, ackTimerEvent: time.After(synTime), } go sr.goReceiveEvent() return sr } func (s *udtSocketRecv) configureHandshake(p *packet.HandshakePacket) { s.farNextPktSeq = p.InitPktSeq s.farRecdPktSeq = p.InitPktSeq.Add(-1) s.sentAck = p.InitPktSeq s.recvAck2 = p.InitPktSeq } func (s *udtSocketRecv) goReceiveEvent() { recvEvent := s.recvEvent sockClosed := s.sockClosed sockShutdown := s.sockShutdown for { select { case evt, ok := <-recvEvent: if !ok { return } switch sp := evt.pkt.(type) { case *packet.Ack2Packet: s.ingestAck2(sp, evt.now) case *packet.MsgDropReqPacket: s.ingestMsgDropReq(sp, evt.now) case *packet.DataPacket: s.ingestData(sp, evt.now) case *packet.ErrPacket: s.ingestError(sp) } case _, _ = <-sockShutdown: // socket is shut down, no need to receive any further data return case _, _ = <-sockClosed: // socket is closed, leave now return case <-s.ackSentEvent: s.ackSentEvent = nil case <-s.ackSentEvent2: s.ackSentEvent2 = nil case <-s.ackTimerEvent: s.ackEvent() } } } /* ACK is used to trigger an acknowledgement (ACK). Its period is set by the congestion control module. However, UDT will send an ACK no longer than every 0.01 second, even though the congestion control does not need timer-based ACK. Here, 0.01 second is defined as the SYN time, or synchronization time, and it affects many of the other timers used in UDT. NAK is used to trigger a negative acknowledgement (NAK). Its period is dynamically updated to 4 * RTT_+ RTTVar + SYN, where RTTVar is the variance of RTT samples. EXP is used to trigger data packets retransmission and maintain connection status. Its period is dynamically updated to N * (4 * RTT + RTTVar + SYN), where N is the number of continuous timeouts. To avoid unnecessary timeout, a minimum threshold (e.g., 0.5 second) should be used in the implementation. */ // ingestAck2 is called to process an ACK2 packet func (s *udtSocketRecv) ingestAck2(p *packet.Ack2Packet, now time.Time) { ackSeq := p.AckSeqNo if s.ackHistory == nil { return // no ACKs to search } ackHistEntry, ackIdx := s.ackHistory.Find(ackSeq) if ackHistEntry == nil { return // this ACK not found } if s.recvAck2.BlindDiff(ackHistEntry.lastPacket) < 0 { s.recvAck2 = ackHistEntry.lastPacket } heap.Remove(&s.ackHistory, ackIdx) // Update the largest ACK number ever been acknowledged. if s.largestACK < ackSeq { s.largestACK = ackSeq } s.socket.applyRTT(uint(now.Sub(ackHistEntry.sendTime) / time.Microsecond)) //s.rto = 4 * s.rtt + s.rttVar } // ingestMsgDropReq is called to process an message drop request packet func (s *udtSocketRecv) ingestMsgDropReq(p *packet.MsgDropReqPacket, now time.Time) { stopSeq := p.LastSeq.Add(1) for pktID := p.FirstSeq; pktID != stopSeq; pktID.Incr() { // remove all these packets from the loss list if s.recvLossList != nil { if lossEntry, idx := s.recvLossList.Find(pktID); lossEntry != nil { heap.Remove(&s.recvLossList, idx) } } // remove all pending packets with this message if s.recvPktPend != nil { if lossEntry, idx := s.recvPktPend.Find(pktID); lossEntry != nil { heap.Remove(&s.recvPktPend, idx) } } } if p.FirstSeq == s.farRecdPktSeq.Add(1) { s.farRecdPktSeq = p.LastSeq } if s.recvLossList != nil && len(s.recvLossList) == 0 { s.farRecdPktSeq = s.farNextPktSeq.Add(-1) s.recvLossList = nil } if s.recvPktPend != nil && len(s.recvPktPend) == 0 { s.recvPktPend = nil } // try to push any pending packets out, now that we have dropped any blocking packets for s.recvPktPend != nil && stopSeq != s.farNextPktSeq { nextPkt, _ := s.recvPktPend.Min(stopSeq, s.farNextPktSeq) if nextPkt == nil || !s.attemptProcessPacket(nextPkt, false) { break } } } // ingestData is called to process a data packet func (s *udtSocketRecv) ingestData(p *packet.DataPacket, now time.Time) { s.socket.cong.onPktRecv(*p) seq := p.Seq /* If the sequence number of the current data packet is 16n + 1, where n is an integer, record the time interval between this packet and the last data packet in the Packet Pair Window. */ if (seq.Seq-1)&0xf == 0 { if !s.recvLastProbe.IsZero() { if s.recvPktPairHistory == nil { s.recvPktPairHistory = []time.Duration{now.Sub(s.recvLastProbe)} } else { s.recvPktPairHistory = append(s.recvPktPairHistory, now.Sub(s.recvLastProbe)) if len(s.recvPktPairHistory) > 16 { s.recvPktPairHistory = s.recvPktPairHistory[len(s.recvPktPairHistory)-16:] } } } s.recvLastProbe = now } // Record the packet arrival time in PKT History Window. if !s.recvLastArrival.IsZero() { if s.recvPktHistory == nil { s.recvPktHistory = []time.Duration{now.Sub(s.recvLastArrival)} } else { s.recvPktHistory = append(s.recvPktHistory, now.Sub(s.recvLastArrival)) if len(s.recvPktHistory) > 16 { s.recvPktHistory = s.recvPktHistory[len(s.recvPktHistory)-16:] } } } s.recvLastArrival = now /* If the sequence number of the current data packet is greater than LRSN + 1, put all the sequence numbers between (but excluding) these two values into the receiver's loss list and send them to the sender in an NAK packet. */ seqDiff := seq.BlindDiff(s.farNextPktSeq) if seqDiff > 0 { newLoss := make(receiveLossHeap, 0, seqDiff) for idx := s.farNextPktSeq; idx != seq; idx.Incr() { newLoss = append(newLoss, recvLossEntry{packetID: seq}) } if s.recvLossList == nil { s.recvLossList = newLoss heap.Init(&s.recvLossList) } else { for idx := s.farNextPktSeq; idx != seq; idx.Incr() { heap.Push(&s.recvLossList, recvLossEntry{packetID: seq}) } heap.Init(&newLoss) } s.sendNAK(newLoss) s.farNextPktSeq = seq.Add(1) } else if seqDiff < 0 { // If the sequence number is less than LRSN, remove it from the receiver's loss list. if !s.recvLossList.Remove(seq) { return // already previously received packet -- ignore } if len(s.recvLossList) == 0 { s.farRecdPktSeq = s.farNextPktSeq.Add(-1) s.recvLossList = nil } else { s.farRecdPktSeq, _ = s.recvLossList.Min(s.farRecdPktSeq, s.farNextPktSeq) } } s.attemptProcessPacket(p, true) } func (s *udtSocketRecv) attemptProcessPacket(p *packet.DataPacket, isNew bool) bool { seq := p.Seq // can we process this packet? boundary, mustOrder, msgID := p.GetMessageData() if s.recvLossList != nil && mustOrder && s.farRecdPktSeq.Add(1) != seq { // we're required to order these packets and we're missing prior packets, so push and return if isNew { if s.recvPktPend == nil { s.recvPktPend = dataPacketHeap{p} heap.Init(&s.recvPktPend) } else { heap.Push(&s.recvPktPend, p) } } return false } // can we find the start of this message? pieces := make([]*packet.DataPacket, 0) cannotContinue := false switch boundary { case packet.MbLast, packet.MbMiddle: // we need prior packets, let's make sure we have them if s.recvPktPend != nil { pieceSeq := seq.Add(-1) for { prevPiece, _ := s.recvPktPend.Find(pieceSeq) if prevPiece == nil { // we don't have the previous piece, is it missing? if s.recvLossList != nil { if lossEntry, _ := s.recvLossList.Find(pieceSeq); lossEntry != nil { // it's missing, stop processing cannotContinue = true } } // in any case we can't continue with this log.Printf("Message with id %d appears to be a broken fragment", msgID) break } prevBoundary, _, prevMsg := prevPiece.GetMessageData() if prevMsg != msgID { // ...oops? previous piece isn't in the same message log.Printf("Message with id %d appears to be a broken fragment", msgID) break } pieces = append([]*packet.DataPacket{prevPiece}, pieces...) if prevBoundary == packet.MbFirst { break } pieceSeq.Decr() } } } if !cannotContinue { pieces = append(pieces, p) switch boundary { case packet.MbFirst, packet.MbMiddle: // we need following packets, let's make sure we have them if s.recvPktPend != nil { pieceSeq := seq.Add(1) for { nextPiece, _ := s.recvPktPend.Find(pieceSeq) if nextPiece == nil { // we don't have the previous piece, is it missing? if pieceSeq == s.farNextPktSeq { // hasn't been received yet cannotContinue = true } else if s.recvLossList != nil { if lossEntry, _ := s.recvLossList.Find(pieceSeq); lossEntry != nil { // it's missing, stop processing cannotContinue = true } } else { log.Printf("Message with id %d appears to be a broken fragment", msgID) } // in any case we can't continue with this break } nextBoundary, _, nextMsg := nextPiece.GetMessageData() if nextMsg != msgID { // ...oops? previous piece isn't in the same message log.Printf("Message with id %d appears to be a broken fragment", msgID) break } pieces = append(pieces, nextPiece) if nextBoundary == packet.MbLast { break } } } } } // we've received a data packet, do we need to send an ACK for it? s.unackPktCount++ ackInterval := uint(s.ackInterval.get()) if (ackInterval > 0) && (ackInterval <= s.unackPktCount) { // ACK timer expired or ACK interval is reached s.ackEvent() } else if ackSelfClockInterval*s.lightAckCount <= s.unackPktCount { //send a "light" ACK s.sendLightACK() s.lightAckCount++ } if cannotContinue { // we need to wait for more packets, store and return if isNew { if s.recvPktPend == nil { s.recvPktPend = dataPacketHeap{p} heap.Init(&s.recvPktPend) } else { heap.Push(&s.recvPktPend, p) } } return false } // we have a message, pull it from the pending heap (if necessary), assemble it into a message, and return it if s.recvPktPend != nil { for _, piece := range pieces { s.recvPktPend.Remove(piece.Seq) } if len(s.recvPktPend) == 0 { s.recvPktPend = nil } } msg := make([]byte, 0) for _, piece := range pieces { msg = append(msg, piece.Data...) } s.messageIn <- msg return true } func (s *udtSocketRecv) sendLightACK() { var ack packet.PacketID // If there is no loss, the ACK is the current largest sequence number plus 1; // Otherwise it is the smallest sequence number in the receiver loss list. if s.recvLossList == nil { ack = s.farNextPktSeq } else { ack = s.farRecdPktSeq.Add(1) } if ack != s.recvAck2 { // send out a lite ACK // to save time on buffer processing and bandwidth/AS measurement, a lite ACK only feeds back an ACK number s.sendPacket <- &packet.LightAckPacket{PktSeqHi: ack} } } func (s *udtSocketRecv) getRcvSpeeds() (recvSpeed, bandwidth int) { // get median value, but cannot change the original value order in the window if s.recvPktHistory != nil { ourPktHistory := make(sortableDurnArray, len(s.recvPktHistory)) copy(ourPktHistory, s.recvPktHistory) n := len(ourPktHistory) cutPos := n / 2 FloydRivest.Buckets(ourPktHistory, cutPos) median := ourPktHistory[cutPos] upper := median << 3 // upper bounds lower := median >> 3 // lower bounds count := 0 // number of entries inside bounds var sum time.Duration // sum of values inside bounds // median filtering idx := 0 for i := 0; i < n; i++ { if (ourPktHistory[idx] < upper) && (ourPktHistory[idx] > lower) { count++ sum += ourPktHistory[idx] } idx++ } // do we have enough valid values to return a value? // calculate speed if count > (n >> 1) { recvSpeed = int(time.Second * time.Duration(count) / sum) } } // get median value, but cannot change the original value order in the window if s.recvPktPairHistory == nil { ourProbeHistory := make(sortableDurnArray, len(s.recvPktPairHistory)) copy(ourProbeHistory, s.recvPktPairHistory) n := len(ourProbeHistory) cutPos := n / 2 FloydRivest.Buckets(ourProbeHistory, cutPos) median := ourProbeHistory[cutPos] upper := median << 3 // upper bounds lower := median >> 3 // lower bounds count := 1 // number of entries inside bounds sum := median // sum of values inside bounds // median filtering idx := 0 for i := 0; i < n; i++ { if (ourProbeHistory[idx] < upper) && (ourProbeHistory[idx] > lower) { count++ sum += ourProbeHistory[idx] } idx++ } bandwidth = int(time.Second * time.Duration(count) / sum) } return } func (s *udtSocketRecv) sendACK() { var ack packet.PacketID // If there is no loss, the ACK is the current largest sequence number plus 1; // Otherwise it is the smallest sequence number in the receiver loss list. if s.recvLossList == nil { ack = s.farNextPktSeq } else { ack = s.farRecdPktSeq.Add(1) } if ack == s.recvAck2 { return } // only send out an ACK if we either are saying something new or the ackSentEvent has expired if ack == s.sentAck && s.ackSentEvent != nil { return } s.sentAck = ack s.lastACK++ ackHist := &ackHistoryEntry{ ackID: s.lastACK, lastPacket: ack, sendTime: time.Now(), } if s.ackHistory == nil { s.ackHistory = ackHistoryHeap{ackHist} heap.Init(&s.ackHistory) } else { heap.Push(&s.ackHistory, ackHist) } rtt, rttVar := s.socket.getRTT() numPendPackets := int(s.farNextPktSeq.BlindDiff(s.farRecdPktSeq) - 1) availWindow := int(s.socket.maxFlowWinSize) - numPendPackets if availWindow < 2 { availWindow = 2 } p := &packet.AckPacket{ AckSeqNo: s.lastACK, PktSeqHi: ack, Rtt: uint32(rtt), RttVar: uint32(rttVar), BuffAvail: uint32(availWindow), } if s.ackSentEvent2 == nil { recvSpeed, bandwidth := s.getRcvSpeeds() p.IncludeLink = true p.PktRecvRate = uint32(recvSpeed) p.EstLinkCap = uint32(bandwidth) s.ackSentEvent2 = time.After(synTime) } s.sendPacket <- p s.ackSentEvent = time.After(time.Duration(rtt+4*rttVar) * time.Microsecond) } func (s *udtSocketRecv) sendNAK(rl receiveLossHeap) { lossInfo := make([]uint32, 0) curPkt := s.farRecdPktSeq for curPkt != s.farNextPktSeq { minPkt, idx := rl.Min(curPkt, s.farRecdPktSeq) if idx < 0 { break } lastPkt := minPkt for { nextPkt := lastPkt.Add(1) _, idx = rl.Find(nextPkt) if idx < 0 { break } lastPkt = nextPkt } if lastPkt == minPkt { lossInfo = append(lossInfo, minPkt.Seq&0x7FFFFFFF) } else { lossInfo = append(lossInfo, minPkt.Seq|0x80000000, lastPkt.Seq&0x7FFFFFFF) } } s.sendPacket <- &packet.NakPacket{CmpLossInfo: lossInfo} } // ingestData is called to process an (undocumented) OOB error packet func (s *udtSocketRecv) ingestError(p *packet.ErrPacket) { // TODO: umm something } // assuming some condition has occured (ACK timer expired, ACK interval), send an ACK and reset the appropriate timer func (s *udtSocketRecv) ackEvent() { s.sendACK() ackTime := synTime ackPeriod := s.ackPeriod.get() if ackPeriod > 0 { ackTime = ackPeriod } s.ackTimerEvent = time.After(ackTime) s.unackPktCount = 0 s.lightAckCount = 1 } <file_sep>/udt/packet/packet_err_test.go package packet import ( "testing" ) func TestErrPacket(t *testing.T) { pkt1 := &ErrPacket{ Errno: 90, } pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/packet/packet_lightack_test.go package packet import ( "testing" ) func TestLightAckPacket(t *testing.T) { pkt1 := &LightAckPacket{ PktSeqHi: PacketID{Seq: 91}, } pkt1.SetHeader(59, 100) testPacket(pkt1, t) } <file_sep>/udt/packet/packet_ack2.go package packet // Structure of packets and functions for writing/reading them // Ack2Packet is a UDT packet acknowledging receipt of an ACK packet type Ack2Packet struct { ctrlHeader AckSeqNo uint32 // ACK sequence number } // WriteTo writes this packet to the provided buffer, returning the length of the packet func (p *Ack2Packet) WriteTo(buf []byte) (uint, error) { return p.writeHdrTo(buf, ptAck2, p.AckSeqNo) } func (p *Ack2Packet) readFrom(data []byte) (err error) { p.AckSeqNo, err = p.readHdrFrom(data) return } // PacketType returns the packetType associated with this packet func (p *Ack2Packet) PacketType() PacketType { return ptAck2 }
78618ecd587f645dacf2d8fff458de3c8abf7a0f
[ "Go Module", "Go" ]
45
Go
odysseus654/go-udt
3520cae28f349f6e732da53951b6c21d3a636223
d3992f36f136395443695a99af4fbd27651044d2
refs/heads/master
<file_sep>package io.socket; import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.json.JSONObject; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(io.socket.RandomBlockJUnit4ClassRunner.class) public abstract class AbstractTestSocketIO implements IOCallback { private final static String NODE = "node"; private int port = -1; private static final int TIMEOUT = 1000; LinkedBlockingQueue<String> events; LinkedBlockingQueue<String> outputs; LinkedBlockingQueue<Object> args; Thread stdoutThread; Thread stderrThread; private Process node; private SocketIO socket; static protected String transport = null; @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { assertNotNull("Transport is set correctly", transport); events = new LinkedBlockingQueue<String>(); outputs = new LinkedBlockingQueue<String>(); args = new LinkedBlockingQueue<Object>(); System.out.println("Connect with " + transport); node = Runtime.getRuntime().exec( new String[] { NODE, "./tests/io/socket/socketio.js", "" + getPort(), transport }); stdoutThread = new Thread("stdoutThread") { public void run() { BufferedReader reader = new BufferedReader( new InputStreamReader(node.getInputStream())); String line; try { while ((line = reader.readLine()) != null) { if (line.startsWith("__:")) { System.out.println("Out: " + line); outputs.add(line.substring("__:".length())); } else System.out.println("Node: " + line); } } catch (IOException e) { if (!interrupted()) { e.printStackTrace(); System.err.println("Node read error"); } } System.err.println("Node output end"); } }; stderrThread = new Thread("stderrThread") { public void run() { BufferedReader reader = new BufferedReader( new InputStreamReader(node.getErrorStream())); try { String line; while ((line = reader.readLine()) != null) { System.err.println("Node: " + line); } } catch (IOException e) { if (!interrupted()) { e.printStackTrace(); System.err.println("Node read error"); } } System.err.println("Node output end"); }; }; stderrThread.start(); stdoutThread.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { node.destroy(); } catch (Exception e) { e.printStackTrace(); } } }); assertEquals("OK", takeLine()); } @After public void tearDown() throws Exception { node.destroy(); stderrThread.interrupt(); stdoutThread.interrupt(); node.waitFor(); for (String s : events) { System.out.println("Event in Queue: " + s); } for (String line : outputs) { System.out.println("Line in Queue: " + line); } for (Object o : args) { System.out.println("Argument in Queue: " + o.toString()); } } void doConnect() throws Exception { // Setting up socket connection socket = new SocketIO("http://127.0.0.1:" + getPort(), this); assertEquals("onConnect", takeEvent()); assertEquals(transport, socket.getTransport()); } void doClose() throws Exception { socket.disconnect(); assertEquals("onDisconnect", takeEvent()); while (outputs.size() != 0) { fail("Line in queue: " + outputs.poll()); } while (events.size() != 0) { fail("Event in queue: " + events.poll()); } while (args.size() != 0) { fail("Arguments in queue: " + args.poll()); } } // BEGIN TESTS @Test(timeout=TIMEOUT) public void send() throws Exception { doConnect(); String str = "TESTSTRING"; socket.send(str); assertEquals("MESSAGE:" + str, takeLine()); doClose(); } @Test(timeout=TIMEOUT) public void emitAndOn() throws Exception { doConnect(); String str = "TESTSTRING"; socket.emit("echo", str); assertEquals("Test String", "on", takeEvent()); assertEquals(str, takeArg()); JSONObject obj = new JSONObject("{'foo':'bar'}"); socket.emit("echo", obj); assertEquals("Test JSON", "on", takeEvent()); assertEquals(obj.toString(), takeArg().toString()); doClose(); } @Test(timeout=TIMEOUT) public void emitAndMessage() throws Exception { doConnect(); String str = "TESTSTRING"; socket.emit("echoSend", str); assertEquals("onMessage_string", events.take()); assertEquals(str, takeArg()); /* * // Server sends us a string instead of a JSONObject, strange thing * JSONObject obj = new JSONObject("{'foo':'bar'}"); * socket.emit("echoSend", obj); assertEquals("Test JSON", * "onMessage_json", takeEvent()); assertEquals(obj.toString(), * takeArg().toString()); */ doClose(); } @Test(timeout=TIMEOUT) public void namespaces() throws Exception { SocketIO ns1 = new SocketIO("http://127.0.0.1:" + getPort() + "/ns1", this); assertEquals("onConnect", takeEvent()); // In some very rare cases, it is possible to receive data on an socket // which isn't connected yet, this sleep assures that these events // aren't submitted. This is a server side problem. Maybe socket.io-java // could cache these events until the server drops the connect event. Thread.sleep(100); doConnect(); ns1.disconnect(); assertEquals("onDisconnect", takeEvent()); SocketIO ns2 = new SocketIO("http://127.0.0.1:" + getPort() + "/ns2", this); assertEquals("onConnect", takeEvent()); assertEquals("onMessage_string", takeEvent()); assertEquals("ns2", takeArg()); SocketIO ns2_2 = new SocketIO("http://127.0.0.1:" + getPort() + "/ns2", this); assertEquals("onConnect", takeEvent()); assertEquals("onMessage_string", takeEvent()); assertEquals("ns2", takeArg()); ns2_2.disconnect(); ns2.disconnect(); assertEquals("onDisconnect", takeEvent()); assertEquals("onDisconnect", takeEvent()); doClose(); } @Test(timeout=TIMEOUT) public void error() throws Exception { doConnect(); new SocketIO("http://127.0.0.1:1024/", this); assertEquals("onError", takeEvent()); doClose(); } @Test(timeout=TIMEOUT) public void acknowledge() throws Exception { doConnect(); socket.emit("echoAck", new IOAcknowledge() { @Override public void ack(Object... args) { events.add("ack"); AbstractTestSocketIO.this.args.addAll(Arrays.asList(args)); } }, "TESTSTRING"); assertEquals("ack", takeEvent()); assertEquals("TESTSTRING", takeArg()); doClose(); } // END TESTS String takeEvent() throws InterruptedException { String event = events.poll(TIMEOUT, TimeUnit.SECONDS); if (event == null) { fail("takeEvent Timeout!"); } System.out.println("Event Taken: " + event); return event; } String takeLine() throws InterruptedException { String line = outputs.poll(TIMEOUT, TimeUnit.SECONDS); if (line == null) { fail("takeLine Timeout!"); } System.out.println("Line Taken: " + line); return line; } Object takeArg() throws InterruptedException { Object arg = args.poll(TIMEOUT, TimeUnit.MILLISECONDS); if (arg == null) { fail("takeArg Timeout!"); } System.out.println("Argument Taken: " + arg); return arg; } @Override public void onDisconnect() { events.add("onDisconnect"); } @Override public void onConnect() { events.add("onConnect"); } @Override public void onMessage(String data, IOAcknowledge ack) { events.add("onMessage_string"); this.args.add(data); } @Override public void onMessage(JSONObject json, IOAcknowledge ack) { events.add("onMessage_json"); this.args.add(json); } @Override public void on(String event, IOAcknowledge ack, Object... args) { events.add("on"); this.args.addAll(Arrays.asList(args)); } @Override public void onError(SocketIOException socketIOException) { events.add("onError"); } public int getPort() { if(port == -1) port = 2048 + (int)(Math.random() * 10000); return port; } }
29f7fbc85a2563b3cb52a77cb5ee6b9599c0351a
[ "Java" ]
1
Java
Minecarts/socket.io-java-client
fe01e2012e9f1b8ee98a4963be600699a1e2583a
114e59ab7a6ad1f5a6ce31d75d8e2f13ba9234dd
refs/heads/master
<file_sep>package action; import java.util.List; import javax.annotation.Resource; import model.News; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import service.NewsService; @Action("news") @Results({ @Result(name="list",location="/admin/pages/news-list.jsp"), @Result(name="update",location="/admin/pages/news-update.jsp"), }) @SuppressWarnings("serial") public class NewsAction extends BaseAction{ private News news; private List<News> newses; @Resource private NewsService newsService; //获取列表 public String list(){ newses = newsService.getNewsList((page-1)*size, size); pages = getPages(newsService.getTotal(), size); return "list"; } //添加 public String add(){ newsService.add(news); return list(); } //更新页面 public String updatePage(){ news = newsService.getNews(news.getId()); return "update"; } //更新 public String update(){ newsService.update(news); return list(); } //删除 public String delete(){ newsService.delete(news); return list(); } public News getNews() { return news; } public void setNews(News news) { this.news = news; } public List<News> getNewses() { return newses; } public void setNewss(List<News> newses) { this.newses = newses; } } <file_sep>package dao; import java.util.List; import model.User; import org.springframework.stereotype.Repository; @Repository//注册spring管理bean @SuppressWarnings("unchecked") public class UserDao extends BaseDao{ //根据用户名和密码查找用户 public User getUser(String username, String password) { return (User) getSession().createQuery("from User where username=:username and password=:password") .setParameter("username", username).setParameter("password", password).uniqueResult(); } //根据用户名查找用户 public User getUser(String username) { return (User) getSession().createQuery("from User where username=:username") .setParameter("username", username).uniqueResult(); } //获取所有用户信息 public List<User> getUserList(int i, int size) { return getSession().createQuery("from User").setFirstResult(i).setMaxResults(size).list(); } //根据id获取用户信息 public User getUser(int id) { return (User) getSession().get(User.class, id); } // 获取记录总数 public int getTotal() { return Integer.parseInt(getSession().createQuery("select count(*) from User").uniqueResult().toString()); } } <file_sep>package action; import java.io.File; import java.util.List; import javax.annotation.Resource; import model.Gbook; import model.News; import model.Note; import model.Place; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import service.GbookService; import service.NewsService; import service.NoteService; import service.PlaceService; import util.UploadUtil; @Action("front") @Results({ @Result(name="index",location="/front/index.jsp"), @Result(name="placeList",location="/front/place.jsp"), @Result(name="newsList",location="/front/news.jsp"), @Result(name="noteList",location="/front/note.jsp"), @Result(name="gbookList",location="/front/gbook.jsp"), @Result(name="weatherAndroute",location="/front/weatherAndroute.jsp"), @Result(name="placeIntro",location="/front/pages/place-intro.jsp"), @Result(name="newsIntro",location="/front/pages/news-intro.jsp"), @Result(name="noteIntro",location="/front/pages/note-intro.jsp"), @Result(name="placeSelf",location="/front/pages/place-self.jsp"), @Result(name="newsSelf",location="/front/pages/news-self.jsp"), @Result(name="noteSelf",location="/front/pages/note-self.jsp"), @Result(name="leaveSelf",location="/front/pages/leave-self.jsp"), @Result(name="placeEdit",location="/front/pages/place-edit.jsp"), @Result(name="newsEdit",location="/front/pages/news-edit.jsp"), @Result(name="noteEdit",location="/front/pages/note-edit.jsp"), }) @SuppressWarnings("serial") public class FrontAction extends BaseAction{ private int userid; private Place place; private News news; private Note note; private Gbook gbook; private List<Place> places; private List<News> newses; private List<Note> notes; private List<Gbook> gbooks; @Resource private PlaceService placeService; @Resource private NewsService newsService; @Resource private NoteService noteService; @Resource private GbookService gbookService; private File photo; //��ȡ�ϴ��ļ� private String photoFileName; //��ȡ�ϴ��ļ���� // ��ҳ public String index(){ places = placeService.getIndexList(4); newses = newsService.getIndexList(4); notes = noteService.getIndexList(4); return "index"; } // �����б� public String placeList(){ places = placeService.getPlaceList((page-1)*size, size); pages = getPages(placeService.getTotal(), size); return "placeList"; } // �Ż��б� public String newsList(){ newses = newsService.getNewsList((page-1)*size, size); pages = getPages(newsService.getTotal(), size); return "newsList"; } // �μ��б� public String noteList(){ notes = noteService.getNoteList((page-1)*size, size); pages = getPages(noteService.getTotal(), size); return "noteList"; } // �����б� public String gbookList(){ gbooks = gbookService.getList((page-1)*size, size); pages = getPages(gbookService.getTotal(), size); return "gbookList"; } // ������� public String placeIntro(){ place = placeService.getPlace(place.getId()); return "placeIntro"; } // �Żݽ��� public String newsIntro(){ news = newsService.getNews(news.getId()); return "newsIntro"; } // �μǽ��� public String noteIntro(){ note = noteService.getNote(note.getId()); return "noteIntro"; } // �ҵ��Ż� public String newsSelf(){ newses = newsService.getNewsSelf(userid,(page-1)*size, size); pages = getPages(newsService.getTotalSelf(userid), size); return "newsSelf"; } // �ҵ��μ� public String noteSelf(){ notes = noteService.getNoteSelf(userid,(page-1)*size, size); pages = getPages(noteService.getTotalSelf(userid), size); return "noteSelf"; } // ����Ż� public String newsAdd(){ if (photo != null) { news.setPhoto(UploadUtil.upload(photo, photoFileName, "front/photo/news/").substring("front/".length())); } newsService.add(news); return newsSelf(); } // ����μ� public String noteAdd(){ if (photo != null) { note.setPhoto(UploadUtil.upload(photo, photoFileName, "front/photo/note/").substring("front/".length())); } noteService.add(note); return noteSelf(); } // ������� public String gbookAdd(){ gbookService.add(gbook); return gbookList(); } // ɾ���Ż� public String newsDrop(){ newsService.delete(news); return newsSelf(); } // ɾ���μ� public String noteDrop(){ noteService.delete(note); return noteSelf(); } // �༭�Ż� public String newsEdit(){ news = newsService.getNews(news.getId()); return "newsEdit"; } // �༭�μ� public String noteEdit(){ note = noteService.getNote(note.getId()); return "noteEdit"; } // �����Ż� public String newsSave(){ if (photo != null) { news.setPhoto(UploadUtil.upload(photo, photoFileName, "front/photo/news/").substring("front/".length())); } newsService.update(news); return newsSelf(); } // �����μ� public String noteSave(){ if (photo != null) { note.setPhoto(UploadUtil.upload(photo, photoFileName, "front/photo/note/").substring("front/".length())); } noteService.update(note); return noteSelf(); } public List<News> getNewses() { return newses; } public void setNewses(List<News> newses) { this.newses = newses; } public List<Note> getNotes() { return notes; } public void setNotes(List<Note> notes) { this.notes = notes; }public News getNews() { return news; } public void setNews(News news) { this.news = news; } public Note getNote() { return note; } public void setNote(Note note) { this.note = note; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public Place getPlace() { return place; } public void setPlace(Place place) { this.place = place; } public List<Place> getPlaces() { return places; } public void setPlaces(List<Place> places) { this.places = places; } public Gbook getGbook() { return gbook; } public void setGbook(Gbook gbook) { this.gbook = gbook; } public File getPhoto() { return photo; } public void setPhoto(File photo) { this.photo = photo; } public String getPhotoFileName() { return photoFileName; } public void setPhotoFileName(String photoFileName) { this.photoFileName = photoFileName; } public List<Gbook> getGbooks() { return gbooks; } public void setGbooks(List<Gbook> gbooks) { this.gbooks = gbooks; } } <file_sep>package dao; import java.util.List; import model.News; import org.springframework.stereotype.Repository; @Repository//注册spring管理bean @SuppressWarnings("unchecked") public class NewsDao extends BaseDao{ //获取列表 public List<News> getNewsList(int i, int size) { return getSession().createQuery("from News").setFirstResult(i).setMaxResults(size).list(); } //根据id获取 public News getNews(int id) { return (News) getSession().get(News.class, id); } //我的优惠 public List<News> getNewsList(int traderid, int i, int size) { return getSession().createQuery("from News where trader_id=:tarderid").setInteger("tarderid", traderid).setFirstResult(i).setMaxResults(size).list(); } //获取首页需要数据 public List<News> getIndexList(int count) { return getSession().createQuery("from News").setMaxResults(count).list(); } // 获取记录总数 public int getTotal() { return Integer.parseInt(getSession().createQuery("select count(*) from News").uniqueResult().toString()); } // 获取记录总数 public int getTotalSelf(int traderid) { return Integer.parseInt(getSession().createQuery("select count(*) from News where trader_id=:tarderid").setInteger("tarderid", traderid).uniqueResult().toString()); } } <file_sep>package dao; import java.util.List; import model.Trader; import org.springframework.stereotype.Repository; @Repository//注册spring管理bean @SuppressWarnings("unchecked") public class TraderDao extends BaseDao{ //获取列表 public List<Trader> getTraderList(int i, int size) { return getSession().createQuery("from Trader").setFirstResult(i).setMaxResults(size).list(); } //根据id获取 public Trader getTrader(int id) { return (Trader) getSession().get(Trader.class, id); } //根据用户名获取 public Trader getTrader(String username) { return (Trader) getSession().createQuery("from Trader where username=:username").setString("username", username).uniqueResult(); } //根据用户名和密码获取 public Trader getTrader(String username, String password) { return (Trader) getSession().createQuery("from Trader where username=:username and password=:password").setString("username", username).setString("password", password).uniqueResult(); } // 获取记录总数 public int getTotal() { return Integer.parseInt(getSession().createQuery("select count(*) from Trader").uniqueResult().toString()); } }
0dc02df4ad8bfbfcfc22e39d51f151118135d6be
[ "Java" ]
5
Java
GitWindMan/mytravel
0f1ed95d36028b24a41386ce350aa89fb21bf276
b11bc322027a9a252affb1f7682be967b562dc10
refs/heads/master
<repo_name>jsdev2013/ListView_20200602<file_sep>/app/src/main/java/com/jisu/listview_20200602/MainActivity.kt package com.jisu.listview_20200602 import android.content.Intent import android.os.Bundle import com.jisu.listview_20200602.adapters.RoomAdapter import com.jisu.listview_20200602.datas.Room import kotlinx.android.synthetic.main.activity_main.* class MainActivity : BaseActivity() { val roomArrayList = ArrayList<Room>() lateinit var roomAdapter: RoomAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupEvents() setValues() } override fun setupEvents() { roomListView.setOnItemClickListener { parent, view, position, id -> val clickedRoom = roomArrayList[position] val myIntent = Intent(mContext, ViewRoomDetailActivity::class.java) myIntent.putExtra("roomData", clickedRoom) startActivity(myIntent) } } override fun setValues() { addRooms() roomAdapter = RoomAdapter(mContext, R.layout.room_list_item, roomArrayList) roomListView.adapter = roomAdapter } fun addRooms(){ roomArrayList.add(Room(7500,"마포구 서교동", 3, "망원/홍대역 풀옵션 넓은 원룸형")) roomArrayList.add(Room(28500,"마포구 서교동", 5, "신혼부부의 보금자리 서교동 신축")) roomArrayList.add(Room(1500,"마포구 망원동", 0, "망원/홍대역 풀옵션 넓은 원룸형")) roomArrayList.add(Room(54000,"마포구 망원동", -1, "신혼부부의 보금자리 서교동 신축")) roomArrayList.add(Room(2500,"마포구 망원동", 1, "망원/홍대역 풀옵션 넓은 원룸형")) roomArrayList.add(Room(11100,"마포구 홍대역", -1, "신혼부부의 보금자리 서교동 신축")) roomArrayList.add(Room(6500,"마포구 홍대역", 2, "망원/홍대역 풀옵션 넓은 원룸형")) roomArrayList.add(Room(1500,"마포구 홍대역", 0, "신혼부부의 보금자리 서교동 신축")) roomArrayList.add(Room(8000,"마포구 성산동", 0, "망원/홍대역 풀옵션 넓은 원룸형")) roomArrayList.add(Room(12550,"마포구 성산동", 3, "신혼부부의 보금자리 서교동 신축")) roomArrayList.add(Room(7500,"마포구 성산동", 5, "망원/홍대역 풀옵션 넓은 원룸형")) roomArrayList.add(Room(20000,"마포구 서교동", 3, "신혼부부의 보금자리 서교동 신축")) } } <file_sep>/app/src/main/java/com/jisu/listview_20200602/adapters/RoomAdapter.kt package com.jisu.listview_20200602.adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import com.jisu.listview_20200602.R import com.jisu.listview_20200602.datas.Room import kotlin.math.abs class RoomAdapter(context: Context, resId: Int, list: List<Room>) :ArrayAdapter<Room>(context, resId, list) { val mContext = context val mList = list val inf = LayoutInflater.from(mContext) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var tempRow = convertView /*converView 변수에 재활용할 뷰가 담겨서 getView가 실행됨 * 처음에 몇개를 그릴때는 재활용할 뷰가 아직없다(그려둔 갯수가 부족해서) * converView 변수가 null일 때만 infalte 하자*/ if(tempRow == null){ tempRow = inf.inflate(R.layout.room_list_item, null) } val row = tempRow!! val data = mList.get(position) //val data = mList[position] val price = row.findViewById<TextView>(R.id.priceTxt) var addressFloor = row.findViewById<TextView>(R.id.addressFloorTxt) var discription = row.findViewById<TextView>(R.id.discription) price.text = data.getFormattedPrice() addressFloor.text = "${data.address}, ${data.getFormattedFloor()} " discription.text = data.description return row } }<file_sep>/settings.gradle rootProject.name='ListView_20200602' include ':app'
fd106ea4a558515fea398b6f6bc685d3f70b5ba0
[ "Kotlin", "Gradle" ]
3
Kotlin
jsdev2013/ListView_20200602
7fddbafca660362db3531c239ab80d33a136c05b
fe24b5e59c5e7529c1dc20f3f4f19704e782803c
refs/heads/main
<repo_name>DesignByCodeClientWebsite/CoenieMarais<file_sep>/src/components/Title.js import React, {useEffect, createRef} from 'react' import PropTypes from 'prop-types' import color from "../utils/color" import gsap from 'gsap' import { ScrollTrigger } from 'gsap/ScrollTrigger' gsap.registerPlugin(ScrollTrigger) const Title = ({color, children}) => { const titleRef = createRef() useEffect(() => { gsap.to(titleRef.current, { scale: 1, opacity: 1, duration: 0.25, scrollTrigger: { trigger: titleRef.current, start: "top 80%", end: "bottom 70%", triggerActions: "play none none reverse", scrub: true, markers: false } }) }) return ( <header style={{position: 'relative', display: 'block'}}> <h1 ref={titleRef} className="title title-initial" style={{color: color, fontSize: 'clamp(1rem, 5vw, 3rem)' }}> {children} </h1> </header> ) } Title.propTypes = { color: PropTypes.string, } Title.defaultProps = { color: color.primary } export default Title<file_sep>/src/components/layout/Footer.js import React from 'react' import styled from 'styled-components' import color from "../../utils/color" import Link from 'gatsby-link' const Footer = () => { return ( <FooterBar className="footer"> <div className="wrapper"> <div className="row"> <div className="md-col-8"> <UlLinks> <li> <Link to="/">HOME</Link> </li> <li> <Link to="/about/">ABOUT</Link> </li> <li> <Link to="/services/">SERVICES</Link> </li> <li> <Link to="/work/">OUR WORK</Link> </li> <li> <Link to="/contact/">CONTACT US</Link> </li> </UlLinks> </div> <div className="md-col-4"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores, soluta? </div> <div className='md-col-12'> Design &amp; Developed by <a href="http://designbycode.co.za" target="_blank" rel="noreferrer">DesignByCode</a> </div> </div> </div> </FooterBar> ) } export default Footer const FooterBar = styled.footer` background: ${color.dark}; padding-top: 60px; padding-bottom: 60px; margin-top: auto; a { color: ${color.primary}; text-decoration: none; &[aria-current="page"], &:hover { text-decoration: underline; } } ` const UlLinks = styled.ul` padding: 0; margin: 0; list-style: none; display: flex; flex-direction: row; li { margin-right: 10px; } `<file_sep>/src/components/hero/HeroLogo.js import React from 'react' import styled from 'styled-components' import color from "../../utils/color" import shadow from "../../utils/shadow" import LogoImage from './../../images/logo.svg' import pattern from './../../images/hideout.svg' import withTilt from "../../hoc/WithTilt" const HeroLogo = () => { return ( <div style={{position: 'relative', borderRadius: '10px'}}> <Pattern/> <Pattern2/> <Logo> <Image src={LogoImage} alt="logo" /> </Logo> </div> ) } export default withTilt(HeroLogo, {max: 100}) const Logo = styled.div` position: relative; background: ${color.dark}; border-radius: 10px; padding: 30px; box-shadow: ${shadow.level3}; z-index: 5; transform: translateZ(0px); ` const Image = styled.img` position: relative; max-width: 100%; transform: translateZ(200px); ` const Pattern = styled.div` position: absolute; width: 250px; height: 250px; background-image: url(${pattern}); background-size: 50px; background-position: 15px 5px; z-index: 1; top: -100px; right: -100px; opacity: 0.15; transform: translateZ(-60px); ` const Pattern2 = styled.div` position: absolute; width: 250px; height: 250px; background-image: url(${pattern}); background-size: 50px; background-position: 15px 5px; z-index: 1; bottom: -100px; left: -100px; opacity: 0.15; transform: translateZ(-90px) ` <file_sep>/src/pages/index.js import React from 'react' import styled from 'styled-components' import SEO from "../components/layout/seo" import Hero from "../components/hero/Hero" import Section from "../components/Section" import GridList from "../components/grid/GridList" import color from "../utils/color" import Img1 from './../images/frontpage-first.jpg' import Img2 from './../images/frontpage-2.jpg' import Link from 'gatsby-link' import gsap from 'gsap' import { ScrollTrigger } from 'gsap/ScrollTrigger' gsap.registerPlugin(ScrollTrigger) const index = ({data}) => { return ( <> <SEO title="Home" /> <Hero/> <Section backgroundColor={color.gray.light} svgColor={color.white}> <div className='row'> <div className='md-col-4'> <Images1 src={Img1} alt='Welcome to coenie marais' /> </div> <div className='md-col-8'> <div className='row'> <div className='md-col-12'> <header className='heading-group'> <h1><span aria-label="waving hand" role="img">👋</span> Welcome to</h1> <h2 className='hand'>Coenie Marais</h2> <h3 style={{ borderTop: `solid 3px ${color.primary}`, marginTop: 20}}>Inhouse finishings </h3> </header> </div> <div className='md-col-12' style={{marginTop: 30}}> <p>For most people the biggest investment they will ever make is buying a home. But to make a home as you envisioned it in your dreams isn’t as easy as you might think.</p> <p>That is why we here at Coenie Marais In House Finishing specializing in weaving dreams into reality.</p> <p>From something as simple as a door, a cupboard, skirtings or that dreamy outdoor patio you were thinking about. Yes, all that you mind can conjure up, we can make it into reality with that extra wow factor included to make your home unique to you. All our work is fully guaranteed to give you that extra peace of mind.</p> </div> </div> </div> </div> </Section> <Section backgroundColor={color.white} svgColor={color.gray.light}> <div className='row'> <div className='md-col-8'> <div className='row'> <div className='md-col-12'> <header className='heading-group'> <h1>For your</h1> <h2 className='hand'>Business, Offices <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>🛠️</span> </h2> <h3> &amp; Store Fronts </h3> </header> </div> <div className='md-col-12' style={{marginTop: 30}}> <p>Unlike other company’s out there we can accommodate you with a diverse variety of services. That basically makes us your one stop shop for all your home, business or office needs. This will help you to reduce to number of contractors on site that you need to hire and communicate with. While at the same time giving you a constant theme throughout your project and in turn also bring cost down.</p> <p>See our Services page to learn more about what we can do for u or browse through our gallery to see our work for yourself.</p> <a href="#tag" className="btn btn--dark">Contact Us</a> </div> </div> </div> <div className='md-col-4'> <Images2 src={Img2} alt='Welcome to coenie marais' /> </div> </div> </Section> {/*Temp*/} {/*// <Section backgroundColor={color.secondary} svgColor={color.gray.light}>*/} {/*// <div className='row'>*/} {/*// <div className='md-col-8'>*/} {/*/!* <div className='row'>*!/*/} {/*/!* <div className='md-col-12'>*!/*/} {/*/!* <header className='heading-group'>*!/*/} {/*/!* <h1>For your</h1>*!/*/} {/*// <h2 className='hand'>Business, Offices <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>🛠️</span> </h2>*/} {/*// <h3> &amp; Store Fronts </h3>*/} {/*// </header>*/} {/*// </div>*/} {/*// <div className='md-col-12' style={{marginTop: 30}}>*/} {/*// <p>Unlike other company’s out there we can accommodate you with a diverse variety of services. That*/} {/*// basically makes us your one stop shop for all your home, business or office needs. This will help you to*/} {/*// reduce to number of contractors on site that you need to hire and communicate with. While at the same*/} {/*// time giving you a constant theme throughout your project and in turn also bring cost down.</p>*/} {/*//*/} {/*// <p>See our Services page to learn more about what we can do for u or browse through our gallery to see our*/} {/*// work for yourself.</p>*/} {/*// <a href="#tag" className="btn btn--dark">Contact Us</a>*/} {/*// </div>*/} {/*// </div>*/} {/* </div>*/} {/* <div className='md-col-4'>*/} {/* <ImageHolder>*/} {/* <ImageInner src={Img1} alt='Welcome to coenie marais' />*/} {/* <ImageInner src={Img2} alt='Welcome to coenie marais' />*/} {/* </ImageHolder>*/} {/* </div>*/} {/* </div>*/} {/*</Section>*/} <Section backgroundColor={color.gray.light} svgColor={color.white}> <div className="md-col-6"> <div className="mb"> <header className='heading-group '> <h1>Here is just a few</h1> <h2 className='hand'>of our <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>😊</span> happy clients </h2> <h3>finished projects <span aria-label="sparkels" role="img">✨</span> </h3> </header> <p> I need about 6 business client names and logos. </p> <p>[DUMMY TEST] &rarr; Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid consequatur eaque incidunt molestiae voluptas? Architecto inventore modi nobis non repudiandae, suscipit unde voluptatem. Ipsam obcaecati totam voluptas voluptatum! Amet architecto assumenda aut autem corporis cumque eius, eligendi enim facere ipsam minus mollitia omnis perspiciatis possimus, quas sunt, ullam vero voluptate?</p> <Link to="/work/" className="btn btn--dark">View Our Work</Link> </div> </div> <div className="md-col-6"> <GridList/> </div> </Section> </> ) } export default index const Images1 = styled.img` position: relative; object-fit: cover; max-width: 120%; transform: translate(-20%, -10%); border-radius: 0 10px 10px 0; box-shadow: rgba(0,0,0,0.5) 30px 10px 40px; display: none; @media(min-width: 768px) { display: block; } ` const Images2 = styled(Images1)` transform: translate(10%, -10%); border-radius: 10px 0 0 10px; box-shadow: rgba(0,0,0,0.5) -30px 10px 40px; ` // // const ImageHolder = styled.div` // width: 490px; // height: 600px; // background: ${color.primary}; // transform: translate(10%, -10%); // border-radius: 10px 0 0 10px; // box-shadow: rgba(0,0,0,0.5) -30px 10px 40px; // display: flex; // flex-direction: row; // overflow: hidden; // ` // // const ImageInner = styled.img` // position: relative; // display: block; // width: 100%; // object-fit: fill; // `<file_sep>/src/hoc/WithTilt.js import React from "react" import VanillaTilt from 'vanilla-tilt' function withTilt(Component) { return class WithTilt extends React.Component { constructor(props) { super(props); this.tilt = React.createRef() } tiltAnimation () { VanillaTilt.init(this.tilt.current, { max: 20, speed: 1200, perspective: 1000, glare: true, reset: true // axis: "x" }); } componentDidMount() { this.tiltAnimation() } render() { return ( <div ref={this.tilt} style={{transformStyle: 'preserve-3d'}} > <Component {...this.props}/> </div> ) } } } export default withTilt<file_sep>/src/pages/services.js import React from 'react' import SEO from '../components/layout/seo' import Section from '../components/Section' import color from '../utils/color' const ServicesPage = () => { return ( <> <SEO title="Services"/> <Section svgColor={color.gray.light}> <div className="md-col-6"> <div style={{paddingTop: '90px'}}> <header className='heading-group'> <h1>Services</h1> <h2 className='hand'>checkout <span aria-label="camara with flash" role="img" style={{fontSize: '50%'}}>✔️</span> what </h2> <h3>we can do for you </h3> </header> <p>I need images and content for the about page.</p> <p>This is 60 words from &rarr; Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio laudantium nihil officia sunt? Aliquid dicta esse magnam molestiae nisi non quis quisquam quo veniam voluptatem. Accusamus beatae deserunt dolores et fuga harum hic impedit non. Aliquam aliquid amet aperiam architecto at deleniti earum eius ipsa ipsam itaque laboriosam maiores nihil nisi numquam porro provident, quasi quos tempore vel velit, veniam.</p> <a href="#tag" className="btn btn--dark">Button 1</a> </div> </div> </Section> </> ) } export default ServicesPage<file_sep>/src/components/hero/HeroCardList.js import React from 'react' import styled from 'styled-components' import HeroCard from "./HeroCard" import color from "../../utils/color" import caps from './../../images/caps-case.jpg' import bags from './../../images/bag-rack.jpg' import salon from './../../images/hair-salon.jpg' const HeroCardList = () => { const DATA = [ { color: color.primary, img: caps }, { color: color.secondary, img: salon }, { color: color.dark, img: bags }, ] return ( <List> {DATA && DATA.map((item, index) => { return <HeroCard key={index} color={item.color} img={item.img}/> }) } </List> ) } export default HeroCardList const List = styled.div` display: flex; flex-direction: row; flex-wrap: nowrap; transform: translateX(10%) `<file_sep>/src/pages/work.js import React from "react" import SEO from "../components/layout/seo" import Parallax from '../components/Parallax' import Img1 from './../images/frontpage-first.jpg' import Img2 from './../images/block-table.jpg' import Img3 from './../images/frontpage-2.jpg' import Img4 from './../images/barn-doors.jpg' const WorkPage = ({ data }) => ( <> <SEO title='Our Work' /> <div style={{height: '60px', width: "100%"}}></div> <Parallax img={Img1} > <header className='heading-group'> <h1>Here is just a few</h1> <h2 className='hand'>of our <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>😊</span> happy clients </h2> <h3>work <span aria-label="sparkels" role="img">✨</span> </h3> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium architecto consequuntur neque nulla quae, rem repudiandae soluta temporibus ullam voluptatibus.</p> </Parallax> <Parallax img={Img2}> <header className='heading-group'> <h1>For your</h1> <h2 className='hand'>Business, Offices <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>🛠️</span> </h2> <h3> &amp; Store Fronts </h3> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error ipsum nihil nobis perferendis quibusdam? Aliquid molestias reprehenderit rerum temporibus voluptas?</p> </Parallax> <Parallax img={Img3}> <header className='heading-group'> <h1>For your</h1> <h2 className='hand'>Business, Offices <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>🛠️</span> </h2> <h3> &amp; Store Fronts </h3> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, quis?</p> </Parallax> <Parallax img={Img4}> <header className='heading-group'> <h1>For your</h1> <h2 className='hand'>Business, Offices <span aria-label="smileing" role="img" style={{fontSize: '50%'}}>🛠️</span> </h2> <h3> &amp; Store Fronts </h3> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem, quae!</p> </Parallax> </> ) export default WorkPage <file_sep>/src/utils/color.js export default { primary: 'orangered', secondary: '#81c4c8', gray: { light: '#f6f6f6', medium: '#888', dark: '#333' }, dark: '#111', white: '#fff', black: '#000', }<file_sep>/src/utils/shadow.js export default { level1: "rgba(0,0,0,0.05) 0 3px 10px", level2: "rgba(0,0,0,0.15) 0 6px 20px", level3: "rgba(0,0,0,0.5) 0 8px 30px", level4: "rgba(0,0,0,0.75) 0 8px 40px", }<file_sep>/src/components/hero/HeroCard.js import React from 'react' import styled from 'styled-components' const HeroCard = ({color, img}) => { return ( <Card style={{backgroundColor: color}}> <Border></Border> <Image src={img} alt="caps"/> </Card> ) } export default HeroCard const Card = styled.div` width: 450px; border-radius: 10px; overflow: hidden; box-shadow: rgba(0,0,0,0.5) -30px 10px 40px; transition: all 0.45s ease; &:not(:nth-child(1)) { margin-left: -30%; }; &:nth-child(1) { transform: translateZ(-50px) scale(0.65); }; &:nth-child(2) { transform: translateZ(0px) scale(0.85); }; &:nth-child(3) { transform: translateZ(50px) scale(1); }; &:hover ~ &:nth-child(1) { transform: translateX(200px) translateZ(-50px) scale(0.65); }; &:hover ~ &:nth-child(2) { transform: translateX(200px) translateZ(0px) scale(0.85); }; &:hover ~ &:nth-child(3) { transform: translateX(200px) translateZ(50px) scale(1); }; ` const Image = styled.img` width: 100%; object-fit: cover; display: block; ` const Border = styled.div` position: absolute; z-index: 10; height: calc(100% - 30px); width: calc(100% - 30px); margin: 15px; border: solid 4px rgba(0,0,0,0.5); border-radius: 8px; transform: translateZ(50px) `<file_sep>/src/components/grid/GridList.js import React, { useEffect } from "react" import GridItem from "./GridItem" import gsap from "gsap"; import ScrollTrigger from "gsap/ScrollTrigger"; import ClientDBC from './../../images/clients/designbycode.svg' import { v4 as uuidv4 } from 'uuid' gsap.registerPlugin(ScrollTrigger); const GridList = (props) => { const scrollTriggerRef = React.createRef(); // const scrollAnimation = () => { // gsap.to(".ci", { // scrollTrigger: { // trigger: scrollTriggerRef.current, // toggleActions: "play none none none", // start: "top 80%", // end: "top 20%", // scrub: 1, // markers: false // }, // opacity: 1, // x: 100, // stagger: { // amount: 0.5 // } // }); // }; useEffect(() => { // scrollAnimation(); }); const DATA = [ { id: uuidv4(), name: "DesignByCode", image: ClientDBC }, { id: uuidv4(), name: "<NAME>", image: ClientDBC }, { id: uuidv4(), name: "ZANEL", image: ClientDBC }, { id: uuidv4(), name: "<NAME>", image: ClientDBC }, { id: uuidv4(), name: "Blomma", image: ClientDBC }, { id: uuidv4(), name: "DesignByCode", image: ClientDBC } ] return ( <div ref={scrollTriggerRef} className="row"> {DATA && DATA.map(item => { return( <div key={item.id.toString()} className="xs-col-6 lg-col-4 ci"> <GridItem name={item.name} image={item.image}/> </div> ) })} </div> ) } export default GridList<file_sep>/src/components/grid/GridItem.js import React from 'react' import withTilt from "../../hoc/WithTilt" const GridItem = ({name, image}) => { return ( <div className="grid-item"> <div style={{transform: 'translateZ(50px)'}}> <img style={{width: '100%', textAlign: 'center'}} src={image} alt={name} /> </div> </div> ) } export default withTilt(GridItem)<file_sep>/src/utils/LongShadow.js class LongShadow { args constructor(args) { this.args.element = args.element || '.long-shadow' this.init() } init () { console.log(this.args) } } export default LongShadow<file_sep>/src/components/layout/Nav.js import React, { useState, useEffect } from 'react' import Link from "gatsby-link" import PropTypes from "prop-types" import Headroom from "react-headroom" import styled from 'styled-components' import color from "../../utils/color" // import logo from './../../images/nav-logo.svg' import { FiMenu } from 'react-icons/fi' const Nav = ({siteTitle}) => { let [isOpen, setIsOpen] = useState(true) useEffect(() => { let listener = window.addEventListener('resize', () => { handleResize() }) return window.removeEventListener('resize', listener) }) const handleToggleMenu = (e) => { return setIsOpen(!isOpen) } const handleResize = () => { if (window.innerWidth > 890 && isOpen) { setIsOpen(true) } } return ( <Headroom > <Navbar> <NavIcon onClick={handleToggleMenu}> <FiMenu size={22} strokeWidth={3} stroke={color.primary}/> </NavIcon> {isOpen && <NavbarWrapper className="wrapper"> <Brand className="title"> <Link className="hand" to="/"> <NAME> {/*<img style={{height: '40px'}} src={logo} alt="logo" />*/} </Link> </Brand> <Ul> <li> <Link to="/">HOME</Link> </li> <li> <Link to="/about/">ABOUT</Link> </li> <li> <Link to="/services/">SERVICES</Link> </li> <li> <Link to="/work/">OUR WORK</Link> </li> <li> <Link to="/contact/">CONTACT US</Link> </li> </Ul> </NavbarWrapper> } </Navbar> </Headroom> ) } Nav.propTypes = { siteTitle: PropTypes.string, } Nav.defaultProps = { siteTitle: ``, } export default Nav const Brand = styled.div` font-size: 28px; a { color: ${color.dark}; text-decoration: none; } ` const Navbar = styled.nav` position: fixed; width: 100%; height: 100vh; z-index: 100; background: ${color.white}; transition: box-shadow 0.5s ease; display: flex; flex-direction: column; align-items: center; justify-content: center; transition: ease 0.2s transform; will-change: transform; @media(min-width: 890px) { height: auto; } ` const NavbarWrapper = styled.div` display: flex; align-items: center; justify-content: center; flex-direction: column; ` const Ul = styled.ul` list-style: none; padding: 5px; margin: 0; li { display: inline-block; margin: 8px; width: 100%; @media(min-width: 890px) { width: auto; margin: 0 4px; } } a { padding: 10px 16px; display: block; background: transparent; color: ${color.dark}; border-radius: 10px; text-decoration: none; border-top: solid 1px transparent; border-left: solid 1px transparent; border-bottom: solid 3px transparent; border-right: solid 6px transparent; font-weight: bold; transition: color, border 0.25s ease; transform: skewX(-4deg); &[aria-current="page"] { border-top: solid 1px ${color.primary}; border-left: solid 1px ${color.primary}; border-bottom: solid 3px ${color.primary}; border-right: solid 6px ${color.primary}; color: ${color.primary} } &:not([aria-current="page"]):hover { border-top: solid 1px ${color.dark}; border-left: solid 1px ${color.dark}; border-bottom: solid 3px ${color.dark}; border-right: solid 6px ${color.dark}; color: ${color.dark} } } ` const NavIcon = styled.aside` position: absolute; height: 35px; width: 35px; display: flex; align-items: center; justify-content: center; border-radius: 10px; background: ${color.gray.light}; border: solid 2px ${color.primary}; right: 10px; top: 10px; @media(min-width: 890px) { display: none; } `<file_sep>/src/pages/contact.js import React from 'react' import SEO from '../components/layout/seo' const contact = () => { return ( <> <SEO title="Contact Us" /> <h1>Contact</h1> </> ) } export default contact<file_sep>/src/components/hero/Hero.js import React, { useEffect } from 'react' import styled from 'styled-components' import HeroLogo from "./HeroLogo" import HeroCardList from "./HeroCardList" import LongShadow from '../../utils/LongShadow' const Hero = () => { useEffect(() => { }) return ( <HeroSection> <div className="wrapper"> <div className="row" style={{alignItems: 'center'}}> <div className="md-col-4"> <HeroLogo/> </div> <div className="md-col-8"> <HeroCardList/> </div> </div> </div> </HeroSection> ) } export default Hero const HeroSection = styled.section` min-height: 100vh; width: 100%; display: flex; align-items: center; padding: 140px 0 90px 0; `
179de03efb8e90365345de428b3231c4e0949de0
[ "JavaScript" ]
17
JavaScript
DesignByCodeClientWebsite/CoenieMarais
686fe62f9e826d7963313356afc3e3b8236ffec6
7e47d49833c637a8c60eb957109d32685af79ecb
refs/heads/master
<repo_name>paultursuru/rails-mister-cocktail<file_sep>/app/controllers/cocktails_controller.rb class CocktailsController < ApplicationController before_action :set_cocktail, only: %I[index, show, upvote] def index @cocktails = Cocktail.all.order(votes: :desc) end def show @cocktail = Cocktail.find(params[:id]) end def new @cocktail = Cocktail.new end def create @cocktail = Cocktail.new(cocktail_params) @cocktail.save redirect_to new_cocktail_dose_path(@cocktail) end def upvote @cocktail.votes += 1 @cocktail.save redirect_to root_path end private def set_cocktail @cocktail = Cocktail.find(params[:id]) end def cocktail_params params.require(:cocktail).permit(:name, :photo, :vote) end end <file_sep>/db/migrate/20191210110138_add_changes_to_cocktails.rb class AddChangesToCocktails < ActiveRecord::Migration[5.2] def change remove_column :cocktails, :favorite add_column :cocktails, :votes, :integer, default: 0 end end <file_sep>/db/seeds.rb Dose.destroy_all Ingredient.destroy_all Cocktail.destroy_all require 'json' require 'open-uri' require 'faker' url = 'https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list' ingredients_serialized = open(url).read ingredients = JSON.parse(ingredients_serialized) puts "ok url" ingredients["drinks"].each do |i| Ingredient.create(name: i["strIngredient1"]) end 10.times do cocktail_name = Faker::Creature::Horse.breed cocktail = Cocktail.new(name: cocktail_name) file = URI.open("https://source.unsplash.com/300x300/?horse") cocktail.photo.attach(io: file, filename: "some-image.jpg", content_type: 'image/jpg') cocktail.save puts "cocktails ok" rand(2..5).times do dose_name = "#{rand(1..3)} parts" Dose.create(description: dose_name, cocktail: cocktail, ingredient: Ingredient.all.sample) end end
d94381e99dd9fa3b6b9dda637c53e31b8a457413
[ "Ruby" ]
3
Ruby
paultursuru/rails-mister-cocktail
74e973e14a2fa9c5d743aef5a6c35b2d746f1c0f
74261069b76bb9b9f593adba5b231a835dea825e
refs/heads/master
<file_sep>$togDebug=false #---Hex operations def hex_str_to_char_arr(str) temp_arr=[] str.gsub(/([0-9a-zA-Z]{2})/) {|f| temp_arr<<f} return temp_arr end def hex_to_asc(hex_code) #hex code string (i.e. "20" for space) as input hex_code.hex.chr end #--Array operations def combine_arrs(arr) all_arrs=[] arr.each do |a| all_arrs<<hex_str_to_char_arr(a) end return all_arrs end def and_arrays(arr_coll) #takes collection of arrays as input, outputs AND of all those arrays max_len=0 arr_coll.each do |el| #find length of longest array in collection of arrays if el.length > max_len max_len = el.length end end result = arr_coll[0][0..(max_len-1)] arr_coll[1..arr_coll.length].each do |arr| arr[0..max_len-1].each_with_index do |el, ind| if el != result[ind] result[ind]=0 end end end return result end #Xor functions def xor_hex(char1,char2) (char1.hex ^ char2.hex).to_s(16) end def xor_array_els_as_hex(a,b) #input two arrays each with hex characters as elements xoredarr=[] if a.length > b.length || a.length == b.length for i in 0..b.length-1 xored = (a[i].hex ^ b[i].hex).to_s(16) xoredarr<<xored end else b.length > a.length for i in 0..a.length-1 xored = (a[i].hex ^ b[i].hex).to_s(16) xoredarr<<xored end end return xoredarr end #Functions for analysis of ciphertexts def find_shifted_case(orig,final) #input arrays of same length and with ascii characters shifted_case=Array.new(orig.length,0) orig.each_with_index do |el, i| el=hex_to_asc(el) fin=hex_to_asc(final[i]) if (el == fin.downcase) || (fin == el.downcase) #if original element matches upper or lowercase of final element in same position shifted_case[i]=1 #mark as shift in case end end return shifted_case end def build_key_from_spaces(spaces_array, cts_array) #array of arrays showing spaces in cts key=[] spaces_array.each_with_index do |arr, arr_ind| arr.each_with_index do |el, el_ind| if el==1 #i.e. there is a space there #xor hex space (20) with the appropriate ct element --> that is the key value for that index (s ^ k ^ s = k) key[el_ind] = ("20".hex ^ cts_array[arr_ind][el_ind].hex).to_s(16) end end end return key end def decode(ct, key, debug=false) #given ciphertext array and key array, output plaintext as ascii string pt=[] ct.each_with_index do |el, ind| if ind>98 sp=" " else sp=" " end if !key[ind].nil? pt << (el.hex ^ key[ind].hex).chr + sp else pt << "."+sp end end if debug pt=pt.join("|") else pt=pt.join("") end end def decode_cts(cts_array,key,debug) #use decode method to do whole set of ciphertexts i=1 cts_array.each do |arr| pt=decode(arr,key,debug) if debug j=0 print "\n" print "ct #{i}: " arr.length.times.reject {|el| el==0}.each do |num| if num < 10 print "#{num} |" #add a space to preserve alignment with double digit stuff else print "#{num}|" end end print "\n" end puts "ct #{i}: #{pt}" i += 1 end end def set_key_val(ct_arr,ct_num, key, index, pt_value) #set specific key values if pt_value.length ==1 key[index]=xor_hex(pt_value.ord.to_s(16),ct_arr[ct_num-1][index]) else #add a few letters in a row from a given starting point n=0 pt_value.chars.each do |ltr| key[index+n]=xor_hex(ltr.ord.to_s(16),ct_arr[ct_num-1][index+n]) n=n+1 end end end def main_key_build_run(ct_array, ct_tar_arr, debug=$togDebug) spaces_arrays=[] #for one given ct...... ct_array.each_with_index do |curr_ct_1,k| shifts_array_for_indiv_ct = [] #....xor one at a time with another ct --> result is m1^ m2 (but don't compare against self because xor would just be 0) ct_array.each_with_index.reject { |el,i| i == (ct_array.index(curr_ct_1)) }.each_with_index do |curr_ct_2,j| curr_ct_2=curr_ct_2[0] xor12 = xor_array_els_as_hex(curr_ct_1,curr_ct_2) #Then xor m1^m2 with an array of spaces (hex 20) arr_spaces=Array.new(xor12.length,"20") xored_w_sp=xor_array_els_as_hex(xor12,arr_spaces) # --> m1^m2^s #then compare m1^m2 and m1^m2^s to see if any hex values correspond to a shift in case #if so, that means m1 is a space -- s^m2 would result in shift in case (a-->A) and then s^s^m2 would shift it back a=find_shifted_case(xor12,xored_w_sp) #store that comparison between two cts shifts_array_for_indiv_ct << a end #after comparing one ct against all others, if one position consistently shifted register when xored with space (hex 20) then #it is most likely a space in that first ct --> we can find that by ANDing all arrays together spaces_in_ct=and_arrays(shifts_array_for_indiv_ct) #store an array showing likely spaces for an invividual ct into a larger array that will hold individual arrays for each ct spaces_arrays<<spaces_in_ct #do this all over again but with the next ct as the main comparison end #after all cts have been analyzed, build the key using that data #this is done by taking the array showing where spaces are in each plaintext, and where each space is, xor that ct (hex) value with #the value for space (hex 20), and that is the key value for that character position, i.e. where m1=s (m1^k^s=s^k^s=k) key=build_key_from_spaces(spaces_arrays, ct_array) return key end def print_decoded_cts(key, ct_array, ct_tar_arr, debug=false) puts "key = #{key}" #try and decode target decoded_tar = decode(ct_tar_arr, key) puts "targ: #{decoded_tar}" decode_cts(ct_array,key,debug) end def pop_array(file) arr=[] File.open(file).each_line { |s| arr << s } arr end def process_inp(input, ct_arr, ct_tar_arr, key) #matches input (i.e. "1,5, cipher") to fill text "cipher" starting at position 5 on ct# 1 ct_arr=[ct_tar_arr]+ct_arr ct_num, pos, txtval = input.split(/,[ ]*/) if ct_num.nil? || pos.nil? || txtval.nil? puts "improper input; should be ct_num,position,value" else if ct_num == ("tar" || "t") ct_num=0 else ct_num=ct_num.to_i+1 end set_key_val(ct_arr,ct_num, key, (pos.to_i-1), txtval) end end if __FILE__ == $0 #run this if executed from command line if ARGV.empty? puts %Q{\nProper usage is:\n\n '#{$0} cts_file'\n\nwhere cts_file is a file containing all ciphertexts, separated by a blank line} puts %Q{\nFrom there, the ciphertexts are analyzed and you can fill in the remaining blanks using the super fancy method of:\n\n txt_num,pos,val\n\n} puts %Q{for example: 1,1,X to change the first character in the first text to X -- all changes are then replicated across other texts} Process.exit end #load cts in file, each separated by blank line, with target as last line (actually doesn't matter bc all cts will be decrypted) ct_file = ARGV[0] ct_inp=File.open(ct_file).read.split("\n").reject { |el| el==""} ct_strs=ct_inp[0..ct_inp.length-2] ct_tar=ct_inp[ct_inp.length-1] #convert ct_strs to array of arrays containing each hex code (2 digits) in an array ct_array=combine_arrs(ct_strs) # i.e. ["asdflk","asdkfjsaldj"]->[["as","df","lk"],["as",....]] ct_tar_arr=hex_str_to_char_arr(ct_tar) # same, but only one array #do analysis, etc. up to and including building the key key=main_key_build_run(ct_array, ct_tar_arr) ct_arr=combine_arrs(ct_strs) #then we enter loop where once can: while true print_decoded_cts(key,ct_arr,ct_tar_arr,$togDebug) inp = $stdin.gets.chomp case inp # 1) toggle between debug and not when "D" if $togDebug $togDebug=false else $togDebug=true end # 2) quit when "Q" Process.exit else begin # 3) add our own observations to help build the key process_inp(inp, ct_arr, ct_tar_arr,key) rescue => msg puts "Something went wrong: #{msg}" end end end # there is also and undo function end #Best computed guess before filling in blanks mentally: #targ: T h e s e c r e t m e s s a g e i s : W h e . . . s . . . a s t r e a m c i p h e r , n e . . . . . s e t h e k . y m . r e . t h a n . n . . <file_sep>## Decryption Analysis of One-Time-Pad One-time-pad/key encryption is more or less the only completely secure form of encryption. However, when one uses a one-time-key more than once, then it opens itself to analysis, and possibly decryption. This program takes an input of a text file containing encrypted "messages" (the more, the better) and analyzes them as best it can (you can review the code and comments for exact details of the implementation). From there, the decrypted text isn't nearly complete, but there is typically enough for a human to fill in the blanks. ### Running the program You run the program with: ```bash ruby decryptOTP.rb ct_file ``` where ct_file is the file containing the encrypted texts, with a blank line separating each. #### Compeleting the manual process For any blanks you wish to fill in, just type: ```bash ctext_num,position,value ``` i.e. if you see, in the first ciphertext ```bash ct 1: T . . c a t a n d t h e d o g . . ``` you could type ```bash 1,2,he ``` to complete ```bash ct 1: T h e c a t a n d t h e d o g . . ``` ### Options You can type 'D' to toggle analysis mode, which displays the position of each character above it, for ease in manual decryption You can type 'Q' to quit ...and that is it, for now. ### Other stuff This is 100% just a quick project that resulted from a cryptography course, and I added some extensions to make the process as automatic as I could, so....no complaints bitte.
e9a28114191d4fba5f510d7e112319384232d5af
[ "Markdown", "Ruby" ]
2
Ruby
estromlund/onetimepad_analysis
38c0763dd8def70bccf29eac875bfac77ca1eeee
1e76c4b9021e15e63595e34efd4094724999939f
refs/heads/master
<repo_name>snowyowl981/TankAttack2021<file_sep>/Assets/02.Scripts/Cannon.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cannon : MonoBehaviour { [SerializeField] private float cannonSpeed; public GameObject expEffect; public string shooter; // Start is called before the first frame update void Start() { GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * cannonSpeed); } void OnCollisionEnter(Collision coll) { GameObject exp = Instantiate(expEffect, transform.position, Quaternion.identity); Destroy(exp, 1f); Destroy(this.gameObject); } } <file_sep>/Assets/02.Scripts/TankCtrl.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using UnityStandardAssets.Utility; using TMPro; public class TankCtrl : MonoBehaviour, IPunObservable { [SerializeField] private float moveSpeed; [SerializeField] private float rotationSpeed; [SerializeField] private float cannonRoatationSpeed; // 필요 컴포넌트 private Transform tankTr; private PhotonView pv; public GameObject cannonPrefab; [SerializeField] private Transform firePos; public Transform cannonMesh; private new AudioSource audio; public AudioClip cannonFireSfx; public TMPro.TMP_Text userIdText; // Start is called before the first frame update void Start() { tankTr = GetComponent<Transform>(); pv = GetComponent<PhotonView>(); audio = GetComponent<AudioSource>(); userIdText.text = pv.Owner.NickName; // 무게중심 if(pv.IsMine) { Camera.main.GetComponent<SmoothFollow>().target = transform.Find("CamPivot").transform; GetComponent<Rigidbody>().centerOfMass = new Vector3(0, -5.0f, 0); } else { GetComponent<Rigidbody>().isKinematic = true; } } // Update is called once per frame void Update() { if(pv.IsMine) { float v = Input.GetAxis("Vertical"); float h = Input.GetAxis("Horizontal"); //이동 및 회전 tankTr.Translate(Vector3.forward * Time.deltaTime * moveSpeed * v); tankTr.Rotate(Vector3.up * Time.deltaTime * rotationSpeed * h); // 포탄 발사 로직 if(Input.GetMouseButtonDown(0)) { pv.RPC("Fire", RpcTarget.AllViaServer, pv.Owner.NickName); } // 포신 회전 float r = Input.GetAxis("Mouse ScrollWheel"); cannonMesh.Rotate(Vector3.right * Time.deltaTime * r * cannonRoatationSpeed); } else { if((tankTr.position - receivePos).sqrMagnitude > 3.0f * 3.0f) { tankTr.position = receivePos; } else { tankTr.position = Vector3.Lerp(tankTr.position, receivePos, Time.deltaTime * 10f); } tankTr.rotation = Quaternion.Slerp(tankTr.rotation, receiveRot, Time.deltaTime * 10f); } } [PunRPC] void Fire(string shooterName) { GameObject _cannon = Instantiate(cannonPrefab, firePos.position, firePos.rotation); audio?.PlayOneShot(cannonFireSfx); // 혹은 Awake영역으로 올릴 것 _cannon.GetComponent<Cannon>().shooter = shooterName; } Vector3 receivePos = Vector3.zero; Quaternion receiveRot = Quaternion.identity; public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) { if(stream.IsWriting) // PhotonView.IsMine == true; { stream.SendNext(tankTr.position); // 위치 stream.SendNext(tankTr.rotation); // 회전값 } else { // 두번 보내서 두번 받음 receivePos = (Vector3)stream.ReceiveNext(); receiveRot = (Quaternion)stream.ReceiveNext(); } } }
c31b6a7bf9ca0625ada58869c647ba6a659b27fe
[ "C#" ]
2
C#
snowyowl981/TankAttack2021
e18d6c0e312d0991a4d43278c19815fd0fddc96e
6d8661835ec4c2089f2e1d7c895649ec45502fcc
refs/heads/master
<file_sep>package Collection; import java.util.*; public class LinkedListDemo { public static void main(String[] args) { LinkedList l = new LinkedList(); l.add(97); l.add("java"); l.add('a'); l.add(null); System.out.println(l); l.set(2, 94); l.removeLast(); l.addFirst("neha"); System.out.println(l.getLast()); System.out.println(l); } } <file_sep>package Collection; import java.util.*; public class ListIteratorDemo { public static void main(String[] args) { LinkedList a = new LinkedList(); a.add("Neha"); a.add("Aarati"); a.add("Bhavisha"); a.add("Renu"); ListIterator lt = a.listIterator(); while(lt.hasNext()) { String I = (String)lt.next(); System.out.println(I); //System.out.println(I.nextIndex()); // if(I.equals("Neha")){ // lt.add("Amitha"); // } if(I.equals("Neha")) { lt.nextIndex(); }} while(lt.hasPrevious()) { String I1 = (String)lt.previous(); System.out.println(I1); } }}
a0cb8dfdab5a31a54f0837d2e7524824a24ad030
[ "Java" ]
2
Java
Neha2486/collectionNeha
a8ab3677b08916c905b2b14948678599b0ca3247
e41988b4f94163731d453335079d7fc980f9df7a
refs/heads/master
<repo_name>aikrasnov/python-selenium<file_sep>/conftest.py import os import pytest import datetime from selenium import webdriver AVAILABLE_BROWSERS = { "chrome": "chrome", "firefox": "firefox" } @pytest.fixture(scope="function") def driver(request, param): browser_type = request.config.getoption("--browser") or param save_screen = request.config.getoption("--screenonfail") or param username = None access_key = None try: username = os.environ["SAUCE_USERNAME"] access_key = os.environ["SAUCE_ACCESS_KEY"] except KeyError: pass has_sauce_lab = username and access_key caps = {} command_executor = f"https://{username}:{access_key}@ondemand.eu-central-1.saucelabs.com:443/wd/hub" if AVAILABLE_BROWSERS["chrome"] in browser_type: # use "none" only for Chrome, because there some trouble in geckrodriver with this strategy caps.update({"pageLoadStrategy": "none"}) if has_sauce_lab: caps.update({"browserName": "chrome", "platform": "Windows 10", "version": "71.0"}) browser = webdriver.Remote(desired_capabilities=caps, command_executor=command_executor) else: browser = webdriver.Chrome(desired_capabilities=caps) elif AVAILABLE_BROWSERS["firefox"] in browser_type: if has_sauce_lab: caps.update({"browserName": "firefox", "platform": "Windows 10", "version": "64.0"}) browser = webdriver.Remote(desired_capabilities=caps, command_executor=command_executor) else: browser = webdriver.Firefox(desired_capabilities=caps) else: raise RuntimeError(f"Unknown browser ${browser_type}") yield browser if request.node.rep_call.failed and save_screen: screenshots_path = f"./screenshots/{browser_type}/{request.node.name}/" if not os.path.exists(screenshots_path): os.makedirs(screenshots_path) now = datetime.datetime.now() browser.save_screenshot(f"{screenshots_path}{now.day}-{now.month}-{now.year}.png") browser.quit() @pytest.fixture(scope="function") def param(request): # we don"t have request.param when not parametrize tests with pytest_generate_tests try: return request.param except AttributeError: pass def pytest_addoption(parser): parser.addoption("--browser", action="append", help=f"Browser. Valid options are {AVAILABLE_BROWSERS.keys()}") parser.addoption("--allbrowsers", default=False, action="store_true", help="Run tests in all available browsers") parser.addoption("--screenonfail", default=False, action="store_true", help="Save screenshot on test fail") def pytest_generate_tests(metafunc): if metafunc.config.getoption("allbrowsers") and not metafunc.config.getoption("browser"): metafunc.parametrize("param", AVAILABLE_BROWSERS.keys()) # https://automated-testing.info/t/pytest-krivo-otobrazhaet-kejsy-parametrizaczii-na-russkom/17908 def pytest_make_parametrize_id(config, val): return repr(val) # https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): # execute all other hooks to obtain the report object outcome = yield rep = outcome.get_result() # set a report attribute for each phase of a call, which can # be "setup", "call", "teardown" setattr(item, "rep_" + rep.when, rep) <file_sep>/tests/test_suggest-2.py from src.pages.main_page import MainPage import pytest @pytest.mark.parametrize("text", ["@@@@@"]) @pytest.allure.testcase("http://test-tracker/suggest-2") @pytest.allure.feature("SUGGEST-2: Саджест не должен появляться") def test_suggest_2(driver, text): page = MainPage(driver) page.open() input_text = text with pytest.allure.step("suggest should not be visible"): page.check_suggest_not_visible() with pytest.allure.step(f"should type text {input_text}"): page.enter_query(input_text) with pytest.allure.step("suggest should not be visible"): page.check_suggest_not_visible_with_timeout() <file_sep>/tests/test_suggest-1.py from src.pages.main_page import MainPage from src.wait.conditions import CONDITIONS import pytest @pytest.mark.parametrize("text", ["foobar", "бесплатно", "без регистрации", "中文"]) @pytest.allure.testcase("http://test-tracker/suggest-1") @pytest.allure.feature("SUGGEST-1: Саджест должен появляться") @pytest.mark.debug def test_suggest_1(driver, text): page = MainPage(driver) page.open() input_text = text with pytest.allure.step("suggest should not be visible"): page.check_suggest_not_visible() with pytest.allure.step(f"should type text {input_text}"): page.enter_query(input_text) with pytest.allure.step("suggest should be visible"): page.check_suggest_visible() with pytest.allure.step(f"suggest should have text {input_text}"): page.check_suggest_text(CONDITIONS.contains, input_text) with pytest.allure.step("should clear search field"): page.clear_query() with pytest.allure.step("suggest should disappear"): page.check_suggest_not_visible() <file_sep>/tests/test_suggest-3.py from src.pages.search import Search from src.pages.main_page import MainPage from src.wait.conditions import CONDITIONS import pytest @pytest.mark.parametrize("suggest_item", [{"text": "torrent", "position": "first"}, {"text": "Мэил.ру", "position": "last"}]) @pytest.allure.testcase("http://test-tracker/suggest-3") @pytest.allure.feature("SUGGEST-3: Поиск через саджест") def test_suggest_3(driver, suggest_item): main = MainPage(driver) search = Search(driver) main.open() input_text = suggest_item["text"] item_position = suggest_item["position"] suggest_length = 10 with pytest.allure.step(f"should type text '{input_text}'"): main.enter_query(input_text) with pytest.allure.step("suggest should be visible"): main.check_suggest_visible() with pytest.allure.step("should have more than one item in suggest"): main.check_suggest_item_count(CONDITIONS.equal, suggest_length) with pytest.allure.step(f"should get text from item {item_position}"): item_text = main.get_suggest_item_text(item_position) with pytest.allure.step(f"should click at '{item_position}' suggest item"): main.click_at_suggest_item(item_position) with pytest.allure.step(f"should open search page with '{item_text}' in input"): search.check_search_input_text(item_text) <file_sep>/src/pages/main_page.py from selenium.webdriver.remote.webdriver import WebDriver from src.wait.wait import Wait from config.config import BASE_URL from src.wait.conditions import CONDITIONS from time import sleep class MainPage(object): def __init__(self, browser: WebDriver): self.__url = BASE_URL self.__browser = browser self.__wait = Wait(self.__browser) self.__query_input = "#q" self.__suggest_select = ".go-suggests__wrap" self.__suggest_select_item = ".go-suggests__item__text" def open(self): self.__browser.get(self.__url) self.__wait.wait_until_visible_by_css_selector(self.__query_input) def enter_query(self, query: str): self.__wait.wait_until_visible_by_css_selector(self.__query_input) self.__browser.find_element_by_css_selector(self.__query_input).click() self.__browser.find_element_by_css_selector(self.__query_input).send_keys(query) def clear_query(self): self.__wait.wait_until_visible_by_css_selector(self.__query_input) self.__browser.find_element_by_css_selector(self.__query_input).clear() def check_suggest_visible(self): self.__wait.wait_until_visible_by_css_selector(self.__suggest_select) def check_suggest_not_visible(self): self.__wait.wait_until_not_visible_by_css_selector(self.__suggest_select) def check_suggest_not_visible_with_timeout(self, timeout=5): sleep(timeout) self.check_suggest_not_visible() def check_suggest_text(self, condition: str, text: str,): self.__wait.wait_until_visible_by_css_selector(self.__suggest_select_item) elements = self.__browser.find_elements_by_css_selector(self.__suggest_select_item) if condition == CONDITIONS.contains: for element in elements: assert text in element.text, f"suggest text should contain {text}" elif condition == CONDITIONS.equal: for element in elements: assert text == element.text, f"suggest text should be equal {text}, not {element.text}" else: raise RuntimeError(f"Unknown condition {condition}") def check_suggest_item_count(self, condition: str, count: int): self.__wait.wait_elements_count_by_css_selector(self.__suggest_select_item, condition, count) def get_suggest_item_text(self, position: str) -> str: self.__wait.wait_until_visible_by_css_selector(self.__suggest_select_item) texts = [el.text for el in self.__browser.find_elements_by_css_selector(self.__suggest_select_item)] if position == "first": return texts[0] elif position == "last": return texts[-1] else: raise RuntimeError(f"Unknown position {position}") def click_at_suggest_item(self, position): self.__wait.wait_until_visible_by_css_selector(self.__suggest_select_item) elements = self.__browser.find_elements_by_css_selector(self.__suggest_select_item) if position == "first": elements[0].click() elif position == "last": elements[-1].click() else: raise RuntimeError(f"Unknown position {position}") <file_sep>/src/pages/search.py from selenium.webdriver.remote.webdriver import WebDriver from src.wait.wait import Wait from config.config import BASE_URL class Search(object): def __init__(self, browser: WebDriver): self.url = BASE_URL + "search/" self.__browser = browser self.__wait = Wait(self.__browser) self.__search_input = "(//input[@type='text'])[1]" def check_search_input_text(self, input_text: str): self.__wait.wait_until_visible_by_xpath_locator(self.__search_input) text = self.__browser.find_element_by_xpath(self.__search_input).get_property("value") assert text == input_text, f"Text from input should be equal {text}" <file_sep>/src/wait/wait.py from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.remote.webdriver import WebDriver from src.wait.conditions import CONDITIONS class Wait(object): def __init__(self, browser: WebDriver, timeout=10): self.__browser = browser self.__timeout = timeout self.__wait = WebDriverWait(self.__browser, self.__timeout) def __wait_until(self, fn): # не смотря на ошибки, пытаемся дождаться появления элемента def safe_wait(wait_function, browser): try: return wait_function(browser) except (StaleElementReferenceException, NoSuchElementException) as exc: return False self.__wait.until(lambda browser: safe_wait(fn, browser)) def wait_until_visible_by_xpath_locator(self, selector: str): self.__wait_until(lambda browser: browser.find_element_by_xpath(selector).is_displayed()) def wait_until_visible_by_css_selector(self, selector: str): self.__wait_until(lambda browser: browser.find_element_by_css_selector(selector).is_displayed()) def wait_until_not_visible_by_css_selector(self, selector: str): self.__wait_until((lambda browser: not browser.find_element_by_css_selector(selector).is_displayed())) def wait_elements_count_by_css_selector(self, selector: str, condition: str, count: int): if condition == CONDITIONS.equal: self.__wait_until(lambda browser: len(browser.find_elements_by_css_selector(selector)) == count) else: raise RuntimeError(f"Unknown condition {condition}") <file_sep>/src/wait/conditions.py class conditions(object): def __init__(self): self.above = "above" self.equal = "equal" self.contains = "contains" CONDITIONS = conditions() <file_sep>/tests/test_suggest-4.py from src.pages.main_page import MainPage from src.wait.conditions import CONDITIONS import pytest @pytest.mark.parametrize("text", ["!@#$%^"]) @pytest.allure.testcase("http://test-tracker/suggest-4") @pytest.allure.feature("SUGGEST-4: Саджест. Спецсимволы") def test_suggest_4(driver, text): page = MainPage(driver) page.open() input_text = text message = "как минимум один специальный символ !@#$%^&*?_~+=." with pytest.allure.step("suggest should not be visible"): page.check_suggest_not_visible() with pytest.allure.step(f"should type text {input_text}"): page.enter_query(input_text) with pytest.allure.step(f"should have message {message}"): page.check_suggest_text(CONDITIONS.equal, message) <file_sep>/readme.md [![Build Status](https://travis-ci.org/aikrasnov/python-selenium.svg?branch=master)](https://travis-ci.org/aikrasnov/python-selenium) ## Как запустить тесты ### Локально 0) Установить firefox, chrome и положить их драйвера в PATH ([chromedriver](http://chromedriver.chromium.org/), [geckodriver](https://github.com/mozilla/geckodriver/releases)) 1) Склонировать репу 2) Установить pipenv ([инструкция](https://github.com/pypa/pipenv#installation)) 3) Запустить `pipenv install --dev && pipenv run pytest` ### В Sauce Lab 1) Выполнить все те же шаги (кроме драйверов в PATH) 2) Установить переменные окружения SAUCE_USERNAME and SAUCE_ACCESS_KEY 3) Запустить тесты ### Изменить количество ретраев `pytest -reruns number` ([подробности](https://pypi.org/project/pytest-rerunfailures/)) ### Изменить количество параллельных тестов `pytest -n number` ([подробности](https://pypi.org/project/pytest-xdist/)) ### Изменить браузер `pytest --browser firefox` `pytest --browser chrome` ### Сохранять скриншот при падении теста `pytest --screenonfail` ### Посмотреть отчеты 1) Установить allure ([инструкция](https://docs.qameta.io/allure/#_installing_a_commandline)) 2) Запустить тесты 3) Выполнить `allure generate report --clean && allure open allure-report` TODO: 1) Публиковать отчеты по запускам в travis ci 2) Вынести из conftest установку капабилити, создание объектов webdriver.Remote / Firefox / Chrome 3) Кастомизировать отчеты в консоли 4) Добавить репорты в телеграм / слак 5) Вынести повторяющеся ошибки в отдельный модуль 6) Вынести повторяющиеся ассерты из PO 7) "Прорастить" ретраи в allure-отчеты 8) Определять окружение через параметр для pytest, а не из config.py 9) Добавить сохранение логов драйверов 10) Привет, Отус! <file_sep>/pytest.ini [pytest] addopts = -v -s --reruns 2 -p no:warnings -n 2 --allbrowsers --alluredir report <file_sep>/config/config.py # may be changed in different environments BASE_URL = "https://go.mail.ru/" <file_sep>/Pipfile [requires] python_full_version = "3.7" [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] flake8 = "*" flake8-quotes = "*" [packages] selenium = "==3.141.0" pytest = "==4.0.1" pytest-rerunfailures = "==5.0" pytest-xdist = "==1.25.0" pytest-allure-adaptor = "==1.7.10" attrs = "==19.1.0"
ce4fd055659a5e5ee3917fd1e2467b16521e0041
[ "Markdown", "TOML", "Python", "INI" ]
13
Python
aikrasnov/python-selenium
f78fab03ec78849f6e2cf54d645277a535bc339e
3d8fa1d0fc420be830579509f73e6a867a94321a
refs/heads/master
<repo_name>Askannz/unicorn-hat-hd-rs<file_sep>/Cargo.toml [package] name = "unicorn_hat_hd" version = "0.2.1" authors = ["<NAME> <<EMAIL>>"] description = "Provides an interface to the Pimoroni Unicorn HAT HD on a Raspberry PI" repository = "https://github.com/jhelwig/unicorn-hat-hd-rs" readme = "README.md" license = "BSD-3-Clause" keywords = ["pimoroni"] categories = ["hardware-support"] exclude = [ ".vscode/*", ] [features] default = ["hardware"] hardware = ["spidev"] fake-hardware = ["ansi_term"] [dependencies] ansi_term = { version = "0.12.0", optional = true } failure = "0.1.1" rgb = "0.8" spidev = { version = "0.3.0", optional = true } <file_sep>/src/lib.rs #[cfg(feature = "fake-hardware")] extern crate ansi_term; extern crate failure; extern crate rgb; #[cfg(feature = "hardware")] extern crate spidev; #[cfg(feature = "fake-hardware")] use ansi_term::Color::RGB; #[cfg(feature = "fake-hardware")] use ansi_term::ANSIStrings; use failure::Error; #[cfg(feature = "hardware")] use rgb::ComponentSlice; #[cfg(feature = "hardware")] use std::io::prelude::*; #[cfg(feature = "hardware")] use spidev::{SPI_MODE_0, Spidev, SpidevOptions}; const BLACK: rgb::RGB8 = rgb::RGB8 { r: 0, g: 0, b: 0 }; /// Possible rotations of the buffer before displaying to the /// Unicorn HAT HD. pub enum Rotate { /// Default rotation. RotNone, /// Rotate the output by 90 degrees clockwise. RotCW90, /// Rotate the output by 90 degrees counter-clockwise. RotCCW90, /// Rotate the output by 180 degrees. Rot180, } #[cfg(feature = "hardware")] /// Provide high-level access to the Unicorn HAT HD. pub struct UnicornHatHd { leds: [rgb::RGB8; 256], spi: Spidev, rotation: Rotate, } #[cfg(feature = "fake-hardware")] /// Provide high-level access to an emulated Unicorn HAT HD. pub struct UnicornHatHd { leds: [rgb::RGB8; 256], rotation: Rotate, } impl UnicornHatHd { #[cfg(feature = "hardware")] /// Create a new `UnicornHatHd` with the provided path /// /// The Unicorn HAT HD should be addressable using the spidev /// device with the provided path /// /// Typically, the path will be something like `"/dev/spidev0.0"` /// where the first number if the bus and the second number /// is the chip select on that bus for the device being targeted. pub fn new(spi_path: &str) -> Result<UnicornHatHd, Error> { let mut spidev = try!(Spidev::open(spi_path)); let options = SpidevOptions::new() .bits_per_word(8) .max_speed_hz(9_000_000) .mode(SPI_MODE_0) .build(); try!(spidev.configure(&options)); Ok(UnicornHatHd { leds: [BLACK; 256], spi: spidev, rotation: Rotate::RotNone, }) } #[cfg(feature = "fake-hardware")] /// Create a fake `UnicornHatHd` /// /// `_spi_path` is completely unused by the fake `UnicornHatHd`. pub fn new(_spi_path: &str) -> Result<UnicornHatHd, Error> { Ok(UnicornHatHd { leds: [BLACK; 256], rotation: Rotate::RotNone, }) } /// Rotate the display buffer by [`Rotate`](enum.Rotate.html) degrees /// before sending to the Unicorn HAT HD. /// /// This allows for different mounting orientations of the Unicorn HAT HD /// without having to translate the `(x, y)` of each pixel to account for the /// physical rotation of the display. pub fn set_rotation(&mut self, rot: Rotate) { self.rotation = rot; } #[cfg(feature = "hardware")] /// Write the display buffer to the Unicorn HAT HD. pub fn display(&mut self) -> Result<(), Error> { self.spi.write(&[0x72])?; let data = self.as_array(); self.spi.write(&data)?; Ok(()) } #[cfg(feature = "fake-hardware")] /// Write the display buffer to the Unicorn HAT HD. pub fn display(&mut self) -> Result<(), Error> { println!("Unicorn HAT HD:"); for y in 0..16 { let mut line = vec![]; for x in 0..16 { let pixel = self.get_pixel(x, y); line.push(RGB(pixel.r, pixel.g, pixel.b).paint("*")); } println!("{}", ANSIStrings(&line)); } Ok(()) } /// Set an individual pixel's RGB value. /// /// The origin (`(0, 0)`) is the top-left of the display, with `x` & `y` /// increasing to the right, and down, respectively. pub fn set_pixel(&mut self, x: usize, y: usize, c: rgb::RGB8) { self.leds[(y * 16) + x] = c; } /// Return a tuple of an individual pixel's RGB value. /// /// The origin (`(0, 0)`) is the top-left of the display, with `x` & `y` /// increasing to the right, and down, respectively. /// /// *NOTE*: This returns what's in the display buffer, not what the /// physical pixel is set to. pub fn get_pixel(&self, x: usize, y: usize) -> rgb::RGB8 { self.leds[(y * 16) + x] } /// Clear the internal buffer of pixel states. /// /// To clear the display itself, you'll still need to call /// [`display`](#method.display) to update the Unicorn HAT HD. pub fn clear_pixels(&mut self) { self.leds = [BLACK; 256]; } #[cfg(feature = "hardware")] /// Translate the internal buffer into a `Vec<u8>` of RGB values. The LEDs on /// the Unicorn HAT HD are addressed in the following order, with each LED /// consisting of three `u8`, one each for the R, G, and B values (assuming no /// rotation has been set): /// /// Physical LEDs => Vec<u8> order /// 1 2 3 /// 4 5 6 => 1 2 3 4 5 6 7 8 9 /// 7 8 9 fn as_array(&self) -> Vec<u8> { let mut arr: Vec<u8> = vec![]; match self.rotation { // 1 2 3 1 2 3 // 4 5 6 => 4 5 6 => 1 2 3 4 5 6 7 8 9 // 7 8 9 7 8 9 Rotate::RotNone => arr.extend_from_slice(self.leds.as_slice()), // 1 2 3 7 4 1 // 4 5 6 => 8 5 2 => 7 4 1 8 5 2 9 6 3 // 7 8 9 9 6 3 Rotate::RotCW90 => for x in 0..16 { for y in (0..16).rev() { let led = self.get_pixel(x, y); arr.extend_from_slice(led.as_slice()); } }, // 1 2 3 3 6 9 // 4 5 6 => 2 5 8 => 3 6 9 2 5 8 1 4 7 // 7 8 9 1 4 7 Rotate::RotCCW90 => for x in (0..16).rev() { for y in 0..16 { let led = self.get_pixel(x, y); arr.extend_from_slice(led.as_slice()); } }, // 1 2 3 9 8 7 // 4 5 6 => 6 5 4 => 9 8 7 6 5 4 3 2 1 // 7 8 9 3 2 1 Rotate::Rot180 => for led in self.leds.iter().rev() { arr.extend_from_slice(led.as_slice()); }, } arr } } impl Default for UnicornHatHd { /// Create a `UnicornHatHd` using the default path of "`/dev/spidev0.0`". /// /// This will panic if the default path is not usable. fn default() -> UnicornHatHd { UnicornHatHd::new("/dev/spidev0.0").unwrap() } } <file_sep>/README.md # unicorn-hat-hd [![Build Status](https://travis-ci.org/jhelwig/unicorn-hat-hd-rs.svg?branch=master)](https://travis-ci.org/jhelwig/unicorn-hat-hd-rs) Rust library for interacting with the Pimoroni Unicorn HAT HD. ## Documentation The docs can be found online at [docs.rs](https://docs.rs/unicorn_hat_hd/), or be built using `cargo doc`. ## Example Add `unicorn_hat_hd` to your `Cargo.toml`. ```toml [dependencies] unicorn_hat_hd = "0.2" ``` Add `unicorn_hat_hd` to your crate root. ```rust extern crate unicorn_hat_hd; ``` Create a default `UnicornHatHd`, and start setting some pixels. ```rust use unicorn_hat_hd::UnicornHatHd; pub fn main() { let mut hat_hd = UnicornHatHd::default(); loop { for y in 0..16 { for x in 0..16 { hat_hd.set_pixel(x, y, [255, 255, 255].into()); hat_hd.display().unwrap(); hat_hd.set_pixel(x, y, [0, 0, 0].into()); } } } } ``` ## Emulated display In order to help make development of apps that use the library a little faster/easier/less-painful, you can turn on emulation of the physical display, so that it can compile on platforms other than Linux & the Raspberry PI. In the `Cargo.toml`: ```toml [dependencies.unicorn_hat_hd] version = "*" default-features = false features = ["fake-hardware"] ``` Though, you should replace the `version = "*"` with an actual version constraint. Another thing of note is that the emulated display mode does not respect any display rotation that has been set, and will always output as though `Rotate::RotNone` were set. ## Copyright and license Copyright (c) 2017 <NAME>. Released under the [BSD license](LICENSE).
9bf39ecff9cf9042392c01fa29fdf772f9e02429
[ "TOML", "Rust", "Markdown" ]
3
TOML
Askannz/unicorn-hat-hd-rs
88b3e01abcfaa65030de669f61d2b0c76869dd2c
a78a561bd9da8a9ee2c383a87d1ca57871d9ddac
refs/heads/master
<repo_name>satnamram/tiny<file_sep>/db.go package tiny import ( "github.com/boltdb/bolt" "time" ) type DB struct { path string db *bolt.DB } func (db *DB) Store() Store { return Store{ path: []string{}, db: db.db, } } func Open(path string) (*DB, error) { db, err := bolt.Open(path, 0600, &bolt.Options{Timeout: 5 * time.Second}) if err != nil { return nil, err } err = db.Update(func(tx *bolt.Tx) error { return ensureDBSchema(tx) }) if err != nil { return nil, err } return &DB{ path: path, db: db, }, nil } func (db *DB) Path() string { return db.path } func (db *DB) Close() error { return db.db.Close() } <file_sep>/tiny.go // Package tiny implements persistent data structures. package tiny var ( // meta bucket and keys for the first layer dbMetaBucketKey = []byte{0x00} dbMetaCreatedKey = []byte{0x00} // the root bucket on the first layer dbRootBucketKey = []byte{0x01} // meta bucket and keys for Store layers storeMetaBucketKey = []byte{0x00} storeMetaBucketTypeKey = []byte{0x00} // Store bucket key for Store layers storeValueBucketKey = []byte{0x01} ) type Mode int const ( ModeDisk = iota ModeMem ) <file_sep>/tiny_test.go package tiny import ( "time" ) var testModes = map[string]Mode{ "mem": ModeMem, "disk": ModeDisk, } type TestStruct struct { String string Int int Float float64 Time time.Time Map map[string]string Slice []float64 } func newTestStruct() *TestStruct { return &TestStruct{ String: "aösldkaödl", Int: 23123123123, Float: 1231231.31231233, Time: time.Now().Round(time.Nanosecond), Map: map[string]string{"asdas": "adas"}, Slice: []float64{1213123.123123, 123.1231313123, 5555.33333333}, } } <file_sep>/map_test.go package tiny import ( "testing" "os" "reflect" ) func TestMap_SetGet(t *testing.T) { db, err := Open("test.db") if err != nil { t.Fatal(err) } defer func() { db.Close() os.Remove("test.db") }() for name, mode := range testModes { t.Run(name, func(t *testing.T) { m, err := db.Store().OpenMap("map", mode, "") if err != nil { t.Fatal(err) } v := "value" err = m.Put("key", &v) if err != nil { t.Fatal(err) } value, err := m.Get("key") if err != nil { t.Fatal(err) } if *value.(*string) != "value" { t.Fail() } }) } } func TestMapBasic(t *testing.T) { db, err := Open("test.db") if err != nil { t.Fatal(err) } defer func() { db.Close() os.Remove("test.db") }() m, err := db.Store().OpenMap("map", ModeMem, TestStruct{}) if err != nil { t.Fatal(err) } // insert struct pointer, check if get returns the same address ts := newTestStruct() err = m.Put("key", ts) if err != nil { t.Fatal(err) } ts2, err := m.Get("key") if err != nil { t.Fatal(err) } if ts != ts2 { t.Fail() } // reopen and check if test struct values equal db.Close() db, err = Open("test.db") if err != nil { t.Fatal(err) } m, err = db.Store().OpenMap("map", ModeMem, TestStruct{}) if err != nil { t.Fatal(err) } ts3, err := m.Get("key") if err != nil { t.Fatal(err) } if ts2 == ts3 { t.Fatal("fail") } if !reflect.DeepEqual(ts2, ts3) { t.Fatal("ts2 should equal ts3") } // remove key and check if it stays gone after database reload err = m.Remove("key") if err != nil { t.Fatal(err) } if _, err := m.Get("key"); err.Error() != "key 'key' does not exist" { t.Fatal("expected not exist error") } db.Close() db, err = Open("test.db") if err != nil { t.Fatal(err) } m, err = db.Store().OpenMap("map", ModeMem, TestStruct{}) if err != nil { t.Fatal(err) } if _, err := m.Get("key"); err.Error() != "key 'key' does not exist" { t.Fatal("expected not exist error") } // open submap in disk mode, insert teststruct, read twice and check for different pointers (because of disk mode) // and equal values m2, err := m.Store().OpenMap("submap", ModeDisk, TestStruct{}) if err != nil { t.Fatal(err) } err = m2.Put("submapkey", ts) if err != nil { t.Fatal(err) } ts4, err := m2.Get("submapkey") if err != nil { t.Fatal(err) } ts5, err := m2.Get("submapkey") if err != nil { t.Fatal(err) } if ts4 == ts5 { t.Fatal("ts4 should have a different address than ts5") } if !reflect.DeepEqual(ts4, ts5) { t.Fatal("ts4 does not equal ts5") } // test some list outcomes dbList, err := db.Store().List() if err != nil { t.Fatal(err) } if len(dbList) != 1 || dbList[0] != "map" { t.Fatal("expected single element slice with element 'map'") } mList, err := m.Store().List() if err != nil { t.Fatal(err) } if len(mList) != 1 || mList[0] != "submap" { t.Fatal("expected single element slice with element 'submap'") } // remove parent map, reopen and check outcome err = db.Store().Remove("map") if err != nil { t.Fatal(err) } db.Close() db, err = Open("test.db") if err != nil { t.Fatal(err) } dbList, err = db.Store().List() if err != nil { t.Fatal(err) } if len(dbList) != 0 { t.Fatal("expected empty slice") } if db.Store().Remove("map").Error() != "store 'map' not found" { t.Fatal() } } <file_sep>/map.go package tiny import ( "github.com/boltdb/bolt" "reflect" "sync" "errors" "encoding/json" ) type Map struct { store Store mutex sync.Mutex vtype reflect.Type data map[string]interface{} } func (s Store) OpenMap(name string, mode Mode, v interface{}) (m *Map, err error) { if reflect.TypeOf(v).Kind() == reflect.Ptr { return nil, errors.New("pointer types are not allowed") } err = s.db.Update(func(tx *bolt.Tx) error { b, err := s.gotoBucket(tx) if err != nil { return err } err = ensureStoreSchema(b, name, "map") if err != nil { return err } m = &Map{ store: Store{ db: s.db, path: append(s.path, name), mode: mode, }, data: make(map[string]interface{}), vtype: reflect.TypeOf(v), } // if memory mode is enabled preload everything if m.store.mode == ModeMem { valueBucket, err := m.store.gotoValueBucket(tx) if err != nil { return err } if err := valueBucket.ForEach(func(k, data []byte) error { v := reflect.New(m.vtype).Interface() err := json.Unmarshal(data, v) if err != nil { return err } m.data[string(k)] = v return nil }); err != nil { return err } } return nil }) if err != nil { return nil, err } return m, nil } func (m *Map) Store() Store { return m.store } func (m *Map) Foreach(f func(k string, v interface{}) error) error { m.mutex.Lock() defer m.mutex.Unlock() if m.store.mode == ModeMem { for k, v := range m.data { err := f(k, v) if err != nil { return err } } return nil } return m.store.db.View(func(tx *bolt.Tx) error { b, err := m.store.gotoValueBucket(tx) if err != nil { return err } return b.ForEach(func(k, data []byte) error { v := reflect.New(m.vtype).Interface() err := json.Unmarshal(data, v) if err != nil { return err } return f(string(k), v) }) }) } func (m *Map) Contains(k string) bool { m.mutex.Lock() defer m.mutex.Unlock() if m.store.mode == ModeMem { if _, exist := m.data[k]; exist { return true } return false } exist := false if err := m.store.db.View(func(tx *bolt.Tx) error { b, err := m.store.gotoValueBucket(tx) if err != nil { return err } if b.Get([]byte(k)) != nil { exist = true } return nil }); err != nil { return false } return exist } func (m *Map) Get(k string) (interface{}, error) { m.mutex.Lock() defer m.mutex.Unlock() // memory mode: get value from map data if m.store.mode == ModeMem { if value, exist := m.data[k]; exist { return value, nil } return nil, errors.New("key '"+k+"' does not exist") } // disk mode: load value from disk var v interface{} if err := m.store.db.View(func(tx *bolt.Tx) error { b, err := m.store.gotoValueBucket(tx) if err != nil { return err } data := b.Get([]byte(k)) if data == nil { return errors.New("key '" + k + "' does not exist") } v = reflect.New(m.vtype).Interface() err = json.Unmarshal(data, v) if err != nil { return err } return nil }); err != nil { return nil, err } return v, nil } func (m *Map) Put(k string, v interface{}) error { if v == nil { return errors.New("value cannot be nil") } m.mutex.Lock() defer m.mutex.Unlock() // validate pointer of vtype t := reflect.TypeOf(v) if t.Kind() != reflect.Ptr || t.Elem() != m.vtype { return errors.New("value must be of type '*" + m.vtype.String() + "'") } // serialize and save data, err := json.Marshal(v) if err != nil { return err } if err = m.store.db.Update(func(tx *bolt.Tx) error { b, err := m.store.gotoValueBucket(tx) if err != nil { return err } return b.Put([]byte(k), data) }); err != nil { return err } // write to map data if using memory mode if m.store.mode == ModeMem { m.data[string(k)] = v } return nil } func (m *Map) Remove(k string) error { m.mutex.Lock() defer m.mutex.Unlock() // remove from database if err := m.store.db.Update(func(tx *bolt.Tx) error { b, err := m.store.gotoValueBucket(tx) if err != nil { return err } return b.Delete([]byte(k)) }); err != nil { return err } // remove from memory if m.store.mode == ModeMem { delete(m.data, k) } return nil }<file_sep>/README.md # tiny persistent data structures based on boltdb Status: deprecated <file_sep>/store.go package tiny import ( "github.com/boltdb/bolt" "errors" "strings" "bytes" ) type Store struct { db *bolt.DB path []string mode Mode } func (s Store) Remove(name string) error { return s.db.Update(func(tx *bolt.Tx) error { b, err := s.gotoBucket(tx) if err != nil { return err } err = b.DeleteBucket([]byte(name)) if err != nil { return errors.New("store '" + name + "' not found") } return nil }) } func (s Store) List() ([]string, error) { list := []string{} s.db.View(func(tx *bolt.Tx) error { b, err := s.gotoBucket(tx) if err != nil { return err } return b.ForEach(func(k, v []byte) error { if bytes.Equal(k, storeMetaBucketKey) || bytes.Equal(k, storeValueBucketKey) { return nil } list = append(list, string(k)) return nil }) }) return list, nil } func (s Store) gotoValueBucket(tx *bolt.Tx) (*bolt.Bucket, error) { b, err := s.gotoBucket(tx) if err != nil { return nil, err } return b.Bucket(storeValueBucketKey), nil } func (s Store) gotoBucket(tx *bolt.Tx) (*bolt.Bucket, error) { b := tx.Bucket(dbRootBucketKey) for i, seg := range s.path { b = b.Bucket([]byte(seg)) if b == nil { return nil, errors.New("bucket '" + strings.Join(s.path[:i], "/") + "' does not exist") } } return b, nil } <file_sep>/schema.go package tiny import ( "errors" "github.com/boltdb/bolt" "time" "bytes" ) func ensureDBSchema(tx *bolt.Tx) (error) { if tx.Bucket(dbMetaBucketKey) != nil && tx.Bucket(dbRootBucketKey) != nil { return nil } if tx.Bucket(dbRootBucketKey) != nil { return errors.New("database corrupted (root bucket missing)") } if tx.Bucket(dbMetaBucketKey) != nil { return errors.New("database corrupted (meta bucket missing)") } meta, err := tx.CreateBucket(dbMetaBucketKey) if err != nil { return err } created, err := time.Now().MarshalBinary() if err != nil { return err } err = meta.Put(dbMetaCreatedKey, created) if err != nil { return err } _, err = tx.CreateBucket(dbRootBucketKey) if err != nil { return err } return nil } func ensureStoreSchema(b *bolt.Bucket, name string, t string) error { if existingBucket := b.Bucket([]byte(name)); existingBucket != nil { // validate base schema meta := existingBucket.Bucket(storeMetaBucketKey) if meta == nil { return errors.New("meta bucket does not exist") } if existingBucket.Bucket(storeValueBucketKey) == nil { return errors.New("value bucket does not exist") } // validate schema type metaType := meta.Get(storeMetaBucketTypeKey) if metaType == nil { return errors.New("meta bucket type key not set") } if !bytes.Equal(metaType, []byte(t)) { return errors.New("cannot open " + string(metaType) + " as " + t) } } else { // create base schema b, err := b.CreateBucket([]byte(name)) if err != nil { return err } meta, err := b.CreateBucket(storeMetaBucketKey) if err != nil { return err } _, err = b.CreateBucket(storeValueBucketKey) if err != nil { return err } // write type err = meta.Put(storeMetaBucketTypeKey, []byte(t)) if err != nil { return err } } return nil }
6ba3cf5c03d19cc854dd1d21efaef590287e0c7e
[ "Markdown", "Go" ]
8
Go
satnamram/tiny
e9365b4ed9a4c75d5aae9594ac88d423578c2d28
5d4f834bd0d6307ba3618eb34c2b754768096f70
refs/heads/master
<file_sep>function install_chef { #Check whether chef is already installed rpm -qa | grep "^rubygems-chef" if [ $? == 0 ]; then touch /tmp/chef_already_installed echo "Chef already installed, exiting" return 0 fi local INSTALL_TYPE=${1:-"CLIENT"} # CLIENT/SERVER local CDN_BASE="http://4ad0a2808a2c43e9d0d6-330deec3c994fad5a61c9255051a5d28.r28.cf1.rackcdn.com" local CLIENT_TARBALL="chef-client-0.10.8-rhel5.x86_64.tar.gz" local SERVER_TARBALL="chef-server-0.10.8-rhel5-x86_64.tar.gz" local BOOTSTRAP="chef-0.10.8-solo-bootstrap.tar.gz" local RUBY_VERSION="1.8.7.352" local RUBYGEMS_VERSION="1.8.10" rpm -q wget &> /dev/null || yum install -y -q wget #Download bootstrap script for chef-solo wget "$CDN_BASE/$BOOTSTRAP" -O "/tmp/bootstrap.tar.gz" &> /dev/null \ || { echo "Failed to download bootstrap tarball."; exit 1; } #Download RPMs for chef-client installation wget "$CDN_BASE/$CLIENT_TARBALL" -O "/tmp/chef-client.tar.gz" &> /dev/null \ || { echo "Failed to download Chef client RPM tarball."; exit 1; } cd /tmp tar -zxf chef-client.tar.gz || { echo "Failed to extract Chef client tarball."; exit 1; } cd /tmp/chef-client* #Install chef client yum install --nogpgcheck -q -y \ ruby-${RUBY_VERSION}-5.x86_64.rpm \ ruby-devel-${RUBY_VERSION}-5.x86_64.rpm \ ruby-irb-${RUBY_VERSION}-5.x86_64.rpm \ ruby-ri-${RUBY_VERSION}-5.x86_64.rpm \ ruby-rdoc-${RUBY_VERSION}-5.x86_64.rpm \ ruby-libs-${RUBY_VERSION}-5.x86_64.rpm \ rubygems-${RUBYGEMS_VERSION}-1.el5.noarch.rpm \ ruby-shadow-1.4.1-7.el5.x86_64.rpm \ rubygems-chef-0.10.8-1.noarch.rpm \ rubygems-bunny-0.6.0-1.noarch.rpm \ rubygems-erubis-2.7.0-1.noarch.rpm \ rubygems-highline-1.6.11-1.noarch.rpm \ rubygems-json-1.6.1-1.noarch.rpm \ rubygems-mime-types-1.17.2-1.noarch.rpm \ rubygems-mixlib-authentication-1.1.4-1.noarch.rpm \ rubygems-mixlib-cli-1.2.2-1.noarch.rpm \ rubygems-mixlib-config-1.1.2-1.noarch.rpm \ rubygems-mixlib-log-1.3.0-1.noarch.rpm \ rubygems-moneta-0.6.0-1.noarch.rpm \ rubygems-net-ssh-2.1.4-1.noarch.rpm \ rubygems-net-ssh-gateway-1.1.0-1.noarch.rpm \ rubygems-net-ssh-multi-1.1-1.noarch.rpm \ rubygems-ohai-0.6.10-1.noarch.rpm \ rubygems-polyglot-0.3.3-1.noarch.rpm \ rubygems-rest-client-1.6.7-1.noarch.rpm \ rubygems-systemu-2.2.0-1.noarch.rpm \ rubygems-treetop-1.4.10-1.noarch.rpm \ rubygems-uuidtools-2.1.2-1.noarch.rpm \ rubygems-yajl-ruby-0.7.9-1.noarch.rpm rm -rf /tmp/chef-client* if [[ "$INSTALL_TYPE" == "SERVER" ]]; then #Download RPMs for chef server installation wget "$CDN_BASE/$SERVER_TARBALL" -O "/tmp/chef-server.tar.gz" &> /dev/null \ || { echo "Failed to download Chef server RPM tarball."; exit 1; } cd /tmp tar -zxf chef-server.tar.gz || { echo "Failed to extract Chef server tarball."; exit 1; } cd /tmp/chef-server* #Install chef server components. yum install --nogpgcheck -q -y \ couchdb-0.11.2-2.el5.x86_64.rpm \ erlang-R12B-5.10.el5.x86_64.rpm \ gecode-3.5.0-1.el5.x86_64.rpm \ gecode-devel-3.5.0-1.el5.x86_64.rpm \ java-1.6.0-openjdk-1.6.0.0-1.23.1.9.10.el5_7.x86_64.rpm \ java-1.6.0-openjdk-devel-1.6.0.0-1.23.1.9.10.el5_7.x86_64.rpm \ libxml2-devel-2.6.26-2.1.12.x86_64.rpm \ rabbitmq-server-2.2.0-1.el5.noarch.rpm \ zlib-devel-1.2.3-4.el5.x86_64.rpm \ alsa-lib-1.0.17-1.el5.x86_64.rpm \ erlang-ibrowse-2.1.0-1.el5.x86_64.rpm \ erlang-mochiweb-1.4.1-5.el5.x86_64.rpm \ erlang-oauth-1.0.1-1.el5.x86_64.rpm \ giflib-4.1.3-7.3.3.el5.x86_64.rpm \ jpackage-utils-1.7.3-1jpp.2.el5.noarch.rpm \ js-1.70-8.el5.x86_64.rpm \ libX11-1.0.3-11.el5_7.1.x86_64.rpm \ libXext-1.0.1-2.1.x86_64.rpm \ libXi-1.0.1-4.el5_4.x86_64.rpm \ libXrender-0.9.1-3.1.x86_64.rpm \ libXtst-1.0.1-3.1.x86_64.rpm \ libicu-3.6-5.16.1.x86_64.rpm \ pkgconfig-0.21-2.el5.x86_64.rpm \ tk-8.4.13-5.el5_1.1.x86_64.rpm \ tzdata-java-2011l-4.el5.x86_64.rpm \ unixODBC-2.2.11-7.1.x86_64.rpm \ rubygems-chef-expander-0.10.8-1.noarch.rpm \ rubygems-chef-server-api-0.10.8-1.noarch.rpm \ rubygems-chef-server-webui-0.10.8-1.noarch.rpm \ rubygems-chef-solr-0.10.8-1.noarch.rpm \ rubygems-addressable-2.2.6-1.noarch.rpm \ rubygems-amqp-0.6.7-1.noarch.rpm \ rubygems-bundler-1.0.21-1.noarch.rpm \ rubygems-coderay-1.0.5-1.noarch.rpm \ rubygems-daemons-1.1.6-1.noarch.rpm \ rubygems-dep_selector-0.0.8-1.noarch.rpm \ rubygems-em-http-request-0.2.15-1.noarch.rpm \ rubygems-eventmachine-0.12.10-1.noarch.rpm \ rubygems-extlib-0.9.15-1.noarch.rpm \ rubygems-fast_xs-0.7.3-1.noarch.rpm \ rubygems-haml-3.1.4-1.noarch.rpm \ rubygems-merb-assets-1.1.3-1.noarch.rpm \ rubygems-merb-core-1.1.3-1.noarch.rpm \ rubygems-merb-haml-1.1.3-1.noarch.rpm \ rubygems-merb-helpers-1.1.3-1.noarch.rpm \ rubygems-merb-param-protection-1.1.3-1.noarch.rpm \ rubygems-rack-1.4.1-1.noarch.rpm \ rubygems-rake-0.9.2.2-1.noarch.rpm \ rubygems-ruby-openid-2.1.8-1.noarch.rpm \ rubygems-thin-1.3.1-1.noarch.rpm rm -rf /tmp/chef-server* fi }
cbe6184c49a1a5b3f5650e889f1de6fe1a3bfdad
[ "Shell" ]
1
Shell
RSEmail/chef_vpc_toolkit
f4e1bc525c546bcbde206045b18ae2f85ff8c84e
c2185268770e71c015ebd64c08d2e6130010ba7f
refs/heads/master
<repo_name>robcmp/te-cuido-back-end<file_sep>/migrations/versions/4b428232849d_.py """empty message Revision ID: 4b428232849d Revises: Create Date: 2021-10-09 12:28:23.640145 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('document', sa.Column('id', sa.Integer(), nullable=False), sa.Column('doc_type', sa.Integer(), nullable=True), sa.Column('doc_description', sa.String(length=20), nullable=True), sa.Column('image', sa.LargeBinary(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=30), nullable=False), sa.Column('lastname', sa.String(length=30), nullable=False), sa.Column('password', sa.String(length=30), nullable=False), sa.Column('email', sa.String(length=30), nullable=False), sa.Column('numberID', sa.String(length=30), nullable=False), sa.Column('country', sa.String(length=20), nullable=False), sa.Column('city', sa.String(length=20), nullable=False), sa.Column('phone', sa.String(length=20), nullable=False), sa.Column('vaccinated', sa.Boolean(), nullable=False), sa.Column('occupation', sa.String(length=30), nullable=False), sa.Column('user_type', sa.Integer(), nullable=True), sa.Column('isActive', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('docs', sa.Column('document_id', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['document_id'], ['document.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ) ) op.create_table('payment', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=30), nullable=True), sa.Column('date', sa.DateTime(), nullable=True), sa.Column('description', sa.String(length=150), nullable=True), sa.Column('image', sa.LargeBinary(), nullable=True), sa.Column('person_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['person_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('service', sa.Column('id', sa.Integer(), nullable=False), sa.Column('date_init', sa.DateTime(), nullable=False), sa.Column('date_end', sa.DateTime(), nullable=False), sa.Column('age_start', sa.Integer(), nullable=False), sa.Column('age_end', sa.Integer(), nullable=False), sa.Column('notes', sa.String(length=300), nullable=False), sa.Column('gender_ser', sa.Enum('FEMALE', 'MALE', name='gender'), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('reserve', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=30), nullable=True), sa.Column('gender_res', sa.Enum('FEMALE', 'MALE', name='gender'), nullable=True), sa.Column('age', sa.Integer(), nullable=True), sa.Column('notes', sa.String(length=300), nullable=True), sa.Column('date', sa.DateTime(), nullable=True), sa.Column('payment_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['payment_id'], ['payment.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('reserve') op.drop_table('service') op.drop_table('payment') op.drop_table('docs') op.drop_table('user') op.drop_table('document') # ### end Alembic commands ### <file_sep>/app.py from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from models import db, User from flask_migrate import Migrate from flask_cors import CORS, cross_origin app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:ecomsur@localhost:5432/tecuido' #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['DEBUG'] = True app.config['ENV'] = "development" cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' db.init_app(app) Migrate(app, db) @app.route('/') def home(): return jsonify('Creando Back-End Te-Cuido') @app.route("/user", methods=["POST", "GET"]) def user(): if request.method == "GET": user = User.query.all() user = list(map(lambda user: user.serialize(), user)) if user is not None: return jsonify(user) else: user = User() user.name = request.json.get("name") user.lastname = request.json.get("lastname") user.password = request.json.get("password") user.email = request.json.get("email") user.numberID = request.json.get("numberID") user.country = request.json.get("country") user.city = request.json.get("city") user.phone = request.json.get("phone") user.occupation = request.json.get("occupation") user.vaccinated = request.json.get("vaccinated") user.user_type = request.json.get("user_type") user.isActive = request.json.get("isActive") #user.payments = request.json.get("payments") db.session.add(user) db.session.commit() return jsonify(user.serialize()), 200 @app.route("/user/<int:id>", methods=["GET","POST"]) def userById(id): if request.method == "GET": if id is not None: user = User.query.get(id) if user is None: return jsonify('Missing id parameter in route'), 404 else: return jsonify(user.serialize()), 200 else: return jsonify('Missing id parameter in route'), 404 else: user = User() user.name = request.json.get("name") user.lastname = request.json.get("lastname") user.password = request.json.get("password") user.email = request.json.get("email") user.numberID = request.json.get("numberID") user.country = request.json.get("country") user.city = request.json.get("city") user.phone = request.json.get("phone") user.occupation = request.json.get("occupation") user.vaccinated = request.json.get("vaccinated") user.user_type = request.json.get("user_type") user.isActive = request.json.get("isActive") #user.payments = request.json.get("payments") db.session.add(user) db.session.commit() return jsonify(user.serialize()), 200 @app.route("/login", methods=["POST"]) @cross_origin() def login(): request.get_json(force=True) print(request.json) email = request.json.get("email", None) password = request.json.get("password", None) # Query your database for username and password user = User.query.filter_by(email=email, password=password).first() if user is None: # the user was not found on the database return jsonify({"msg": "Usuario o contraseña invalida"}), 401 # create a new token with the user id inside return jsonify({ "msg": "Sesión iniciada satisfactoriamente" }), 200 if __name__ == "__main__": app.run() <file_sep>/models.py from flask_sqlalchemy import SQLAlchemy from sqlalchemy import ForeignKey, Table, Integer,Enum import enum from sqlalchemy.sql.schema import Column from sqlalchemy.orm import backref, relationship db = SQLAlchemy() class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), nullable=False) lastname = db.Column(db.String(30), nullable=False) password = db.Column(db.String(30), nullable=False) email = db.Column(db.String(30), nullable=False) numberID = db.Column(db.String(30), nullable=False) country = db.Column(db.String(20), nullable=False) city = db.Column(db.String(20), nullable=False) phone = db.Column(db.String(20), nullable=False) occupation = db.Column(db.String(30), nullable=False) vaccinated = db.Column(db.Boolean, nullable=False) user_type = db.Column(db.Integer) isActive = db.Column(db.Boolean, default=False) payments = db.relationship('Payment',backref='user',lazy=True) def __repr__(self): return "<User %r>" % self.id def serialize(self): return { 'id': self.id, 'name': self.name, 'lastname': self.name, 'password': <PASSWORD>, 'email': self.email, 'numberID': self.numberID, 'country': self.country, 'city': self.city, 'phone': self.phone, 'occupation': self.occupation, 'vaccinated': self.vaccinated, 'user_type': self.user_type, 'isActive': self.isActive #'payments': self.payments } def serialize_just_login(self): return { 'email': self.email, 'password': <PASSWORD> } #Enum class gender to be set in class Service class gender(enum.Enum): FEMALE = 'Female' MALE = 'Male' class Service(db.Model): __tablename__ = 'service' id = db.Column(db.Integer, primary_key=True) date_init = db.Column(db.DateTime, nullable=False) date_end = db.Column(db.DateTime, nullable=False) age_start = db.Column(db.Integer, nullable=False) age_end = db.Column(db.Integer, nullable=False) notes = db.Column(db.String(300), nullable=False) gender_ser = db.Column(db.Enum(gender)) user_id = Column(Integer, ForeignKey('user.id')) user = relationship("User") def __repr__(self): return "<Service %r>" % self.id def serialize(self): return { 'id': self.id, 'date_init': self.date_init, 'date_end': self.date_end, 'age_start': self.age_start, 'age_end': self.age_end, 'notes': self.notes } #Helper to made Many to Many Relationship with User and Document docs = db.Table('docs', db.Column('document_id',db.Integer, db.ForeignKey('document.id')), db.Column('user_id',db.Integer, db.ForeignKey('user.id')) ) class Document(db.Model): __tablename__ = 'document' id = db.Column(db.Integer, primary_key=True) doc_type = db.Column(db.Integer) doc_description= db.Column(db.String(20)) image = db.Column(db.LargeBinary) users = db.relationship('User',secondary=docs,backref=db.backref('users',lazy=True)) def __repr__(self): return "<Document %r>" % self.id def serialize(self): return { 'id': self.id, 'doc_type': self.doc_type, 'doc_description': self.doc_description, 'image': self.image } class Payment(db.Model): __tablename__ = 'payment' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30)) date= db.Column(db.DateTime) description= db.Column(db.String(150)) image = db.Column(db.LargeBinary) person_id=db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False) reserve = db.relationship('Reserve', backref='reserve',uselist=False) class Reserve(db.Model): __tablename__ = 'reserve' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30)) gender_res = db.Column(db.Enum(gender)) age = db.Column(db.Integer) notes= db.Column(db.String(300)) date=db.Column(db.DateTime) payment_id = db.Column(db.Integer,db.ForeignKey('payment.id'))
e0d63e3221b6c1550b22177129bcf20534d26d0f
[ "Python" ]
3
Python
robcmp/te-cuido-back-end
1f9fee714e7d45b215a3303d7c3871a5e9f292b1
901db32ee8e6daa9496041e786d20b9c0a2a8cec
refs/heads/master
<file_sep># -*- coding: utf-8 require 'em-monitor' require 'librato/metrics' require 'time' unless ENV['LIBRATO_USERNAME'] && ENV['LIBRATO_TOKEN'] puts "Please export LIBRATO_USERNAME= and LIBRATO_TOKEN=" exit 1 end puts "You can watch the graph being drawn at https://metrics.librato.com/metrics/cpu-breakdown" Librato::Metrics.authenticate ENV['LIBRATO_USERNAME'], ENV['LIBRATO_TOKEN'] EM::run do # Every second, upload the % of time spent in CPU-spans of various lengths to # librato. # We hack the source property to let us use the builtin stacking function. EM::monitor_histogram(interval: 1) do |hist, from, to| queue = Librato::Metrics::Queue.new hist.each do |k, v| queue.add "cpu-breakdown" => {:type => :counter, :value => (v * 100000).to_i, :source => "spans-#{k}", :display_name => "EM CPU utilization by span-length", :description => "The total of CPU-time used by spans of length X or shorter.", :attributes => {:display_units_long => 'microseconds', :display_units_short => 'μs'} } print "#{k}: #{v}; " end puts queue.submit end # Generate some sample data. samples = [0.0005] * 100000 + [0.005] * 10000 + [0.05] * 1000 + [0.5] * 100 + [5] * 10 + [10] * 1 EM::PeriodicTimer.new(rand * 0.02) do sleep samples.sample end end <file_sep>$: << './lib' require 'em-monitor' require 'minitest/autorun' require 'pry' class TestEmMonitor < MiniTest::Unit::TestCase def test_before_running e = assert_raises(RuntimeError){ EM::monitor_spans } assert_equal "EventMachine not initialized", e.message end def test_monitor_spans spans = from = to = nil EM::run do EM::monitor_spans(interval: 0.1) do |*a| spans, from, to = a EM::stop end 10.times do EM::next_tick{ sleep 0.005 } end sleep 0.05 end assert_equal spans.size, 11 assert_in_delta spans.first, 0.05 spans.drop(1).each do |span| assert_in_delta span, 0.005 end assert_in_delta(to - from, 0.1, 0.002) end def test_span_raising_exception spans = from = to = nil EM::run do EM::monitor_spans(interval: 0.1) do |*a| spans, from, to = a EM::stop end EM::error_handler do sleep 0.006 end EM::next_tick do sleep 0.004 raise "oops" end sleep 0.002 end assert_in_delta spans[0], 0.002 assert_in_delta spans[1], 0.004 assert_in_delta spans[2], 0.006 end def test_monitor_histograms histogram = from = to = nil EM::run do EM::monitor_histogram(interval: 0.6, buckets: [0.01, 0.02, 0.03, 0.04]) do |*a| histogram, from, to = a EM::stop end 4.times do |i| EM::next_tick{ 5.times do EM::next_tick{ sleep(0.005 + i * 0.01) } end } end sleep 0.055 end assert_equal histogram.keys, [0.01, 0.02, 0.03, 0.04, 1/0.0] assert_in_delta histogram[0.01], 0.025 assert_in_delta histogram[0.02], 0.075 assert_in_delta histogram[0.03], 0.125 assert_in_delta histogram[0.04], 0.175 assert_in_delta histogram[1 / 0.0], 0.055 assert_in_delta(to - from, 0.6, 0.002) end def test_stacked_histogram histogram = from = to = nil EM::run do EM::monitor_histogram(interval: 0.5, buckets: [0.01, 0.02, 0.03, 0.04], stacked: true) do |*a| histogram, from, to = a EM::stop end 4.times do |i| EM::next_tick{ 5.times do EM::next_tick{ sleep(0.005 + i * 0.01) } end } end sleep 0.055 end assert_equal histogram.keys, [0.01, 0.02, 0.03, 0.04, 1/0.0] assert_in_delta histogram[0.01], 0.025, 0.01 assert_in_delta histogram[0.02], 0.100, 0.01 assert_in_delta histogram[0.03], 0.225, 0.01 assert_in_delta histogram[0.04], 0.400, 0.01 assert_in_delta histogram[1 / 0.0], 0.455, 0.01 assert_in_delta(to - from, 0.5, 0.02) end def test_cumulative_histogram histogram = from = to = nil histogram2 = from2 = to2 = nil second_time = false EM::run do trigger = lambda do 4.times do |i| EM::next_tick{ 5.times do EM::next_tick{ sleep(0.005 + i * 0.01) } end } end end EM::monitor_histogram(interval: 0.5, buckets: [0.01, 0.02, 0.03, 0.04], cumulative: true) do |*a| if second_time histogram2, from2, to2 = a EM::stop else histogram, from, to = a histogram = histogram.dup second_time = true trigger.() sleep 0.066 end end trigger.() sleep 0.055 end assert_equal histogram.keys, [0.01, 0.02, 0.03, 0.04, 1/0.0] assert_in_delta histogram[0.01], 0.025, 0.01 assert_in_delta histogram[0.02], 0.075, 0.01 assert_in_delta histogram[0.03], 0.125, 0.01 assert_in_delta histogram[0.04], 0.175, 0.01 assert_in_delta histogram[1 / 0.0], 0.055, 0.01 assert_in_delta(to - from, 0.5, 0.02) assert_equal to, from2 assert_in_delta histogram2[0.01], 0.025 * 2, 0.01 assert_in_delta histogram2[0.02], 0.075 * 2, 0.01 assert_in_delta histogram2[0.03], 0.125 * 2, 0.01 assert_in_delta histogram2[0.04], 0.175 * 2, 0.01 assert_in_delta histogram2[1 / 0.0], 0.055 + 0.066, 0.01 assert_in_delta(to2 - from2, 0.566, 0.01) end def test_cumulative_stacked_histogram histogram = from = to = nil histogram2 = from2 = to2 = nil second_time = false EM::run do trigger = lambda do 4.times do |i| EM::next_tick{ 5.times do EM::next_tick{ sleep(0.005 + i * 0.01) } end } end end EM::monitor_histogram(interval: 0.5, buckets: [0.01, 0.02, 0.03, 0.04], cumulative: true, stacked: true) do |*a| if second_time histogram2, from2, to2 = a EM::stop else histogram, from, to = a histogram = histogram.dup second_time = true trigger.() sleep 0.066 end end trigger.() sleep 0.055 end assert_equal histogram.keys, [0.01, 0.02, 0.03, 0.04, 1/0.0] assert_in_delta histogram[0.01], 0.025, 0.01 assert_in_delta histogram[0.02], 0.100, 0.01 assert_in_delta histogram[0.03], 0.225, 0.01 assert_in_delta histogram[0.04], 0.400, 0.01 assert_in_delta histogram[1 / 0.0], 0.455, 0.01 assert_in_delta(to - from, 0.5, 0.02) assert_equal to, from2 assert_in_delta histogram2[0.01], 0.025 * 2, 0.01 assert_in_delta histogram2[0.02], 0.100 * 2, 0.01 assert_in_delta histogram2[0.03], 0.225 * 2, 0.01 assert_in_delta histogram2[0.04], 0.400 * 2, 0.01 assert_in_delta histogram2[1 / 0.0], 0.455 + 0.466, 0.01 assert_in_delta(to2 - from2, 0.566, 0.01) end def test_span_longer_than_interval spans = from = to = nil EM::run do EM::monitor_spans(interval: 0.001) do |*a| spans, from, to = a EM::stop end EM::next_tick{ sleep 0.005 } end assert_equal spans.size, 2 assert_in_delta(spans.last, 0.005) assert_in_delta(to - from, 0.005, 0.002) end end <file_sep> task :test do exec 'ruby ./test/*.rb' end task :default => [:test] <file_sep>require 'lspace/eventmachine' # EM::Monitor adds a few methods to eventmachine that can help you # keep track of 'lag' caused by long-running CPU spans on the reactor thread. module EventMachine class << self alias_method :run_without_monitor, :run private :run_without_monitor end # Run the eventmachine reactor with monitoring. def self.run(*args, &block) run_without_monitor(*args) do |*a, &b| EM::Monitor.new do |monitor| @em_monitor = monitor block.call(*a, &b) if block_given? end end ensure @em_monitor = nil end # Set the block to be called periodically with timing data. # # @param [Hash] opts Configuration # @param [Proc] block the block to call. # # @option opts [Number] :interval (60) # The approximate number of seconds between calls to your block. # If your event loop regularly runs long CPU-spans then the actual time between # calls can vary significantly. # # @yieldparam [Array<Float>] spans The number of seconds spent by each CPU-span in the # monitoring interval # @yieldparam [Time] from The start of the monitoring interval # @yieldparam [Time] to The end of the monitoring interval # # @example # EM::monitor_spans do |spans, from, to| # puts "Used %.2f seconds of CPU in the last %.2f seconds." % (spans.inject(&:+), to - from) # end def self.monitor_spans(opts = {}, &block) raise "EventMachine not initialized" unless @em_monitor @em_monitor.monitor_spans(opts[:interval] || Monitor::DEFAULT_INTERVAL, &block) end # Set the block to be called periodically with histogram data. # # This is a convenience wrapper around {monitor_spans} for the common use-case of # wanting to plot a histogram of loop utilisation split into time-chunks. # # In the normal case you can plot these values directly and it will tell you # how much CPU-time was used by spans shorter than a given length. However, care # should be taken if CPU-spans are often of similar length to :interval. This can # cause the actual delay between calls to the block to vary significantly and so # if you're trying to plot a line of CPU-utilization then it can give you misleading # answers. If this is a concern to you then you might want to use the :cumulative # mode and ask your graphing library to plot the derivative of the values over time. # # @param [Hash] opts Configuration for the histogram # @param [Proc] block the block to call. # # @option opts [Number] :interval (60) # The approximate number of seconds between calls to your block. # If your event loop regularly runs long CPU-spans then the actual time between # calls can vary significantly. # # @option opts [Array<Number>] :buckets ([0.001, 0.01, 0.1, 1, 10, Infinity]) # The boundaries of the histogram buckets, Infinity will be added even if it's not # specified by you to ensure that all spans are included. # CPU-spans are put into the smallest bucket with a limit longer than the span. # # @option opts [Boolean] :stacked (false) # When true larger buckets include the sum of all smaller buckets in addition to # the number of seconds spent in CPU-spans that fell into that bucket directly. # When false each CPU-span will be put into exactly one bucket # # @option opts [Boolean] :cumulative (false) # When true the values of each bucket will increase monotonically over the # lifetime of the process and the derivative over time can be used to tell # how much CPU was used by spans in each bucket in the current monitoring # interval. # When false the values of each bucket are only the amount of time spent # by CPU-spans in that bucket in the current monitoring interval. # # @yieldparam [Hash<Float,Float>] histogram A histogram from bucket-size to # amount of CPU-time spent in that bucket. # @yieldparam [Time] from The start of the monitoring interval # @yieldparam [Time] to The end of the monitoring interval # # @example # # Create an input file suitable for feeding to gnuplot. # # # EM::monitor_histogram(stacked: true) do |hist, from, to| # gnuplot_input.puts #{to.iso8601} #{hist.values.join(" ")}" # end def self.monitor_histogram(opts = {}, &block) stacked = !!opts[:stacked] cumulative = !!opts[:cumulative] interval = opts[:interval] || Monitor::DEFAULT_INTERVAL buckets = (opts[:buckets] || Monitor::DEFAULT_BUCKETS).sort buckets << (1/0.0) # create the histogram keys in (sorted) bucket order to ensure # that histogram.values.join(" ") always does the right thing hist = buckets.each_with_object({}){ |bucket, h| h[bucket] = 0 } monitor_spans(opts) do |spans, from, to| unless cumulative hist = buckets.each_with_object({}){ |bucket, h| h[bucket] = 0 } end if stacked spans.each do |span| buckets.each do |bucket| hist[bucket] += span if bucket > span end end else spans.each do |span| hist[buckets.detect{ |bucket| bucket > span }] += span end end block.call hist, from, to end end # The monitor object itself deals with maintaining lspace and # timers. class Monitor # How long (by default) between calls to monitors DEFAULT_INTERVAL = 60 # Which buckets to include in the histogram by default DEFAULT_BUCKETS = [0.001, 0.01, 0.1, 1, 10] # Create a new monitor. # # The block will be called in the monitor's LSpace, all further # EM work should happen within the block to ensure that we measure # everything. # # @param [Proc] block The block during which to monitor events # @yieldparam [Monitor] self def initialize(&block) create_lspace.enter do block.call self end end # Attach a listener to this monitor. # # Only one listener can be active at a time, and the interval set # here will take affect after the next tick of the previous interval. # # @param [Number] interval The (lower bound of) time in seconds between calls to block # @param [Proc] block The block to call # @yieldparam [Array<Float>] spans Each number of seconds the event loop spent processing. # @yieldparam [Time] from The time at which the block was previously called # @yieldparam [Time] to The current time # @see EM.monitor_spans def monitor_spans(interval, &block) @periodic_timer ||= create_timer(interval) @periodic_timer.interval = interval @monitor = block end private # Add an around_filter to LSpace that wraps every CPU-span in a timing function. # # @return [LSpace] def create_lspace LSpace.new.around_filter do |&block| start = Time.now begin block.call ensure @timings << Time.now - start if @timings end end end # Add a periodic timer that will periodically call @monitor with the contents # of @timings. # # @param [Number] interval The interval to use for the timer. # @return [EM::PeriodicTimer] def create_timer(interval) @timings = [] time = Time.now EM::PeriodicTimer.new(interval) do # Set last_time to *before* we call the monitor. # This is because the duration of the monitor will be included in the next set of # timings. last_time, time = time, Time.now timings = @timings.slice!(0..-1) @monitor.call timings, last_time, time end end end end <file_sep>em-monitor is a gem that lets you monitor your eventmachine reactor. Introduction ============ As we all know, event loops are an awesome programming model. You can (mostly) forget about thread-safety, but you can still do a bazillion IO-things in parallel. They do have one significant downside though: you can only run one CPU-thing at a time. This means that if you accidentally spend 30 seconds running a bad regex, everything in your loop is going to get stuck for 30 seconds (that's about a million years in computer terms). This is particularly bad because one user who triggers a bad regex slows down all your other users for *all 30 seconds*. EM::Monitor can't fix your code for you, but it can let you know you have a problem. Usage ===== em-monitor wraps every CPU-span of code in your program and measures how long is spent executing it. You can then extract this data periodically in two ways. `EM::monitor_spans` calls a block with an array of raw measurements on a regular interval (by default 60 seconds), `EM::monitor_histogram` buckets all the measurements and then sums them. This lets you plot the amount of time that your event loop is spending running short CPU-spans against the amount of time that your event loop is spending running long CPU-spans. ```ruby EM::monitor_spans(interval: 1) do |spans, from, to| puts "Between #{from} and #{to} (#{to-from}seconds) there were #{spans.size} CPU-spans:" puts spans.inspect end #=> Between 2013-02-07 02:19:37 and 2013-02-07 02:19:38 (1.00 seconds) there were 7 CPU-spans: #=> [0.000565469, 0.000564702, 0.000568218, 0.000564348, 0.005066146, 0.050109482, 0.050113617] EM::monitor_histogram(interval: 1) do |histogram, from, to| puts "In the last #{from - to} real seconds, we used #{histogram.values.inject(&:+)} CPU-seconds" histogram.each do |key, value| puts "#{value} CPU-seconds in spans shorter than #{key} seconds" end end #=> In the last 1.00 real seconds, we used 0.1572 CPU-seconds # => 0.0452 CPU-seconds in spans shorter than 0.001 seconds # => 0.0619 CPU-seconds in spans shorter than 0.01 seconds # => 0.0500 CPU-seconds in spans shorter than 0.1 seconds # => 0 CPU-seconds in spans shorter than 1 seconds # => 0 CPU-seconds in spans shorter than 10 seconds # => 0 CPU-seconds in spans shorter than Infinity seconds ``` Plotting results ================ The easiest way to plot the histogram data is as a stacked chart. If your tool of choice can't stack charts directly you can call `EM::monitor_histogram(stacked: true)` and this will cause larger buckets to include the sum of all the smaller buckets in addition to the CPU-spans that fell into that bucket directly. This will give you a graph of absolute time used per minute, which you can normalize to a utilization percentage in two ways: ```ruby # The absolute magnitude of the lines plotted here will be correct, # however if you plot a stacked area graph the area will under-estimate the impact # of CPU-spans of similar order of magnitude to `interval`. histogram.map{ |key, value| value * 100 / (to - from) } # Looking at the absolute magnitude of this graph will over-estimate CPU-spans # in the short term, however if you plot a stacked area graph the area will be # more correct. histogram.map{ |key, value| value * 100 / interval } ``` If you need to combine the results from multiple machines you should instead use the `EM::monitor_histogram(cumulative: true)`, and centrally keep track of the total cumulative CPU. Plotting the derivative after summing will give you a stable plot that makes sense when averaged. To get a feel for how this works look at `example/gnuplot.rb` or `example/librato.rb`. Meta-fu ======= There's [API documentation](http://rdoc.info/github/ConradIrwin/em-monitor/master/frames) if you'd like it. Everything is licensed under the MIT license, see `LICENSE.MIT` for details. Pull requests and bug reports are very welcome. <file_sep>Gem::Specification.new do |gem| gem.name = 'em-monitor' gem.version = '0.1' gem.summary = 'Monitor the distribution of your eventmachine CPU usage' gem.description = "EventLoops are awesome unless you're doing a lot of blocking CPU stuff, at which point they become useless. This gem lets you easily graph the lengths of CPU-blocked spans so that you can take action to make your eventmachine server faster" gem.authors = ['<NAME>'] gem.email = %w(<EMAIL>) gem.homepage = 'http://github.com/ConradIrwin/em-monitor' gem.license = 'MIT' gem.required_ruby_version = '>= 1.9.3' gem.add_dependency 'eventmachine' gem.add_dependency 'lspace' gem.files = `git ls-files`.split("\n") end <file_sep>require 'em-monitor' require 'time' at_exit do exec %(gnuplot -e 'load "example/stacked.plot"' -p) end puts "When you've gathered enough data (about 30s should be enough) hit <Ctrl-C>" EM::run do file = File.open("/tmp/to_plot", "w") # Every second, output the % of time spent in CPU-spans of various lengths in a # gnuplot-readable format. EM::monitor_histogram(interval: 1, stacked: true) do |hist, from, to| percentages = hist.map{ |k, v| (v * 100 / (to - from)) } file.puts "#{Time.now.utc.iso8601} #{percentages.join(" ")}" file.flush puts "#{Time.now.utc.iso8601} #{percentages.map{ |x| "%0.2f" % x }.join(" ")}" end # Generate some sample data. samples = [0.0005] * 100000 + [0.005] * 10000 + [0.05] * 1000 + [0.5] * 100 + [5] * 10 + [10] * 1 EM::PeriodicTimer.new(rand * 0.02) do sleep samples.sample end end
dabaebd34ae8318f87ae84687658f237bab158b4
[ "Markdown", "Ruby" ]
7
Ruby
ept/em-monitor
ee1d50dc65108064b5cd325bacfa79e9aa7ea67b
db94fef20374c42911f5d42a935627850e6f7a59
refs/heads/master
<repo_name>luzmcosta/on3<file_sep>/src/transformer.js import fs from 'fs'; import pkg from '../package.json'; let transformer = { template: { /** * Wrap code to create a node module. * * @param {str} code The module's code. import statements should be here. * @param {str} moduleName The name of the module to export. * @return {str} An ES6 module. */ node: (code, moduleName) => { if (/export default/.test(code)) { return code; } return code + '\nexport default ' + moduleName + ';'; }, /** * Wrap code to create a node executable. * * @param {str} code * @return {str} */ cli: (code) => { return `#!/usr/bin/env node\n;(function(){\n${code}\n})();`; }, }, }; /** * Executes the full workflow: from getting the src code to writing a new file. * * @param {obj} src File name of source file. * {str} fileName File name of intended output file. * {str} code The output file's intended content. * {obj} pkg An object containing the Babel configuration. * {str} type The kind of file we're building. ["cli", "node:moduleName"] * @return {obj} transformer */ transformer.set = ({fileName, code, pkg, type}) => { if (/node/.test(type)) { code = transformer.template.node(code, type.split(':')[1]); } transformer.write(fileName, transformer.prepare(transformer.get(code, pkg), type)); return transformer; }; /** * Uses Babel to transform code into the CommonJS format for Node. * * @param {str} code The ESNext code to parse. * @param {obj} pkg An object containing the Babel configuration. * @return {str} ES5-valid code */ transformer.get = (code, pkg) => { // @note One reason I'm using require here: babel-core fails w/ `import`. return require('babel-core').transform(code, pkg.babel).code; }; /** * Returns code wrapped in the template the type variable indicates. * * @param {str} code Code to parse. * @param {str} type The kind of file we're building. ["cli", "node:moduleName"] * @return {str} If type is "cli," code is wrapped to create a node executable. */ transformer.prepare = (code, type) => { if (type === 'cli') { if (transformer.template[type]) { return transformer.template[type](code); } console.log('WARNING: Invalid type "' + type + '" entered.'); } return code; }; /** * Write file to system. * * @param {str} fileName The name of the output file. * @param {str} code The contents of the output file. * @return {obj} transformer */ transformer.write = (fileName, code) => { fs.writeFile(fileName, code, (err) => { if (err) { throw err; } console.log('Built ' + fileName + '.'); return true; }); return transformer; }; transformer.getFile = (output, type) => { return (err, data) => { if (err) { throw err; } // Transform code & write to file. transformer.set({fileName: output, code: data.toString(), pkg, type}); return data; }; }; /** * Transforms an ES6 file into an executable. * * @param {str} src File name of source file. * @param {str} output File name of intended output file. * @param {str} type The kind of file we're building. ["cli", "node:moduleName"] * @return {obj} transformer */ transformer.exec = (src, output, type) => { // Determine whether we're handling a file or a directory. const isFile = /[\/|.]\w*/.test(src); // If directory, loop through files. if (!isFile) { // Get the source directory. fs.readdir(src, (err, files) => { files.forEach(fileName => { let filePath = src + '/' + fileName, outputFile = output + '/' + fileName; console.log('CONVERT >> ', filePath, '->', outputFile); fs.readFile(filePath, transformer.getFile(outputFile, type)); }); }); } else { // Get file contents. fs.readFile(src, transformer.getFile(output, type)); } return transformer; }; export default transformer; <file_sep>/index.js module.exports = require('./build/app.js'); <file_sep>/bin/gi.js #!/usr/bin/env node ;(function(){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _shelljs = require('shelljs'); var _shelljs2 = _interopRequireDefault(_shelljs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Holds Git-related commands. var gi = {}; // Confirm this is a Git repository. gi.is = function () { if (!_shelljs2.default.which('git')) { _shelljs2.default.echo(app.errors.nogit); return false; } return true; }; gi.add = function (file) { _shelljs2.default.exec('git add ' + file); return gi; }; gi.commit = function (msg) { _shelljs2.default.exec('git commit -m ' + msg); return gi; }; gi.push = function (branch) { _shelljs2.default.exec('git push origin ' + branch); return gi; }; gi.tag = function (tag, msg) { _shelljs2.default.exec('git tag ' + tag + ' -m ' + msg); return gi; }; exports.default = gi; })();<file_sep>/bin/app.js #!/usr/bin/env node ;(function(){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _shelljs = require('shelljs'); var _shelljs2 = _interopRequireDefault(_shelljs); var _np = require('./np'); var _np2 = _interopRequireDefault(_np); var _gi = require('./gi'); var _gi2 = _interopRequireDefault(_gi); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PKG = _np2.default.getPackage(); var app = { defaults: { branch: 'master', v: 'prepatch' }, errors: { nogit: 'This script requires git. Consider executing `git init`.' }, flags: { increment: '--no-git-tag-version -f' } }; app.init = function () { if (!_gi2.default.is()) { _shelljs2.default.exit(1); } this.package = PKG; return this; }; // Gets options passed. app.getOptions = function (args) { return args.options ? args.options : args; }; // Communicates a dry run. app.dryrun = function (_ref) { var project = _ref.project, msg = _ref.msg, oldVersion = _ref.oldVersion, currentVersion = _ref.currentVersion, pkgPath = _ref.pkgPath, gittag = _ref.gittag, branch = _ref.branch; // Updates user. console.info('Dry run complete.'); console.info('The commit would have been tagged ' + gittag + '.'); console.info('You would have pushed to the branch ' + branch + '.'); }; // @TODO Refactor. app.set = function (options, msg, oldVersion) { var currentVersion = _np2.default.getVersion(), branch = options.branch || app.defaults.branch, npmtag = options.npmtag || options.tag || 'next', gitmsg = void 0, gittag = void 0, pkg = _np2.default.getPackage(), pkgName = pkg ? pkg.name : undefined, pkgPath = _np2.default.PKG_PATH, project = pkgName + '@' + currentVersion + '#' + npmtag; if (!pkgName) { console.warn('We are unable to find a package.json for this project. ' + 'Exiting ...'); return app; } msg += ' to v' + currentVersion + '."'; // Set the values requiring knowledge of new version. gitmsg = options.gitmsg || msg; gittag = options.gittag || 'v' + currentVersion; if (!options.dryrun) { // Executes Git publishing process. _gi2.default.add(pkgPath).commit(msg).tag(gittag, gitmsg).push(branch); // Executes npm publishing process. _np2.default.publish(npmtag); // Updates user. console.info('Done! You\'ve published ' + project + '.'); } else { app.dryrun({ project: project, msg: msg, oldVersion: oldVersion, currentVersion: currentVersion, pkgPath: pkgPath, gittag: gittag, branch: branch }); } return app; }; app.pwd = function (args, callback) { var pwd = _shelljs2.default.pwd(); console.info(pwd); // In CLI, returns user to application. callback(); }; app.version = function (args, callback) { var version = _np2.default.getVersion(); console.info(version); // In CLI, returns user to application. callback(); }; app.publish = function (args, _callback) { // Validates. app.init(); // Empowers API users to set their args outside an options object. var options = app.getOptions(args), version = options.version || app.defaults.v, pkg = _np2.default.getPackage(), currentVersion = _np2.default.getVersion(), pkgName = pkg ? pkg.name : undefined, msg = options.dryrun ? 'DRYRUN: ' : ''; if (!pkgName) { console.warn('We are unable to find a package.json for this project. ' + 'Exiting ...'); // In CLI, returns user to application. _callback(); return app; } console.log(msg + 'Publish ' + version + ' update to ' + pkgName + '@' + currentVersion + '.'); // Starts building the message. msg = '"Increments from v' + currentVersion; // Increments node module version. Does not git tag nor git commit. _np2.default.increment({ callback: function callback() { // Send old version to `set` method. app.set(options, msg, currentVersion); // In CLI, returns user to our application rather than exit. // In API, this can be anything to which the user sets it. _callback(); }, dryrun: options.dryrun, flags: app.flags.increment, message: undefined, version: version }); return app; }; app.increment = function (args, callback) { // Empowers API users to set their args outside an options object. var options = app.getOptions(args), flags = options.flag; if (options.only) { flags = app.flags.increment; } // In CLI, the callback returns the user to our application. _np2.default.increment({ callback: callback, dryrun: options.dryrun, flags: flags, message: options.message, version: options.version || app.defaults.v }); return app; }; exports.default = app; })();<file_sep>/src/test.js import on3 from './app.js'; console.log('on3 ', on3); on3.increment({flag: '', gitmsg: 'This is a test.', dryrun: true}, () => {return;}); on3.publish({gitmsg: 'This is also a test.', dryrun: true}, () => {return;}); <file_sep>/bin/test.js #!/usr/bin/env node ;(function(){ 'use strict'; var _app = require('./app.js'); var _app2 = _interopRequireDefault(_app); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } console.log('on3 ', _app2.default); _app2.default.increment({ flag: '', gitmsg: 'This is a test.', dryrun: true }, function () { return; }); _app2.default.publish({ gitmsg: 'This is also a test.', dryrun: true }, function () { return; }); })();<file_sep>/bin/make.js #!/usr/bin/env node ;(function(){ 'use strict'; var _transformer = require('./transformer'); var _transformer2 = _interopRequireDefault(_transformer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _transformer2.default.exec('src', 'bin', 'cli'); _transformer2.default.exec('src', 'build', 'node:app'); })();<file_sep>/README.md on3 simplifies common workflows for managing a Node module under Git version control. Increment your Node module's version, commit, push to GitHub, and publish to npm in one command. ``` npm install -g on3 ``` Submit your pull requests and feedback to [GitHub](https://github.com/luzmcosta/on3/issues). # API **publish** `on3.publish(args: {}, callback: fn)` `branch` {str} The branch to push. This is set to "master" by default. `gittag` {str} By default, this is a "v" followed by the package version in package.json, e.g. "v1.0.0-0". `gitmsg` {str} Sets the Git commit message. `npmtag` {str} The tag to apply when executing `npm publish`. This is set to "next" by default so publishing to the "latest" tag is a conscious decision. This should mitigate the risk of accidentally releasing breaking changes. `version` {str} Any value valid to [`npm version`](https://docs.npmjs.com/cli/version). This is set to "prepatch" by default. `dryrun` Report the would-be changes without executing them. **increment** `on3.increment(args: {}, callback: fn)` `message` {str} Sets the Git commit message. `flag` {str} Sets the flags to pass to `npm version`. `only` {bool} If true, increments the version without committing the changes. `version` {str} Any value valid to [`npm version`](https://docs.npmjs.com/cli/version). This is set to "prepatch" by default. `--dryrun` Report the would-be changes without executing them. # CLI ```shell # Example on3 # alias: on publish -v patch -n latest ``` **publish** _[alias: p]_ Increments the package's version, commits as instructed, then pushes and publishes the package. `publish -b master -v prepatch -g v1.0.1 -n next -m "Increments from v1.0.1-0 to v1.0.1-1."` `-b, --branch [branch]` Sets which branch to push to GitHub. Defaults to master. `-g, --gittag [tag]` Tags the Git commit. The new version number is used by default. `-m, --gitmsg ["message"]` Sets the Git commit message. Wrapping your comment in double quotes is recommended. `-n, --npmtag [tag]` Tags the node module. This is set as "next" by default so releasing as "latest" is a conscious choice. `-v, --version [version]` Increments the package to the given version. Uses "prepatch" by default. `--dryrun` Report the would-be changes without executing them. **increment** Increments the package version, commits the changes, and tags the commit with the new version number. See `-o` to avoid the latter two steps. `increment -m "Your Git commit message here."` `increment -f "--no-git-tag-version -f"` `-f, --flags` Sets the flags on the `npm version` command. `-m, --message` Sets the git commit message. `-o, --only` Ignore your repo's status, and do not commit. Only update the version in package.json. `--dryrun` Report the would-be changes without executing them. # Contributing Submit your pull requests and feedback to [GitHub](https://github.com/luzmcosta/on3/issues). ## Engineering Tasks (@todo) - Improve the user experience with better, colored feedback - Improve test coverage - Consider other pains in managing a Node module ## Development Guidelines ### eslint `npm run lint` ## Testing `npm run build && node build/test.js` ## Dependencies Developers contributing to this project require the tools that support it: * [ShellJS](https://www.npmjs.com/package/shelljs) * [Vorpal](https://www.npmjs.com/package/vorpal) * [Babel](https://babeljs.io/) * [ESLint](http://eslint.org/) * [Node and npm](http://nodejs.org/): Node provides an environment on which to execute JavaScript processes, while npm manages packages. <file_sep>/src/np.js import shell from 'shelljs'; import fs from 'fs'; const PWD = shell.pwd(); const PKG_PATH = PWD + '/package.json'; // Holds Node-related commands. let np = {PWD, PKG_PATH}; np.getPackage = (path=PKG_PATH) => { let pkg = fs.readFileSync(path); if (pkg) { return JSON.parse(pkg); } else { console.warn(`We were unable to retrieve the package.json at ${path}`); return {}; } }; // Get version of given package. np.getVersion = (pkg=np.getPackage()) => { return pkg.version; }; // Increment the version in the package.json. np.increment = ({version, flags, message, callback, dryrun}) => { flags = flags && flags !== true ? ' ' + flags : ''; message = message ? ' -m ' + message : ''; if (!dryrun) { shell.exec('npm' + flags + message + ' version ' + version); } else { console.log('Your package would be updated from ' + np.getVersion() + ' to the next ' + version + ' version.'); } if (callback) { callback(); } return np; }; // Publish the module to the npm public repository. np.publish = (tag) => { shell.exec('npm publish --tag=' + tag); return np; }; export default np; <file_sep>/bin/np.js #!/usr/bin/env node ;(function(){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _shelljs = require('shelljs'); var _shelljs2 = _interopRequireDefault(_shelljs); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PWD = _shelljs2.default.pwd(); var PKG_PATH = PWD + '/package.json'; // Holds Node-related commands. var np = { PWD: PWD, PKG_PATH: PKG_PATH }; np.getPackage = function () { var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : PKG_PATH; var pkg = _fs2.default.readFileSync(path); if (pkg) { return JSON.parse(pkg); } else { console.warn('We were unable to retrieve the package.json at ' + path); return {}; } }; // Get version of given package. np.getVersion = function () { var pkg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : np.getPackage(); return pkg.version; }; // Increment the version in the package.json. np.increment = function (_ref) { var version = _ref.version, flags = _ref.flags, message = _ref.message, callback = _ref.callback, dryrun = _ref.dryrun; flags = flags && flags !== true ? ' ' + flags : ''; message = message ? ' -m ' + message : ''; if (!dryrun) { _shelljs2.default.exec('npm' + flags + message + ' version ' + version); } else { console.log('Your package would be updated from ' + np.getVersion() + ' to the next ' + version + ' version.'); } if (callback) { callback(); } return np; }; // Publish the module to the npm public repository. np.publish = function (tag) { _shelljs2.default.exec('npm publish --tag=' + tag); return np; }; exports.default = np; })();<file_sep>/src/app.js import fs from 'fs'; import shell from 'shelljs'; import np from './np'; import gi from './gi'; const PKG = np.getPackage(); let app = { defaults: { branch: 'master', v: 'prepatch', }, errors: { nogit: 'This script requires git. Consider executing `git init`.', }, flags: { increment: '--no-git-tag-version -f', }, }; app.init = function() { if (!gi.is()) { shell.exit(1); } this.package = PKG; return this; }; // Gets options passed. app.getOptions = (args) => { return args.options ? args.options : args; }; // Communicates a dry run. app.dryrun = ({ project, msg, oldVersion, currentVersion, pkgPath, gittag, branch }) => { // Updates user. console.info(`Dry run complete.`); console.info(`The commit would have been tagged ${gittag}.`); console.info(`You would have pushed to the branch ${branch}.`); }; // @TODO Refactor. app.set = (options, msg, oldVersion) => { let currentVersion = np.getVersion(), branch = options.branch || app.defaults.branch, npmtag = options.npmtag || options.tag || 'next', gitmsg, gittag, pkg = np.getPackage(), pkgName = pkg ? pkg.name : undefined, pkgPath = np.PKG_PATH, project = `${pkgName}@${currentVersion}#${npmtag}`; if (!pkgName) { console.warn('We are unable to find a package.json for this project. ' + 'Exiting ...'); return app; } msg += ' to v' + currentVersion + '."'; // Set the values requiring knowledge of new version. gitmsg = options.gitmsg || msg; gittag = options.gittag || 'v' + currentVersion; if (!options.dryrun) { // Executes Git publishing process. gi.add(pkgPath).commit(msg).tag(gittag, gitmsg).push(branch); // Executes npm publishing process. np.publish(npmtag); // Updates user. console.info(`Done! You've published ${project}.`); } else { app.dryrun({ project, msg, oldVersion, currentVersion, pkgPath, gittag, branch }); } return app; }; app.pwd = (args, callback) => { const pwd = shell.pwd(); console.info(pwd); // In CLI, returns user to application. callback(); }; app.version = function(args, callback) { const version = np.getVersion(); console.info(version); // In CLI, returns user to application. callback(); }; app.publish = (args, callback) => { // Validates. app.init(); // Empowers API users to set their args outside an options object. let options = app.getOptions(args), version = options.version || app.defaults.v, pkg = np.getPackage(), currentVersion = np.getVersion(), pkgName = pkg ? pkg.name : undefined, msg = options.dryrun ? 'DRYRUN: ' : ''; if (!pkgName) { console.warn('We are unable to find a package.json for this project. ' + 'Exiting ...'); // In CLI, returns user to application. callback(); return app; } console.log(msg + 'Publish ' + version + ' update to ' + pkgName + '@' + currentVersion + '.'); // Starts building the message. msg = '"Increments from v' + currentVersion; // Increments node module version. Does not git tag nor git commit. np.increment({ callback: () => { // Send old version to `set` method. app.set(options, msg, currentVersion); // In CLI, returns user to our application rather than exit. // In API, this can be anything to which the user sets it. callback(); }, dryrun: options.dryrun, flags: app.flags.increment, message: undefined, version, }); return app; }; app.increment = (args, callback) => { // Empowers API users to set their args outside an options object. let options = app.getOptions(args), flags = options.flag; if (options.only) { flags = app.flags.increment; } // In CLI, the callback returns the user to our application. np.increment({ callback, dryrun: options.dryrun, flags, message: options.message, version: options.version || app.defaults.v, }); return app; }; export default app; <file_sep>/src/make.js import transformer from './transformer'; transformer.exec('src', 'bin', 'cli'); transformer.exec('src', 'build', 'node:app');
028d7035b952d7fb71d41ac62b0d2cc67e085ce5
[ "JavaScript", "Markdown" ]
12
JavaScript
luzmcosta/on3
86f5881a26147c6d57c30642bc39e8868b653a80
479a23eddfbcdfacb5e2cba6352f92fb9b557af6
refs/heads/master
<repo_name>drumwithrum/boostt<file_sep>/src/views/ExhibitionPreview/ExhibitionPreview.style.js import styled from 'styled-components'; import { View, Button as BaseButton } from '../../components'; export const Wrapper = styled(View)` padding-left: 13px; padding-right: 13px; display: flex; flex-wrap: wrap; height: 100%; z-index: 99; box-sizing: border-box; padding-top: 8px; padding-bottom: 32px; `; export const Button = styled(BaseButton)` width: 248px; margin-top: 32px; align-self: center; `; export const ButtonWrapper = styled('div')` width: 100%; display: flex; justify-content: center; `; <file_sep>/src/views/Collections/CollectionList/CollectionListItem/index.js export { default } from './CollectionListItem'; <file_sep>/src/views/Collections/CollectionList/CollectionList.style.js import styled from 'styled-components'; export const Wrapper = styled('div')` width: 100%; display: flex; flex-wrap: wrap; `; export const Row = styled('div')` width: 100%; `; export const Cell = styled('div')` box-sizing: border-box; flex-basis: 50%; flex-shrink: 0; margin-bottom: 6px; &:nth-child(2n + 1) { padding-right: 9px; } &:nth-child(2n) { padding-left: 9px; } ` <file_sep>/src/components/ExpandPanel/index.js export { default } from './ExpandPanel'; <file_sep>/src/config/dateManager.js import moment from 'moment'; export const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; export const getMonthName = (date) => moment(date).format('MMMM'); export const getFormattedDate = (date, dateFormat = 'D MMMM') => { return `${moment(date).format(dateFormat)}`; }; export const getHour = (date) => { const hours = moment(date).hours(); const minutes = moment(date).minutes(); const suffix = hours >= 12 ? 'pm' : 'am'; let hour = hours % 12; hour = hour ? hour : 12; // the hour '0' should be '12' const minute = minutes < 10 ? `0${minutes}` : minutes; return `${hour}:${minute}${suffix}`; } <file_sep>/src/components/Drawer/DrawerMenu/DrawerMenuItem/DrawerMenuItem.jsx import React from 'react'; import { func, object, bool } from 'prop-types'; import { Wrapper, IconContainer, TextContainer, Button } from './DrawerMenuItem.style'; const DrawerMenuItem = ({ onItemClick, title, icon, input, header, button, children, ...props }) => { const Content = () => ( <> <IconContainer> <img src={icon} alt={title} /> </IconContainer> <TextContainer header={header}> {Boolean(children) ? children : title } </TextContainer> </> ) return button ? ( <Button onClick={onItemClick}> <Content /> </Button> ) : ( <Wrapper> <Content /> </Wrapper> ) } DrawerMenuItem.propTypes = { onItemClick: func, input: object, header: bool, button: bool, } DrawerMenuItem.defaultProps = { input: null, header: false, button: false, } export default DrawerMenuItem; <file_sep>/src/views/ExhibitionPreview/Header/Header.style.js import styled from 'styled-components'; import { Typography } from '../../../components'; import colors from '../../../config/colors'; export const Wrapper = styled('div')` width: 100%; position: relative; min-height: 20px; `; export const Spacer = styled('div')` width: calc(100% - 10px); height: 1px; position: absolute; bottom: 0px; left: 5px; background-color: ${colors.disabled}; `; export const TitleWrapper = styled('div')` width: 100%; display: flex; justify-content: space-between; align-items: center; height: 18px; transition: all .3s; margin-bottom: ${p => p.expanded ? '10px' : '0px'}; `; export const Title = styled(Typography)` font-size: 10px; line-height: 12px; `; export const Icon = styled('img')` transform: ${p => p.expanded ? 'rotateZ(180deg)' : 'rotateZ(0deg)'}; transition: all .3s; `; export const Description = styled(Typography)` font-size: 10px; margin-top: 10px; line-height: 15px; height: 100%; box-sizing: border-box; padding-bottom: 10px; text-transform: none; `; <file_sep>/src/views/Collections/Collections.style.js import styled from 'styled-components'; import { View } from '../../components'; export const Wrapper = styled(View)` padding-left: 13px; padding-right: 13px; height: 100%; display: flex; flex-direction: column; `; export const Content = styled('div')` display: flex; align-items: flex-start; width: 100%; ` <file_sep>/src/components/ExhibitionData/ExhibitionData.jsx import React from 'react'; import { string, number, func } from 'prop-types'; import { Wrapper, Title, Subtitle, Hint } from './ExhibitionData.style'; const ExhibitionData = ({ type, title, floor, subtitle, onClick, ...props }) => ( <Wrapper onClick={onClick}> {type && <Hint>{type}</Hint>} {title && <Title>{title}</Title>} {subtitle && <Subtitle>{subtitle}</Subtitle>} {floor && <Hint>{`Floor: ${floor}`}</Hint>} </Wrapper> ) ExhibitionData.propTypes = { title: string, subtitle: string, floor: number, type: string, onClick: func, } ExhibitionData.defaultProps = { title: '', subtitle: '', floor: '', type: '', } export default ExhibitionData; <file_sep>/src/config/router.js export const routes = { LOGIN: { url: '/login', title: '' }, EXHIBITIONS: { url: '/exhibitions', title: '' }, COLLECTIONS: { url: '/collections', title: 'Collections' }, SHOP: { url: '/shop', title: 'Shop' }, TICKETS: { url: '/tickets', title: 'Plan Your Visit', } }; export const getTitle = () => { const location = window.location.pathname; const path = Object.values(routes).find(item => item.title && item.url.includes(location)); return path ? path.title : ''; } <file_sep>/src/components/Drawer/DrawerMenu/DrawerMenuItem/DrawerMenuItem.style.js import styled from 'styled-components'; import colors from '../../../../config/colors' import BaseButton from '../../../Button' const wrapperStyles = ` width: 100%; height: 55px; display: flex; align-items: center; font-family: Montserrat; font-style: normal; font-weight: normal; font-size: 18px; line-height: 22px; color: ${colors.white}; box-shadow: none; `; export const Wrapper = styled('div')` ${wrapperStyles} padding-right: 25px; box-sizing: border-box; `; export const Button = styled(BaseButton)` ${wrapperStyles} `; export const IconContainer = styled('div')` width: 59px; height: 100%; display: flex; justify-content: center; align-items: center; `; export const TextContainer = styled('div')` box-sizing: border-box; height: 100%; display: flex; align-items: center; flex-grow: 1; padding-left: ${p => p.header ? '0px' : '4px'}; `; <file_sep>/src/components/Typography/Typography.style.js import styled from 'styled-components'; import colors from '../../config/colors'; export const Base = styled('div')` font-family: Montserrat; font-style: normal; font-weight: normal; color: ${p => p.color || colors.black}; text-transform: uppercase; white-space: pre-wrap; ` export const Hint = styled(Base)` color: ${p => p.color || colors.hint}; font-size: 10px; line-height: 12px; ` export const Title = styled(Base)` font-size: 24px; line-height: 29px; color: ${p => p.color || colors.black}; ` export const Subtitle = styled(Base)` font-size: 18px; line-height: 22px; color: ${p => p.color || colors.main}; ` <file_sep>/src/components/DotsStepper/DotsStepper.jsx import React from 'react'; import { arrayOf, number, any } from 'prop-types'; import { Wrapper, StepperItem } from './DotsStepper.style'; const DotsStepper = ({ items, activeItem, ...props }) => { return ( <Wrapper> {items.map((img, index) => <StepperItem key={`stepper-item-${index}`} active={index === activeItem} />)} </Wrapper> ) } DotsStepper.propTypes = { items: arrayOf(any), activeItem: number.isRequired, } DotsStepper.defaultProps = { items: [], } export default DotsStepper; <file_sep>/src/views/Shop/ShopItem/Gallery/Gallery.jsx import React, { useState } from 'react'; import Carousel from 'nuka-carousel'; import { Wrapper, GalleryItem, StepperWrapper, GalleryItemWrapper } from './Gallery.style'; import { DotsStepper } from '../../../../components'; import { arrayOf, string } from 'prop-types'; const carouselSettings = { withoutControls: true, slidesToShow: 1, } const Gallery = ({ images, ...props }) => { const [slideIndex, setSlideIndex] = useState(0); return ( <Wrapper> <Carousel {...carouselSettings} afterSlide={index => setSlideIndex(index)} slideIndex={slideIndex}> {images.map((image, index) => ( <GalleryItemWrapper key={`gallery-item-${index}`}> <GalleryItem src={image} /> </GalleryItemWrapper> ))} </Carousel> <StepperWrapper> <DotsStepper activeItem={slideIndex} items={images} /> </StepperWrapper> </Wrapper> ) } Gallery.propTypes = { images: arrayOf(string).isRequired, } Gallery.defaultProps = { images: ['https://www.quantabiodesign.com/wp-content/uploads/No-Photo-Available.jpg'], } export default Gallery; <file_sep>/src/views/Exhibitions/ExhibitionModal/ExhibitionModal.style.js import styled from 'styled-components'; export const Wrapper = styled('div')` top: 0; left: 0px; position: fixed; width: 100vw; height: 100vh; transform: ${p => p.isOpen ? 'translateY(0)' : 'translateY(-100%)'}; transition: transform .6s; z-index: 99999; `; <file_sep>/src/views/Tickets/Tickets.jsx import React, { useState } from 'react'; import { Tabs, TabPanel } from '../../components'; import moment from 'moment'; import PricingBox from './PricingBox'; import DateInfo from './DateInfo'; import Summary from './Summary'; import { getFormattedDate, getHour } from '../../config/dateManager'; import { Wrapper, Title, Subtitle, PricingsWrapper, Button, TitleWrapper } from './Tickets.style'; const items = [{ title: 'Today', date: moment(), timeFrom: moment().minute(0).hour(12), timeTo: moment().minute(0).hour(19), }, { title: 'Tomorrow', date: moment().add(1, 'days'), timeFrom: moment().minute(30).hour(10), timeTo: moment().minute(30).hour(17), }, { title: 'Other', }]; const DATE_INFO_FORMAT = 'MMMM D, YYYY'; const basePrice = 10; const pricings = [{ title: 'Adults', price: basePrice, }, { title: 'Seniors', subtitle: '65+ with ID', price: basePrice * 0.6, }, { title: 'Students', subtitle: 'with ID', price: basePrice * 0.8, }] const Tickets = ({...props }) => { const [activeTab, setActiveTab] = useState(0); const [tickets, setTickets] = useState({ adults: 0, seniors: 0, students: 0, }); const onChange = (pricing, quantity) => { const newTickets = { ...tickets }; newTickets[pricing] = quantity; return setTickets(newTickets); } const getPrice = () => Object.keys(tickets) .reduce((prev, curr) => { const price = pricings.find((item) => item.title.toLowerCase() === curr).price; return prev + price * tickets[curr]; }, 0) return ( <Wrapper> <TitleWrapper> <Title>{'Skip the Line.\nPurchase Tickets.'}</Title> <Subtitle>{'All exhibitions, audio tours, and films included in the price of admission.'}</Subtitle> </TitleWrapper> <Tabs activeTab={activeTab} onTabClick={setActiveTab} titles={items.map(item => item.title)} /> <TabPanel index={activeTab}> {items.map(item => ( <DateInfo title={item.date ? getFormattedDate(item.date, DATE_INFO_FORMAT) : 'No other exhibitions available'} subtitle={item.timeFrom && item.timeTo ? `Open ${getHour(item.timeFrom)} - ${getHour(item.timeTo)}` : ''} /> ) )} </TabPanel> <PricingsWrapper> {pricings.map((pricing, index) => { const key = pricing.title.toLowerCase(); const onItemChange = (quantity) => onChange(key, quantity); return <PricingBox key={`pricing-${index}`} quantity={tickets[key]} onChange={onItemChange} title={pricing.title} subtitle={pricing.subtitle} /> })} </PricingsWrapper> <Summary quantity={getPrice()} title="Total" /> <Button>Continue to Payment</Button> </Wrapper> ) } export default Tickets; <file_sep>/src/components/Input/Input.style.js import styled from 'styled-components'; import colors from '../../config/colors' export const Wrapper = styled('div')` height: 42px; width: 100%; position: relative; ` export const InputBase = styled('input')` height: 100%; width: 100%; font-family: Montserrat; font-style: normal; font-weight: normal; font-size: 12px; line-height: 15px; padding: 0px; padding-left: 15px; display: flex; align-items: center; outline: none; border: none; box-sizing: border-box; color: ${p => p.color || colors.black}; background-color: ${p => p.backgroundColor || colors.white}; border: 2px solid ${p => p.color || colors.black}; &::placeholder { color: ${p => p.color || colors.black}; } `; export const Icon = styled('img')` position: absolute; right: 6px; ` <file_sep>/src/views/Shop/ShopItem/ShopItem.style.js import styled from 'styled-components'; import { ExpandPanel as ExpandPanelBase, Button as ButtonBase, Typography } from '../../../components'; import colors from '../../../config/colors'; export const Wrapper = styled('div')` width: 100%; padding-bottom: 22px; position:relative; &:not(:last-child) { margin-bottom: 22px; } `; export const Title = styled(Typography)` text-transform: none; font-size: 24px; line-height: 29px; color: ${colors.black}; margin-bottom: 20px; `; export const Content = styled('div')` width: 100%; ` export const ExpandPanel = styled(ExpandPanelBase)` padding-right: 20px; ` export const Button = styled(ButtonBase)` width: 248px; ` export const Description = styled('div')` text-transform: none; font-weight: 300; font-size: 10px; line-height: 15px; color: ${colors.hint}; height: 100%; ` export const PriceWrapper = styled('div')` display: flex; flex-direction: column; ` export const PriceTitle = styled(Typography)` text-transform: none; font-size: 14px; line-height: 21px; display: flex; align-items: center; color: ${colors.tabTitle}; ` export const PriceSubtitle = styled(Typography)` text-transform: none; font-size: 12px; line-height: 17px; display: flex; align-items: center; color: ${colors.disabled}; ` export const ExpandIcon = styled('img')` position: absolute; right: 5px; bottom: 3px; transform: ${p => p.expanded ? 'rotateX(180deg)' : 'rotateX(0deg)'}; transition: all .5s; ` export const ButtonWrapper = styled('div')` display:flex; justify-content: center; margin-top: 10px; ` export const OrderPanel = styled('div')` display: flex; justify-content: space-between; align-items: center; box-sizing: border-box; padding: 12px 0px 12px 0px; ` export const Spacer = styled('div')` position: absolute; bottom: 0; width: calc(100% - 10px); height: 1px; background-color: ${colors.disabled}; left: 5px; ` <file_sep>/src/views/Tickets/DateInfo/DateInfo.style.js import styled from 'styled-components'; import { Typography } from '../../../components'; import colors from '../../../config/colors'; export const Wrapper = styled('div')` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; min-height: 35px; margin-top: 4px; ` export const Title = styled(Typography)` font-size: 12px; line-height: 15px; text-transform: none; ` <file_sep>/src/views/Login/LoginForm/FormInput/FormInput.style.js import styled from 'styled-components'; import colors from '../../../../config/colors'; export const InputBase = styled('input')` height: 42px; width: 100%; font-family: Montserrat; font-style: normal; font-weight: normal; font-size: 12px; line-height: 15px; padding: 0px; padding-left: 15px; display: flex; align-items: center; outline: none; border: none; box-sizing: border-box; color: ${colors.black}; &:not(:last-child) { border-bottom: 1px solid black; } `; <file_sep>/src/components/QuantityField/QuantityField.jsx import React from 'react'; import QuantityButton from './QuantityButton'; import { func, number } from 'prop-types'; import { Wrapper, QuantityText } from './QuantityField.style'; const QuantityField = ({ quantity, onChange, ...props }) => { const onItemAdd = () => onChange(quantity + 1); const onItemRemove = () => onChange(quantity - 1); return ( <Wrapper> <QuantityButton onClick={onItemRemove} disabled={!quantity} /> <QuantityText active={Boolean(quantity)}>{quantity}</QuantityText> <QuantityButton onClick={onItemAdd} adding /> </Wrapper> ); } QuantityField.propTypes = { onChange: func.isRequired, quantity: number, } QuantityField.defaultProps = { quantity: 0, } export default QuantityField; <file_sep>/src/views/Login/LoginForm/LoginForm.jsx import React , { useState } from 'react'; import { withRouter } from 'react-router'; import { Wrapper, Title, Hint, Subtitle, InputWrapper, InfoWrapper, LoginButton, } from './LoginForm.style'; import { routes } from '../../../config/router'; import FormInput from './FormInput'; const LoginForm = ({history, ...props }) => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); return ( <Wrapper> <InfoWrapper> <Title> {`your\nart\nmuseum`} </Title> <Subtitle> {`151 3rd St\nSan Francisco, CA94103`} </Subtitle> </InfoWrapper> <InputWrapper> <FormInput name="email" type="email" placeholder="Email address" onChange={e => setEmail(e.target.value)} value={email} /> <FormInput name="password" type="password" placeholder="<PASSWORD>" onChange={e => setPassword(e.target.value)} value={password} /> <Hint justify="flex-end"> Forgot your password? </Hint> </InputWrapper> <LoginButton onClick={() => history.push(routes.EXHIBITIONS.url)}> Log In </LoginButton> <Hint> Don't have an account? </Hint> </Wrapper> ) } export default withRouter(LoginForm); <file_sep>/src/views/Collections/images/index.js import american from './american.png'; import americanPhotography from './americanPhotography.png'; import greek from './greek.png'; import decorative from './decorative.png'; import cubism from './cubism.png'; import destijl from './destijl.png'; export default { american, americanPhotography, greek, decorative, cubism, destijl, beksinski: 'https://images-na.ssl-images-amazon.com/images/I/71s%2Bq3OMKyL._SY606_.jpg', mucha: 'https://images.fineartamerica.com/images-medium-large-5/daydream-alphonse-mucha.jpg', } <file_sep>/src/views/Login/Login.style.js import styled from 'styled-components'; import { View } from '../../components'; import backgroundSrc from './images/background.png'; export const Wrapper = styled(View)` padding: 0px 60px 54px 64px; background-image: url('${backgroundSrc}'); display: flex; align-items: flex-end; height: 100%; `; <file_sep>/src/views/Tickets/PricingBox/PricingBox.style.js import styled from 'styled-components'; import { Typography } from '../../../components'; export const TextWrapper = styled('div')` display: flex; flex-direction: column; `; export const Title = styled(Typography)` font-size: 18px; line-height: 22px; text-transform: none; ` export const Subtitle = styled(Typography)` font-size: 11px; line-height: 13px; ` export const Wrapper = styled('div')` display: flex; justify-content: space-between; align-items: center; min-height: 28px; &:not(:last-child) { margin-bottom: 32px; } width: 100%; ` <file_sep>/src/views/Login/LoginForm/FormInput/FormInput.jsx import React from 'react'; import { string, func } from 'prop-types'; import { InputBase } from './FormInput.style'; const FormInput = ({ placeholder, onChange, value, name, type, ...props }) => ( <InputBase onChange={onChange} placeholder={placeholder} value={value} type={type} {...props} /> ); FormInput.propTypes = { placeholder: string, onChange: func.isRequired, name: string.isRequired, type: string, value: string, } FormInput.defaultProps = { placeholder: '', value: '', type: 'text', } export default FormInput; <file_sep>/src/components/QuantityField/QuantityButton/images/index.js import minus from './minus.svg'; import plus from './plus.svg'; export default { plus, minus, } <file_sep>/src/views/Tickets/Summary/Summary.style.js import styled from 'styled-components'; import { Typography } from '../../../components'; import colors from '../../../config/colors'; export const Wrapper = styled('div')` display: flex; flex-direction: column; width: 100%; ` export const Bar = styled('div')` width: 100%; height: 2px; position: relative; `; export const LayoutBar = styled('div')` width: 100%; height: 100%; background-color: ${colors.disabled}; position: absolute; top: 0; z-index: 99; `; export const ColorBar = styled('div')` width: ${p =>p.active ? '100%' : '0%'}; height: 100%; position: absolute; top: 0; z-index: 999; transition: all .35s; background-color: ${colors.main}; left: ${p => p.active ? '0%' : '50%'}; transform: ${p => p.active ? 'translateX(0%)' : 'translateX(-50%)'}; `; export const Title = styled(Typography)` font-size: 18px; line-height: 22px; color: ${p => p.active ? colors.black : colors.disabled}; text-transform: none; transition: .35s all; ` export const Content = styled(Typography)` display: flex; justify-content: space-between; box-sizing: border-box; padding-left: 10px; padding-right: 16px; margin-top: 4px; ` <file_sep>/src/components/ExhibitionData/ExhibitionData.style.js import styled from 'styled-components'; import Typography from '../Typography'; import colors from '../../config/colors' export const Wrapper = styled('div')` `; export const Title = styled(Typography)` font-size: 24px; line-height: 28px; display: flex; align-items: center; white-space: pre-wrap; `; export const Subtitle = styled(Typography)` font-size: 18px; line-height: 22px; color: ${colors.main}; height: 36px; display: flex; align-items: center; `; export const Hint = styled(Typography)` color: ${colors.hint}; font-size: 10px; line-height: 12px; height: 18px; display: flex; align-items: center; ` <file_sep>/src/views/Exhibitions/ExhibitionModal/index.js export { default } from './ExhibitionModal'; <file_sep>/src/components/Tabs/Tabs.jsx import React from 'react'; import { number, string, arrayOf, func } from 'prop-types'; import { Stepper, Layout, ActiveStep, Wrapper, TabsWrapper, Tab } from './Tabs.style'; const Tabs = ({ activeTab, onTabClick, titles, ...props }) => ( <Wrapper> <TabsWrapper> {titles.map((item, index) => ( <Tab key={`tab-item-${item}`} itemsAmount={titles.length} isActive={activeTab === index} onClick={() => onTabClick(index)}> {item} </Tab> ))} </TabsWrapper> <Stepper {...props }> <Layout /> <ActiveStep activeTab={activeTab} itemsAmount={titles.length} /> </Stepper> </Wrapper> ) Tabs.propTypes = { titles: arrayOf(string).isRequired, activeTab: number, onTabClick: func.isRequired, } Tabs.defaultProps = { activeTab: 0, } export default Tabs; <file_sep>/src/views/Exhibitions/ExhibitionInfo/images/index.js import pin from './pin.svg'; import clock from './clock.svg'; export default { pin, clock, } <file_sep>/src/utils/cart.js class Cart { static CART_KEY = 'cart'; static saveItemToCart = (itemId, quantity) => { const currentCart = this.getCart(); const updatedCart = currentCart; updatedCart[itemId] = quantity; localStorage.setItem(this.CART_KEY, JSON.stringify(updatedCart)); } static getCart() { const settings = JSON.parse(localStorage.getItem(this.CART_KEY) || 'null'); return settings; } static getQuantityForItem = (id) => { const cart = this.getCart(); return cart[id] || 0; } } export default Cart; <file_sep>/src/components/Drawer/Drawer.style.js import styled from 'styled-components'; import Drawer from '@material-ui/core/Drawer'; import colors from '../../config/colors' export const DrawerBase = styled(Drawer)` & > div { overflow: visible; z-index: 99999; background: none; } `; export const Content = styled('div')` width: 310px; height: 100%; background-color: ${colors.main}; box-shadow: 4px 0px 4px rgba(0, 0, 0, 0.25); ` <file_sep>/src/views/Tickets/DateInfo/DateInfo.jsx import React from 'react'; import { Wrapper, Title } from './DateInfo.style'; import { QuantityField } from '../../../components'; import colors from '../../../config/colors'; import { string } from 'prop-types'; const DateInfo = ({ title, subtitle,...props }) => { return ( <Wrapper {...props}> <Title>{title}</Title> <Title>{subtitle}</Title> </Wrapper> ) } DateInfo.propTypes = { title: string.isRequired, subtitle: string, } DateInfo.defaultProps = { subtitle: '', } export default DateInfo; <file_sep>/src/views/index.jsx import React, { Component } from 'react'; import { MuiThemeProvider } from '@material-ui/core/styles'; import { Switch, Route, Redirect, HashRouter } from 'react-router-dom'; import { withRouter } from 'react-router'; import { ThemeProvider } from 'styled-components'; import Login from './Login'; import Exhibitions from './Exhibitions'; import Collections from './Collections'; import Tickets from './Tickets'; import Shop from './Shop'; import ExhibitionPreview from './ExhibitionPreview'; import theme from '../config/theme'; import { routes } from '../config/router'; export const Router = ( <Switch> <Route exact path={routes.LOGIN.url} component={Login} /> <Route exact path={routes.EXHIBITIONS.url} component={Exhibitions} /> <Route exact path={routes.COLLECTIONS.url} component={Collections} /> <Route exact path={routes.SHOP.url} component={Shop} /> <Route exact path={routes.TICKETS.url} component={Tickets} /> <Route exact path="/preview" component={ExhibitionPreview} /> <Route path="*" render={() => <Redirect to={routes.LOGIN.url} />} /> </Switch> ); class Views extends Component { render() { return ( <HashRouter basename="/"> <MuiThemeProvider theme={theme}> <ThemeProvider theme={theme}>{Router}</ThemeProvider> </MuiThemeProvider> </HashRouter> ); } } export default withRouter(Views); <file_sep>/src/components/ExhibitionData/index.js export { default } from './ExhibitionData'; <file_sep>/src/views/Login/LoginForm/LoginForm.style.js import styled from 'styled-components'; import { Button, Typography as TypographyBase } from '../../../components'; import colors from '../../../config/colors'; export const Wrapper = styled('div')` width: 100%; `; export const Typography = styled(TypographyBase)` color: ${colors.appBar}; font-weight: 300; text-transform: none; ` export const Title = styled(Typography)` text-transform: uppercase; white-space: pre-wrap; font-size: 36px; line-height: 44px; height: 150px; `; export const Hint = styled(Typography)` font-size: 10px; line-height: 12px; height: 24px; display: flex; align-items: center; justify-content: ${p => p.justify || 'flex-start'}; ` export const Subtitle = styled(Typography)` white-space: pre-wrap; font-size: 12px; line-height: 15px; ` export const InputWrapper = styled('div')` margin-top: 20px; margin-bottom: 27px; ` export const InfoWrapper = styled('div')` padding-left: 5px; ` export const LoginButton = styled(Button)` margin-bottom: 5px; ` <file_sep>/src/views/Tickets/Summary/Summary.jsx import React from 'react'; import { Wrapper, Title, Bar, LayoutBar, ColorBar, Content } from './Summary.style'; import { number, string } from 'prop-types'; const Summary = ({ quantity, title, ...props }) => { return ( <Wrapper {...props}> <Bar> <LayoutBar /> <ColorBar active={Boolean(quantity)}/> </Bar> <Content> <Title active={Boolean(quantity)}>{title}</Title> <Title active={Boolean(quantity)}>{`$${quantity}`}</Title> </Content> </Wrapper> ) } Summary.propTypes = { quantity: number, title: string, } Summary.defaultProps = { quantity: 0, title: '', } export default Summary; <file_sep>/src/components/QuantityField/QuantityField.style.js import styled from 'styled-components'; import Typography from '../Typography'; import colors from '../../config/colors'; export const Wrapper = styled('div')` display: flex; align-items: center; position: relative; `; export const QuantityText = styled(Typography)` display: flex; font-size: 18px; line-height: 22px; display: flex; align-items: center; text-align: center; color: ${p => p.active ? colors.black : colors.disabled}; text-decoration: ${p => p.active ? 'underline' : 'none'}; margin: 0px 8px 0px 8px; min-width: 20px; justify-content: center; transition: all .3s; `; <file_sep>/src/views/Exhibitions/ExhibitionInfo/ExhibitionInfo.style.js import styled from 'styled-components'; import { Button as ButtonBase } from '../../../components'; export const Wrapper = styled('div')` width: 100%; box-sizing: border-box; height: calc(100vh - 60px); display: flex; flex-wrap: wrap; align-items: flex-start; `; export const Footer = styled('div')` width: 100%; display: flex; justify-content: space-between; height: 40px; margin-top: 30px; ` export const Content = styled('div')` padding-left: 13px; padding-right: 13px; box-sizing: border-box; width: 100%; position: relative; ` export const Thumbnail = styled('div')` width: 100%; height: 250px; background-image: ${p => p.src ? `url('${p.src}')` : 'none'}; display: flex; justify-content: center; align-items: center; margin-bottom: 12px; ` export const Button = styled(ButtonBase)` margin-top: 50px; width: 250px; position: relative; left: 50%; transform: translateX(-50%); ` <file_sep>/src/views/Collections/CollectionList/CollectionListItem/CollectionListItem.style.js import styled from 'styled-components'; import { Typography as TypographyBase } from '../../../../components'; import colors from '../../../../config/colors'; export const Wrapper = styled('div')` width: 100%; `; export const Thumbnail = styled('div')` width: 100%; height: 124px; background-image: url('${p => p.src}'); background-size: cover; background-position: center center; ` export const Typography = styled(TypographyBase)` text-transform: none; font-size: 12px; line-height: 15px; color: ${colors.main}; white-space: pre-wrap; text-transform: uppercase; margin-top: 6px; height: 32px; ` <file_sep>/src/components/Button/Button.style.js import styled, { keyframes } from 'styled-components'; import colors from '../../config/colors' export const ButtonBase = styled('button')` width: 100%; height: 42px; background: ${colors.main}; box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25); font-family: 'Montserrat'; border: none; outline: none; color: ${colors.white}; font-size: 12px; line-height: 15px; position: relative; overflow: hidden; `; const ripple = keyframes` to { transform: scale(2.5); opacity: 0; } ` export const Ripple = styled('div')` border-radius: 50%; background-color: rgba(255, 255, 255, 0.5); position: absolute; transform: scale(0); animation: ${ripple} 0.6s linear; `; <file_sep>/src/components/Input/Input.jsx import React from 'react'; import { string, func } from 'prop-types'; import { InputBase, Wrapper, Icon } from './Input.style'; const FormInput = ({ placeholder, onChange, value, name, type, color, backgroundColor, icon, inputProps, ...props }) => ( <Wrapper {...props}> <InputBase onChange={onChange} placeholder={placeholder} value={value} type={type} color={color} backgroundColor={backgroundColor} {...inputProps} /> {icon && <Icon src={icon} alt={`${name}-input-icon`} />} </Wrapper> ); FormInput.propTypes = { placeholder: string, onChange: func.isRequired, name: string.isRequired, type: string, value: string, icon: string, } FormInput.defaultProps = { placeholder: '', value: '', type: 'text', color: '', icon: '', } export default FormInput; <file_sep>/src/views/Tickets/PricingBox/index.js export { default } from './PricingBox'; <file_sep>/src/components/AppBar/AppBar.jsx import React from 'react'; import { Wrapper, TextLogo, MenuIcon, Title } from './AppBar.style'; import { func, bool, string } from 'prop-types'; import menuIconSrc from './images/menu.svg'; import { getTitle } from '../../config/router'; const AppBar = ({ children, onClick, isMenuOpen, title, ...props }) => ( <Wrapper> <TextLogo> {`the\nart\nmuseum`} </TextLogo> <Title>{title || getTitle()}</Title> <MenuIcon moved={isMenuOpen} onClick={onClick} src={menuIconSrc} /> </Wrapper> ) AppBar.propTypes = { onClick: func, isMenuOpen: bool, title: string, } AppBar.defaultProps = { isMenuOpen: false, title: '', } export default AppBar; <file_sep>/src/views/Tickets/Tickets.style.js import styled from 'styled-components'; import { View, Button as BaseButton, Typography } from '../../components'; import colors from '../../config/colors'; export const Wrapper = styled(View)` padding-left: 13px; padding-right: 13px; display: flex; align-items: center; padding-top: 12px; box-sizing: border-box; padding-bottom: 24px; overflow: scroll; flex-wrap: wrap; height: 100%; `; export const Title = styled(Typography)` text-transform: none;; font-size: 24px; line-height: 29px; display: flex; align-items: center; color: ${colors.black}; width: 275px; ` export const TitleWrapper = styled('div')` width: 100%; display: flex; flex-direction: column; ` export const Subtitle = styled(Typography)` text-transform: none; font-size: 12px; line-height: 15px; display: flex; align-items: center; color: ${colors.main}; width: 275px; padding: 3px 0px 3px 0px; margin-bottom: 12px; ` export const PricingsWrapper = styled('div')` display: flex; flex-direction: column; margin: 54px 0px 54px 0px; width: 100%; ` export const Button = styled(BaseButton)` width: 248px; align-self: center; margin-top: 38px; position: relative; left: 50%; transform: translateX(-50%); `; <file_sep>/src/views/ExhibitionPreview/ExhibitionPreview.jsx import React from 'react'; import Header from './Header'; import Gallery from './Gallery'; import { ExhibitionData } from '../../components'; import { date, shape, string, number, arrayOf, bool, func } from 'prop-types'; import { getFormattedDate } from '../../config/dateManager'; import { Wrapper, Button, ButtonWrapper } from './ExhibitionPreview.style'; const ExhibitionPreview = ({ data: { title, type, from, to, floor }, images, headers, isDrawerOpen, onClose, ...props }) => ( <Wrapper title="Exhibition Preview"> <ExhibitionData title={title} type={type} subtitle={`${getFormattedDate(from)} - ${getFormattedDate(to)}`} floor={floor} /> <Gallery images={images} /> {headers.map((item, index) => <Header data={item} key={`exhibition-${index}`} />)} <ButtonWrapper> <Button onClick={onClose}>Back</Button> </ButtonWrapper> </Wrapper> ) ExhibitionPreview.propTypes = { data: shape({ title: string, type: string, addressLine1: string, addressLine2: string, to: date, from: date, timeTo: date, timeFrom: date, floor: number, }), images: arrayOf(shape({ title: string, src: string, type: string, year: string, })).isRequired, headers: arrayOf(shape({ title: string, description: string, })), onClose: func.isRequired, isDrawerOpen: bool, } ExhibitionPreview.defaultProps = { isDrawerOpen: false, headers: [], } export default ExhibitionPreview; <file_sep>/src/views/Shop/ShopItem/ShopItem.jsx import React, { useState } from 'react'; import Gallery from './Gallery'; import { string, arrayOf, shape, number, bool } from 'prop-types'; import { QuantityField } from '../../../components'; import arrowIcon from './images/arrow.svg'; import { Wrapper, Title, Description, Content, PriceWrapper, ExpandPanel, ExpandIcon, Button, ButtonWrapper, PriceSubtitle, PriceTitle, OrderPanel, Spacer, } from './ShopItem.style'; const ShopItem = ({ data: { title, description, price: { member: memberPrice, all: normalPrice }, images, }, quantity, spacer, ...props }) => { const [isPanelExpanded, setExpansionState] = useState(false); const [itemQuantity, setQuantity] = useState(quantity); const onExpandClick = () => setExpansionState(!isPanelExpanded); return ( <Wrapper> <Gallery images={images} /> <Content> <Title>{title}</Title> <ExpandPanel height={72} expanded={isPanelExpanded}> <Description>{description}</Description> <ExpandIcon src={arrowIcon} alt="expand icon" onClick={onExpandClick} expanded={isPanelExpanded} /> </ExpandPanel> <OrderPanel> <PriceWrapper> <PriceTitle>{`$${normalPrice.toFixed(2)}`}</PriceTitle> {memberPrice && <PriceSubtitle>{`$${memberPrice.toFixed(2)} Member Price`}</PriceSubtitle>} </PriceWrapper> <QuantityField quantity={itemQuantity} onChange={setQuantity} /> </OrderPanel> </Content> <ButtonWrapper> <Button>Add to Cart</Button> </ButtonWrapper> {spacer && <Spacer />} </Wrapper> ); } ShopItem.propTypes = { data: shape({ title: string, description: string, price: shape({ all: number.isRequired, member: number, }), images: arrayOf(string), }).isRequired, quantity: number, spacer: bool, } ShopItem.defaultProps = { quantity: 0, } export default ShopItem; <file_sep>/src/views/Exhibitions/ExhibitionInfo/ExhibitionDetails/ExhibitionDetails.style.js import styled from 'styled-components'; import { Typography as TypographyBase } from '../../../../components'; import colors from '../../../../config/colors'; export const Wrapper = styled('div')` height: 100%; display: flex; `; export const Icon = styled('img')` margin-right: 12px; `; export const Typography = styled(TypographyBase)` text-transform: none; font-size: 12px; line-height: 15px; color: ${colors.main}; ` export const TextWrapper = styled('div')` display: flex; flex-direction: column; align-items: flex-start; justify-content: flex-end; ` <file_sep>/src/views/Tickets/PricingBox/PricingBox.jsx import React from 'react'; import { Wrapper, Title, Subtitle, TextWrapper } from './PricingBox.style'; import { QuantityField } from '../../../components'; import colors from '../../../config/colors'; import { func, number, string } from 'prop-types'; const PricingBox = ({ quantity, onChange, title, subtitle,...props }) => { return ( <Wrapper {...props}> <TextWrapper> <Title>{title}</Title> <Subtitle color={colors.disabled}>{subtitle}</Subtitle> </TextWrapper> <QuantityField onChange={onChange} quantity={quantity} /> </Wrapper> ) } PricingBox.propTypes = { onChange: func.isRequired, quantity: number, title: string, subtitle: string, } PricingBox.defaultProps = { quantity: 0, title: '', subtitle: '', } export default PricingBox; <file_sep>/src/views/Collections/Collections.jsx import React, { useState } from 'react'; import CollectionList from './CollectionList'; import Search from './Search'; import images from './images'; import { Wrapper, Content } from './Collections.style'; const items = [{ title: 'Decorative\narts & crafts', img: images.decorative, }, { title: 'american\nimpressionism', img: images.american, }, { title: 'de stijl', img: images.destijl, }, { title: 'cubism', img: images.cubism, }, { title: 'american photography', img: images.americanPhotography, }, { title: 'greek antiques', img: images.greek, }, { title: '<NAME>', img: images.beksinski, }, { title: '<NAME>', img: images.mucha, }] const Collections = ({...props }) => { const [searchValue, setSearchValue] = useState(''); const filteredItems = items.filter(item => item.title.toLowerCase().includes(searchValue.toLowerCase())) return( <Wrapper> <Search value={searchValue} onChange={setSearchValue} /> <Content> <CollectionList items={filteredItems} /> </Content> </Wrapper> ) } export default Collections; <file_sep>/src/components/DotsStepper/DotsStepper.style.js import styled from 'styled-components'; import colors from '../../config/colors' export const Wrapper = styled('div')` width: 100%; display: flex; justify-content: center; align-items: center; padding-top: 1px; padding-bottom: 8px; `; export const StepperItem = styled('div')` width: 6px; height: 6px; border-radius: 100px; transition: all .225s; background-color: ${p => p.active ? colors.main : colors.stepperDisabled}; &:not(:last-child) { margin-right: 2px; } &:not(:first-child) { margin-left: 2px; } ` <file_sep>/src/components/Drawer/Drawer.jsx import React from 'react'; import { func, bool } from 'prop-types'; import DrawerMenu from './DrawerMenu'; import { DrawerBase, Content } from './Drawer.style'; const Drawer = ({ children, open, onClose, ...props }) => ( <DrawerBase variant="persistent" anchor="left" open={open} ModalProps={{ keepMounted: true, // Better open performance on mobile. }} {...props} > <Content> <DrawerMenu /> </Content> </DrawerBase> ) Drawer.propTypes = { open: bool, onClose: func, } Drawer.defaultProps = { open: false, } export default Drawer; <file_sep>/src/views/Shop/ShopItem/Gallery/Gallery.style.js import styled from 'styled-components'; const itemHeight = 300 export const Wrapper = styled('div')` width: calc(100% + 8px); margin-left: -4px; `; export const GalleryItem = styled('div')` width: 100%; height: ${itemHeight}px; background-size: cover; background-image: url('${p => p.src}'); background-position: center center; box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25); overflow: visible; outline: none; ` export const GalleryItemWrapper = styled('div')` width: 100%; padding-left: 4px; padding-right: 4px; box-sizing: border-box; height: ${itemHeight + 10}px; ` export const StepperWrapper = styled('div')` ` <file_sep>/src/views/Exhibitions/index.js export { default } from './Exhibitions'; <file_sep>/src/components/Button/Button.jsx import React, { useState } from 'react'; import { ButtonBase, Ripple } from './Button.style'; const Button = ({ children, onClick, ...props }) => { const initialState = [] const [ripples, setRipples] = useState(initialState); const onRippleAdd = (e) => { const rippleContainer = e.currentTarget; const size = rippleContainer.offsetWidth; const pos = rippleContainer.getBoundingClientRect(); const x = e.pageX - pos.x - (size / 2); const y = e.pageY - pos.y - (size / 2); const ripple = { position: 'absolute', top: y + 'px', left: x + 'px', height: size + 'px', width: size + 'px' }; setRipples([...ripples, ripple]); } const handleClick = (e) => { onRippleAdd(e); onClick && onClick(); } return ( <ButtonBase onClick={handleClick} {...props}> {ripples.map((item, index) => <Ripple style={item} key={`riplpe-item-${index}`} />)} {children} </ButtonBase> ) } export default Button;
cbb9b0c6b946b0b91b1f954192f707aa99c2330f
[ "JavaScript" ]
57
JavaScript
drumwithrum/boostt
4886dd5c5efaad08cdb57cbb7f34e6a68521b2d3
2330cdf55759b017d2602e07e5e77d1f38bf65ac
refs/heads/master
<repo_name>Ljingjing/jd<file_sep>/js/category.js window.addEventListener('load', function() { var jdCategory=new JdCategory(); jdCategory.initLeftSlide(); jdCategory.initRightSlide(); jdCategory.leftCeiling(); }); var JdCategory=function(){ } JdCategory.prototype={ initLeftSlide:function(){ // 初始化左边 var swiper = new Swiper('.category-left .swiper-container', { direction: 'vertical', slidesPerView: 'auto', freeMode: true, scrollbar: { el: '.swiper-scrollbar', }, mousewheel: true, }); }, initRightSlide:function(){ // 初始化右边 var swiper = new Swiper('.category-right .swiper-container', { direction: 'vertical', slidesPerView: 'auto', freeMode: true, scrollbar: { el: '.swiper-scrollbar', }, mousewheel: true, }); }, // 左侧吸顶效果 leftCeiling:function(){ // 1.给所有li添加点击事件 // 当需要给很多子元素添加重复的事件的时候可以给父元素添加使用事件 捕获到子元素 var ul = document.querySelector('.category-left ul'); var lis=ul.children; // 2. 给所有li添加一个index索引 for (var i = 0; i < lis.length; i++) { lis[i].index=i; } // 给ul添加的点击事件 ul.addEventListener('click',function(e){ // 真正触发事件的其实是子元素 由于a在最里面所以是a的parentNode父元素 // 3.获取当前点击的li var li = e.target.parentNode; console.dir(li); console.log(li.index); // 4.获取当前点击的li的索引 var index = li.index; // 5.获取当前点击的li的高度 var liHeight=li.offsetHeight; // 6.计算当前需要位移的距离 var distanceY = -index*liHeight; // 7.判断当前位移的距离是否大于最大的位移的距离 // 如果大于就使用当前计算的,如果小于使用最大位移距离 // 值是负的 var maxDistanceY = document.querySelector('.category-left').offsetHeight-ul.offsetHeight; if (distanceY>maxDistanceY) { // 8.给当前swiper滑动的所有图片容器元素(ul的父元素的父元素)设置位移 ul.parentNode.parentNode.style.transform='translate3d(0px,'+distanceY+'px,0px)'; }else{ ul.parentNode.parentNode.style.transform='translate3d(0px,'+maxDistanceY+'px,0px)'; } // 10.给当前的位移的元素添加一个过渡效果让他慢慢位移 ul.parentNode.parentNode.style.transitionDuration='300ms'; // 11.给所有的li删除active 给当前的li添加active for (var i = 0; i < lis.length; i++) { lis[i].classList.remove('active'); } li.classList.add('active'); }); } }
014faaab5af6248532abc722e5bad3b07f96c3b7
[ "JavaScript" ]
1
JavaScript
Ljingjing/jd
ca2cb57e8eeb855205871839bfa68732c5a7d3d9
5ac2fc476a38dce634a417183e0855d5a0acbb39
refs/heads/master
<repo_name>runbookbb/ruby-examples<file_sep>/accessor_example.rb class Shopname attr_accessor :name end visted_shop = Shopname.new visted_shop.name = "SevenEleven" puts visted_shop.name # => "SevenEleven" <file_sep>/setter_example.rb class My_shopping_cart def item_list=(value) @item_list = value end end Joe_account = My_shopping_cart.new Joe_account.item_list = "Apples" #puts Joe_account.item_list<file_sep>/getter_example.rb class My_shopping_cart def item_list=(value) @item_list = value end def item_list @item_list end end Joe_account = My_shopping_cart.new Joe_account.item_list = "Apples" puts Joe_account.item_list
330884d00d4668012324683ff679c33465920b01
[ "Ruby" ]
3
Ruby
runbookbb/ruby-examples
73a41a07e401559939354e53d9281e49c20cb39a
f3475ba9cef96e993a66fbe049889b10c0de3dc9
refs/heads/master
<file_sep>def plus_two(num) total = num + 2 end
cecdd9497ae817a892d5df6c70c923b577e671a8
[ "Ruby" ]
1
Ruby
sgoldfarb2/debugging-with-pry-001-prework-web
5dcbf7bf1b38ba9ae246a77f463277c0529452f8
916fbdb2b9d1ad7d8706e55fba5990f84b5bc659
refs/heads/main
<file_sep>#1152 print(len(list(map(str, input().split()))))<file_sep>백준 문제 풀었던거 기록용으로 올린거.<br> ㄱㄱㅇ 갈 생각하니까 할게 너무 많아서 코딩을 지금이라도 해야하나 생각 중인데 안 늦었을까요<br> _늦었다고 생각할 땐 진짜 늦은거라는데..그리고 전 python 하기 싫어요. Java나 JS 하고싶은데 어려워요 자바.<br>_ _웹이 바로바로 눈에 보여서 재밌는데... 풀스택을 어케해요! 어플 만들고 싶다 ... 근데 마땅한 아이디어가 없음<br><br><br>_ 그리고 python은 뭐 저런 쓸데없는 파일이 많은가요? 지워도 되려나 노트북 용량이 부족해요..<br> 파일 지우면 github에서도 지워질텐데 그러면 노트북 용량을 추가해야겠네요. 샘송 추천 좀 ..<br> _데스트탑은 알아보기도 귀찮고 옮기기도 번거롭고 놓을 자리도 없고 전자파 때문에 머리 아픔._<br><br><br> <h2> 코딩의 노예가 돼야 하는게 답일까 ...<br> 쉬운 일도 하기 싫고 어려운 일도 하기 싫다. 평생 공부 ... 꿱
7e7791e6403daa6b13b29ba8674093941af6b54b
[ "Markdown", "Python" ]
2
Python
um2n/100Jun
f79f2ed37c2529b3f44f3c03ae51f6f1284e9840
ad87ccfe97fb8395076b1d473bfa9c088e3aba7c
refs/heads/master
<file_sep>[![Swift](https://img.shields.io/badge/Swift-4.0-green.svg?style=flat)](https://img.shields.io/badge/Swift-4.0-green.svg?style=flat) # RxVIP Templates Precondition add RxSwift Dependency to your Project: https://github.com/ReactiveX/RxSwift <file_sep>// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import UIKit import RxSwift protocol ___VARIABLE_moduleNameIdentifier___ViewInputProtocol: class { var viewModelSubject: PublishSubject<___VARIABLE_moduleNameIdentifier___ViewModel> {get} } class ___VARIABLE_moduleNameIdentifier___ViewController: UIViewController { var interactor: ___VARIABLE_moduleNameIdentifier___InteractorProtocol? var router: ___VARIABLE_moduleNameIdentifier___RouterProtocol? var viewModelSubject = PublishSubject<___VARIABLE_moduleNameIdentifier___ViewModel>() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() viewModelSubject.subscribe(onNext: { [weak self] in print("Viewmodel \($0) was changed in \(String(describing: self))") }).disposed(by: disposeBag) self.interactor?.viewDidLoad() } // MARK: Object lifecycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { let viewController = self let interactor = ___VARIABLE_moduleNameIdentifier___Interactor() let presenter = ___VARIABLE_moduleNameIdentifier___Presenter() let router = ___VARIABLE_moduleNameIdentifier___Router() viewController.interactor = interactor viewController.router = router interactor.presenter = presenter presenter.viewController = viewController router.viewController = viewController } } extension ___VARIABLE_moduleNameIdentifier___ViewController: ___VARIABLE_moduleNameIdentifier___ViewInputProtocol { } <file_sep>// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import UIKit protocol ___VARIABLE_moduleNameIdentifier___InteractorOutputProtocol: class { func showModel(model: ___VARIABLE_moduleNameIdentifier___ViewModel) } class ___VARIABLE_moduleNameIdentifier___Presenter { weak var viewController: ___VARIABLE_moduleNameIdentifier___ViewInputProtocol! } extension ___VARIABLE_moduleNameIdentifier___Presenter: ___VARIABLE_moduleNameIdentifier___InteractorOutputProtocol { func showModel(model: ___VARIABLE_moduleNameIdentifier___ViewModel) { viewController.viewModelSubject.onNext(model) } } <file_sep>// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import UIKit protocol ___VARIABLE_moduleNameIdentifier___InteractorProtocol { func viewDidLoad() } class ___VARIABLE_moduleNameIdentifier___Interactor { var presenter: ___VARIABLE_moduleNameIdentifier___InteractorOutputProtocol? } extension ___VARIABLE_moduleNameIdentifier___Interactor: ___VARIABLE_moduleNameIdentifier___InteractorProtocol { func viewDidLoad() { presenter?.showModel(model: ___VARIABLE_moduleNameIdentifier___ViewModel()) } } <file_sep>// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import UIKit struct ___VARIABLE_moduleNameIdentifier___Scene { static let storyboardName: String = "___VARIABLE_moduleNameIdentifier___" static let viewControllerIdentifer: String = "___VARIABLE_moduleNameIdentifier___ViewControllerIdentifier" } <file_sep>// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import UIKit struct ___VARIABLE_moduleNameIdentifier___Scene { static let nibName: String = "___VARIABLE_moduleNameIdentifier___" }
3998867eec7cab3c0b8ff6346f95681e4ef71d48
[ "Markdown", "Swift" ]
6
Markdown
Egeiz/RxVIP-Template
1792d74ee12f65bc252109f1eed5b34a5456ee06
7880164e075840154a0ff3a3957d55d38ec37cc8
refs/heads/master
<repo_name>wahabshah/clinic-website<file_sep>/header_post.php <!-- link to the CSS files for this menu type --> <link rel="stylesheet" type="text/css" href="style/main.css" > <link href="style/superfish.css" rel="stylesheet" type="text/css"> <!-- link to the JavaScript files--> <!-- Add jQuery library --> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <!--(hoverIntent is optional) --> <script src="javascripts/jquery.hoverIntent.js"></script> <script src="javascripts/superfish.js"></script> <!-- initialise Superfish plugin --> <script> $(document).ready(function(){ $('ul.sf-menu').superfish(); }); </script> <!-- include Cycle plugin --> <script src="http://malsup.github.com/jquery.cycle.all.js"></script> <script > $(document).ready(function() { $('#hero').cycle({ width: '100%', fit: 1, fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc... speed: 2000, timeout: 2000 }); }); </script> <!--Slider for News updates --> <script> $(document).ready(function() { $('#slider').cycle({ fx: 'scrollUp', timeout: 6000, delay: -4000, next: '#slider', pause: 1 , }); }); </script> <!--Slider for Holiday Notification(Temp) --> <!--<script> $(document).ready(function() { $('#holiday_notification').cycle({ fx: 'scrollLeft', speed: 5000, continuous: 1, }); }); </script>--> <!-- Add fancyBox --> <link rel="stylesheet" href="style/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" /> <script type="text/javascript" src="javascripts/jquery.fancybox.pack.js?v=2.1.5"></script> <!-- Optionally add helpers - button, thumbnail and/or media --> <link rel="stylesheet" href="style/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" /> <script type="text/javascript" src="javascripts/jquery.fancybox-buttons.js?v=1.0.5"></script> <script type="text/javascript" src="javascripts/jquery.fancybox-media.js?v=1.0.6"></script> <link rel="stylesheet" href="style/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" /> <script type="text/javascript" src="javascripts/jquery.fancybox-thumbs.js?v=1.0.7"></script> <script> $(document).ready(function() { $(".img-pop").fancybox({ openEffect : 'elastic', closeEffect : 'elastic', helpers : { title : { type : 'inside' } } }); }); </script> <!-- include Marquee plugin --> <script src="javascripts/jquery.marquee.min.js"></script> <!--Include jQuery pause plugin for pause on hover --> <script src="javascripts/jquery.pause.min.js"></script> <script> $(function() { $('#holiday_notification').marquee({ speed: 10000, gap: 50, delayBeforeStart: 0, direction: 'left', duplicated: true, pauseOnHover: true }); }); </script> <!-- gigya.js script should only be included once --> <script src="http://cdn.gigya.com/js/gigya.js?apiKey=<KEY>"> </script> </head> <body> <!-- Google Analytics START--> <?php include_once("analyticstracking.php") ?> <!-- Google Analytics END--> <div id="wrapper"> <!--Header--> <header id="top"> <!-- Logo --> <img src="images/headerLogo.png" alt="Nazeef Dental Clinic Logo" width="420" id="logo"/> <img src="images/headerLogo-address.png" alt="Nazeef Dental Clinic Address" width="270" id="logo-address"/> <!-- Navigation bar --> <nav id="mainnav"> <ul class="sf-menu"> <!-- 1 Home --> <li> <a href="index.php" id="#">Home</a> </li> <!-- 2 Procedures--> <li><a href="#" class="sf-with-ul">Procedures<span class="sf-sub-indicator"> »</span> </a> <ul style="width:15em; text-align:left;"> <!-- 2.1 Implant Restorations --> <li> <a href="implant.php"> Implant Restorations </a> </li> <!-- 2.2 Crown Bridge--> <li> <a href="crown_bridge.php"> Crown & Bridge </a> </li> <!-- 2.3 Braces--> <li> <a href="braces.php"> Braces </a> </li> <!-- 2.4 Cosmetic Dentistry--> <li> <a href="cosmetic_dentistry.php"> Cosmetic Dentistry </a> </li> <!-- 2.5 Prosthetic--> <li> <a href="prosthetic.php"> Prosthetic </a> </li> <!-- 2.6 Root Canal & Filling --> <li> <a href="root_canals.php"> Root Canals & Filling </a> </li> </ul> <!-- 3 About Us--> <li> <a href="#" class="sf-with-ul">About Us<span class="sf-sub-indicator"> »</span></a> <ul style="width:12em; text-align:left;"> <!-- 3.1 Meet Dr. Nazeef --> <li> <a href="dr_nazeefshah.php">Meet Dr. Nazeef</a> </li> <!-- 3.2 Our Facility --> <li> <a href="facility.php">Our Facility </a> </li> </ul> </li> <!--4 Testiomials--> <li > <a href="testimonials.php">Testimonials</a> </li> <!--5 Contact Us--> <li > <a href="#" class="sf-with-ul">Contact Us<span class="sf-sub-indicator"> »</span></a> <ul style="width:14em; text-align:left;"> <!--5.1 Contact Form--> <li> <a href="contact_form.php">Contact Form</a> </li> <!--5.2 Office/Maps--> <li> <a href="maps.php">Office/Map Directions</a> </li> </ul> </li> </ul> </nav> </header> <!-- Slide show --> <div id="hero"> <img src="images/Advanced_Cosmetic_Dentistry.jpg" alt=""/> <img src="images/Modern_Treatment_Methods.jpg" alt=""/> <img src="images/The_Art_of_the_Smile.jpg" alt=""/> <!-- <img src="images/secretary-slide.jpg" alt=""/> --> </div> <div id="holiday_notification"> Clinic will remain closed until September 19, 2016!! &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Appointments can still be made by calling 0333 5192837 </div> <file_sep>/contact_form.php <?php require('header.php'); ?> <article id="main"> <div id="prosthetic"> <h1>Contact Us</h1> <p> Please fill out this form and we’ll get in touch right away. <br>Or, if you’d prefer, you can call us at: <b>(051) 2299447</b> <p> <form name="contactform" method="post" action="contact_form_success.php"> <table width="450px"> <tr> <td valign="top"> <label for="first_name">First Name *</label> </td> <td valign="top"> <input type="text" name="first_name" maxlength="50" size="30"> </td> </tr> <tr> <td valign="top"> <label for="last_name">Last Name *</label> </td> <td valign="top"> <input type="text" name="last_name" maxlength="50" size="30"> </td> </tr> <tr> <td valign="top"> <label for="email">Email Address *</label> </td> <td valign="top"> <input type="text" name="email" maxlength="80" size="30"> </td> </tr> <tr> <td valign="top"> <label for="telephone">Telephone Number</label> </td> <td valign="top"> <input type="text" name="telephone" maxlength="30" size="30"> </td> </tr> <tr> <td valign="top"> <label for="comments">Comments *</label> </td> <td valign="top"> <textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea> </td> </tr> <tr> <td colspan="2" style="text-align:center"> <input type="submit" value="Submit"> </td> </tr> </table> </form> </div> </article> <?php require('footer.php'); ?><file_sep>/header.php <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link rel="shortcut icon" href="images/favicon.ico" > <title id="page_title">Nazeef Dental Clinic | Islamabad Dentist | Islamabad Dental Surgeon| <NAME></title> <!-- Add jQuery library --> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <!-- link to the CSS files for this menu type --> <link rel="stylesheet" type="text/css" href="style/main.css" > <link href="style/superfish.css" rel="stylesheet" type="text/css"> <!-- link to the JavaScript files--> <!--</script> <script src="javascripts/jquery.js"></script>--> <!--(hoverIntent is optional) --> <script src="javascripts/jquery.hoverIntent.js"></script> <script src="javascripts/superfish.js"></script> <!-- initialise Superfish --> <script> $(document).ready(function(){ $('ul.sf-menu').superfish(); }); </script> <!-- include jQuery library --> <!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>--> <!-- include Cycle plugin --> <script type="text/javascript" src="http://malsup.github.com/jquery.cycle.all.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#hero').cycle({ //slideResize: 1, //containerResize: 0, width: '100%', //height:'100%', fit: 1, //next: '#next', //prev: '#prev', fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc... speed: 2000, timeout: 2000 }); }); </script> <!--Slider for News updates --> <script type="text/javascript"> $(document).ready(function() { $('#slider').cycle({ fx: 'scrollUp', timeout: 6000, delay: -4000 }); }); </script> <!--Slider for Holiday Notification(Temp) --> <script> $(document).ready(function() { $('#holiday_notification').cycle({ fx: 'scrollLeft', speed: 5000, continuous: 1 }); }); </script> <!-- Add jQuery library --> <!--<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>--> <!-- Add fancyBox --> <link rel="stylesheet" href="style/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" /> <script type="text/javascript" src="javascripts/jquery.fancybox.pack.js?v=2.1.5"></script> <!-- Optionally add helpers - button, thumbnail and/or media --> <link rel="stylesheet" href="style/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" /> <script type="text/javascript" src="javascripts/jquery.fancybox-buttons.js?v=1.0.5"></script> <script type="text/javascript" src="javascripts/jquery.fancybox-media.js?v=1.0.6"></script> <link rel="stylesheet" href="style/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" /> <script type="text/javascript" src="javascripts/jquery.fancybox-thumbs.js?v=1.0.7"></script> <script type="text/javascript"> $(document).ready(function() { $(".img-pop").fancybox({ openEffect : 'elastic', closeEffect : 'elastic', helpers : { title : { type : 'inside' } } }); }); </script> <!--<script> $(window).resize(function(){ $('#hero').each(function(){ newWidth = $(this).parent('div').width() $(this).width(newWidth) $(this).children('div').width(newWidth) }); }); </script>--> <!-- gigya.js script should only be included once --> <script type="text/javascript" src="http://cdn.gigya.com/js/gigya.js?apiKey=<KEY>"> </script> <!-- Google Maps --> <script src="https://maps.googleapis.com/maps/api/js?client=737813904197-3ffp83f9fgs2a4hrcp0101dq489u8qpt.apps.googleusercontent.com&sensor=false&v=3.16"></script> <script src="http://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false"> </script> <script> var myCenter=new google.maps.LatLng(33.695895,73.013207); function initialize() { var mapProp = { center:myCenter, zoom:15, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp); var marker=new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"Nazeef Dental Clinic" }); infowindow.open(map,marker); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <!-- Google Analytics START--> <?php include_once("analyticstracking.php") ?> <!-- Google Analytics END--> <div id="wrapper"> <!--Header--> <header id="top"> <!-- Logo --> <img src="images/headerLogo.png" alt="Dental Clinic Logo" width="420" id="logo"/> <!--Address--> <p id="address"> Shop #19-20, Block 7-B,<br> Warraich-Plaza, F-10 Markaz,<br> 44000, Islamabad, Pakistan<br> 051 2299447,0333 5192837 </p> <!-- Navigation bar --> <nav id="mainnav"> <ul class="sf-menu"> <!-- 1 Home --> <li> <a href="index.php" id="#">Home</a> </li> <!-- 2 Procedures--> <li><a href="#" class="sf-with-ul">Procedures<span class="sf-sub-indicator"> »</span> </a> <ul style="width:15em; text-align:left;"> <!-- 2.1 Implant Restorations --> <li> <a href="implant.php"> Implant Restorations </a> </li> <!-- 2.2 Crown Bridge--> <li> <a href="crown_bridge.php"> Crown & Bridge </a> </li> <!-- 2.3 Braces--> <li> <a href="braces.php"> Braces </a> </li> <!-- 2.4 Cosmetic Dentistry--> <li> <a href="cosmetic_dentistry.php"> Cosmetic Dentistry </a> </li> <!-- 2.5 Prosthetic--> <li> <a href="prosthetic.php"> Prosthetic </a> </li> <!-- 2.6 Root Canal & Filling --> <li> <a href="root_canals.php"> Root Canals & Filling </a> </li> </ul> <!-- 3 About Us--> <li> <a href="#" class="sf-with-ul">About Us<span class="sf-sub-indicator"> »</span></a> <ul style="width:12em; text-align:left;"> <!-- 3.1 Meet Dr. Nazeef --> <li> <a href="dr_nazeefshah.php">Meet Dr. Nazeef</a> </li> <!-- 3.2 Our Facility --> <li> <a href="facility.php">Our Facility </a> </li> </ul> </li> <!--4 Testiomials--> <li > <a href="testimonials.php">Testimonials</a> </li> <!--5 Contact Us--> <li > <a href="#" class="sf-with-ul">Contact Us<span class="sf-sub-indicator"> »</span></a> <ul style="width:14em; text-align:left;"> <!--5.1 Contact Form--> <li> <a href="contact_form.php">Contact Form</a> </li> <!--5.2 Office/Maps--> <li> <a href="maps.php">Office/Map Directions</a> </li> </ul> </li> </ul> </nav> </header> <!-- Slide show --> <!--<div id="hero" style="position: relative;"> <img src="images/Advanced_Cosmetic_Dentistry.jpg" alt="Visiting area picture" style="position: absolute; top: 0px; left: 0px; display: none; z-index: 3; opacity: 0; width:900px; height:230px;"/> <img src="images/The_Art_of_the_Smile.jpg" alt="Treating the patient" style="position: absolute; top: 0px; left: 0px; display: none; z-index: 3; opacity: 0; width:900px; height:230px;"/> <img src="images/secretary-slide.jpg" alt="secratary" style="position: absolute; top: 0px; left: 0px; display: none; z-index: 3; opacity: 0; width:900px; height:230px;"/> </div>--> <div id="hero" > <img src="images/Advanced_Cosmetic_Dentistry.jpg" alt=""/> <img src="images/Modern_Treatment_Methods.jpg" alt=""/> <img src="images/The_Art_of_the_Smile.jpg" alt=""/> <!-- <img src="images/secretary-slide.jpg" alt=""/> --> </div> <div id="holiday_notification"> <div> <p>Clinic will remain closed until September 19, 2016!!</p></div> <div><p></p></div> <div><p>Appointments can still be made by calling 0333 5192837</p></div> <div><p></p></div> </div><file_sep>/root_canals.php <?php require('header.php'); ?> <article id="main"> <div id="root_canals"> <h1>Endodontics & Root Canals</h1> <p> Endodontics, more commonly known as root canal, is the prevention, diagnosis and treatment of disorders of the dental pulp (the soft tissue inside the tooth). </p> <p> Root canal therapy is a remarkable treatment with a very high rate of success, and involves removing the diseased tissue, halting the spread of infection and restoring the healthy portion of the tooth. In fact, root canal therapy is designed to save a problem tooth; before the procedure was developed and gained acceptance, the only alternative for treating a diseased tooth was extraction. </p> <h2>Procedure</h2> <p> Root canal therapy usually entails one to three visits. During the first visit, a small hole is drilled through the top of the tooth and into the inner chamber. Diseased tissue is removed, the inner chamber cleansed and disinfected, and the tiny canals reshaped. The cleansed chamber and canals are filled with an elastic material and medication designed to prevent infection. If necessary, the drilled hole is temporarily filled until a permanent seal is made with a crown. </p> <p> Most patients who have root canal experience little or no discomfort or pain, and enjoy a restored tooth that can last almost as long as its healthy original.</p> </div> </article> <?php require('footer.php'); ?><file_sep>/cosmetic_dentistry.php <?php require('header.php'); ?> <article id="main"> <div id="cosmetic_dentistry"> <h1>Cosmetic Dentistry</h1> <h2 id="Teeth_Whitening">Teeth Whitening</h2> <p> We can help you dramatically whiten your teeth in just about an hour with the scientifically advanced ZOOM! Teeth Whitening System. The ZOOM! Chair side Whitening System is safe, fast and effective.</p> <p> Extensive clinical and research studies indicate that dentist supervised teeth whitening is safe. Almost everyone can benefit from teeth whitening in order to remove tooth discoloration caused by coffee, colas, tobacco, red wine, tea, aging, old restorations or use of antibiotics.</p> <p> Crowns are also used to attach bridges, cover implants, prevent a cracked tooth from becoming worse, or an existing filling is in jeopardy of becoming loose or dislocated. Crowns also serve an aesthetic use, and are applied when a discolored or stained tooth needs to be restored to its natural appearance.</p> <p> We also offer home bleaching tooth whitening. With this system, you can whiten your teeth at home at your convenience. </p> </div> </article> <?php require('footer.php'); ?><file_sep>/maps.php <?php require('header_pre.php'); ?> <title id="page_title">Address and Opening Timings</title> <meta name="description" content="Location in Google maps and Opening timings of the clinic"> <meta name="keywords" content="Location,Address,Timings"> <?php require('header_post.php'); ?> <article id="main"> <div id="maps"> <h1>Contact Information</h1> <dl> <dt>Opening Timings</dt> <dd>Mon- Sat : 10:00AM-2:00PM<br> <span id="timing">4:00PM-10:00PM<span></dd> <dt>Address</dt> <dd> Shop #19-20, Block 7-B,<br> Warraich-Plaza, F-10 Markaz,<br> 44000, Islamabad, Pakistan</dd> <dt>Phone</dt> <dd> 051 2299447<br> 0333 5192837 </dd> </dl> <h1>Directions on Google Maps</h1> <div> <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d829.8788053063391!2d73.0128891785104!3d33.69561473606508!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x38dfbe6b3b5cf1cb%3A0xae36808ad3ac5006!2sNazeef+Dental+Clinic!5e0!3m2!1sen!2sde!4v1402516038963" width="600" height="450" frameborder="0" style="border:0"></iframe> </div> </article> <?php require('footer.php'); ?><file_sep>/braces.php <?php require('header.php'); ?> <article id="main"> <div id="braces"> <h1>Braces</h1> <p> For most people, a beautiful smile is the most obvious benefit of orthodontics. After your braces come off, you'll feel more self-confident. During your treatment, we want you to feel as comfortable as possible. </p> <h2>How Orthodontic Treatment Works</h2> <p> Orthodontic appliances can be made of metal, ceramic, or plastic. They may be removable or they may be brackets bonded to the teeth. By placing a constant, gentle force in a carefully controlled direction, braces slowly move teeth to a corrected position. This is a great time to wear braces! Gone are the days when a metal band with a bracket was placed around each tooth. You can choose brackets that are clear or metallic color. You can choose the color of the ties that hold the wire in brackets. Wires are also less noticeable than they used to be and the latest materials move teeth faster with less discomfort to patients. </p> <h2>Orthodontics for Children</h2> <p> It's best for the orthodontist to see children by age 7 to advise if orthodontic treatment is required and it is the best time for that patient to be treated. The first permanent molars and incisors have usually come in by that time and crossbites, crowding, and other problems can be evaluated. When treatment is begun early, the orthodontist can guide the growth of the jaw and guide incoming permanent teeth. Early treatment can also regulate the width of the upper and lower dental arches, gain space for permanent teeth, avoid the need for permanent tooth extractions, reduce likelihood of impacted permanent teeth, correct thumb-sucking, and eliminate abnormal swallowing or speech problems. In other words, early treatment can simplify later treatment. </p> <h2>Orthodontics for Adults</h2> <p> Orthodontic treatment can be successful at any age, and adults especially appreciate the benefits of a beautiful smile. One of every five patients in orthodontic treatment is over 21. </p> <h2>Duration of Treatment</h2> <p> Treatment time typically ranges from one to three years, depending on the growth of the patient's mouth and face and the severity of the problem. Patients grow at different rates and will respond variously to orthodontic treatment, so the time to case completion may differ from the original estimate. The patient's diligent use of any prescribed rubber bands or headgear is an important factor in achieving the most efficient treatment. Interceptive, or early treatment procedures, may take as few as six months. </p> </div> </article> <?php require('footer.php'); ?><file_sep>/notfound.php <?php header("HTTP/1.0 404 Not Found"); require('header_pre.php'); ?> <title id="page_title">Error Page not found</title> <meta name="description" content="Error 404 Page not found"> <meta name="keywords" content=""> <?php require('header_post.php'); ?> <article id="main"> <h1> Page not found! </h1> <div id="#error"> <!--Script for 404 Error from Google --> <script type="text/javascript"> var GOOG_FIXURL_LANG = 'en'; var GOOG_FIXURL_SITE = 'http://www.nazeefdentalclinic.info' </script> <script type="text/javascript" src="http://linkhelp.clients.google.com/tbproxy/lh/wm/fixurl.js"> </script> </div> </article> <?php require('footer.php'); ?><file_sep>/facility.php <?php require('header.php'); ?> <article id="main"> <h1>Our Facility</h1> <!--Dental Clinic Pictures --> <div id="#facility"> <figure class="facility centered"><img src="images/working-on-patient-image.JPG"/><figcaption class="facility">Dr. Nazeef Working on the patient</figcaption></figure> <figure class="facility centered"> <img src="images/secretary-image.JPG"/><figcaption class="facility">Waiting area</figcaption></figure> </div> </article> <?php require('footer.php'); ?><file_sep>/crown_bridge.php <?php require('header.php'); ?> <article id="main"> <div id="crown_bridge"> <h1>Crown</h1> <p> As time passes, our teeth begin to weaken. Large cavities, pressure from chronic grinding, and physical trauma can put our teeth in danger of cracks and breaks. Taking action before our teeth succumb to breaks will preserve natural structure and help prevent the need for a root canal or extraction. Porcelain crowns will encompass and protect weakened teeth while improving the look of your smile. And we think that’s a winning combination. </p> <h2> Reasons to Get Dental Crowns </h2> <p> Crowns are appropriate in so many situations, so we’ve listed the three main instances in which crowns are helpful:</p> <ul> <li> Strengthening a tooth – When tooth structure has been damaged by decay or an accident, the tooth may falter. It could succumb to a serious break or to infection without fresh support. A dental crown will cap the tooth and protect remaining structure. Crowns are also helpful after root canals, to preserve the treated teeth.</li> <li> Improving a tooth’s appearance – The cosmetic changes possible with dental crowns are too numerous to list; suffice it to say that crowns can make nearly any alteration possible. Because they add a great deal of structure, they can be right for more involved changes than porcelain veneers. Several crowns will completely rebuild and transform your smile.</li> <li> Replacing a missing tooth – A crown paired with a dental implant will replace the entirety of a tooth, both above and below the gum line. Crowns are also an indispensable component of dental bridges. Crowns will rebuild your smile without draining any of its beauty. Learn more by getting in touch with our office. </li> </ul> <h1>Bridge</h1> <p>A bridge allows the dentist to replace lost teeth without the use of a denture or dental implant. Basically a false tooth is held in place by being attached to a tooth next door. The disadvantage is that the teeth next to the space have to be prepared in a similiar way to a crown in order to accept the bridge. If these teeth already have crowns or big restorations then this is not a problem, the major concern however is when these teeth have small or no restorations (fillings). One compromise is the 'acid etched bridge', with this type a fine ledge is placed on the back of the adjacent teeth</p> <p> One disadvantage of a bridge is that the patient should wait three months before placement as the 'gum' shrinks' after a tooth is extracted. If the bridge was fitted early a gap would appear underneath the pontic (the false tooth). At the back of the mouth this may not be a problem, at the front of the mouth however this may appear as a black line along the gum.</p> </div> </article> <?php require('footer.php'); ?><file_sep>/index.php <?php require('header_pre.php'); ?> <title id="page_title">Nazeef Dental Clinic - dentist, dental implants</title> <meta name="description" content="We provide the best dental services including cosmetic dentistry, dentures, implants, braces and more in Islamabad region. Dr. Nazeef has 40 years of experience."> <meta name="keywords" content="Islamabad Dental Surgeon,Islamabad Dentist, Dentist in Islamabad, Dental Clinic Islamabad"> <?php require('header_post.php'); ?> <article id="main"> <!-- Introduction division--> <div id="intro"> <h1>Nazeef Dental Clinic; a place to meet your professional dentist needs in Islamabad</h1> <!--Potrait image with fancy box--> <a class="img-pop" href="images/potraitA_big.jpg" title="Dr. <NAME>"> <figure class="potrait floatleft"><img src="images/potraitA_thumb.jpg" alt="<NAME>"/> <figcaption class="potrait">Dr. <NAME></figcaption> </figure> </a> <div id="description"> <p>Dr. <NAME> and staff welcome you to our office. We are committed to delivering uncompromising excellence in dental care. Our mission is to provide a compassionate professional environment to make your experience safe and comfortable. We provide advanced dental and cosmetic services using the latest technologies and best materials. We closely work with dental specialists to provide comprehensive treatment with best results.</p> <p>If you are looking for an experienced dentist in Islamabad for general dental or cosmetic work including dental implants, Dr. Nazeef and his team strive to make your experience positive and enjoyable. The first step towards looking and feeling your best is to schedule your initial consultation. Please contact NAZEEF DENTAL CLINIC today at <span class="tel_num">(051)-2299447</span> or email us at <a href="mailto:<EMAIL>"><span class="email_addr"><EMAIL></span></a>. </p> </div> </div> <div id="services"> <h2>Featured Services</h2> <h3>Dental Implants</h3> <p>When one loses a tooth to decay, damage, or age, that smile is compromised. We hope to restore it in a way that maintains the smile’s natural integrity. With dental implants, replacement teeth become as secure as your natural teeth. Implants are the most biologically and aesthetically ideal tooth replacement option.<a href="implant.php">More info…</a> </p> <h3>Braces</h3> <p>For most people, a beautiful smile is the most obvious benefit of orthodontics. After your braces come off, you'll feel more self-confident. During your treatment, we want you to feel as comfortable as possible.<a href ="braces.php" >More info…</a></p> <h3></h3> <p> </p> <h3>Teeth Whitening</h3> <p> Coffee, cigarettes, tea, aging, and even certain medications can discolor your teeth to such an extent that you may not want to smile. Zoom laser whitening is a popular procedure, and so is at-home tooth bleaching. We are happy to discuss the teeth bleaching method that might work best for you. Gain a beautiful smile. <a href="cosmetic_dentistry.php#Teeth_Whitening">More info…</a> </p> </div> </article> <?php require('footer.php'); ?><file_sep>/testimonials.php <?php require('header.php'); ?> <article id="main"> <h1>Testimonials</h1> <!-- <blockquote class="testi"> "Dr. Nazeef has been treating my whole family for the past 6 years and we are very satisfied. His skills and experience are well known and we are all very happy that we have a dentist who knows what he is doing but has no airs about himself. When we visited UK, my wife had a tooth accident but she adamantly refused to see anyone there and bore the pain until we came back to see Dr. Nazeef. Its just a matter of trust. I highly recommend him." </blockquote> <span class="tesi-namedates"> <cite> skhan </cite> on 19-Mar-2011 </span> <blockquote class="testi"> "A very competent dentist. Dr. Nazeef has been my dentist for the past 15 years and I absolutely trust his knowledge and skills. He helped me when my previous dentist had gotten me into so many complications with my fillings and extractions and then I went to him and he rectified all my problems. May God give him long life. I will recommend him to anyone who is in need of a competent and kind hearted dentist." </blockquote> <span class="tesi-namedates"> <cite> mr_kyani </cite> on 05-Jan-2011 </span > --> <div id='ratingDiv'></div> <div id="commentsDiv" ></div> <script type='text/javascript'> // Present the Rating plugin var ratingsParams = { categoryID: 'TestimonialsWiki', // Comments category ID (from Comments Setup page) streamID: 'ReviewsTest', containerID: 'ratingDiv', linkedCommentsUI: 'commentsDiv' // link the Ratings plugin to the Comments plugin. //The '# reviews' link becomes an anchor to the Comments plugin on the page. } gigya.comments.showRatingUI(ratingsParams); // Present the Review(Comments) plugin var params ={ categoryID: 'TestimonialsWiki', streamID: 'ReviewsTest', containerID: 'commentsDiv', cid:'', enabledShareProviders: 'facebook,twitter,yahoo,linkedin' } gigya.comments.showCommentsUI(params); </script> </article> <?php require('footer.php'); ?><file_sep>/dr_nazeefshah.php <?php require('header_pre.php'); ?> <title id="page_title">Dr. <NAME></title> <?php require('header_post.php'); ?> <article id="main"> <h1>Meet the dentist</h1> <!--Potrait image with fancy box--> <a class="img-pop" href="images/potrait_big.jpg" title="Dr. <NAME>"> <figure class="potrait floatright"><img src="images/potrait_thumb.jpg"/><figcaption class="potrait">Dr. <NAME></figcaption></figure> </a> <p> Dr. Nazeef is devoted to providing quality personal dental care. His treatment approach combines the most innovative techniques and state-of-the-art appliances and equipment. He enjoys creating long-term relationships with his patients and their families.</p> <p>Dr. Nazeef received his Dental Medicine Doctrine degree from the Kyber Medical & Dental College (1974), and his postgraduate certificate from Iran (1978). Later on, he did his specalization in Orthodontics from Manilla and recently acquiring an implantology degree from USA.</p> <p>Dr. Nazeef is a member of Pakistan Dental Association(PDA) and the American Denal Association(ADA) and attends various training seminars in USA on a regular basis.</p> <p>Dr. <NAME> has two wonderful children and spends most of his free time with his family.</p> <p> Dr. <NAME> is a Islamabad,Pakistan dentist specializing in general and cosmetic dentistry including inlays and veneers, crowns and bridges,implants and dentures, root canals, and teeth whitening. Serving the Islamabad and Rawalpindi areas.</p> <p>Whether you are considering general or cosmetic dental work, Dr. Nazeef and his team strive to make your experience positive and enjoyable. The first step towards looking and feeling your best is to schedule your initial consultation. Please contact NAZEEF DENTAL CLINIC today at <span class="tel_num">(051)-2299447</span> or email us at <a href="mailto:<EMAIL>"><span class="email_addr"><EMAIL></span></a>. </p> </article> <?php require('footer.php'); ?><file_sep>/prosthetic.php <?php require('header.php'); ?> <article id="main"> <div id="prosthetic"> <h1>Prosthetic</h1> <h2>Fixed & Removable Dentures</h2> <p> A Denture is a set of false teeth. This can be made of acrylic, fiber-glass, metal, or a combination of these materials. A denture is generally made to replace missing teeth that are not possible to replace by a fixed bridge. This means that a fixed bridge is superior to a removable denture, but there are situations when it is technically not possible to make a bridge. A denture that replaces some teeth is called a Partial denture, while one that replaces all teeth is called a Full or Complete denture. Immediate denture is the type of denture that we insert in same appointment right after removing teeth.</p> <p> Getting a denture made can prevent problems that arise when missing teeth are not replaced:</p> <ul> <li>Inability to eat properly.</li> <li>Appearance problems - missing teeth in the front of the mouth are obviously visible. The lips and cheeks may also sink-in to give a wrinkled appearance.</li> <li>Drifting of adjoining teeth and over-eruption of opposing teeth.</li> </ul> <p> We can begin constructing your denture once the extraction sockets have healed and your mouth has been rid of any existing infection. In some cases we can construct the denture before removing teeth, so you don't have to leave the office without teeth. The mouth has to be healthy to be able to take the additional load of a denture. After examining your mouth your dentist can recommend the denture that will suit you.</p> <p> A well-made denture will help you eat better, feel better and look better. But these dentures have a life span, depending on the material chosen. After a denture has given it's life it needs to be replaced to prevent damaging your mouth.</p> <p> It is very important to look after your dentures properly to ensure that they serve you well. Dentures need to be removed after every meal, cleaned and then reinserted.</p> <p> They must be removed at night and stored in water - this gives the mouth some rest - please remember that the parts of your mouth supporting the denture were not originally designed for this purpose. It is necessary to thorough clean your dentures at least once every day to remove the accumulated deposits.</p> <p> Your new dentures are likely to hurt for some time after being inserted in the mouth. This should settle down within a few days. This is something new for the mouth and the mouth will need some days to adjust. If your dentures still hurt after the initial period, you may need to get them adjusted.</p> <p> It is important to appreciate that a denture is basically a compromise. Only when other solutions are not possible will your dentist think of making a denture. But then having some teeth to chew with and show-off is better than having nothing in the mouth.</p> </div> </article> <?php require('footer.php'); ?><file_sep>/implant.php <?php require('header.php'); ?> <article id="main"> <!--<div id="implant">--> <h1>Dental Implants</h1> <figure class="implant_description floatright"> <img src="images/implant_description.gif"/> <figcaption class="implant_description">Implant Procedural Steps</figcaption> </figure> <p> Modern advances in dental science now allow us to offer patients multiple options to help you enjoy a functional, secure, confident and beautiful smile -- all in our office. One of the many safe, successful and proven procedures is dental implants. It involves the installation of permanent replacement teeth supported by artificial dental root forms called dental implants. These tooth replacements look, feel and function like natural teeth. Dental implants have solved many problems associated with tooth loss that previously required replacement by removable full or partial dentures. </p> <p> The procedure, referred to as osseo or biointegration, provides patients with the comfort and assurance of permanent teeth. Many patients find that dental implants restore their self-confidence and self-esteem and improve their quality of life. </p> <p> Dental implants are designed to provide a foundation for replacement teeth that look, feel, and function like natural teeth. After the procedure the patient regains the ability to eat virtually anything and can smile with confidence, knowing that teeth appear natural and that facial contours will be preserved. The implants themselves are titanium posts that are placed into the jawbone where teeth are missing. The bone bonds with the titanium or bioceramic surface coating on top of the titanium alloy, creating a strong foundation for artificial teeth. In addition, implants can help preserve facial structure, preventing the bone deterioration which occurs when teeth are missing. </p> <p> Dental implants are a great way to replace missing teeth. Implants also provide excellent support and stability for removable partial or complete dentures when dental appliances are required. </p> <h2>Reasons for Dental Implants</h2> <ul> <li> Replace one or more missing teeth without affecting adjacent teeth. </li> <li> Resolve joint pain or bite problems caused by teeth shifting into missing tooth space. </li> <li> Restore a patient’s confident smile. </li> <li> Restore chewing, speech, and digestion. </li> <li> Restore or enhance facial tissues. </li> <li> Support a bridge or denture, making them more secure and comfortable. </li> </ul> <p> Dental implants are changing the way people live! With them, people are rediscovering the comfort and confidence to eat, speak, laugh and enjoy life. </p> <!--</div>--> </article> <?php require('footer.php'); ?>
2beb9c7e70e814c89dc1c8105606079d9834fc3c
[ "PHP" ]
15
PHP
wahabshah/clinic-website
812e412e75e904ca369a91a221e9378399594a21
90595b02821c0659202f1fb6b3ce31167bfc8518
refs/heads/master
<file_sep>thirdplot <- function() { # use read.table() to read the text data file into R alldata <- read.table("./household_power_consumption.txt", header = TRUE, sep = ";") # subset the two days in February into an R object data <- alldata[which(alldata$Date == "1/2/2007" | alldata$Date == "2/2/2007"), ] # copy the subset to another object for comparison data2 <- data # change the classes of columns 3-8 from factor to numeric for(i in 3:8) { data2[, i] <- as.numeric(as.character(data[, i])) } # combine the Date and Time columns into one column called Date/Time # and use as.Date() to set the values/class of the Date column temp <- paste(data$Date, data$Time) temp2 <- strptime(temp, "%d/%m/%Y %H:%M:%S") data2$Date <- as.Date(temp2) data2$Time <- temp2 names(data2)[2] <- "DateTime" # reset the graphic parameters and set mfrow for one plot graphic_default <- par(no.readonly = TRUE) par(graphic_default) par(mfrow = c(1, 1)) # generate the plot of plot3 plot(data2$DateTime, # the data for the x-axis data2$Sub_metering_1, # first set of data for the y-axis type = "l", # plot type is line xlab = "", # no label for the x-axis ylab = "Energy sub metering", # label for the y-axis cex.lab = 0.7, # set the font size for the labels cex.axis = 0.7 # set the width of the axes ) # second set of data for the y-axis lines(data2$DateTime, data2$Sub_metering_2, type = "l", col = "red") # third set of data for the y-axis lines(data2$DateTime, data2$Sub_metering_3, type = "l", col = "blue") # add a legend legend("topright", # place the legend in the upper right c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), # label each of the three plots lty= c(1, 1, 1), # each plot is line type lwd = c(1.5, 1.5, 1.5), # set the width of each colored line in the legend col = c("black", "red", "blue"), # set the color of each plot cex = 0.7, # set the font size of the plot labels seg.len = 1, # adjust the length of each colored line in the legend adj = c(-0.1, 0.5), # adjust the spacing between the legend text and the upper right plot corner x.intersp = -0.1, # adjust the spacing between the colored lines and plot labels y.intersp = 0.8 # adjust the vertical spacing of plot labels ) # copy the graphic to a png device called plot3.png dev.copy(png, file = "plot3.png") dev.off() }<file_sep>secondplot <- function() { # use read.table() to read the text data file into R alldata <- read.table("./household_power_consumption.txt", header = TRUE, sep = ";") # subset the two days in February into an R object data <- alldata[which(alldata$Date == "1/2/2007" | alldata$Date == "2/2/2007"), ] # copy the subset to another object for comparison data2 <- data # change the classes of columns 3-8 from factor to numeric for(i in 3:8) { data2[, i] <- as.numeric(as.character(data[, i])) } # combine the Date and Time columns into one column called Date/Time # and use as.Date() to set the values/class of the Date column temp <- paste(data$Date, data$Time) temp2 <- strptime(temp, "%d/%m/%Y %H:%M:%S") data2$Date <- as.Date(temp2) data2$Time <- temp2 names(data2)[2] <- "DateTime" # reset the graphic parameters and set mfrow for one plot graphic_default <- par(no.readonly = TRUE) par(graphic_default) par(mfrow = c(1, 1)) # generate the plot of plot2 plot(data2$DateTime, # data for the x-axis data2$Global_active_power, # data for the y-axis type = "l", # plot type is line xlab = "", # no label for the x-axis ylab = "Global Active Power (kilowatts)", # label the y-axis cex.lab = 0.7, # set the font size for the labels cex.axis = 0.7 # set the width of the axes ) # copy the graphic to a png device called plot2.png dev.copy(png, file = "plot2.png") dev.off() }<file_sep>firstplot <- function() { # use read.table() to read the text data file into R alldata <- read.table("./household_power_consumption.txt", header = TRUE, sep = ";") # subset the two days in February into an R object data <- alldata[which(alldata$Date == "1/2/2007" | alldata$Date == "2/2/2007"), ] # copy the subset to another object for comparison data2 <- data # change the classes of columns 3-8 from factor to numeric for(i in 3:8) { data2[, i] <- as.numeric(as.character(data[, i])) } # combine the Date and Time columns into one column called Date/Time # and use as.Date() to set the values/class of the Date column temp <- paste(data$Date, data$Time) temp2 <- strptime(temp, "%d/%m/%Y %H:%M:%S") data2$Date <- as.Date(temp2) data2$Time <- temp2 names(data2)[2] <- "DateTime" # reset the graphic parameters and set mfrow for one plot graphic_default <- par(no.readonly = TRUE) par(graphic_default) par(mfrow = c(1, 1)) # generate the histogram of plot1 hist(data2$Global_active_power, # use global active power col = "red", # make the bars of the histogram red main = "Global Active Power", # label the main title of the plot cex.main = 0.9, # adjust the main title font size as desired xlab = "Global Active Power (kilowatts)", # label the x-axis of the plot cex.lab = 0.7, # adjust the x- and y-label font size as desired freq = TRUE, # plot the counts of global active power axes = FALSE # generate the axes ticks separately below ) # set the tick marks and magnification of axis annotation for each axis axis(2, at=seq(0, 1200, 200), cex.axis = 0.7) axis(1, at=seq(0, 6, 2), cex.axis = 0.7) # copy the graphic to a png device called plot1.png dev.copy(png, file = "plot1.png") dev.off() } <file_sep>fourthplot <- function() { # use read.table() to read the text data file into R alldata <- read.table("./household_power_consumption.txt", header = TRUE, sep = ";") # subset the two days in February into an R object data <- alldata[which(alldata$Date == "1/2/2007" | alldata$Date == "2/2/2007"), ] # copy the subset to another object for comparison data2 <- data # change the classes of columns 3-8 from factor to numeric for(i in 3:8) { data2[, i] <- as.numeric(as.character(data[, i])) } # combine the Date and Time columns into one column called Date/Time # and use as.Date() to set the values/class of the Date column temp <- paste(data$Date, data$Time) temp2 <- strptime(temp, "%d/%m/%Y %H:%M:%S") data2$Date <- as.Date(temp2) data2$Time <- temp2 names(data2)[2] <- "DateTime" # reset the graphic parameters graphic_default <- par(no.readonly = TRUE) par(graphic_default) # generate the plot of plot4 # set mfrow for two plots on top of two plots par(mfrow = c(2, 2)) # create the four different plots with(data2, { # first plot in upper left with arguments similar to previous plots plot(data2$DateTime, data2$Global_active_power, type = "l", xlab = "", ylab = "Global Active Power", cex.lab = 0.7, cex.axis = 0.7) # second plot in upper right with arguments mostly similar to previous plots plot(data2$DateTime, Voltage, type = "l", xlab = "datetime", ylab = "Voltage", cex.lab = 0.7, cex.axis = 0.7) # third plot in lower left similar to plot3 with some different arguments for the legend plot(data2$DateTime, data2$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering", cex.lab = 0.7, cex.axis = 0.7) lines(data2$DateTime, data2$Sub_metering_2, type = "l", col = "red") lines(data2$DateTime, data2$Sub_metering_3, type = "l", col = "blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty= c(1, 1, 1), lwd = c(1.5, 1.5, 1.5), col = c("black", "red", "blue"), cex = 0.7, seg.len = 1.0, adj = c(-0.22, 0.5), # adjust the spacing between the legend text and the upper right plot corner x.intersp = -1, # adjust the spacing between the colored lines and plot labels y.intersp = 0.5, # adjust the vertical spacing of plot labels bty = "n", # remove the box border of the legend inset = c(0, -0.08) # move the legend closer to the corner of the plot ) # fourth plot in lower right plot(data2$DateTime, data2$Global_reactive_power, type = "l", xlab = "datetime", ylab = "Global_reactive_power", cex.lab = 0.7, cex.axis = 0.7) }) # copy the graphic to a png device called plot4.png dev.copy(png, file = "plot4.png") dev.off() }
ed10e64650bbc92d05e535dcf9f6d1cfa2d0aead
[ "R" ]
4
R
sams-stuff/ExData_Plotting1
ddf500c905c3ee81e66c836f402c57a64454c6ce
2392df53db19c9864eb3b3ebf45cd0f6c531074f
refs/heads/master
<repo_name>shiruken1/meteor-docker<file_sep>/Dockerfile # ------------------------------------------------------------------------------ # Start with the base image # ------------------------------------------------------------------------------ FROM phusion/baseimage:0.9.19 # Set correct environment variables ENV HOME /root ENV DEBIAN_FRONTEND noninteractive # Use Supervisor to run and manage all other services CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"] # ------------------------------------------------------------------------------ # Provision the server # ------------------------------------------------------------------------------ # Copy data COPY provision /provision COPY app /app # Set up and install RUN chmod 755 /provision/bin/setup.sh RUN /provision/bin/setup.sh # Expose ports EXPOSE 80<file_sep>/docker-ssh #!/bin/bash # docker id might be given as a parameter DID=$1 if [[ "$DID" == "" ]]; then # if no id given simply just connect to the first running instance echo "Please specify a container ID. Below are the currently running containers:" sudo docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Names}}" exit; fi sudo docker exec -it $DID /bin/bash <file_sep>/provision/bin/setup.sh #1) Install dependencies apt-get update apt-get install -y python nginx wget git vim supervisor \ sysv-rc software-properties-common unzip mongodb-server nodejs npm add-apt-repository ppa:webupd8team/java apt-get update echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections apt-get install -y oracle-java8-installer oracle-java8-set-default cd /tmp && wget https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/deb/elasticsearch/2.3.1/elasticsearch-2.3.1.deb dpkg -i elasticsearch-2.3.1.deb # curl -sL https://deb.nodesource.com/setup_0.12 | sh curl https://install.meteor.com | sh #3) Set the locale locale-gen en_US.UTF-8 # export LANG=en_US.UTF-8 export LANGUAGE=en_US:en export LC_ALL=en_US.UTF-8 update-locale LANG=en_US.UTF-8 #4) Copy files into their respective places #mkdir /var/run/sshd && chmod 0755 /var/run/sshd mkdir -p /etc/supervisord/ && mkdir /var/log/supervisord #mkdir /root/.ssh && mkdir -p /root/.ssh && chmod 700 /root/.ssh && chown root:root /root/.ssh cd /provision cp conf/supervisor.conf /etc/supervisord.conf cp conf/nginx-development /etc/nginx/sites-available/nginx-development rm /etc/nginx/sites-enabled/default ln -s /etc/nginx/sites-available/nginx-development /etc/nginx/sites-enabled/nginx-development cp service/*.conf /etc/supervisord/ #5) Set file values and permissions nginx -s reload # for MongoDB mkdir /data mkdir /data/db #6) Run commands #7) Initialize the app cd /app npm install meteor npm install --save bcrypt #8) Clean up apt-get -y --purge autoremove apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /provision <file_sep>/README.md # meteor-docker A Phusion-based docker image containing ElasticSearch, MongoDB, NginX, Supervisor and Meteor
40ceed913e494635950276c9715762fac2ceaf9d
[ "Markdown", "Dockerfile", "Shell" ]
4
Dockerfile
shiruken1/meteor-docker
69e72413b82a7660c0d5ec6459894406d0c83ca6
b8a5c7ec072198c6c2a4a4eb5c656c1c74213e73
refs/heads/master
<repo_name>mordmytro/MyCurrency<file_sep>/app/src/main/java/com/example/mycurrency/Main2Activity.java package com.example.mycurrency; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.arch.lifecycle.Observer; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class Main2Activity extends AppCompatActivity implements Observer<List<String>> { private RecyclerView recyclerView; private currencyAdapter currencyAdapter1; private LiveData<List<String>> listLiveData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); recyclerView = findViewById(R.id.recyclerView); List<String> list0 = new ArrayList<>(); currencyAdapter1 = new currencyAdapter(list0); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(currencyAdapter1); Bundle arguments = getIntent().getExtras(); String toEUR = arguments.get("1").toString(); String toGBP = arguments.get("2").toString(); String toUAH = arguments.get("3").toString(); String toRUB = arguments.get("4").toString(); String toJPY = arguments.get("5").toString(); List<String> currencies = new ArrayList<>(); currencies.add("1 USD \n = \n" + toEUR + " EUR"); currencies.add("1 USD \n = \n" + toGBP + " GBP"); currencies.add("1 USD \n = \n" + toUAH + " UAH"); currencies.add("1 USD \n = \n" + toRUB + " RUB"); currencies.add("1 USD \n = \n" + toJPY + " JPY"); listLiveData = new MutableLiveData<>(); ((MutableLiveData<List<String>>) listLiveData).setValue(currencies); listLiveData.observe(this,this); } @Override public void onChanged(@Nullable List<String> list) { currencyAdapter1.func(list); } } <file_sep>/app/src/main/java/com/example/mycurrency/API.java package com.example.mycurrency; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; interface CurrencyAPI { @GET("live?access_key=1043b6b41db493130e26be85d9f90978&currencies=USD,EUR,GBP,UAH,RUB,JPY&format=1") Call<APIData> currency(); } class APIData { public boolean success; public String terms; public String privacy; public int timestamp; public String source; class CurrencyData { public String USDUSD; public String USDEUR; public String USDGBP; public String USDUAH; public String USDRUB; public String USDJPY; } public CurrencyData quotes; } interface GraphAPI { @GET("exchange") Call<List<GraphPoint>> getDataByDate(@Query("date") String date, @Query("json") String json, @Query("valcode") String currency); } class GraphPoint { public String txt; public float rate; public String cc; public String exchangedate; public String message; } <file_sep>/app/src/main/java/com/example/mycurrency/LogPageActivity.java package com.example.mycurrency; import android.arch.persistence.room.Room; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.List; public class LogPageActivity extends AppCompatActivity { private EditText login, password; private Button btn, btn_save; public static FragmentManager fragmentManager; public static MyAppDatabase myAppDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_page); fragmentManager = getSupportFragmentManager(); myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class, "userdb").allowMainThreadQueries().build(); addListenerOnButton(); } public void addListenerOnButton () { final LogPageActivity logPageActivity = this; login = (EditText)findViewById(R.id.login); password = (EditText)findViewById(R.id.password); btn = (Button)findViewById(R.id.button); btn_save = (Button)findViewById(R.id.button_save); btn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { List<User> users = myAppDatabase.myDao().getUserPass(login.getText().toString()); for (User usr : users) { String log = usr.getUser_login(); String pass = usr.getUser_password(); if (password.getText().toString().equals(pass)) { Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(logPageActivity, MainActivity.class); intent.putExtra("1", log); startActivity(intent); } else { Toast.makeText(getBaseContext(), "Failure", Toast.LENGTH_SHORT).show(); } } } } ); btn_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String log = login.getText().toString(); String pass = password.getText().toString(); List<User> allUsers = myAppDatabase.myDao().getUserPass(login.getText().toString()); boolean bool = true; for (User usr : allUsers) { String logUser = usr.getUser_login(); if (log.equals(logUser)) { bool = false; } } if (bool) { User user = new User(); user.setUser_login(log); user.setUser_password(<PASSWORD>); myAppDatabase.myDao().addUser(user); Toast.makeText(getBaseContext(), "User added", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getBaseContext(), "Choose another login", Toast.LENGTH_SHORT).show(); } } }); } }<file_sep>/app/src/main/java/com/example/mycurrency/GraphActivity.java package com.example.mycurrency; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static com.example.mycurrency.MainActivity.firstSelected; import static com.example.mycurrency.MainActivity.secondSelected; public class GraphActivity extends AppCompatActivity { List<Float> points1 = new ArrayList<Float>(); List<Float> points2= new ArrayList<Float>(); LineGraphSeries<DataPoint> series; boolean bool = true; int days = -90; int daysToShow = days; String text = "Choose period"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_graph); final GraphActivity graphActivity = this; TextView textView = (TextView)findViewById(R.id.textView4); textView.setText(firstSelected + " to " + secondSelected + " graph"); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://bank.gov.ua/NBUStatService/v1/statdirectory/") .addConverterFactory(GsonConverterFactory.create()) .build(); GraphAPI graphAPI = retrofit.create(GraphAPI.class); for (int i = days; i <= 0; i++) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, i); Date current = calendar.getTime(); String pattern = "yyyyMMdd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String dateString = simpleDateFormat.format(current); if (firstSelected.equals("UAH")) { this.points1.add(new Float(1)); this.updateGraph(); } else { Call<List<GraphPoint>> call = graphAPI.getDataByDate(dateString, "", firstSelected); call.enqueue(new Callback<List<GraphPoint>>() { @Override public void onResponse(Call<List<GraphPoint>> call, Response<List<GraphPoint>> response) { List<GraphPoint> data = response.body(); GraphPoint point = data.get(0); graphActivity.points1.add(point.rate); graphActivity.updateGraph(); } @Override public void onFailure(Call<List<GraphPoint>> call, Throwable t) { } }); } if (MainActivity.firstSelected.equals(MainActivity.secondSelected)) { bool = false; } if (MainActivity.secondSelected.equals("UAH")) { this.points2.add(new Float(1)); this.updateGraph(); } else { Call<List<GraphPoint>> call = graphAPI.getDataByDate(dateString, "", MainActivity.secondSelected); call.enqueue(new Callback<List<GraphPoint>>() { @Override public void onResponse(Call<List<GraphPoint>> call, Response<List<GraphPoint>> response) { List<GraphPoint> data = response.body(); GraphPoint point = data.get(0); Log.e("fy", String.valueOf(point.rate)); graphActivity.points2.add(point.rate); graphActivity.updateGraph(); } @Override public void onFailure(Call<List<GraphPoint>> call, Throwable t) { } }); } } } public double min = 1000; public double max = -1000; public void updateGraph () { GraphView graph = (GraphView) findViewById(R.id.graph); List<DataPoint> dataPointArr = new ArrayList<DataPoint>(); int i = 0; for (Float p : this.points1) { if(this.points2.size() <= i){ break; } if(-i < daysToShow) break; double d = p / this.points2.get(i); if(d > max) max = d; if(d < min) min = d; dataPointArr.add(new DataPoint(i, d)); i++; } DataPoint[] dataPoints = dataPointArr.toArray(new DataPoint[dataPointArr.size()]); LineGraphSeries<DataPoint> seriesGraph = new LineGraphSeries<DataPoint>(dataPoints); graph.addSeries(seriesGraph); graph.getViewport().setMaxX(90); if (bool) { graph.getViewport().setMaxY(max); graph.getViewport().setMinY(min); } else { graph.getViewport().setMaxY(2); graph.getViewport().setMinY(0); } } public void updateGraph(int points){ GraphView graph = (GraphView) findViewById(R.id.graph); List<DataPoint> dataPointArr = new ArrayList<DataPoint>(); int i = 0; for (Float p : this.points1) { if(this.points2.size() <= i){ break; } if(-i < daysToShow) break; double d = p / this.points2.get(i); dataPointArr.add(new DataPoint(i, d)); i++; Log.e("maxmin", max + " " + min); } LineGraphSeries<DataPoint> seriesGraph = new LineGraphSeries<DataPoint>((DataPoint[])dataPointArr.toArray(new DataPoint[dataPointArr.size()])); graph.addSeries(seriesGraph); graph.getViewport().setMaxX(points); if (bool) { graph.getViewport().setMaxY(max); graph.getViewport().setMinY(min); } else { graph.getViewport().setMaxY(2); graph.getViewport().setMinY(0); } } public void on7 (View view) { daysToShow = 7; updateGraph(daysToShow); text = firstSelected + " to " + MainActivity.secondSelected + " plot " + "for 7 days"; TextView textView = (TextView)findViewById(R.id.textView4); textView.setText(text); } public void on30 (View view) { daysToShow = 30; updateGraph(daysToShow); text = firstSelected + " to " + MainActivity.secondSelected + " plot " + "for 30 days"; TextView textView = (TextView)findViewById(R.id.textView4); textView.setText(text); } public void on90 (View view) { daysToShow = 90; updateGraph(daysToShow); text = firstSelected + " to " + MainActivity.secondSelected + " plot " + "for 90 days"; TextView textView = (TextView)findViewById(R.id.textView4); textView.setText(text); } }
d138c00fffdea9136b5b0e0c5c8d46d85d5f9509
[ "Java" ]
4
Java
mordmytro/MyCurrency
f08270504d9d374279040be99dab65b6fb0f81ce
3055f7a8851b748ddf1f2d4fd01d7483d9253ca1
refs/heads/master
<file_sep>#Deadset A reworking of the amazing [semantic.gs](https://github.com/tylertate/semantic.gs/) system. Instead of margin to define columns, columns are a full width and content is defined via padding. **Because fuck presentational classes** ##How To Use Simply include the _deadset file within the appropriate language to your project as an include. Create a structure as normal and wrap each structural section with a containing class, in this case the class is 'row' but the class names are arbitrary. On that class, apply the mixin of row. For each section of content, apply the column mixin and supply the number of columns you want the element to span. Example: **HTML** <div class="wrapper"> <div class="row"> <header class="top"> // Header Content goes here \\ </header> </div> <div class="row"> <section class="content"> // Content Goes here \\ </section> <aside class="sidebar"> // Sidebar content goes here \\ </aside> </div> **SCSS** .wrapper { max-width: 1080px; margin: 0 auto; } .row { @include row(); } header.top { @include column(12); } section.content { @include column(8); } aside.sidebar { @include column(4); } ###Making things responsive. By default, the columns are set by percentage. Therefore if you want to change things on different devices, simply use a media query and provide a new value to the mixin. **SCSS** @media all and (max-width: 480) { section.content { @include column(12); } } ##Fork it, change it , do what you will. Just make awesome shit. [drewminns.com](drewminns.com) made this [@drewisthe](http://twitter.com/drewisthe)<file_sep><?php get_header(); ?> <div class="main"> <div class="container"> <div class="content singlePortfolio"> <!-- <div class="innerWrapper"> --> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div class="postImage"> <?php the_post_thumbnail('full'); ?> </div> <div class="postContent"> <div class="postInfo"> <h2><?php the_title(); ?></h2> <?php if ( get_field( 'client_name' ) ): ?> <p><strong>Client Name:</strong> <?php the_field('client_name'); ?></p> <?php endif; ?> <?php the_content(); ?> </div> <!-- /.postInfo --> <div class="postLinks"> <div class="viewAt"> <?php if ( get_field( 'live_demo') ): ?> <a href="<?php the_field('live_demo') ?>">View Live</a> <?php endif; ?> <?php if ( get_field( 'github_link' ) ): ?> <a href="<?php the_field('github_link') ?>">View On GitHub</a> <?php endif; ?> </div> <div class="technologies singleTechnologies"> <h3>Technologies Used</h3> <p class="technologies"> <?php $terms = get_the_terms($post->ID, 'technologies' ); ?> <?php if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) : ?> <ul> <?php foreach ( $terms as $term ) : ?> <li><?php echo $term->name ?></li> <?php endforeach ?> </ul> <?php endif ?> </p> <?php // the_terms($post->ID, 'technologies', '', ''); ?> </div> <div class="portNav"><?php previous_post_link('%link', 'PREV'); ?> | <?php next_post_link('%link', 'NEXT'); ?></div> </div> <!-- /.postLinks --> <div class="images"> <?php while(has_sub_field('images')) : ?> <?php //for every image/caption combo, this code is run ?> <figure> <?php $image = get_sub_field('image'); ?> <img src="<?php echo $image['sizes']['square']; ?>" alt="<?php echo $image['title']; ?>"> <figcaption><?php the_sub_field('caption'); ?></figcaption> </figure> <?php endwhile; //end images loop ?> </div> <?php //the_content(); ?> </div> <?php endwhile; // end of the loop. ?> <!-- </div> /.innerWrapper --> </div> <!-- /.content --> </div> <!-- /.container --> </div> <!-- /.main --> <?php get_footer(); ?><file_sep><?php get_header(); ?> <div class="main"> <div class="container archivePortContainer"> <div class="innerWrapper"> <div class="content archivePortContent"> <h2 class="portTitle">Portfolio</h2> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <?php if ( has_post_thumbnail() ) : ?> <div class="featuredPost clearfix"> <?php if ( has_post_thumbnail() ) : ?> <div class="portImage"> <?php the_post_thumbnail('full'); ?> </div> <div class="portfolioInfo"> <div class="portContent"> <h2><?php the_title(); ?></h2> <?php if ( get_field( 'client_name' ) ): ?> <p><strong>Client Name:</strong> <?php the_field('client_name'); ?></p> <?php endif; ?> <?php the_content(); ?> <h3>Technologies Used:</h3> <?php $terms = get_the_terms($post->ID, 'technologies' ); ?> <?php if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) : ?> <ul> <?php foreach ( $terms as $term ) : ?> <li><?php echo $term->name ?></li> <?php endforeach ?> </ul> <div class="viewOn"> <?php if ( get_field( 'live_demo') ): ?> <a href="<?php the_field('live_demo') ?>">View Live</a> <?php endif; ?> <?php if ( get_field( 'github_link' ) ): ?> <a href="<?php the_field('github_link') ?>">View On GitHub</a> <?php endif; ?> <?php endif ?> </div> </div> </div> <!-- /.portfolioOverlay --> <?php endif; ?> </div> <!-- /.featuredPost --> <?php endif; ?> <?php endwhile; // end of the loop. ?> </div> </div> <!-- /.innerWrapper --> </div> <!-- /.container --> </div> <!-- /.main --> <?php get_footer(); ?><file_sep><?php /* Template Name: Custom Home Page */ get_header(); ?> <div class="main"> <div class="container row homePage"> <?php // Start the loop ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <!-- ============== header section ============== --> <section class="headerLogo"> <div class="animateLogo"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 64.702 60.623" enable-background="new 0 0 64.702 60.623" xml:space="preserve"> <path id="path3" fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d=" M28.612,5.949l33.994,14.164 M28.612,5.949H13.314 M13.314,20.113L2.267,43.06 M13.314,5.949L2.267,43.06"/> <path id="path4" fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d=" M62.606,20.113L34.278,43.06 M62.606,20.113H13.314 M13.314,5.949v14.164 M34.278,43.06l16.656,14.73"/> <path id="path1" fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d=" M28.612,5.949L13.314,20.113 M13.314,20.113L34.278,43.06 M2.267,43.06h32.012 M2.267,43.06l16.005,14.73"/> <path id="path2" fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d=" M18.272,57.79h32.663 M62.606,20.113L50.935,57.79"/> </svg> </div> <h2><?php the_title(); ?></h2> <h3>Front-End Developer</h3> </section> <?php $headerImage = get_post_thumbnail_id(); $headerImageUrl = wp_get_attachment_image_src( $headerImage, 'full', true ); $headerIMG = $headerImageUrl[0]; ?> <!-- =================== background image section ==================== --> <section style="background-image: url('<?php echo $headerIMG ?>')" class="heroImage"> </section> <!-- ============== portfolio section ============== --> <section id="portfolio" class="portfolio clearfix"> <div class="innerWrapper"> <h3 class="headerLine"><span class="linethrough">Featured Work</span></h3> <?php $latestPosts = new WP_Query(array( 'post_type' => 'portfolio', // we only want blog posts 'posts_per_page' => 5, 'order_by' => "asc" )); ?> <?php if ($latestPosts->have_posts()) while($latestPosts->have_posts()) : $latestPosts->the_post(); ?> <div class="featuredPost clearfix"> <?php if ( has_post_thumbnail() ) : ?> <div class="portImage"> <?php //the_post_thumbnail('full'); ?> <a href="<?php the_field('live_demo') ?>" target="_blank"><?php the_post_thumbnail('full') ?></a> </div> <div class="portfolioInfo"> <div class="portContent"> <h2><?php the_title(); ?></h2> <?php if ( get_field( 'client_name' ) ): ?> <p><strong>Client Name:</strong> <?php the_field('client_name'); ?></p> <?php endif; ?> <?php the_content(); ?> <h3>Technologies Used:</h3> <?php $terms = get_the_terms($post->ID, 'technologies' ); ?> <?php if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) : ?> <ul> <?php foreach ( $terms as $term ) : ?> <li><?php echo $term->name ?></li> <?php endforeach ?> </ul> <div class="viewOn"> <?php if ( get_field( 'live_demo') ): ?> <a href="<?php the_field('live_demo') ?>" target="_blank">View Live</a> <?php endif; ?> <?php if ( get_field( 'github_link' ) ): ?> <a href="<?php the_field('github_link') ?>" target="_blank">View On GitHub</a> <?php endif; ?> <?php endif ?> </div> </div> </div> <!-- /.portfolioOverlay --> <?php endif; ?> </div> <!-- /.featuredPost --> <?php endwhile; // end custom loop ?> <?php wp_reset_postdata(); // return end back to regular scheduled programming ?> </div> </section> <!-- ============== about section ============== --> <section id="about" class="about"> <div class="innerWrapper"> <h3 class="headerLine"><span class="linethrough">About Me</span></h3> <div class="aboutImg"> <?php $image = get_field('about_image'); ?> <img src="<?php echo $image['sizes']['medium']; ?>" alt="<?php echo $image['title']; ?>"> </div> <div class="aboutContent"> <?php the_field('about'); ?> <!-- <a target="_blank" href="<?php bloginfo('template_directory'); ?>/heatherbanksresume.pdf" class="resume">View Resume</a> --> <a target="_blank" href="http://heatherbanks.ca/heatherbanksresume.pdf" class="resume">View Resume</a> </div> </div> </section> <!-- ============== skills section ============== --> <section class="skills"> <div class="innerWrapper"> <div class="skillsIHave"> <h3>I Love Using</h3> <?php if ( have_rows('skills') ): ?> <ul> <?php while ( have_rows('skills') ): the_row(); ?> <li> <?php the_sub_field('skills_i_have') ?> </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_postdata(); // return end back to regular scheduled programming ?> </div> <div class="skillsImLearning"> <h3>I'm Learning</h3> <?php if ( have_rows('skills') ): ?> <ul> <?php while ( have_rows('skills') ): the_row(); ?> <li> <?php the_sub_field('skills_im_learning') ?> </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_postdata(); // return end back to regular scheduled programming ?> </div> <div class="skillsIWant"> <h3>I Want to Learn</h3> <?php if ( have_rows('skills') ): ?> <ul> <?php while ( have_rows('skills') ): the_row(); ?> <li> <?php the_sub_field('skills_to_learn') ?> </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_postdata(); // return end back to regular scheduled programming ?> </div> </div> </section> <!-- ============== contact section ============== --> <section id="contact" class="contact clearfix"> <div class="innerWrapper"> <div class="contactInfo"> <h3 class="email">email</h3> <p class="emailAdd"><EMAIL></p> <p class="or">- or -</p> <h3 class="social">find me here</h3> <ul class="socialMediaLinks"> <li><i class="fa fa-twitter"><a href="http://twitter.com/heatherlbanks" target="_blank">heatherlbanks</a></i></li> <li><i class="fa fa-linkedin"><a href="https://www.linkedin.com/pub/heather-banks/50/813/488">heather banks</a></i></li> <li><i class="fa fa-codepen"><a href="http://codepen.io/hbanks" target="_blank">hbanks</a></i></li> <li><i class="fa fa-github"><a href="http://github.com/hbanks" target="_blank">hbanks</a></i></li> </ul> </div> <div class="contactForm"> <?php dynamic_sidebar( 'secondary-widget-area' ); ?> </div> </div> </section> <?php endwhile; // end the loop?> </div> <!-- /.container --> </div> <!-- /.main --> <?php get_footer(); ?><file_sep>$(function() { $('a[href*="'+window.location.hash+'"]').addClass('nav-active'); // smooth scroll $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); // svg animation var svg3 = new Walkway({ selector: '#Layer_1', duration: '3500', easing: 'linear' }); svg3.draw(function() { console.log('Finished test shape!'); }); // when we scroll down the window, do this: $(window).scroll(function(){ //Getting the scroll percentage var windowHeight = $(window).height(); var scrollHeight = $(window).scrollTop(); var scrollPercentage = (scrollHeight / windowHeight); // if we have scrolled past 200, add the alternate class to nav bar if(scrollPercentage > 1) { $('body').addClass('scrolling'); } else { $('body').removeClass('scrolling'); } }); $('input.focused1').on('click', function(){ $('span.label1').removeClass('labelStart'); $('span.label1').addClass('labelSlide'); }); $('input.focused2').on('click', function(){ $('span.label2').removeClass('labelStart'); $('span.label2').addClass('labelSlide'); }); $('input.focused3').on('click', function(){ $('span.label3').removeClass('labelStart'); $('span.label3').addClass('labelSlide'); }); $('textarea.focused4').on('click', function(){ $('span.label4').removeClass('labelStart'); $('span.label4').addClass('labelSlide'); }); // if inputs are empty $('input.focused1').blur(function() { if(!$.trim(this.value).length) { // zero-length string AFTER a trim $('span.label1').removeClass('labelSlide'); $('span.label1').addClass('labelStart'); } }); $('input.focused2').blur(function() { if(!$.trim(this.value).length) { // zero-length string AFTER a trim $('span.label2').removeClass('labelSlide'); $('span.label2').addClass('labelStart'); } }); $('input.focused3').blur(function() { if(!$.trim(this.value).length) { // zero-length string AFTER a trim $('span.label3').removeClass('labelSlide'); $('span.label3').addClass('labelStart'); } }); $('textarea.focused4').blur(function() { if(!$.trim(this.value).length) { // zero-length string AFTER a trim $('span.label4').removeClass('labelSlide'); $('span.label4').addClass('labelStart'); } }); // dropdown nav $('a.mobileNavIcon').on('click', function (e){ e.preventDefault(); $('ul.menu').toggleClass('open'); }); // apply the class of nav-active to the current nav link $('ul.menu a').on('click', function(e) { // e.preventDefault(); $('a.nav-active').removeClass('nav-active'); $(this).addClass('nav-active'); }); });
be888ba3f3779dd308bef5f974ac71cd5262c131
[ "Markdown", "JavaScript", "PHP" ]
5
Markdown
hbanks/portfolio-site
69b88fbccc54f946d6c4d24cb35a4ce6b57c4baf
4403c51be6b589a5eb30614f394765400d0a5241
refs/heads/master
<repo_name>notargetbg/vue-todo-list<file_sep>/src/store/actions.js import Vue from "vue"; const BASE_URL = process.env.NODE_ENV === 'production' ? '/API' : 'http://localhost:5000/API'; function orderById(collection) { return collection.sort((a, b) => { return a.id - b.id; }); } export default { async getTodos({ commit, state }) { commit('recieveTodosStarted'); await Vue.axios.get(`${BASE_URL}/todos`) .then(response => { commit('recieveTodos', orderById(response.data.todos)) }) .catch(e => { state.isLoading = false; throw new Error(e); }); }, async toggleTodo({ commit, state }, id) { const todo = state.todos.find(todo => todo.id === id); await Vue.axios.put(`${BASE_URL}/todos/${id}`, { isDone: !todo.isDone }) .then(response => { commit('toggleTodo', response.data.todo.id); }) .catch(e => { throw new Error(e); }) }, async deleteTodo({ commit, state }, id) { await Vue.axios.delete(`${BASE_URL}/todos/${id}`) .then(response => { const todos = state.todos.reduce((acc, todo) => { if (response.data.id !== todo.id) { acc.push(todo); return acc; } return acc; }, []); commit('recieveTodos', todos) }) .catch(e => { throw new Error(e); }) }, async createNewTodo({ commit, state }, newTitle) { const todo = { // id: createId(state.todos), title: newTitle, isDone: false }; await Vue.axios.post(`${BASE_URL}/todos`, { title: todo.title, isDone: todo.isDone }) .then(response => { commit('addNew', response.data.todo); }) .catch(e => { throw new Error(e); }) } }<file_sep>/server/core/models/todo.js const db = require('../../db'); function getAll() { return db.query('SELECT * FROM todos'); } function create(...args) { return db.query('INSERT INTO todos(title, "isDone") VALUES($1, $2) RETURNING *', args); } function update(...args) { return db.query(` UPDATE todos SET title = COALESCE($1, title), "isDone" = COALESCE($2, "isDone") WHERE id = $3 RETURNING * `, args); } function deleteOne(id) { return db.query('DELETE FROM todos WHERE id = $1 RETURNING id', [ id, ]); } module.exports = { getAll, create, update, deleteOne };<file_sep>/README.md # todo-list Thank you for the opportunity to work on this assignment. It was pleasure and fun to learn Vue/Vuex. Nice framework to work with. Also thank you for the push in order for me to learn to do basic unit testing. I hope you like it. You can check out a demo of the app here: https://todos-vue-designscaster.herokuapp.com *Edit:* Server has changed a bit in order to setup easier deployment to Heroku. It now serves both static /dist folder as well as provides the API routes. Both apps can be still deployed and developed independently. ## Project setup ``` npm install ``` #### - Please install latest postgress and pgadmin in order to run the DB. #### - Backup file for the db table is included in main directory - todos.backup #### - Create an empty table 'todos' and use todos.backup in order to restore the db inside pg admin. DB owner can be postgress. ### Compiles and hot-reloads for development ``` npm run serve ``` ### Runs node/express server ``` node server/server ``` ### Compiles and minifies for production ``` npm run build ``` ### Starts node server and serves the build from dist ``` npm run start ``` ### Run your tests ``` npm run test ``` ### Lints and fixes files ``` npm run lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). <file_sep>/server/server.js const express = require('express'); const bodyParser = require('body-parser'); const todosRouter = require('./core/routes/todos.js'); const app = express(); const port = process.env.PORT || 5000; const path = require('path'); app.use(express.static(path.join(__dirname, '../dist'))); const basePath = '/api'; // console.log that your server is up and running app.listen(port, () => console.log(`Listening on port ${port}`)); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: false})); // parse application/json app.use(bodyParser.json()); // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080'); res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'); res.setHeader('Access-Control-Allow-Credentials', 'true'); res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, Content-Type, Accept, Authorization'); next(); }); app.use(`${basePath}/todos`, todosRouter); app.use(function (err, req, res) { console.error('error:' ,err.stack); res.status(500).send({ message: 'Something broke!', error: err }); });<file_sep>/server/db/index.js const { Client } = require('pg'); const localConf = { host: 'localhost', user: 'postgres', password: '<PASSWORD>', database: 'todos', max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000, }; const prodConf = { connectionString: process.env.DATABASE_URL, ssl: true, }; const config = process.env.NODE_ENV === 'production' ? prodConf : localConf; const db = new Client(config); db.connect(); module.exports = { query: (text, params, callback) => { return db.query(text, params, callback); } };<file_sep>/server/core/routes/todos.js const express = require('express'); const router = express.Router(); const todo = require('../models/todo.js'); router.get('/', (req, res, next) => { todo.getAll() .then(result => { res.status(200).send({ todos: result.rows }); }) .catch(err => next(err)); }); router.post('/', (req, res, next) => { if (!req.body.title || typeof req.body.isDone === 'undefined') { return res.status(400).send({ message: 'Input data missing.' }); } todo.create( req.body.title, req.body.isDone ) .then(result => { res.status(200).send({ message: 'OK.', todo: result.rows[0] }); }) .catch(err => { next(err); }); }); router.put('/:id', (req, res, next) => { if (!req.body.title && typeof req.body.isDone === 'undefined') { return res.status(400).send({ message: 'Input data missing.' }); } todo.update( req.body.title, req.body.isDone, req.params.id ) .then(result => { if(result.rowCount === 0) { res.status(400).send({ message: 'Nothing is updated.' }); } else { res.status(200).send({ message: 'OK.', todo: result.rows[0] }); } }) .catch(err => next(err)); }); router.delete('/:id', (req, res ,next) => { todo.deleteOne( req.params.id, ) .then(result => { if(result.rowCount === 0) { res.status(400).send({ message: 'Nothing is deleted.' }); } else { res.status(200).send({ message: 'OK.', ...result.rows[0] }); } }) .catch(err => next(err)); }); module.exports = router;
9f8ea2d27866a3102ff32edf12a65b79d12db814
[ "JavaScript", "Markdown" ]
6
JavaScript
notargetbg/vue-todo-list
d7b3a9c9f322e441cc87d1aabdc6b7eaf3ceece9
7452e979fdc26e26854c5d9d35f89c7ab8b34abb
refs/heads/master
<repo_name>codenik1591/Socket-Programming-Multi-Thread<file_sep>/ATM-Socket-Multi-thread/AllTextFiles/Account_Details.properties 11111111_customer_name=Alice 11111111_atm_pin=1234 11111111_card_number=11111111 00000000_customer_name=Tom 00000000_atm_pin=5678 00000000_card_number=00000000<file_sep>/README.md # Socket-Programming-Multi-Thread ATM demo for Socket Programming in Java using multi-threading concept <file_sep>/ATM-Socket-Multi-thread/src/server/ServerHandler1.java package server; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Properties; public class ServerHandler1 implements Runnable { Socket s; String accountDetailPath,balanceDetailsPath; public ServerHandler1() { accountDetailPath = ".\\AllTextFiles\\Account_Details.properties"; balanceDetailsPath = ".\\AllTextFiles\\BalanceDetails.properties"; } public ServerHandler1(Socket sin) { this.s = sin; System.out.println("In the constructor of server handler"); } public void depositMoney(int cusChoice) throws IOException { PrintWriter outToClient = new PrintWriter(s.getOutputStream(),true); @SuppressWarnings("unused") BufferedReader inFromClient = new BufferedReader(new InputStreamReader(s.getInputStream())); File fAccountDetails,fBalanceDetails; FileInputStream fisAccountDetails=null, fisBalanceDetails=null;//InputStream Declaration @SuppressWarnings("unused") FileOutputStream fosAccountDetails = null,fosBalanceDetails = null;//OutputStram Declaration Properties propAccountDetails,propBalanceDetails; /*File fAlice,fTom; FileInputStream fisAlice = null,fisTom = null; FileOutputStream fosAlice = null,fosTom = null; Properties propAlice,propTom;*/ String savingBalAmount="",checkingBalAmount=""; outToClient.println("Please Enter Your Account Type(saving/checking) : "); System.out.println("Check -- Please Enter Your Account Type(saving/checking) : "); BufferedReader brAccountType = new BufferedReader(new InputStreamReader(s.getInputStream())); String AccountType = brAccountType.readLine().toUpperCase(); if(cusChoice == 1) { fAccountDetails = new File(accountDetailPath); fisAccountDetails = new FileInputStream(fAccountDetails);//InputStream for AccountDetails propAccountDetails = new Properties(); propAccountDetails.load(fisAccountDetails); fBalanceDetails = new File(balanceDetailsPath); fisBalanceDetails = new FileInputStream(fBalanceDetails);//InputStream for BalanceDetails propBalanceDetails = new Properties(); propBalanceDetails.load(fisBalanceDetails); if(AccountType.equals("SAVING")) { savingBalAmount = propBalanceDetails.getProperty("11111111_saving_balance"); int savAmt = Integer.parseInt(savingBalAmount); String name = propAccountDetails.getProperty("11111111_customer_name"); outToClient.println("Dear "+name+", you have $"+savAmt+" in your Saving Account."); System.out.println("Check -- Dear "+name+", you have $"+savAmt+" in your Saving Account."); outToClient.println("Please Enter The Amount to Deposit : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String depAmount = brDepAmount.readLine(); int depositAmount = Integer.parseInt(depAmount); int totalAmount = depositAmount+savAmt; fisAccountDetails.close(); //Close the InputStream for AccountDetails File fisBalanceDetails.close(); //Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println("Balance of Alice in Saving Account is : $" + totalAmount); propBalanceDetails.setProperty("11111111_saving_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else if(AccountType.equals("CHECKING")) { checkingBalAmount = propBalanceDetails.getProperty("11111111_checking_balance"); int chkAmt = Integer.parseInt(checkingBalAmount); String name = propAccountDetails.getProperty("11111111_customer_name"); outToClient.println("Dear "+name+", you have $"+chkAmt+" in your Saving Account."); outToClient.println("Please Enter The Amount to Deposit : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String depAmount = brDepAmount.readLine(); int depositAmount = Integer.parseInt(depAmount); int totalAmount = depositAmount+chkAmt; fisAccountDetails.close();//Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println(" Balance of Alice in Checking Account is : $" + totalAmount); propBalanceDetails.setProperty("11111111_checking_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else { outToClient.println("The Type of Account Does not Exist, Please check...!!!!!"); } } if(cusChoice == 0) { fAccountDetails = new File(accountDetailPath); fisAccountDetails = new FileInputStream(fAccountDetails);//InputStream for AccountDetails propAccountDetails = new Properties(); propAccountDetails.load(fisAccountDetails); fBalanceDetails = new File(balanceDetailsPath); fisBalanceDetails = new FileInputStream(fBalanceDetails);//InputStream for BalanceDetails propBalanceDetails = new Properties(); propBalanceDetails.load(fisBalanceDetails); if(AccountType.equals("SAVING")) { savingBalAmount = propBalanceDetails.getProperty("00000000_saving_balance"); int savAmt = Integer.parseInt(savingBalAmount); String name = propAccountDetails.getProperty("00000000_customer_name"); outToClient.println("Dear "+name+", you have $"+savAmt+" in your Saving Account."); outToClient.println("Please Enter The Amount to Deposit : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String depAmount = brDepAmount.readLine(); int depositAmount = Integer.parseInt(depAmount); int totalAmount = depositAmount+savAmt; fisAccountDetails.close();//Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println(" Balance of Tom in Saving Account is : $" + totalAmount); propBalanceDetails.setProperty("00000000_saving_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else if(AccountType.equals("CHECKING")) { checkingBalAmount = propBalanceDetails.getProperty("00000000_checking_balance"); int chkAmt = Integer.parseInt(checkingBalAmount); String name = propAccountDetails.getProperty("00000000_customer_name"); outToClient.println("Dear "+name+", you have $"+chkAmt+"in your Saving Account."); outToClient.println("Please Enter The Amount to Deposit : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String depAmount = brDepAmount.readLine(); int depositAmount = Integer.parseInt(depAmount); int totalAmount = depositAmount+chkAmt; fisAccountDetails.close();//Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println(" Balance of Tom in Checking Account is : $" + totalAmount); propBalanceDetails.setProperty("00000000_checking_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } } } public void withdrawMoney(int cusChoice) throws IOException { PrintWriter outToClient = new PrintWriter(s.getOutputStream(),true); @SuppressWarnings("unused") BufferedReader inFromClient = new BufferedReader(new InputStreamReader(s.getInputStream())); File fAccountDetails,fBalanceDetails; FileInputStream fisAccountDetails=null, fisBalanceDetails=null;//InputStream Declaration @SuppressWarnings("unused") FileOutputStream fosAccountDetails = null,fosBalanceDetails = null;//OutputStram Declaration Properties propAccountDetails,propBalanceDetails; String savingBalAmount="",checkingBalAmount=""; outToClient.println("Pleasse Enter Your Account Type(saving/checking) : $"); BufferedReader brAccountType = new BufferedReader(new InputStreamReader(s.getInputStream())); String AccountType = brAccountType.readLine().toUpperCase(); if(cusChoice == 1) { fAccountDetails = new File(accountDetailPath); fisAccountDetails = new FileInputStream(fAccountDetails);//InputStream for AccountDetails propAccountDetails = new Properties(); propAccountDetails.load(fisAccountDetails); fBalanceDetails = new File(balanceDetailsPath); fisBalanceDetails = new FileInputStream(fBalanceDetails);//InputStream for BalanceDetails propBalanceDetails = new Properties(); propBalanceDetails.load(fisBalanceDetails); if(AccountType.equals("SAVING")) { savingBalAmount = propBalanceDetails.getProperty("11111111_saving_balance"); int savAmt = Integer.parseInt(savingBalAmount); String name = propAccountDetails.getProperty("11111111_customer_name"); outToClient.println("Dear "+name+", you have $"+savAmt+" in your Saving Account."); int amtlimit = 0; amtlimit = savAmt-10000; if(amtlimit>0) { outToClient.println("Please Enter The Amount you Want to With Draw(Maximum=$"+amtlimit+") : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String WDAmount = brDepAmount.readLine(); int WithDrawlAmount = Integer.parseInt(WDAmount); int chkLimit =0; chkLimit = savAmt-WithDrawlAmount; int totalAmount=0; if(chkLimit>10000 || chkLimit==10000) { totalAmount = savAmt-WithDrawlAmount; fisAccountDetails.close(); //Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println("Balance of Alice in Saving Account after Withdrawl is : $" + totalAmount); propBalanceDetails.setProperty("11111111_saving_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else { outToClient.println("You can withdraw at max $"+amtlimit+" from your Account, so that balance should be more than $10000..!!! You cannot withdraw more...."); } } else if(amtlimit==0) { outToClient.println("Since you have reached your debit limit, you cannot withdraw more money..!!!!"); } } else if(AccountType.equals("CHECKING")) { checkingBalAmount = propBalanceDetails.getProperty("11111111_checking_balance"); int chkAmt = Integer.parseInt(checkingBalAmount); String name = propAccountDetails.getProperty("11111111_customer_name"); outToClient.println("Dear "+name+", you have $"+chkAmt+" in your Saving Account."); int amtlimit = 0; amtlimit = chkAmt-10000; if(amtlimit>0) { outToClient.println("Please Enter The Amount you Want to With Draw(Maximum=$"+amtlimit+") : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String WDAmount = brDepAmount.readLine(); int WithDrawlAmount = Integer.parseInt(WDAmount); int chkLimit =0; chkLimit = chkAmt-WithDrawlAmount; int totalAmount=0; if(chkLimit>10000 || chkLimit==10000) { totalAmount = chkAmt-WithDrawlAmount; fisAccountDetails.close(); //Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println("Balance of Alice in Checking Account after Withdrawl is : $" + totalAmount); propBalanceDetails.setProperty("11111111_checking_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else { outToClient.println("You can withdraw at max $"+amtlimit+" from your Account, so that balance should be more than $10000..!!! You cannot withdraw more...."); } } else if(amtlimit==0) { outToClient.println("Since you have reached your debit limit, you cannot withdraw more money..!!!!"); } } else { outToClient.println("The Type of Account Does not Exist, Please check...!!!!!"); } } else if(cusChoice == 0) { fAccountDetails = new File(accountDetailPath); fisAccountDetails = new FileInputStream(fAccountDetails);//InputStream for AccountDetails propAccountDetails = new Properties(); propAccountDetails.load(fisAccountDetails); fBalanceDetails = new File(balanceDetailsPath); fisBalanceDetails = new FileInputStream(fBalanceDetails);//InputStream for BalanceDetails propBalanceDetails = new Properties(); propBalanceDetails.load(fisBalanceDetails); /*fTom = new File(tomPath); fisTom = new FileInputStream(fTom); propTom = new Properties(); propTom.load(fisTom);*/ if(AccountType.equals("SAVING")) { savingBalAmount = propBalanceDetails.getProperty("00000000_saving_balance"); int savAmt = Integer.parseInt(savingBalAmount); String name = propAccountDetails.getProperty("00000000_customer_name"); outToClient.println("Dear "+name+", you have $"+savAmt+" in your Saving Account."); int amtlimit = 0; amtlimit = savAmt-10000; if(amtlimit>0) { outToClient.println("Please Enter The Amount you Want to With Draw(Maximum=$"+amtlimit+") : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String WDAmount = brDepAmount.readLine(); int WithDrawlAmount = Integer.parseInt(WDAmount); int chkLimit =0; chkLimit = savAmt-WithDrawlAmount; int totalAmount=0; if(chkLimit>10000 || chkLimit==10000) { totalAmount = savAmt-WithDrawlAmount; fisAccountDetails.close(); //Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println("Balance of Tom in Saving Account after Withdrawl is : $" + totalAmount); propBalanceDetails.setProperty("00000000_saving_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else { outToClient.println("You can withdraw at max $"+amtlimit+" from your Account, so that balance should be more than $10000..!!! You cannot withdraw more...."); } } else if(amtlimit==0) { outToClient.println("Since you have reached your debit limit, you cannot withdraw more money..!!!!"); } } else if(AccountType.equals("CHECKING")) { checkingBalAmount = propBalanceDetails.getProperty("00000000_checking_balance"); int chkAmt = Integer.parseInt(checkingBalAmount); String name = propAccountDetails.getProperty("00000000_customer_name"); outToClient.println("Dear "+name+", you have $"+chkAmt+" in your Saving Account."); int amtlimit = 0; amtlimit = chkAmt-10000; if(amtlimit>0) { outToClient.println("Please Enter The Amount you Want to With Draw(Maximum=$"+amtlimit+") : $"); BufferedReader brDepAmount = new BufferedReader(new InputStreamReader(s.getInputStream())); String WDAmount = brDepAmount.readLine(); int WithDrawlAmount = Integer.parseInt(WDAmount); int chkLimit =0; chkLimit = chkAmt-WithDrawlAmount; int totalAmount=0; if(chkLimit>10000 || chkLimit==10000) { totalAmount = chkAmt-WithDrawlAmount; fisAccountDetails.close(); //Close the InputStream for AccountDetails File fisBalanceDetails.close();//Close the InputStream for BalanceDetails File //Open the OutPutStream, After closing the InputStream fosBalanceDetails = new FileOutputStream(fBalanceDetails); outToClient.println("Balance of Tom in Checking Account after Withdrawl is : $" + totalAmount); propBalanceDetails.setProperty("00000000_checking_balance", ""+totalAmount); propBalanceDetails.store(fosBalanceDetails, null); fosBalanceDetails.close();//Close OutPutStream for BalanceDetail File } else { outToClient.println("You can withdraw at max $"+amtlimit+" from your Account, so that balance should be more than $10000..!!! You cannot withdraw more...."); } } else if(amtlimit==0) { outToClient.println("Since you have reached your debit limit, you cannot withdraw more money..!!!!"); } } else { outToClient.println("The Type of Account Does not Exist, Please check...!!!!!"); } } } @SuppressWarnings("hiding") public void run() { System.out.println("In the run of ServerHandler"); ServerHandler1 sh1 = new ServerHandler1(); String accountDetailPath,balanceDetailsPath; accountDetailPath = ".\\AllTextFiles\\Account_Details.properties"; balanceDetailsPath = ".\\AllTextFiles\\BalanceDetails.properties"; @SuppressWarnings("unused") String cus_name,card_no,atm_pin; File fAccountDetails,fBalanceDetails; FileInputStream fisAccountDetails=null, fisBalanceDetails=null;//InputStream Declaration Properties propAccountDetails,propBalanceDetails; BufferedReader inFromClient = null; PrintWriter outToClient = null; try { inFromClient = new BufferedReader(new InputStreamReader(s.getInputStream())); outToClient = new PrintWriter(s.getOutputStream(),true); } catch (IOException e1) { e1.printStackTrace(); } try { while(true) { fAccountDetails = new File(accountDetailPath); fisAccountDetails = new FileInputStream(fAccountDetails);//InputStream for AccountDetails propAccountDetails = new Properties(); propAccountDetails.load(fisAccountDetails); fBalanceDetails = new File(balanceDetailsPath); fisBalanceDetails = new FileInputStream(fBalanceDetails);//InputStream for BalanceDetails propBalanceDetails = new Properties(); propBalanceDetails.load(fisBalanceDetails); //System.out.println(); System.out.println("===========================Welcome to ATM ========================================"); System.out.println("\t0. Quit"); System.out.println("\t1. Deposit Amount"); System.out.println("\t2. WithDraw Amount"); System.out.println("==================================================================================="); outToClient.println("===========================Welcome to ATM ========================================"); outToClient.println("\t0. Quit"); outToClient.println("\t1. Deposit Amount"); outToClient.println("\t2. WithDraw Amount"); outToClient.println("==================================================================================="); outToClient.println("Please Enter your choice : "); System.out.println("Check -- Before Readline from client..!!!"); String choice = inFromClient.readLine(); //this is for Deposit of Money if(choice.equals("1")) { outToClient.println("Please Enter your Card Number : "); String cardNumber = inFromClient.readLine(); if(cardNumber.equals("11111111")) { cus_name = propAccountDetails.getProperty("11111111_customer_name"); card_no = propAccountDetails.getProperty("11111111_card_number"); atm_pin = propAccountDetails.getProperty("11111111_atm_pin"); outToClient.println("Dear "+cus_name+" Please Enter your PIN : "); BufferedReader brAtmPin = new BufferedReader(new InputStreamReader(s.getInputStream())); String pinNumber = brAtmPin.readLine(); if(pinNumber.equals(atm_pin)) { sh1.depositMoney(1); } else { outToClient.println("The Pin You Have Entered is incorrect..!!!"); } } else if(cardNumber.equals("00000000")) { cus_name = propAccountDetails.getProperty("00000000_customer_name"); card_no = propAccountDetails.getProperty("00000000_card_number"); atm_pin = propAccountDetails.getProperty("00000000_atm_pin"); outToClient.println("Dear "+cus_name+" Please Enter your PIN : "); BufferedReader brAtmPin = new BufferedReader(new InputStreamReader(s.getInputStream())); String pinNumber = brAtmPin.readLine(); if(pinNumber.equals(atm_pin)) { sh1.depositMoney(0); } else { outToClient.println("The Pin You Have Entered is incorrect..!!!"); } } else { outToClient.println("Not a Valid Account Number, Please check your Account Number and Try Again...!!!"); } } /* * this is the testing one.... * if(choice.equals("0")) { outToClient.println("Server : You chose to Exit..!!!"); outToClient.println(""); } else if(choice.equals("1")) { outToClient.println("Server : You chose to Deposit..!!!"); outToClient.println(""); System.out.println("Server : You chose to Deposit..!!!"); } else if(choice.equals("2")) { outToClient.println("Server : You chose to Withdraw..!!!"); outToClient.println(""); System.out.println("Server : You chose to Withdraw..!!!"); } else { outToClient.println("Server : You chose a invalid choice..!!!"); outToClient.println(""); System.out.println("Server : You chose a invalid choice..!!!"); } * */ //this is for WithDrawl of Money else if(choice.equals("2")) { outToClient.println("Please Enter your Card Number : "); BufferedReader brCardNumber = new BufferedReader(new InputStreamReader(s.getInputStream())); String cardNumber = brCardNumber.readLine(); if(cardNumber.equals("11111111")) { cus_name = propAccountDetails.getProperty("11111111_customer_name"); card_no = propAccountDetails.getProperty("11111111_card_number"); atm_pin = propAccountDetails.getProperty("11111111_atm_pin"); outToClient.println("Dear "+cus_name+" Please Enter your PIN : "); BufferedReader brAtmPin = new BufferedReader(new InputStreamReader(s.getInputStream())); String pinNumber = brAtmPin.readLine(); if(pinNumber.equals(atm_pin)) { sh1.withdrawMoney(1); } else { outToClient.println("The Pin You Have Entered is incorrect..!!!"); } } else if(cardNumber.equals("00000000")) { cus_name = propAccountDetails.getProperty("00000000_customer_name"); card_no = propAccountDetails.getProperty("00000000_card_number"); atm_pin = propAccountDetails.getProperty("00000000_atm_pin"); outToClient.println("Dear "+cus_name+" Please Enter your PIN : "); BufferedReader brAtmPin = new BufferedReader(new InputStreamReader(s.getInputStream())); String pinNumber = brAtmPin.readLine(); if(pinNumber.equals(atm_pin)) { sh1.withdrawMoney(0); } else { outToClient.println("The Pin You Have Entered is incorrect..!!!"); } } else { outToClient.println("Not a Valid Account Number, Please check your Account Number and Try Again...!!!"); } } } } catch (IOException e) { e.printStackTrace(); } outToClient.close(); try { inFromClient.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/ATM-Socket-Multi-thread/src/server/ServerDriver1.java package server; public class ServerDriver1 { public static void main(String[] args) { System.out.println("This is ServerDriver..!!!"); Runnable server = new Server1(8000); Thread serverThrd = new Thread(server); System.out.println("Server Thread Started..!!!"); System.out.println("Server_Thread_Name : "+serverThrd.getName()); serverThrd.start(); } } <file_sep>/ATM-Socket-Multi-thread/src/cllient/ClientDriver1.java package cllient; /*import clientSide.Client;*/ public class ClientDriver1 { public static void main(String[] args) { System.out.println("This is ClientDriver..!!!"); Runnable client = new Client1(); Thread clientThrd = new Thread(client); clientThrd.setName("Client_Thread"); System.out.println(clientThrd.getName()); clientThrd.start(); } }
85dd44f2ed2fc8284fb52fadee150dfc892080f6
[ "Markdown", "Java", "INI" ]
5
INI
codenik1591/Socket-Programming-Multi-Thread
e58e3bd4fbc7aadfcecfdf7e3ac225bf360629d7
5ce885269a7cc712e33eab1c548b92d12c84b21d
refs/heads/master
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>TestNG Report</title> <style type="text/css">table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}th,td {border:1px solid #009;padding:.25em .5em}th {vertical-align:bottom}td {vertical-align:top}table a {font-weight:bold}.stripe td {background-color: #E6EBF9}.num {text-align:right}.passedodd td {background-color: #3F3}.passedeven td {background-color: #0A0}.skippedodd td {background-color: #DDD}.skippedeven td {background-color: #CCC}.failedodd td,.attn {background-color: #F33}.failedeven td,.stripe .attn {background-color: #D00}.stacktrace {white-space:pre;font-family:monospace}.totop {font-size:85%;text-align:center;border-bottom:2px solid #000}.invisible {display:none}</style> </head> <body> <table> <tr><th>Test</th><th># Passed</th><th># Skipped</th><th># Failed</th><th>Time (ms)</th><th>Included Groups</th><th>Excluded Groups</th></tr> <tr><th colspan="7">Test suite no1</th></tr> <tr><td><a href="#t0">Free test</a></td><td class="num">15</td><td class="num">0</td><td class="num">0</td><td class="num">152,263</td><td></td><td></td></tr> </table> <table id='summary'><thead><tr><th>Class</th><th>Method</th><th>Start</th><th>Time (ms)</th></tr></thead><tbody><tr><th colspan="4">Test suite no1</th></tr></tbody><tbody id="t0"><tr><th colspan="4">Free test &#8212; passed</th></tr><tr class="passedeven"><td rowspan="4">com.mf.testcases.ContactFormTest</td><td><a href="#m0">fillForm</a></td><td rowspan="2">1560348962419</td><td rowspan="2">3038</td></tr><tr class="passedeven"><td><a href="#m1">fillForm</a></td></tr><tr class="passedeven"><td><a href="#m2">testTitle</a></td><td rowspan="1">1560348937315</td><td rowspan="1">1066</td></tr><tr class="passedeven"><td><a href="#m3">testUrl</a></td><td rowspan="1">1560348926618</td><td rowspan="1">1139</td></tr><tr class="passedodd"><td rowspan="4">com.mf.testcases.ExamplesPageTest</td><td><a href="#m4">goToContactFormTest</a></td><td rowspan="1">1560348904480</td><td rowspan="1">396</td></tr><tr class="passedodd"><td><a href="#m5">goToSurverFormPageTest</a></td><td rowspan="1">1560348915181</td><td rowspan="1">402</td></tr><tr class="passedodd"><td><a href="#m6">testTitle</a></td><td rowspan="1">1560348894039</td><td rowspan="1">26</td></tr><tr class="passedodd"><td><a href="#m7">testUrl</a></td><td rowspan="1">1560348882772</td><td rowspan="1">22</td></tr><tr class="passedeven"><td rowspan="3">com.mf.testcases.HomePageTest</td><td><a href="#m8">openExamplesPageTest</a></td><td rowspan="1">1560348871956</td><td rowspan="1">799</td></tr><tr class="passedeven"><td><a href="#m9">testTitle</a></td><td rowspan="1">1560348871916</td><td rowspan="1">36</td></tr><tr class="passedeven"><td><a href="#m10">testUrl</a></td><td rowspan="1">1560348871826</td><td rowspan="1">78</td></tr><tr class="passedodd"><td rowspan="4">com.mf.testcases.SurveyFormTest</td><td><a href="#m11">testCheckBox</a></td><td rowspan="2">1560349008736</td><td rowspan="2">4790</td></tr><tr class="passedodd"><td><a href="#m12">testCheckBox</a></td></tr><tr class="passedodd"><td><a href="#m13">testTitle</a></td><td rowspan="1">1560348985237</td><td rowspan="1">1060</td></tr><tr class="passedodd"><td><a href="#m14">testUrl</a></td><td rowspan="1">1560348975127</td><td rowspan="1">1061</td></tr></tbody> </table> <h2>Free test</h2><h3 id="m0">com.mf.testcases.ContactFormTest#fillForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th></tr><tr class="param stripe"><td>first2</td><td>last2</td><td><EMAIL></td><td>This is message number 2</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m1">com.mf.testcases.ContactFormTest#fillForm</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th></tr><tr class="param stripe"><td>first1</td><td>last1</td><td><EMAIL></td><td>This is message number 1</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m2">com.mf.testcases.ContactFormTest#testTitle</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m3">com.mf.testcases.ContactFormTest#testUrl</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m4">com.mf.testcases.ExamplesPageTest#goToContactFormTest</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m5">com.mf.testcases.ExamplesPageTest#goToSurverFormPageTest</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m6">com.mf.testcases.ExamplesPageTest#testTitle</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m7">com.mf.testcases.ExamplesPageTest#testUrl</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m8">com.mf.testcases.HomePageTest#openExamplesPageTest</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m9">com.mf.testcases.HomePageTest#testTitle</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m10">com.mf.testcases.HomePageTest#testUrl</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m11">com.mf.testcases.SurveyFormTest#testCheckBox</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th></tr><tr class="param stripe"><td>No</td><td>About what I expected</td><td>Other</td><td>Good</td><td>Better</td><td>Best Ever!</td><td>Good</td><td>No</td><td>123Test!@#$%^!</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m12">com.mf.testcases.SurveyFormTest#testCheckBox</h3><table class="result"><tr class="param"><th>Parameter #1</th><th>Parameter #2</th><th>Parameter #3</th><th>Parameter #4</th><th>Parameter #5</th><th>Parameter #6</th><th>Parameter #7</th><th>Parameter #8</th><th>Parameter #9</th></tr><tr class="param stripe"><td>Yes</td><td>Much longer that what I expected</td><td>Word of Mouth</td><td>Poor</td><td>Good</td><td>Better</td><td>Best Ever!</td><td>Yes</td><td>Message One Test</td></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m13">com.mf.testcases.SurveyFormTest#testTitle</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> <h3 id="m14">com.mf.testcases.SurveyFormTest#testUrl</h3><table class="result"><tr><th class="invisible"/></tr></table><p class="totop"><a href="#summary">back to summary</a></p> </body> </html> <file_sep>package com.mf.pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import com.mf.base.BaseClass; public class SurveyFormPage extends BaseClass { WebDriver driver; // Elements By reservationList = By.name("element_6"); By waitingList = By.name("element_7"); By learningList = By.xpath("//input[@*='checkbox']"); By selectionList = By.xpath("//tr[@id='mr_2']/td/input/.."); By servicesList = By.xpath("//tr[@id='mr_3']/td/input/.."); By pricingList = By.xpath("//tr[@id='mr_4']/td/input/.."); By cleanList = By.xpath("//tr[@id='mr_5']/td/input/.."); By recommendationList = By.name("element_8"); By otherField = By.id("element_1_other"); By messageField = By.name("element_9"); public SurveyFormPage(WebDriver driver) { this.driver = driver; } // Url check public String checkUrl() { return driver.getCurrentUrl(); } // Title check public String checkTitle() { return driver.getTitle(); } // Fill form with data public void submitForm(String strReservation, String strWaiting, String strLearn, String strMen, String strStuff, String strPricing, String strClean, String strRecommend, String strMessage) { // Reservation click List<WebElement> reservations = driver.findElements(reservationList); int sizeReservation = reservations.size(); // System.out.println("Reservation RadioButton size: " + sizeReservation); for (int i = 0; i < sizeReservation; i++) { String textReservation = reservations.get(i).getAttribute("id"); // System.out.println("Reservation RadioButton id: " + textReservation); WebElement labelReservation = driver.findElement(By.cssSelector("label[for='" + textReservation + "'")); if (labelReservation.getAttribute("textContent").equalsIgnoreCase(strReservation)) { labelReservation.click(); } } // Time waiting click List<WebElement> times = driver.findElements(waitingList); int waitingSize = times.size(); // // System.out.println(waitingSize); for (int i = 0; i < waitingSize; i++) { String textWaiting = times.get(i).getAttribute("id"); WebElement labelTime = driver.findElement(By.cssSelector("label[for='" + textWaiting + "'")); // System.out.println("Time labels: " + labelTime.getText()); if (labelTime.getAttribute("textContent").equalsIgnoreCase(strWaiting)) { labelTime.click(); } } // Learning check List<WebElement> learnings = driver.findElements(learningList); int learningSize = learnings.size(); // System.out.println(size); for (int i = 0; i < learningSize; i++) { String textLearning = learnings.get(i).getAttribute("id"); WebElement labelLearning = driver.findElement(By.cssSelector("label[for='" + textLearning + "'")); // System.out.println("Learning labels: " + labelLearning.getText()); if (labelLearning.getAttribute("textContent").equalsIgnoreCase(strLearn)) { labelLearning.click(); } if (labelLearning.getAttribute("textContent").equalsIgnoreCase(strLearn) && labelLearning.getAttribute("textContent").equalsIgnoreCase("Other")) { labelLearning.click(); driver.findElement(otherField).sendKeys("<NAME>"); } } // Scroll page down JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollTo(0,document.body.scrollHeight)"); // Menu selection List<WebElement> selections = driver.findElements(selectionList); // list of values from the radio button WebElement valueSelection; // loop for searching the particular element for (WebElement selection : selections) { // Getting the value of the element valueSelection = selection.findElement(By.cssSelector("label")); // condition to click on the element if (valueSelection.getAttribute("textContent").equalsIgnoreCase(strMen)) { // If condition satisfies, click on the element selection.findElement(By.cssSelector("input")).click(); } } // Staff service List<WebElement> services = driver.findElements(servicesList); WebElement valueService; for (WebElement service : services) { valueService = service.findElement(By.cssSelector("label")); if (valueService.getAttribute("textContent").equalsIgnoreCase(strStuff)) { service.findElement(By.cssSelector("input")).click(); } } // Menu pricing List<WebElement> pricing = driver.findElements(pricingList); WebElement valuePricing; for (WebElement priceElement : pricing) { valuePricing = priceElement.findElement(By.cssSelector("label")); if (valuePricing.getAttribute("textContent").equalsIgnoreCase(strPricing)) { priceElement.findElement(By.cssSelector("input")).click(); } } // Cleanliness of restaurant List<WebElement> cleanlinesses = driver.findElements(cleanList); WebElement valueCleaness; for (WebElement clean : cleanlinesses) { valueCleaness = clean.findElement(By.cssSelector("label")); if (valueCleaness.getAttribute("textContent").equalsIgnoreCase(strClean)) { clean.findElement(By.cssSelector("input")).click(); } } // Recommend check List<WebElement> recommendations = driver.findElements(recommendationList); int recomemendationSize = recommendations.size(); for (int i = 0; i < recomemendationSize; i++) { String textRecommnedation = recommendations.get(i).getAttribute("id"); WebElement labelRecommendation = driver .findElement(By.cssSelector("label[for='" + textRecommnedation + "'")); labelRecommendation.getText(); if (labelRecommendation.getAttribute("textContent").equalsIgnoreCase(strRecommend)) { labelRecommendation.click(); } } // Message input driver.findElement(messageField).sendKeys(strMessage); } } <file_sep>package com.mf.base; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.events.EventFiringWebDriver; import com.mf.util.AppUtil; import com.mf.util.WebEventListener; public class BaseClass { public static WebDriver driver; public static Properties prop; public static EventFiringWebDriver fireDriver; public static WebEventListener eventListener; public BaseClass() { try { prop = new Properties(); FileInputStream fis = new FileInputStream( System.getProperty("user.dir") + "/src/main/java/com/mf/config/config.properties"); prop.load(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void initialize() { String browserName = prop.getProperty("browser"); if (browserName.equals("chrome")) { System.setProperty("webdriver.chrome.driver", "E:/SeleniumBrowserDriver/chromedriver.exe/"); driver = new ChromeDriver(); } fireDriver = new EventFiringWebDriver(driver); eventListener = new WebEventListener(); fireDriver.register(eventListener); driver = fireDriver; // driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(AppUtil.LONG_TIMEOUT, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(AppUtil.IMPLICIT_WAIT, TimeUnit.SECONDS); driver.get(prop.getProperty("url")); } } <file_sep>package com.mf.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.mf.base.BaseClass; public class ContactFormPage extends BaseClass { WebDriver driver; // Elements By firstNameField = By.xpath("//*[@id=\"element_1_1\"]"); By lastNameField = By.xpath("//*[@id=\"element_1_2\"]"); By emailField = By.xpath("//*[@id=\"element_2\"]"); By messageFirld = By.xpath("//*[@id=\"element_3\"]"); By submitButton = By.id("submit_form"); public ContactFormPage(WebDriver driver) { this.driver = driver; } // Url check public String checkUrl() { return driver.getCurrentUrl(); } // Title check public String checkTitle() { return driver.getTitle(); } // Fill form with data public void submitForm(String strFirstName, String strLastName, String strEmail, String strMessage) { // Data input driver.findElement(firstNameField).sendKeys(strFirstName); driver.findElement(lastNameField).sendKeys(strLastName); driver.findElement(emailField).sendKeys(strEmail); driver.findElement(messageFirld).sendKeys(strMessage); driver.findElement(submitButton).click(); } }
d5bd7db8b155d197415cd86b5343a9b613187c4d
[ "Java", "HTML" ]
4
HTML
snezanaKrstovic/SeleniumMatchForm
76730c5a9da289e3de56cad9c08c73ced21c80c5
802a394ac76ba5c401f9eb5fe9c31281e5a3b02d
refs/heads/main
<file_sep>import turtle, random WinX = int(input("Resolution of the screen on X: ")) WinY = int(input("Resolution of the screen on Y: ")) List_Of_Airports = [] List_Of_Planes = [] Active_Routes = [] List_Of_Positions = [] Speed = 0.1 HowManyPlanesToSpawn = 1 class Program: def __init__(self): self.main() def main(self): global HowManyPlanesToSpawn self.CreateWindow(WinX, WinY) self.CreateAirports(int(input("How many airports: "))) for Airport in List_Of_Airports: HowManyPlanesToSpawn += 1 self.UpdateWindow() def MoveMultiplePlanes(self): global Speed IDE = 0 for Plane in List_Of_Planes: Plane.forward(Speed) self.CheckArrival(IDE) IDE += 1 def UpdateSpeed(self): global Speed HowManyPlanes = int(len(List_Of_Planes)) Speed = 0.1 * HowManyPlanes def CheckArrival(self, ID): Plane = List_Of_Planes[ID] Positions = List_Of_Positions[ID] PosX = Positions[0] PosY = Positions[1] if Plane.distance(PosX, PosY) <= 2: List_Of_Planes.pop(ID) List_Of_Positions.pop(ID) Plane.hideturtle() def PreparePlane(self, PosX, PosY, ID): Plane = List_Of_Planes[ID] Plane.setheading(Plane.towards(PosX, PosY)) List_Of_Positions.append([PosX, PosY]) def CreatePlane(self, PosX, PosY): Plane = turtle.Turtle() Plane.hideturtle() Plane.color("white") Plane.shapesize(1.2, 1) Plane.pencolor("black") Plane.pensize(4) Plane.penup() Plane.goto(PosX, PosY) Plane.showturtle() Plane.pendown() List_Of_Planes.append(Plane) def CreateRoute(self): Route = turtle.Turtle() Route.hideturtle() Route.penup() Route.color("red") Airport_Start = random.randint(0, len(List_Of_Airports) -1) Airport_End = random.randint(0, len(List_Of_Airports)-1) while Airport_Start == Airport_End: Airport_Start = random.randint(0, len(List_Of_Airports)-1) Airport_End = random.randint(0, len(List_Of_Airports)-1) Airport_Start = List_Of_Airports[Airport_Start] Airport_End = List_Of_Airports[Airport_End] Route.goto(Airport_Start.xcor(), Airport_Start.ycor()) Route.pensize(1.5) Route.pendown() Route.setheading(Route.towards(Airport_End.xcor(), Airport_End.ycor())) Route.forward(Route.distance(Airport_End.xcor(), Airport_End.ycor())) Active_Routes.append([Airport_Start, Airport_End]) def CreateAirports(self, HowMany): for i in range(HowMany): Random_LocationX = random.randint(-WinX/2, WinX/2) Random_LocationY = random.randint(-WinY/2, WinY/2) for Airport in List_Of_Airports: if Airport.distance(Random_LocationX, Random_LocationY) <= 200: while Airport.distance(Random_LocationX, Random_LocationY) <= 200: Random_LocationX = random.randint(-WinX/2, WinX/2) Random_LocationY = random.randint(-WinY/2, WinY/2) self.CreateAirport(Random_LocationX, Random_LocationY) def CreateAirport(self, PosX, PosY): Airport = turtle.Turtle() Airport.hideturtle() Airport.penup() Airport.color("midnight blue") Airport.setheading(Airport.towards(PosX, PosY)) Airport.forward(Airport.distance(PosX, PosY)) Airport.shape("circle") Airport.shapesize(2, 2) Airport.showturtle() List_Of_Airports.append(Airport) def CreateWindow(self, SizeX, SizeY): Screen = turtle.Screen() Screen.setup(SizeX, SizeY) Screen.bgcolor("black") def UpdateWindow(self): global Finished_Routes while True: AIE = 0 Chance = random.randint(int(-500/HowManyPlanesToSpawn), int(500/HowManyPlanesToSpawn)) if Chance == 0: self.CreateRoute() ID = int(len(Active_Routes) - 1) Route = Active_Routes[ID] Airport_Start = Route[0] Airport_End = Route[1] self.CreatePlane(Airport_Start.xcor(), Airport_Start.ycor()) self.PreparePlane(Airport_End.xcor(), Airport_End.ycor(), len(List_Of_Planes)-1) self.UpdateSpeed() self.MoveMultiplePlanes() for Plane in List_Of_Planes: self.CheckArrival(AIE) AIE += 1 turtle.Screen().update() if __name__ == "__main__": Program()
e67b44d9e9e68d348d21ebf4c374b8cf5f329666
[ "Python" ]
1
Python
MrMc32/Plane-Simulator
996b051a45e2da6b44078d2d950554c21c1ed985
65863cc77e6b509aa16789fb91d2461ae2537090
refs/heads/master
<repo_name>phyneswlgore/eb-all-in-one<file_sep>/README.md # eb-all-in-one This is a git repository to test the process of including a docker file in a php applciations root directory. lastic Beanstalk will then use the repository to build a Docker container with the application <file_sep>/Dockerfile #Description: Generic Dockerfile for hosting php applications on apache #Date:07.10.15 FROM php:5.6-apache #Author MAINTAINER "<NAME>" #Install the dependecies (GIT) #RUN apt-get update -y #Clean up the container RUN cd /var/www/html/ RUN rm * COPY * /var/www/html/ RUN rm /var/www/html/Docker* /var/www/html/README.md #RUN rsync -r --verbose --exclude 'Docker*' * /var/www/html/ #Expose port 80 EXPOSE 80 <file_sep>/index.php <p>Hi Krishna!</p>
07c530e3218240840f0e894615f51d1d897432a2
[ "Markdown", "Dockerfile", "PHP" ]
3
Markdown
phyneswlgore/eb-all-in-one
459f9e6ee20fd6be1942b11faeb73e30dfcd18b3
ab6339b293bbf34aba063a0e79be1425fe4c58d7
refs/heads/master
<file_sep>// native scope import * as path from 'path'; export { path }; // @pushrocks scope import * as smartcli from '@pushrocks/smartcli'; import * as smartlog from '@pushrocks/smartlog'; import * as smartlogDestinationLocal from '@pushrocks/smartlog-destination-local'; export { smartcli, smartlog, smartlogDestinationLocal }; <file_sep>import { expect, tap } from '@pushrocks/tapbundle'; process.env.CLI_CALL = 'true'; import * as finplusCli from '../ts/index'; tap.test('first test', async () => { console.log(finplusCli); }); tap.start(); <file_sep>import * as plugins from './finplus-cli.plugins'; export const packageDir = plugins.path.join(__dirname, '../');<file_sep>import * as plugins from './finplus-cli.plugins'; import * as paths from './paths'; import { logger } from './finplus-cli.logging'; import { ProjectInfo } from '@pushrocks/projectinfo'; const run = async () => { const projectInfo = new ProjectInfo(paths.packageDir); logger.log('info', `Starting finplus-cli ${projectInfo.npm.version}`); }; if(process.env.CLI_CALL) { run(); }
6aea321d6efedd6204c62b058c9361af927cfd7a
[ "TypeScript" ]
4
TypeScript
financeplus/finplus-cli
957a2e1820c2be498b69bb007328ed27ae0323e8
ae019c7194c3281d0ec4c84738ea0e16ab6a4e14
refs/heads/master
<file_sep>var pg = require('pg'); var Promise = require('bluebird'); function pluckId (row) { return +row[0].id; } function SqlError (args, error) { this.name = 'SqlError'; this.args = args; this.details = error; this.message = 'Can\'t complete SQL query due to error.'; } function mysqlToPg (sql) { var index = 1; return sql.replace(/\?/g, function () { return '$' + index++; }); } function ctor (connectionParameters) { return function query () { var args = Array.prototype.slice.call(arguments); var isInsert = args[0].indexOf('insert into') == 0; if (isInsert) { args[0] += ' returning id'; } args[0] = mysqlToPg(args[0]); var promise = new Promise(function(resolve, reject) { pg.connect(connectionParameters, function (error, client, done) { if (error) { return reject(new SqlError(args, error)); } args.push(function (error, result) { done(); // Release connection to pool if (error) { reject(new SqlError(args, error)); } else { resolve(result.rows); } }); client.query.apply(client, args); }); }); if (isInsert) { promise = promise.then(pluckId); } return promise; }; } module.exports = ctor; <file_sep># sqlcut-pg PostgreSQL API adapter for [sqlcut](https://github.com/titarenko/sqlcut) module. # API "Promises" means "returns promise". ## query(sql, paramsArray) Promises array of results. ```js var sqlcut = require('sqlcut'); var db = sqlcut('sqlcut-pg', connectionParameters); db.query('select * from products where name = ?', ['beer']).then(console.log); ``` # License BSD
4ca889d609279030796dea1282fa9c55f93d85b9
[ "JavaScript", "Markdown" ]
2
JavaScript
boo1ean/sqlcut-pg
b466ab8a3e36fa9651d4cbdee8f5074848e237f9
0771fd84cddf2038deb5265928afbabbef68c1b5
refs/heads/master
<file_sep>// --------------------------------------------------------------------------- // This code shows a simple controller for a 3D PotterBot extruder only // A Button is used to enable or disable the extruder // A 24 v Relay shield is used to read I/Os from the robot to activate the tool (if required) // The max. and minimum ranges of speed are controlled through a Potentiometer // LCD displays Extruder state (Enable/ Disabled, ON, OFF and Speed %) // 2016 <NAME> // v 1.0 #include <SoftwareSerial.h> //Kuka Pin for reading I/O 2 const int KukaPin = 2; //LCD SoftwareSerial myLCD(3, 4); // pin 3 = TX, pin 4 = RX (unused) char powerstring[10], spdstring[10]; // create string arrays //fan is controlled through a Relay const int fanPin = 10; // const int driverPin = 11; const int dirPin = 8; const int stepperPin = 9; //Potentiometer const int potPin = A0; String powerState; int speedExtrude, speedPrint; int KukaPinState, potValue, reading, extruderState; boolean secondOFF = false; // Variables button: const int buttonPin = 7; int driverState = LOW; // the current state of the output pin int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 30; // the debounce time void setup() { //LCD setup myLCD.begin(9600); // set up serial port for 9600 baud delay(500); // wait for display to boot up myLCD.write(254); // cursor to beginning of first line myLCD.write(128); myLCD.write("Power: "); // clear display + legends myLCD.write("Speed: "); pinMode(KukaPin, INPUT); pinMode(dirPin, OUTPUT); pinMode(stepperPin, OUTPUT); pinMode(potPin, INPUT); pinMode(fanPin, OUTPUT); pinMode(driverPin, OUTPUT); digitalWrite(driverPin, driverState); delay(1000); } void readKuka () { //Uncomment if not reading from Kuka I/O //KukaPinState = LOW; if (KukaPinState == LOW) { powerState = " ON "; digitalWrite(fanPin, HIGH); secondOFF = false; } else { powerState = " OFF "; digitalWrite(fanPin, LOW); //Retraction test //if (secondOFF == false) { //step(false, 2000); //secondOFF= true; //} } //Turn ON/OFF extruder digitalWrite(driverPin, !KukaPinState); //digitalWrite(fanPin, driverState); } //Function reads I/O from Kuka to enable/disable the extruder void readPower() { reading = digitalRead(buttonPin); if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // if the button state has changed: if (reading != buttonState) { buttonState = reading; // only toggle the extruderState (Enabled/Diabled) if the new button state is HIGH if (buttonState == HIGH) { extruderState = !extruderState; } } } lastButtonState = reading; if (extruderState == HIGH) { //powerState = " ENABLED "; readKuka(); } else { powerState = " DISABLED "; digitalWrite(driverPin, LOW); } } //Function reads potentiometer to change extrusion speed and prints data void readPot() { potValue = analogRead(potPin); // 500 and 2000 were extreme working values according to test speedExtrude = map (potValue, 0, 1023, 500, 2000); // 0-100% of speed allowance speedPrint = map (speedExtrude, 500, 2000, 100, 0); //Print feedback data in LCD sprintf(spdstring, "%4d", speedPrint); // right-justify to 4 spaces //Print POWER ON/OFF state myLCD.write(254); // cursor to 7th position on first line myLCD.write(134); myLCD.print(powerState); //Print SPEED % myLCD.write(254); myLCD.write(198); myLCD.write(spdstring); } //Step function void step(boolean dir, int steps) { if (dir) digitalWrite(dirPin, HIGH); else digitalWrite(dirPin, LOW); for (int i = 0; i < steps; i++) { delayMicroseconds(speedExtrude); digitalWrite(stepperPin, HIGH); delayMicroseconds(speedExtrude); digitalWrite(stepperPin, LOW); } } void loop() { readPower(); readPot(); // The motor should revolve one revolution/200 steps in one direction step(true, 200); //delay(5); } <file_sep># ClayExtruder ClayExtruder is an Arduino based open source controller for a 3D PotterBot * Extruder only * for use as end effector of a robotic arm. You'll need: - an Arduino, we are using Uno - PotterBot extruder, NEMA 23 stepper http://www.deltabots.com/products/3d-potterbot-20 - Polulu DRV8825 Stepper Motor Driver Carrier, High Current - 5v 1 channel Relay Module for turning ON/OFF the fan. - Small fan (we used a 12V) - 12V power supply for the stepper and fan - 24v Relay shield if you want to read robot I/Os to activate extruder. - Serial LCD - Button
d358e04fac3d5bd157f645c5703b4304ddc7cfc1
[ "Markdown", "C++" ]
2
C++
susanaalarcon/ClayExtruder
01e53493694aaf0e53d38ccbcb6fe9e4bea65be9
85de082c08dfd6cb3b58b2194088061f6415e8ad
refs/heads/master
<repo_name>yduf/stylo<file_sep>/core/fb.cc // FrameBuffer implementation #include <cerrno> #include <cstdint> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <linux/fb.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <string> #include <iostream> // #include "mxcfb.h" // use libremarkable/legacy-c-impl/libremarkable/lib.h which is cleaner&complete struct Point { int x, y; }; struct Rect { Point topLeft; Point bottomRight; int height() const { return bottomRight.y - topLeft.y; } int width() const { return bottomRight.x - topLeft.x; } }; // from libremarkable/legacy-c-impl/libremarkable/lib.h // 0x4048 is the Remarkable Prefix // 'F' (0x46) is the namespace #define REMARKABLE_PREFIX(x) (0x40484600 | x) typedef enum _eink_ioctl_command { MXCFB_SET_WAVEFORM_MODES = 0x2B, // takes struct mxcfb_waveform_modes MXCFB_SET_TEMPERATURE = 0x2C, // takes int32_t MXCFB_SET_AUTO_UPDATE_MODE = 0x2D, // takes __u32 MXCFB_SEND_UPDATE = 0x2E, // takes struct mxcfb_update_data MXCFB_WAIT_FOR_UPDATE_COMPLETE = 0x2F, // takes struct mxcfb_update_marker_data MXCFB_SET_PWRDOWN_DELAY = 0x30, // takes int32_t MXCFB_GET_PWRDOWN_DELAY = 0x31, // takes int32_t MXCFB_SET_UPDATE_SCHEME = 0x32, // takes __u32 MXCFB_GET_WORK_BUFFER = 0x34, // takes unsigned long MXCFB_SET_TEMP_AUTO_UPDATE_PERIOD = 0x36, // takes int32_t MXCFB_DISABLE_EPDC_ACCESS = 0x35, MXCFB_ENABLE_EPDC_ACCESS = 0x36 } eink_ioctl_command; typedef enum _update_mode { UPDATE_MODE_PARTIAL = 0, UPDATE_MODE_FULL = 1 } update_mode; typedef enum _waveform_mode { WAVEFORM_MODE_INIT = 0x0, /* Screen goes to white (clears) */ WAVEFORM_MODE_GLR16 = 0x4, /* Basically A2 (so partial refresh shouldnt be possible here) */ WAVEFORM_MODE_GLD16 = 0x5, /* Official -- and enables Regal D Processing */ // Unsupported? WAVEFORM_MODE_DU = 0x1, /* [Direct Update] Grey->white/grey->black -- remarkable uses this for drawing */ WAVEFORM_MODE_GC16 = 0x2, /* High fidelity (flashing) */ WAVEFORM_MODE_GC4 = WAVEFORM_MODE_GC16, /* For compatibility */ WAVEFORM_MODE_GC16_FAST = 0x3, /* Medium fidelity -- remarkable uses this for UI */ WAVEFORM_MODE_GL16_FAST = 0x6, /* Medium fidelity from white transition */ WAVEFORM_MODE_DU4 = 0x7, /* Medium fidelity 4 level of gray direct update */ WAVEFORM_MODE_REAGL = 0x8, /* Ghost compensation waveform */ WAVEFORM_MODE_REAGLD = 0x9, /* Ghost compensation waveform with dithering */ WAVEFORM_MODE_GL4 = 0xA, /* 2-bit from white transition */ WAVEFORM_MODE_GL16_INV = 0xB, /* High fidelity for black transition */ WAVEFORM_MODE_AUTO = 257 /* Official */ } waveform_mode; typedef enum _display_temp { TEMP_USE_AMBIENT = 0x1000, TEMP_USE_PAPYRUS = 0X1001, TEMP_USE_REMARKABLE_DRAW = 0x0018, TEMP_USE_MAX = 0xFFFF } display_temp; typedef struct { uint32_t top; uint32_t left; uint32_t width; uint32_t height; } mxcfb_rect; typedef struct { uint32_t update_marker; uint32_t collision_test; } mxcfb_update_marker_data; typedef struct { uint32_t phys_addr; uint32_t width; /* width of entire buffer */ uint32_t height; /* height of entire buffer */ mxcfb_rect alt_update_region; /* region within buffer to update */ } mxcfb_alt_buffer_data; typedef struct { mxcfb_rect update_region; uint32_t waveform_mode; // Choose between FULL and PARTIAL uint32_t update_mode; // Checkpointing uint32_t update_marker; int temp; // 0x1001 = TEMP_USE_PAPYRUS unsigned int flags; // 0x0000 /* * Dither mode is entirely unused since the following means v1 is used not v2 * * arch/arm/configs/zero-gravitas_defconfig 173:CONFIG_FB_MXC_EINK_PANEL=y firmware/Makefile 68:fw-shipped-$(CONFIG_FB_MXC_EINK_PANEL) += \ drivers/video/fbdev/mxc/mxc_epdc_fb.c 4969:#ifdef CONFIG_FB_MXC_EINK_AUTO_UPDATE_MODE 5209:#ifdef CONFIG_FB_MXC_EINK_AUTO_UPDATE_MODE drivers/video/fbdev/mxc/mxc_epdc_v2_fb.c 5428:#ifdef CONFIG_FB_MXC_EINK_AUTO_UPDATE_MODE 5662:#ifdef CONFIG_FB_MXC_EINK_AUTO_UPDATE_MODE drivers/video/fbdev/mxc/Makefile 10:obj-$(CONFIG_FB_MXC_EINK_PANEL) += mxc_epdc_fb.o 11:obj-$(CONFIG_FB_MXC_EINK_V2_PANEL) += mxc_epdc_v2_fb.o * */ int dither_mode; int quant_bit; // used only when dither_mode is > PASSTHROUGH and < MAX mxcfb_alt_buffer_data alt_buffer_data; // not used when flags is 0x0000 } mxcfb_update_data; // end from libremarkable/legacy-c-impl/libremarkable/lib.h class FrameBuffer: public Rect { public: int device; std::string path; int frame_length; uint8_t* mem_map; fb_var_screeninfo vinfo; fb_fix_screeninfo finfo; public: static FrameBuffer open( const char* path = "/dev/fb0") { FrameBuffer fb; fb.path = path; fb.device = ::open( path, O_RDWR); if( fb.device < 1) throw "FrameBuffer: could not open '" + fb.path + "'\n"; fb.vinfo = fb.get_vinfo(); fb.bottomRight = Point{ (int) fb.vinfo.xres, (int) fb.vinfo.yres}; if( fb.vinfo.bits_per_pixel != 16) throw "FrameBuffer: expected 16 bits per pixel, but got " + std::to_string( fb.vinfo.bits_per_pixel) + "\n" + " If running on rM2, you should use rmf2b\n"; fb.finfo = fb.get_finfo(); // map the memory fb.frame_length = fb.finfo.line_length * fb.vinfo.yres; fb.mem_map = (uint8_t*) mmap( 0, fb.frame_length, PROT_READ | PROT_WRITE, MAP_SHARED, fb.device, 0); if( fb.mem_map == nullptr) throw "FrameBuffer: unable to mmap frame '" + fb.path + "'\n"; return fb; } void to_s() const { std::cerr << "opened '" << path << "' - " << vinfo.xres << "x" << vinfo.yres << ", depth: " << vinfo.bits_per_pixel << " bits" << ", row: " << finfo.line_length << " bytes" << ", addr: " << (void*) mem_map << ", size:" << frame_length << " bytes" << std::endl; } // Not sure we should implement this // kernel should take of that => and we should not copy that object ~FrameBuffer() { std::cerr << "closed" << std::endl; // ::close( device); } // raw info fb_var_screeninfo raw_vinfo() const { // Fetch the size of the display. fb_var_screeninfo screenInfo; if( ioctl(device, FBIOGET_VSCREENINFO, &screenInfo)) throw "FrameBuffer: could not FBIOGET_VSCREENFINO '" + path + "'.\n"; return screenInfo; } // update info void raw_vinfo( const fb_var_screeninfo& screenInfo) const { if( ioctl(device, FBIOPUT_VSCREENINFO, &screenInfo)) throw "FrameBuffer: could not FBIOPUT_VSCREENINFO '" + path + "'.\n"; } // update vinfo // on rm2/rm2buffer raw output: opened '/dev/fb0' - 260x1408, depth: 32bits // using rmfb2 once fixed: opened '/dev/fb0' - 1404x1872, depth: 16 bits, row: 2808 bytes, addr: 0x752f5000, size:5256576 bytes // taken from libremarkable rust code fb_var_screeninfo get_vinfo() const { auto var_screen_info = raw_vinfo(); var_screen_info.xres = 1404; var_screen_info.yres = 1872; var_screen_info.rotate = 1; var_screen_info.width = 0xffff'ffff; var_screen_info.height = 0xffff'ffff; var_screen_info.pixclock = 6250; var_screen_info.left_margin = 32; var_screen_info.right_margin = 326; var_screen_info.upper_margin = 4; var_screen_info.lower_margin = 12; var_screen_info.hsync_len = 44; var_screen_info.vsync_len = 1; var_screen_info.sync = 0; var_screen_info.vmode = 0; // FB_VMODE_NONINTERLACED var_screen_info.accel_flags = 0; raw_vinfo( var_screen_info); // fix device definition return raw_vinfo(); } fb_fix_screeninfo get_finfo() const { fb_fix_screeninfo finfo; if( ioctl( device, FBIOGET_FSCREENINFO, &finfo)) throw "FrameBuffer: could not FBIOGET_FSCREENINFO '" + path + "'\n"; return finfo; } // basic drawing void fill( uint8_t color ) { std::memset( mem_map, color, frame_length ); } // full refresh void refresh() const { mxcfb_update_data whole{ mxcfb_rect{0,0,vinfo.xres,vinfo.yres}, WAVEFORM_MODE_GL16_FAST, //waveform, UPDATE_MODE_PARTIAL, // UPDATE_MODE_FULL, // mode, 0x2a, // marker, 0x0018, //TEMP_USE_AMBIENT, // temp, 0, // flags 0, //dither_mode, 0, // quant_bit, mxcfb_alt_buffer_data{} }; int status; if( status = ioctl( device, REMARKABLE_PREFIX(MXCFB_SEND_UPDATE), &whole)) throw "FrameBuffer: failed to MXCFB_SEND_UPDATE: " + std::to_string(status) + " (errno= " + std::to_string(errno) + ") \n"; } // fast refresh of selected area void refresh( const Rect& r) const { mxcfb_update_data whole{ mxcfb_rect{ r.topLeft.y, r.topLeft.x, r.width(), r.height()}, WAVEFORM_MODE_DU, //waveform, UPDATE_MODE_PARTIAL, // UPDATE_MODE_FULL, // mode, 0x2a, // marker, 0x0018, //TEMP_USE_AMBIENT, // temp, 0, // flags 0, //dither_mode, 0, // quant_bit, mxcfb_alt_buffer_data{} }; int status; if( status = ioctl( device, REMARKABLE_PREFIX(MXCFB_SEND_UPDATE), &whole)) throw "FrameBuffer: failed to MXCFB_SEND_UPDATE: " + std::to_string(status) + " (errno= " + std::to_string(errno) + ") \n"; } // animation: fast refresh of selected areas void refresh( const Rect& r1, const Rect& r2) { refresh( r1); refresh( r2); } }; <file_sep>/core/test/animation_test.cc #include <iostream> #include <math.h> #include "../fb.cc" using namespace std; #include "cairo.h" // small wrapper around cairo // for test (see cairomm as alternative) /* Destroy a cairo surface */ struct Draw { cairo_surface_t* surface; cairo_t *cr; Draw( FrameBuffer& fb) { /* Create the cairo surface which will be used to draw to */ surface = cairo_image_surface_create_for_data( fb.mem_map, CAIRO_FORMAT_RGB16_565, fb.vinfo.xres, fb.vinfo.yres, cairo_format_stride_for_width(CAIRO_FORMAT_RGB16_565, fb.vinfo.xres)); cairo_surface_set_user_data(surface, NULL, this, &cairo_linuxfb_surface_destroy); cr = cairo_create(surface); /* * We clear the cairo surface here before drawing * This is required in case something was drawn on this surface * previously, the previous contents would not be cleared without this. */ //cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR); //cairo_paint(cr); //cairo_set_operator(cr, CAIRO_OPERATOR_OVER); cairo_set_line_width(cr, 0.5); cairo_move_to(cr, 10, 10); cairo_line_to(cr, 1000, 1500); cairo_stroke(cr); fb.refresh(); // full refresh } static void cairo_linuxfb_surface_destroy(void *device) { } Rect draw_at( int x, int y) { cairo_arc(cr, x, y, 10.0, 0.0, 2 * M_PI); cairo_fill_preserve(cr); cairo_stroke(cr); return Rect{ Point{x,y}, Point{x+10,y+10} }; } Rect erase_at( int x, int y ) { return Rect{ Point{x,y}, Point{x+10,y+10} }; } }; int main(int argc,char** argv) { try { cerr << "Hello World" << endl; auto fb = FrameBuffer::open(); fb.to_s(); // drawing tool Draw dr( fb); // orbit a figure around the center of the screen const Point center{ fb.width()/2, fb.height()/2}; const double r = 500; double x = 0, y = 0; for( double a=0; a < 2*3.14; a += 1*3.14/180) { //int a = 0; auto erase_rect = dr.erase_at( x, y); // erase previous // move double x = r*cos(a) + center.x; double y = r*sin(a) + center.y; auto draw_rect = dr.draw_at( x, y); // redraw // fast refresh fb.refresh( draw_rect, erase_rect); } cerr << "done" << endl; } catch(const char* msg) { cerr << "ERROR : " << msg << endl; } catch(const string& msg) { cerr << "ERROR : " << msg << endl; } }<file_sep>/core/test/simple_drawing_test.cc #include <iostream> #include <math.h> #include "../fb.cc" #include "../input.cc" using namespace std; #include "cairo.h" // small wrapper around cairo // for test (see cairomm as alternative) /* Destroy a cairo surface */ struct Draw { cairo_surface_t* surface; cairo_t *cr; Draw( FrameBuffer& fb) { /* Create the cairo surface which will be used to draw to */ surface = cairo_image_surface_create_for_data( fb.mem_map, CAIRO_FORMAT_RGB16_565, fb.vinfo.xres, fb.vinfo.yres, cairo_format_stride_for_width(CAIRO_FORMAT_RGB16_565, fb.vinfo.xres)); cairo_surface_set_user_data(surface, NULL, this, &cairo_linuxfb_surface_destroy); cr = cairo_create(surface); /* * We clear the cairo surface here before drawing * This is required in case something was drawn on this surface * previously, the previous contents would not be cleared without this. */ //cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR); //cairo_paint(cr); //cairo_set_operator(cr, CAIRO_OPERATOR_OVER); cairo_set_line_width(cr, 0.5); cairo_move_to(cr, 10, 10); cairo_line_to(cr, 1000, 1500); cairo_stroke(cr); fb.refresh(); // full refresh } static void cairo_linuxfb_surface_destroy(void *device) { } Rect draw_at( int x, int y) { cairo_arc(cr, x, y, 10.0, 0.0, 2 * M_PI); cairo_fill_preserve(cr); cairo_stroke(cr); return Rect{ Point{x,y}, Point{x+10,y+10} }; } Rect erase_at( int x, int y ) { return Rect{ Point{x,y}, Point{x+10,y+10} }; } }; int main(int argc,char** argv) { try { cerr << "Hello World" << endl; auto fb = FrameBuffer::open(); Input input; fb.to_s(); // drawing tool Draw dr( fb); input.loop([&](auto& event){ if( event.touch) { auto draw_rect = dr.draw_at( event.pos.x, event.pos.y); fb.refresh( draw_rect); // fast refresh } switch( event.key) { case KEY_POWER: cerr << "leaving" << endl; exit(0); } }); cerr << "done" << endl; } catch(const char* msg) { cerr << "ERROR : " << msg << endl; } catch(const string& msg) { cerr << "ERROR : " << msg << endl; } }<file_sep>/README.md # Goal Provide an alternative to xochitl - **Focus** on org mode / note taking - calendar / search / contact - fast virtual keyboard - document linking * handwritting recognition - virtual page - expand / cut - integrated tech drawing * import / export * external integration - android / mail / cloud / PC * external plugin extension (contrary to xochitl) # Plan ## Basic Done: + compile hello world (console print) + basic drawing (libremarakble demo) in c++ + framebuffer basics - https://discord.com/channels/385916768696139794/771436565757952070/813914877717381170 + input basic + simple sketch drawing => follow pen / draws Left to do: - draw text * be able to remote debug with gdb ## Document - define a representation for document <file_sep>/Makefile CXX = arm-linux-gnueabihf-g++ # DO NOT USE -static => it prevent rm2fb-client patching CFLAGS ?= -fPIC -g --std=gnu++17 -Werror=return-type DEVICE_IP ?= '10.11.99.1' DEVICE_HOST ?= root@$(DEVICE_IP) CAIRO ?= /home/yves/DEV/reMarkable/cairo CAIROLIB ?= $(CAIRO)/build-arm LDFLAGS ?= -L $(CAIROLIB)/src/ core: build: core $(CXX) $(CFLAGS) core/test/core_fb_test.cc -o fb_test $(CXX) $(CFLAGS) core/test/input_test.cc -o input_test $(LDFLAGS) -lstdc++fs $(CXX) $(CFLAGS) -I $(CAIRO)/src -I $(CAIROLIB)/src core/test/animation_test.cc -o animation_test $(LDFLAGS) -lcairo $(CXX) $(CFLAGS) -I $(CAIRO)/src -I $(CAIROLIB)/src core/test/simple_drawing_test.cc -o simple_drawing_test $(LDFLAGS) -lcairo -lstdc++fs deploy-lib: scp $(CAIROLIB)/src/libcairo.so.2 $(DEVICE_HOST): scp $(CAIROLIB)/subprojects/pixman/pixman/libpixman-1.so.0 $(DEVICE_HOST): deploy: build scp ./animation_test $(DEVICE_HOST): ssh -t $(DEVICE_HOST) 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. /opt/bin/rm2fb-client ./animation_test' input_test: build scp ./input_test $(DEVICE_HOST): ssh -t $(DEVICE_HOST) './input_test' simple_drawing_test: build scp ./simple_drawing_test $(DEVICE_HOST): ssh -t $(DEVICE_HOST) 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. /opt/bin/rm2fb-client ./simple_drawing_test' <file_sep>/core/test/input_test.cc #include <fcntl.h> #include <unistd.h> #include <linux/input.h> #include <poll.h> #include <iostream> #include <array> #include <vector> using namespace std; #include <filesystem> namespace fs = std::filesystem; // from https://github.com/rmkit-dev/rmkit/blob/master/src/rmkit/input/device_id.cpy // glommed from evtest.c #define BITS_PER_LONG (sizeof(long) * 8) #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) #define OFF(x) ((x)%BITS_PER_LONG) #define BIT(x) (1UL<<OFF(x)) #define LONG(x) ((x)/BITS_PER_LONG) #define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) auto check_bit_set(int fd, int type, int i) { unsigned long bit[NBITS(KEY_MAX)]; ioctl(fd, EVIOCGBIT(type, KEY_MAX), bit); return test_bit(i, bit); } std::string id_by_capabilities(int fd) { int version; // if we can't get version of the fd, its invalid if( ioctl(fd, EVIOCGVERSION, &version)) return "INVALID"; unsigned long bit[EV_MAX]; ioctl(fd, EVIOCGBIT(0, EV_MAX), bit); if( test_bit(EV_KEY, bit)) { if( check_bit_set(fd, EV_KEY, BTN_STYLUS) && test_bit(EV_ABS, bit)) return "STYLUS"; if( check_bit_set(fd, EV_KEY, KEY_POWER)) return "BUTTONS"; if( test_bit(EV_REL, bit) && check_bit_set(fd, EV_ABS, ABS_MT_SLOT)) return "TOUCH"; } return "UNKNOWN"; } // end from https://github.com/rmkit-dev/rmkit/blob/master/src/rmkit/input/device_id.cpy #define SYM(element) [element] = #element array<const char*, EV_CNT> ev_type = {}; array<const char*, SYN_CNT> syn_code = {}; array<const char*, ABS_CNT> abs_code = {}; array<const char*, KEY_CNT> btn_code = {}; template< class T, size_t N> auto to_s( int value, const array<T,N>& label, const string& type) { return value < N ? ( label[value] ? label[value] : type + "=" + to_string( value)) : type + "=" + to_string( value) ; } class Input { vector<pollfd> devices; public: Input() { cerr << "scanning input devices" << endl; for(auto& p: fs::directory_iterator("/dev/input")) { if( !p.is_symlink() && p.is_character_file() ) { int dev = ::open( p.path().c_str(), O_RDONLY | O_NONBLOCK ); std::cerr << p.path() << " " << id_by_capabilities(dev) << endl; pollfd pol = { dev, POLLIN }; devices.push_back( pol); } } cerr << "end" << endl; // define event name ev_type[EV_SYN] = "EV_SYN"; ev_type[EV_KEY] = "EV_KEY"; ev_type[EV_ABS] = "EV_ABS"; // SYN code syn_code[SYN_REPORT] = "SYN_REPORT"; // define ABS code // pen abs_code[ABS_X] = "ABS_X"; abs_code[ABS_Y] = "ABS_Y"; abs_code[ABS_DISTANCE] = "ABS_DISTANCE"; abs_code[ABS_PRESSURE] = "ABS_PRESSURE"; abs_code[ABS_TILT_X] = "ABS_TILT_X"; abs_code[ABS_TILT_Y] = "ABS_TILT_Y"; // btn code btn_code[BTN_TOOL_PEN] = "BTN_TOOL_PEN"; btn_code[BTN_TOOL_RUBBER] = "BTN_TOOL_RUBBER"; // btn_code[KEY_POWER] = "KEY_POWER"; // multitouch abs_code[ABS_MT_SLOT] = "ABS_MT_SLOT"; abs_code[ABS_MT_TOUCH_MAJOR] = "ABS_MT_TOUCH_MAJOR"; abs_code[ABS_MT_TOUCH_MINOR] = "ABS_MT_TOUCH_MINOR"; abs_code[ABS_MT_WIDTH_MAJOR] = "ABS_MT_WIDTH_MAJOR"; abs_code[ABS_MT_WIDTH_MINOR] = "ABS_MT_WIDTH_MINOR"; abs_code[ABS_MT_ORIENTATION] = "ABS_MT_ORIENTATION"; abs_code[ABS_MT_POSITION_X] = "ABS_MT_POSITION_X"; abs_code[ABS_MT_POSITION_Y] = "ABS_MT_POSITION_Y"; abs_code[ABS_MT_TOOL_TYPE] = "ABS_MT_TOOL_TYPE"; abs_code[ABS_MT_BLOB_ID] = "ABS_MT_BLOB_ID"; abs_code[ABS_MT_TRACKING_ID] = "ABS_MT_TRACKING_ID"; abs_code[ABS_MT_PRESSURE] = "ABS_MT_PRESSURE"; for(;;) { int ret = poll( &devices[0], devices.size(), 10000 ); // Check if poll actually succeed if ( ret == -1 ) { // report error and abort cerr << "poll failed" << endl; break; } else if ( ret == 0 ) { // timeout; no event detected cerr << "poll timeout" << endl; continue; } else { // If we detect the event, zero it out so we can reuse the structure for( int i = 0; i < devices.size(); ++i) { auto& pfd = devices[i]; if( pfd.revents & POLLIN ) { // input event on device pfd.revents = 0; cerr << "event on device " << i << endl; read_event( pfd.fd); } } } } } void read_event( int fd) { for(;;) { input_event event; int nbytes = ::read( fd, &event, sizeof( event)); if( nbytes == sizeof(event)) { // ok } else { if (errno != EWOULDBLOCK) { /* real version needs to handle EINTR correctly */ perror("read"); exit(EXIT_FAILURE); } return; // enf of buffer } cerr << "event at " << event.time.tv_sec << ":" << event.time.tv_usec << " " << ::to_s( event.type, ev_type, "type"); switch( event.type) { default: cerr << " code=" << event.code; break; case EV_SYN: cerr << " " << ::to_s( event.code, syn_code, "code"); break; case EV_KEY: // hardware button + pen type cerr << " " << ::to_s( event.code, btn_code, "code"); break; case EV_ABS: // pen + multitouch cerr << " " << ::to_s( event.code, abs_code, "code"); break; } cerr << " value=" << event.value << endl; } } }; int main(int argc,char** argv) { try { // open wacom device cerr << "Hehllo" << endl; Input in; } catch(const char* msg) { cerr << "ERROR : " << msg << endl; } catch(const string& msg) { cerr << "ERROR : " << msg << endl; } }<file_sep>/.devcontainer/Dockerfile FROM ghcr.io/toltec-dev/toolchain:v1.4 ARG USERNAME=yves ARG USER_UID=1000 ARG USER_GID=$USER_UID # add scp / ssh RUN export DEBIAN_FRONTEND=noninteractive \ && apt-get update -y \ && apt-get install -y --no-install-recommends \ openssh-client # Create the user RUN groupadd --gid $USER_GID $USERNAME \ && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME <file_sep>/core/input.cc #include <fcntl.h> #include <unistd.h> #include <linux/input.h> #include <poll.h> #include <iostream> #include <array> #include <vector> using namespace std; #include <filesystem> namespace fs = std::filesystem; // from https://github.com/rmkit-dev/rmkit/blob/master/src/rmkit/input/device_id.cpy // glommed from evtest.c #define BITS_PER_LONG (sizeof(long) * 8) #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) #define OFF(x) ((x)%BITS_PER_LONG) #define BIT(x) (1UL<<OFF(x)) #define LONG(x) ((x)/BITS_PER_LONG) #define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) auto check_bit_set(int fd, int type, int i) { unsigned long bit[NBITS(KEY_MAX)]; ioctl(fd, EVIOCGBIT(type, KEY_MAX), bit); return test_bit(i, bit); } std::string id_by_capabilities(int fd) { int version; // if we can't get version of the fd, its invalid if( ioctl(fd, EVIOCGVERSION, &version)) return "INVALID"; unsigned long bit[EV_MAX]; ioctl(fd, EVIOCGBIT(0, EV_MAX), bit); if( test_bit(EV_KEY, bit)) { if( check_bit_set(fd, EV_KEY, BTN_STYLUS) && test_bit(EV_ABS, bit)) return "STYLUS"; if( check_bit_set(fd, EV_KEY, KEY_POWER)) return "BUTTONS"; if( test_bit(EV_REL, bit) && check_bit_set(fd, EV_ABS, ABS_MT_SLOT)) return "TOUCH"; } return "UNKNOWN"; } // end from https://github.com/rmkit-dev/rmkit/blob/master/src/rmkit/input/device_id.cpy // from rmkit #define WACOMWIDTH 15725.0 #define WACOMHEIGHT 20967.0 #define DISPLAYWIDTH 1404 #define DISPLAYHEIGHT 1872.0 #define WACOM_X_SCALAR (float(DISPLAYWIDTH) / float(WACOMWIDTH)) #define WACOM_Y_SCALAR (float(DISPLAYHEIGHT) / float(WACOMHEIGHT)) // end struct Event { timeval time; // time of events int device; // device from which the event is coming union { // tool detected / or button int tool; int key; }; int touch; // tool touching screen union { struct { Point pos; // position of event }; }; }; // event + loop support class Input { vector<pollfd> devices; public: Input() { cerr << "scanning input devices" << endl; for(auto& p: fs::directory_iterator("/dev/input")) { if( !p.is_symlink() && p.is_character_file() ) { int dev = ::open( p.path().c_str(), O_RDONLY | O_NONBLOCK ); std::cerr << p.path() << " " << id_by_capabilities(dev) << endl; pollfd pol = { dev, POLLIN }; devices.push_back( pol); } } cerr << "end" << endl; }; // Event loop // call lambda on every event gathered template<class Fn> void loop(Fn callback) { for(;;) { int ret = poll( &devices[0], devices.size(), 10000 ); // Check if poll actually succeed if ( ret == -1 ) { // report error and abort cerr << "poll failed" << endl; break; } else if ( ret == 0 ) { // timeout; no event detected cerr << "poll timeout" << endl; continue; } else { // If we detect the event, zero it out so we can reuse the structure for( int i = 0; i < devices.size(); ++i) { auto& pfd = devices[i]; if( pfd.revents & POLLIN ) { // input event on device pfd.revents = 0; cerr << "event on device " << i << endl; readEvent( pfd.fd, callback); } } } } } // convert linux input_event to Event // and call calback when Event is completly defined // see https://www.kernel.org/doc/html/latest/input/event-codes.html template<class Fn> void readEvent( int fd, Fn callback) { static Event res = {}; // let's assume we get a complete set of linux event in buffer each time for(;;) { input_event event; int nbytes = ::read( fd, &event, sizeof( event)); if( nbytes == sizeof(event)) { // ok } else { if (errno != EWOULDBLOCK) { /* real version needs to handle EINTR correctly */ perror("read"); exit(EXIT_FAILURE); } return; // enf of buffer } switch( event.type) { default: cerr << "Unknown event type=" << event.type; break; case EV_SYN: // cerr << " " << ::to_s( event.code, syn_code, "code"); callback( res); break; case EV_KEY: // hardware button + pen type BTN_event( res, event); break; case EV_ABS: // pen + multitouch ABS_event( res, event); break; } } } // void BTN_event( Event& res, const input_event& event ) { switch( event.code ) { default: cerr << "Unknown event code=" << event.code; break; case BTN_TOUCH: res.touch = event.value; case KEY_POWER: case BTN_TOOL_PEN: case BTN_TOOL_RUBBER: res.tool = event.code; break; } } // void ABS_event( Event& res, const input_event& event ) { switch( event.code ) { default: cerr << "Unknown event code=" << event.code; break; // align wacom device with screen buffer coordinates case ABS_X: res.pos.y = DISPLAYHEIGHT - event.value * WACOM_Y_SCALAR; break; case ABS_Y: res.pos.x = event.value * WACOM_X_SCALAR; break; case ABS_DISTANCE: cerr << "hovering "; //res.tool = 0; break; } } };<file_sep>/core/test/core_fb_test.cc #include <iostream> #include "../fb.cc" using namespace std; int main(int argc,char** argv) { try { cerr << "Hello World" << endl; auto fb = FrameBuffer::open(); fb.to_s(); fb.fill( 0x00); fb.refresh(); sleep( 4); fb.fill( 0xFF); fb.refresh(); cerr << "done" << endl; } catch(const char* msg) { cerr << "ERROR : " << msg << endl; } catch(const string& msg) { cerr << "ERROR : " << msg << endl; } }
c0439745273a8fdb344f6148054fdf8f9a3177eb
[ "Markdown", "Makefile", "C++", "Dockerfile" ]
9
C++
yduf/stylo
c84e485c427cdf9d23b9cd7ac96b445f8f7c0494
a3ee7b0e47b0d72bbb0d658996923426a8282445
refs/heads/master
<file_sep>/* * ===================================================================================== * * Filename: PIRDSEvent.cpp * * Description: * * Version: 1.0 * Created: 04/09/2020 14:16:09 * Revision: none * Compiler: gcc * * Author: <NAME> (lauriacl), <EMAIL> * Organization: Public Invention * * ===================================================================================== */ #include "PIRDSEvent.h" void PIRDSEvent::receiveEvent() { if(eventChannel->available()) { } } void PIRDSEvent::sendEvent() { // write the data // ...but for now... eventChannel->print("Event Type:"); eventChannel->println(eventType); eventChannel->print("Event Length:"); eventChannel->println(eventLength); } int PIRDSEvent::setChannel(Stream* channel) { eventChannel = channel; /* need error checking, but this doesn't make much sense yet // wait for connection // serial timeout is 1000 ms delay(2000); // check to see if connection has been established if(eventChannel) { return 1; } else { return 0; } */ return 1; } <file_sep>/* ===================================================================================== * * Filename: PIRDS.h * * Description: * * Version: 1.0 * Created: 04/07/2020 10:35:51 * Revision: none * Compiler: gcc * * Author: <NAME> (lauriaclarke), <EMAIL> * Organization: Public Invention * * ===================================================================================== */ #ifndef PIRDS_H #define PIRDS_H // struct containing measurement event values struct Measurement { char m {'M'}; char measurementType; char deviceType; unsigned char deviceLocation; unsigned long measurementTime; long measurementValue; }; /* PLACEHOLDERS // struct containing assertion event values struct Assertion { }; // struct containing meta event values struct Meta { }; */ #endif <file_sep># Public Invention Respiration Data Standard [Public Invention Respiration Data Standard (PIRDS) v0.1](https://github.com/PubInv/respiration-data-standard/blob/master/PIRDS-v.0.1.md) -- A standard for COVID-19 pandemic ventilator data exchange. This is a sister to the [Public Invention Respiration Control Standard (PIRCS)](https://github.com/PubInv/pubinv-respiration-control-standard). # Rationale The open source, free software, and humanitarian engineering communities are attempting to address the COVID-19 pandemic. Part of this effort is attempts to address and [urgent shortfall of ventilators](https://github.com/PubInv/covid19-vent-list). In order to be safely deployed, rapidly manufactured ventilators require extensive testing. In order to be tested communaly with modular tools, a data interchange format is required. There exists standards for waveform data, such those of [Physionet](https://physionet.org/content/bidmc/1.0.0/). We know of no format specific enough to respiratory data that meets our needs; but our time to research has been limited. # Three Expressions of the Standard JSON is a convenient format for interchange of respiration data over the internet and between teams. Our own test effort, [VentMon](https://github.com/PubInv/ventmon-ventilator-inline-test-monitor), requires a format for transfer between data servers and web pages for data analysis. A byte-level protocol is convenient for electronic transfer between microcomponents and microcontrollers in a working ventilator. In fact, we think of the problem not so much as that of ventilators but modular ventilation systems. A byte-level protocol may support I2C and serial port interfaces. We therefore intend to define an abstract standard, which has both a JavaScript and byte-level expression. # Testing in the repo In order to provide very basic testing of the PIRDS, we will create create Python program and C program on the Arduino platform. The Python program will generate mock data and convert it to the byte-level version and send it to the Arduino via PySerial. The Arduino program will interpret the standard and echo it back to the Python program in the JavaScript format. The Python program will then check abstractly that it has received what it sent in a round trip. # License The file is released under CC0, but names resembling "PubInv Respiration Data Standard" may not be used without the permission of Public Invention. You are welcome to extend the standard; if you do, please submit your improves back to us. However, to avoid confusion (standards must be standards) do not use the name "PubInv" or "Public Invention", which are trademarks for Public Invention, a US 501(c)3 public charity, on any derivative work.
1207b96305cc751ec1f01b71bb486bee6e5f681e
[ "Markdown", "C", "C++" ]
3
C++
cubanmakers/PIRDS-respiration-data-standard
91620cc45dd7e1c53f400844e2a4ba5ca01b94f7
172fad9bcb781eb927236dc5ac3134f7724f3dd3
refs/heads/master
<repo_name>kenthellck/Virtualization<file_sep>/vm.php <?php include '../mainHome/header.php';?> <!-- //////////////////////////////////////////////////////////////////////////// --> <!-- START CONTENT --> <div class="content" > <!-- Start Page Header --> <div class="page-header"> <h1 class="title" align="center" style="font-size:29px;">Virtual Machines</h1> <ol class="breadcrumb"> <li><a href="mainpage.php" style="font-size:19px;">back</a></li> </ol> <!-- Start Page Header Right Div --> <div class="right"> <div class="btn-group" role="group" aria-label="..."> <a href="vm.php" class="btn btn-light"><i class="fa fa-refresh"></i></a> <a href="homePage.php" class="btn btn-light"><button type="button" class="btn btn-rounded btn-option3 btn-icon"><i class="fa fa-home"></i></button></a> </div> </div> <!-- End Page Header Right Div --> </div> <!-- End Page Header --> <!-- //////////////////////////////////////////////////////////////////////////// --> <!-- Start Project Stats 14 --> <div class="col-md-16 col-lg-16"> <div class="panel panel-widget" > <div class="panel-title" ><p class="text-warning" style="font-size:19px;"><b>VM stats</b></p> <span class="label label-info"><?php ?></span> <ul class="panel-tools"> <li><a class="icon minimise-tool"><i class="fa fa-minus"></i></a></li> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> </ul> </div> <div class="panel-body table-responsive"> <table class="table table-hover"> <thead> <tr> <td><p class="text-primary" style="font-size:19px;">vm Name </p></td> <td><p class="text-primary" style="font-size:19px;">Memory</p></td> <td><p class="text-primary" style="font-size:19px;">CPU</p></td> <td><p class="text-primary" style="font-size:19px;">raised date</p></td> <td><p class="text-primary" style="font-size:19px;">level</p></td> </tr> </thead> <tbody> <?php $vmcount =0; foreach ($cursor as $document){ ?> <tr> <?php $string = $document["title"]; $tok = strtok($string, " \n\t"); if ($tok == "VM_TEAM_DASHBOARD_TEST") { $vmcount++; while ($tok !== false) {?> <?php if ($tok == "-") { $tok = strtok(" \n\t"); ?> <td><h6><b><p style="font-size:19px;"><?php echo $tok; ?></p></b> </h6></td> <?php } $tok = strtok(" \n\t"); ?> <?php } ?> <?php $string = $document["description"]; $tok = strtok($string, " \n\t"); while ($tok !== false) { $tok = strtok(" \n\t"); if ($tok == "=") { $tok = strtok(" \n\t"); $c=$tok; $co=(int)$c; if($co<75){ ?> <td><h6><span class="label label-success" style="font-size:19px;"><?php echo $tok; ?></span> </h6></td> <?php } elseif($co>75 && $co<90){ ?> <td><h6><span class="label label-warning" style="font-size:19px;"><?php echo $tok; ?></span> </h6></td> <?php } elseif( $co>=90){ ?> <td><h6><span class="label label-danger" style="font-size:19px;"><?php echo $tok; ?></span> </h6></td> <?php } $tok = strtok(" \n\t"); } } ?> <td><h6><p style="font-size:19px;"><?php echo $document["date_raised"];?></p></h6></td> <td><h6><p style="font-size:19px;"><?php echo $document["category"];?></p></h6></td> </tr> <?php } } if($vmcount == 0) { ?> <!-- Start an Alert --> <div class="kode-alert kode-alert-icon alert1-light"> <a href="#" class="closed">&times;</a> <h2 align="center">NO VIRTUAL MACHINE CONNECTIVITY ALERTS CURRENTLY!</h2> <p align="center" class="text-danger"><b >Host connectivity Alert Count : 0</b></p> </div> <!-- End an Alert --> <?php } ?> </tbody> </table> </div> </div> </div> <!-- end Project Stats 14--> <!-- //////////////////////////////////////////////////////////////////////////// --> <?php include '../mainHome/footer.php';?><file_sep>/SOL/all_alerts.php <!--HEADER PAGE--> <?php include('master/head.php');?> <?php include('dbconnect/sol.php');?> <!-- --> <div class="container-default" style="min-height: 1027px;"> <div class="row"> <div class="col-lg-12 col-md-12 titles" align="center"> <h1>DataStore Alerts</h1> </div> </div> <div class="row"> <div class="col-md-12 col-lg-12"> <div class="panel panel-widget"> <div class="data-panel-title"> All Alerts <span class="label label-info"> <?php echo $datastorecount;?></span> <ul class="panel-tools"> <li><a class="icon minimise-tool"><i class="fa fa-minus"></i></a></li> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panel-search"> </div> <div class="panel-body table-responsive"> <table class="tables3 table-hover"> <thead> <tr> <td>Alert</td> <td align="center">Status</td> </tr> </thead> <tbody> <tr> <td>dsdsdsdsd</td> <td align="center"> <div class="easypie margin-b-50" data-percent="45"><span>45%</span>Storage<canvas height="110" width="110"></canvas></div> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <!--FOOTER PAGE--> <?php include('master/tail.php');?><file_sep>/ICD/index.php <!--HEADER PAGE--> <?php include('../master/head2.php');?> <!-- --> <div class="container-default" style="min-height: 1027px;"> <div class="row"> <div class="col-lg-12 col-md-12 titles" align="center"> <h1>SOL Alerts</h1> </div> </div> <div class="row"> <!-- All Alerts --> <div class="col-md-6 col-lg-4"> <div class="panel panel-primary"> <div class="panels-title"> <h2>All Alerts</h2> <ul class="panel-tools"> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panels-body"> <div class="panel-body table-responsive"> <table class="table table-hover"> <tbody> <tr> <td><h5>All the Alerts can be viewed in this sector</h5></td> <td><a href="#" class="btn btn-host btns-lg">1</a></td> </tr> </tbody> </table> </div> </div> <div class="panel-footer"></div> </div> </div> <!-- Host --> <div class="col-md-6 col-lg-4"> <div class="panel panel-danger"> <div class="panels-title"> <h2>Host Alerts</h2> <ul class="panel-tools"> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panels-body"> <div class="panel-body table-responsive"> <table class="table table-hover"> <tbody> <tr> <td><h5>All the Host Alerts can be viewed in this sector</h5></td> <td><a href="#" class="btn btn-host btns-lg">1</a></td> </tr> </tbody> </table> </div> </div> <div class="panel-footer"></div> </div> </div> <!-- VM --> <div class="col-md-6 col-lg-4"> <div class="panel panel-info"> <div class="panels-title"> <h2>VM Alerts</h2> <ul class="panel-tools"> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panels-body"> <div class="panel-body table-responsive"> <table class="table table-hover"> <tbody> <tr> <td><h5>All the VM Alerts can be viewed in this sector</h5></td> <td><a href="icd_vm.php" class="btn btn-host btns-lg"><?php echo$icd_vmcount;?></a></td> </tr> </tbody> </table> </div> </div> <div class="panel-footer"></div> </div> </div> <!-- Datastore --> <div class="col-md-6 col-lg-4"> <div class="panel panel-warning"> <div class="panels-title"> <h2>Datastore Alerts</h2> <ul class="panel-tools"> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panels-body"> <div class="panel-body table-responsive"> <table class="table table-hover"> <tbody> <tr> <td><h5>All the Datastore Alerts can be viewed in this sector</h5></td> <td><a href="icd_ds.php" class="btn btn-host btns-lg"><?php echo $icd_datastorecount;?></a></td> </tr> </tbody> </table> </div> </div> <div class="panel-footer"></div> </div> </div> <!-- Host Connectivity --> <div class="col-md-6 col-lg-4"> <div class="panel panel-success"> <div class="panels-title"> <h2>Host Connectivity Alerts</h2> <ul class="panel-tools"> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panels-body"> <div class="panel-body table-responsive"> <table class="table table-hover"> <tbody> <tr> <td><h5>All the Host Connectivity Alerts can be viewed in this sector</h5></td> <td><a href="#" class="btn btn-host btns-lg">1</a></td> </tr> </tbody> </table> </div> </div> <div class="panel-footer"></div> </div> </div> <!-- Storage Connectivity --> <div class="col-md-6 col-lg-4"> <div class="panel panel-primary"> <div class="panels-title"> <h2>Storage Connectivity Alerts</h2> <ul class="panel-tools"> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panels-body"> <div class="panel-body table-responsive"> <table class="table table-hover"> <tbody> <tr> <td><h5>All the Storage Connectivity Alerts can be viewed in this sector</h5></td> <td><a href="#" class="btn btn-host btns-lg">1</a></td> </tr> </tbody> </table> </div> </div> <div class="panel-footer"></div> </div> </div> </div> </div> <!--FOOTER PAGE--> <?php include('../master/tail2.php');?><file_sep>/dbconnect/sol.php <!--DATA STORE ALERTS --> <?php $datastorecount =0; foreach ($cursor as $document){ $string = $document["title"]; $tok = strtok($string, " \n\t"); if ($tok == "DATASTORE_VMDASHBOARD") { $datastorecount++; } } ?> <!--VM STORE ALERTS --> <?php $sol_vmcount =0; foreach ($cursor as $document){ $string = $document["title"]; $tok = strtok($string, " \n\t"); if ($tok == "VM_TEAM_DASHBOARD_TEST") { $sol_vmcount++; } } ?> <file_sep>/sol_datastore.php <!--HEADER PAGE--> <?php include('master/head.php');?> <?php include('dbconnect/sol.php');?> <!-- --> <div class="container-default" style="min-height: 1027px;"> <div class="row"> <div class="col-lg-12 col-md-12 titles" align="center"> <h1>DataStore Alerts</h1> </div> </div> <div class="row"> <div class="col-md-12 col-lg-12"> <div class="panel panel-widget"> <div class="data-panel-title"> ICD <span class="label label-info"> <?php echo $datastorecount;?></span> <ul class="panel-tools"> <li><a class="icon minimise-tool"><i class="fa fa-minus"></i></a></li> <li><a class="icon expand-tool"><i class="fa fa-expand"></i></a></li> <li><a class="icon closed-tool"><i class="fa fa-times"></i></a></li> </ul> </div> <div class="panel-search"> <form> <input type="text" class="form-control" placeholder="Search..."> <i class="fa fa-search icon"></i> </form> </div> <div class="panel-body table-responsive"> <table class="tables table-hover"> <thead> <tr> <td>DATASTORE NAME</td> <td>DISK USAGE</td> <td>RAISED DATE</td> <td>LEVEL</td> </tr> </thead> <tbody> <?php $datastorecount =0; foreach ($cursor as $document){ ?> <tr> <?php $string = $document["title"]; $tok = strtok($string, " \n\t"); if ($tok == "DATASTORE_VMDASHBOARD") { $datastorecount++; while ($tok !== false) {?> <?php if ($tok == "-") { $tok = strtok(" \n\t"); ?> <td><h6><?php echo $tok; ?></h6></td> <?php } $tok = strtok(" \n\t"); ?> <?php } ?> <?php $string = $document["description"]; $tok = strtok($string, " \n\t"); while ($tok !== false) { $tok = strtok(" \n\t"); if ($tok == "=") { $tok = strtok(" \n\t"); $c=$tok; $co=(int)$c; if($co<75){ ?> <td><h6 ><span class="label label-success"><?php echo $tok; ?></span> </h6></td> <?php } elseif($co>75 && $co<=85){ ?> <td><h6><span class="label label-warning"><?php echo $tok; ?></span> </h6></td> <?php } elseif( $co>85){ ?> <td><h6><span class="label label-danger"><?php echo $tok; ?></span> </h6></td> <?php } } } ?> <td><h6><?php echo $document["date_raised"];?></h6></td> <td><h6><?php echo $document["category"];?></h6></td> </tr> <?php } } if($datastorecount == 0) { ?> <!-- Start an Alert --> <div class="kode-alert kode-alert-icon alert1-light"> <a href="#" class="closed">&times;</a> <h2 align="center">NO DATASTORE ALERTS CURRENTLY!</h2> <p align="center" class="text-danger"><b>Datastore Alert Count : 0</p></b> </div> <!-- End an Alert --> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> <!--FOOTER PAGE--> <?php include('master/tail.php');?><file_sep>/index.php <!--HEADER PAGE--> <?php include('master/head.php');?> <?php include('dbconnect/icd.php');?> <?php include('dbconnect/sol.php');?> <!-- --> <div class="container-default" style=height: 100%;"> <div class="row"> <div class="col-lg-12 col-md-12 titles" align="center"> <h1>Dashboard For Virtualization Alerts</h1> </div> <!-- ICD--> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3><a href="ICD/index.php">ICD</a> </h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up"><?php echo$icd_vmcount;?></h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3><?php echo$icd_datastorecount;?></h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> <!-- SOL--> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3><a href="SOL/index.php">SOL</a> </h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up"><?php echo $sol_vmcount;?></h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3><?php echo $datastorecount;?></h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3>CORNEL</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up">696</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3>960</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3>ICD</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up">696</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3>960</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3>ICD</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up">696</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3>960</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3>ICD</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up">696</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3>960</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> <div class="col-md-12"> <ul class="topstats clearfix"> <li class="arrow"></li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cubes"></i> V Centre</span> <h3>ICD</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-desktop fa-4x"></i> Host</span> <h3>8</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-cube"></i>VM</span> <h3 class="color-up">696</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-database"></i> Datastore</span> <h3>960</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-sort-amount-asc"></i> Host Connectivity</span> <h3 class="color-up">32</h3> </li> <li class="col-xs-6 col-lg-2"> <span class="title"><i class="fa fa-signal"></i> Storage Connectivity</span> <h3 class="color-down">2</h3> </li> </ul> <br> </div> </div> <div class="row"> </div> </div> <!--FOOTER PAGE--> <?php include('master/tail.php');?><file_sep>/master/head2.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Pearson"> <meta name="keywords" content="Dashboard Pearson" /> <meta http-equiv="refresh" content="15"> <title>DashBoard</title> <!-- ========== Css Files ========== --> <link href="../bootstrap/css/root.css" rel="stylesheet"> <link href="../bootstrap/css/myStyle.css" rel="stylesheet"> </head> <body> <!-- Start Page Loading --> <div class="loading"><img src="../bootstrap/img/loading.gif" alt="loading-img"></div> <!-- End Page Loading --> <!-- //////////////////////////////////////////////////////////////////////////// --> <!-- START TOP --> <div id="top" class="clearfix"> <!-- Start App Logo --> <div class="applogo"> <a href="index.php" class="logo">Dashboard</a> </div> <!-- End App Logo --> <!-- Start Sidebar Show Hide Button --> <a href="#" class="sidebar-open-button"><i class="fa fa-bars"></i></a> <a href="#" class="sidebar-open-button-mobile"><i class="fa fa-bars"></i></a> <!-- End Sidebar Show Hide Button --> <!-- Start Sidepanel Show-Hide Button --> <a href="#sidepanel" class="sidepanel-open-button"><i class="fa fa-outdent"></i></a> <!-- End Sidepanel Show-Hide Button --> </div> <!-- END TOP --> <!-- //////////////////////////////////////////////////////////////////////////// --> <?php $connection = new MongoClient( "mongodb://10.25.7.242:27017" ); // connect to a remote host (default port: 27017) $db= $connection->vcenter; $collection = $db->events; $cursor = $collection->find(); ?> <!-- //////////////////////////////////////////////////////////////////////////// --> <!-- START SIDEBAR --> <div class="sidebar clearfix"> <ul class="sidebar-panel nav"> <li class="sidetitle">MAIN</li> <li><a href="../index.php"><span class="icon color5"><i class="fa fa-home"></i></span>Dashboard</a></li> <li><a href="#"><span class="icon color7"><i class="fa fa-desktop"></i></span>SOL<span class="caret"></span></a> <ul style=""> <li><a href="../SOL/all_alerts.php"><span class="icon color5"><i class="fa fa-bullhorn"></i></span>All Alerts</a></li> <li><a href="../SOL/sol_host.php">HOST</a></li> <li><a href="../SOL/sol_vm.php">VM</a></li> <li><a href="../SOL/sol_ds.php">Data Store</a></li> <li><a href="../SOL/sol_hc.php">Host Connectivity</a></li> <li><a href="../SOL/sol_sc.php">Storage Connectivity</a></li> </ul> </li> <li><a href="#"><span class="icon color5"><i class="fa fa-desktop"></i></span>ICD<span class="caret"></span></a> <ul style=""> <li><a href="../ICD/all_alerts.php"><span class="icon color5"><i class="fa fa-bullhorn"></i></span>All Alerts</a></li> <li><a href="../ICD/icd_host.php">HOST</a></li> <li><a href="../ICD/icd_vm.php">VM</a></li> <li><a href="../ICD/icd_ds.php">Data Store</a></li> <li><a href="../ICD/icd_hc.php">Host Connectivity</a></li> <li><a href="../ICD/icd_sc.php">Storage Connectivity</a></li> </ul> </li> <li><a href="#"><span class="icon color7"><i class="fa fa-desktop"></i></span>Cornel<span class="caret"></span></a> <ul style=""> <li><a href="../CORE/all_alerts.php"><span class="icon color5"><i class="fa fa-bullhorn"></i></span>All Alerts</a></li> <li><a href="../CORE/sol_host.php">HOST</a></li> <li><a href="../CORE/sol_vm.php">VM</a></li> <li><a href="../CORE/sol_ds.php">Data Store</a></li> <li><a href="../CORE/sol_hc.php">Host Connectivity</a></li> <li><a href="../CORE/sol_sc.php">Storage Connectivity</a></li> </ul> </li> </div> <?php include('../dbconnect/icd.php');?> <?php include('../dbconnect/sol.php');?> <div class="content" ><file_sep>/ICD/all_alerts.php <!--HEADER PAGE--> <?php include('../master/head2.php');?> <!-- --> <div class="container-default" style="min-height: 1027px;"> <div class="row"> <div class="col-lg-12 col-md-12 titles" align="center"> <h1>DataStore Alerts</h1> </div> </div> <div class="row"> <div class="panel panel-widget"> <?php ?> <?php $i=0; foreach ($cursor as $document){ echo $i; $string = $document["description"]; $tok = strtok($string, " \n\t"); echo "tok is ".$tok; if ($tok == "DATASTORE_VMDASHBOARD"){ ?> <div class="kode-alert kode-alert-icon alert4-light"> <i class="fa fa-warning"></i> <p style="font-size:22px;"> <?php echo"Alert :: $string"; ?></p> </div> <?php } elseif ($tok == "VM_TEAM_DASHBOARD_TEST"){ ?> <div class="kode-alert kode-alert-icon alert2-light"> <i class="fa fa-warning"></i><p style="font-size:22px;"> <?php echo"Alert :: jk$string"; ?></p> </div> <?php } elseif ($tok == "HOST_VMDASHBOARD"){ ?> <div class="kode-alert kode-alert-icon alert11-light"> <i class="fa fa-warning"></i> <p style="font-size:22px;"> <?php echo"Alert :: $string"; ?></p> </div> <?php } elseif ($tok == "HOST_CONNECTIVITY_DASHBOARD"){ ?> <div class="kode-alert kode-alert-icon alert11-light"> <i class="fa fa-warning"></i> <p style="font-size:22px;"> <?php echo"Alert :: $string"; ?></p> </div> <?php } $i++; } ?> </div> </div> </div> <!--FOOTER PAGE--> <?php include('../master/tail2.php');?><file_sep>/dbconnect/icd.php <!--DATA STORE ALERTS --> <?php $icd_datastorecount =0; foreach ($cursor as $document){ $string = $document["title"]; $tok = strtok($string, " \n\t"); if ($tok == "ICD_DATASTORE") { $icd_datastorecount++; } } ?> <!--VM STORE ALERTS --> <?php $icd_vmcount =0; foreach ($cursor as $document){ $string = $document["title"]; $tok = strtok($string, " \n\t"); if ($tok == "ICD_VM_TEAM_DASHBOARD_TEST") { $icd_vmcount++; } } ?>
56037846f0347b3b6b366b56c6c7da979d1226da
[ "PHP" ]
9
PHP
kenthellck/Virtualization
82150080e6e5efcbe5af61fd5357ab3614417a10
72e1cbd88b51d277114c0628588cf30fa81c4992
refs/heads/develop
<file_sep>const { weatherservice: WeatherService } = global.sails.services module.exports = { getWeather (req, res) { const { query: { lat, lng } } = req // TODO: validation에 대한 처리를 향후 별도의 Error 핸들링용 객체를 이용하는 방식으로 변경할 것 if (!lat || !lng) return res.badRequest({ errorMessage: '위도와 경도는 필수 요소입니다.' }) const response = WeatherService.getWeather(+lat, +lng) return res.json(response) } }
80dd6fb313189e6c7e94b79a3dd3a0fbb90c4a19
[ "JavaScript" ]
1
JavaScript
fureweb-com/weather-api
279ca744fe539bafe3e5b86a2e1aa30f1343f3b4
e5193f5db656a067b8ab4555e7ea9e34ededd20b
refs/heads/master
<file_sep>#!/usr/bin/env python3 from tornado.httpclient import AsyncHTTPClient import argparse import markdown import tornado.ioloop import tornado.web URL = "https://raw.githubusercontent.com/%s/%s.md" def get_md_async(target, path, callback): http_client = AsyncHTTPClient() http_client.fetch(URL % (target, path), callback) def convert_to_html(md): return markdown.markdown(md, extensions=['attr_list']) def convert_to_javascript(md): document_format = "document.write('%s')" html = convert_to_html(md) return document_format % html.replace("'", "\\'").replace("\n", "\\n") class MarkdownHandler(tornado.web.RequestHandler): def initialize(self, target): self.target = target @tornado.web.asynchronous def get(self, path): get_md_async(self.target, path, self._on_download) def _on_download(self, response): self.write(response.body.decode("utf-8")) self.set_header('Content-Type', 'text/plain; charset="utf-8"') self.finish() class HTMLHandler(tornado.web.RequestHandler): def initialize(self, target): self.target = target @tornado.web.asynchronous def get(self, path): get_md_async(self.target, path, self._on_download) def _on_download(self, response): self.write(convert_to_html(response.body.decode("utf-8"))) self.finish() class JavascriptHandler(tornado.web.RequestHandler): def initialize(self, target): self.target = target @tornado.web.asynchronous def get(self, path): get_md_async(self.target, path, self._on_download) def _on_download(self, response): self.write(convert_to_javascript(response.body.decode("utf-8"))) self.set_header('Content-Type', 'application/javascript; charset="utf-8"') self.finish() if __name__ == '__main__': description = ("Parsing markdown from github" "and making javascript for embedding.") parser = argparse.ArgumentParser(description=description) parser.add_argument('--port', help='port number', default=8888, type=int, dest='port') parser.add_argument('target') args = parser.parse_args() app_config = dict(target=args.target) Application = tornado.web.Application application = Application([(r"/(.*)\.html", HTMLHandler, app_config), (r"/(.*)\.js", JavascriptHandler, app_config), (r"/(.*)\.md", MarkdownHandler, app_config)]) application.listen(args.port) tornado.ioloop.IOLoop.instance().start() <file_sep>Markdown==2.5.2 markdown-attr-plus==0.1.1 tornado==4.0.2
1938552acf56aed20acd7186c61ca04516b93f46
[ "Python", "Text" ]
2
Python
sgkim126/embedding-markdown
5fc35ed9e0d92eac798b44e63873c90301be67d4
f395133dfc7d42032e9ba75727615bcd6e0a8fd3
refs/heads/master
<repo_name>Approxiam/ZombieDice<file_sep>/src/ConservativeBot.java public class ConservativeBot extends Player { public String name; public int score; public ConservativeBot(String str){ this.name = str; this.score = 0; } public boolean decide(int brains, int shots, int sc){ if(shots > 0){ System.out.println(name + " decided to stop."); return false; } else { System.out.println(name + " decided to roll again."); return true; } } public String toString(){ return name + " (Conservative Bot)"; } } <file_sep>/src/Player.java public abstract class Player { public String name; public int score; public abstract boolean decide(int brains, int shots, int sc); } <file_sep>/src/ZombieDice.java import java.util.*; public class ZombieDice { public static final List<Player> players = new ArrayList<Player>(); public static List<Die> cup = new ArrayList<Die>(); public static List<Die> setCurrent = new ArrayList<Die>(); public static List<Die> setTemp = new ArrayList<Die>(); public static Random random = new Random(); public static Scanner input = new Scanner(System.in); public static int recklessWins = 0; public static void fillCup(){ cup.clear(); for(int i = 0; i < 6; i++){ Die D = new Die(3,2,1,"green"+i); cup.add(D); } for(int i = 0; i < 4; i++){ Die D = new Die(2,2,2,"yellow"+i); cup.add(D); } for(int i = 0; i < 3; i++){ Die D = new Die(1,2,3,"red"+i); cup.add(D); } } public static Die nextDie(){ Die D = null; if(setCurrent.size() > 0){ D = setCurrent.get(0); setCurrent.remove(0); } else if(cup.size() > 0) { D = cup.get(0); cup.remove(0); } else { fillCup(); Collections.shuffle(cup, random); D = cup.get(0); cup.remove(0); } return D; } public static void playRound(Player p){ int brains = 0; int shots = 0; boolean reroll = true; while(reroll){ for(int i = 0; i < 3; i++){ Die D = nextDie(); String str = D.roll(random); System.out.println("The chosen die is " + D.name + ", after rolling it shows " + str); if(str.equals("footsteps")){ setTemp.add(D); } if(str.equals("brain")){ brains++; } if(str.equals("shot")){ shots++; } } setCurrent = new ArrayList<Die>(setTemp); setTemp.clear(); System.out.println("You have " + brains + " brains, and you are at " + shots + " shots.\n"); if(shots > 2){ System.out.println("Your killing spree has come to an end.\n"); break; } reroll = p.decide(brains, shots, p.score); if(!reroll){ p.score += brains; } } System.out.println("Your score is " + p.score + "\n"); } public static void playGame(){ boolean gameOver = false; while(!gameOver) { System.out.println("A new round begins."); for(int i = 0; i < players.size(); i++){ Player player = players.get(i); System.out.println(player + "'s score is " + player.score); } for(int i = 0; i < players.size(); i++){ Player player = players.get(i); playRound(player); if(player.score > 12){ gameOver = true; } } } } public static void declareWinner(){ int winnerIndex = 0; int maxScore = 0; for(int i = 0; i < players.size(); i++){ Player player = players.get(i); System.out.println(player + " has scored " + player.score + " points."); if(player.score > maxScore){ maxScore = player.score; winnerIndex = i; } } /* if(winnerIndex == 0){ recklessWins++; } */ Player player = players.get(winnerIndex); System.out.println("The winner is " + player); } public static void addPlayers(){ while(true){ System.out.println("What kind of player do you want to add?" +"\n 1: Live player." +"\n 2: Reckless Bot (aims for at least 5 score per round)." +"\n 3: Conservative Bot (stops at the first shot)." +"\n 4: Reasonable Bot." +"\n 0: Finish."); int result; do { while (!input.hasNextInt()) { input.next(); } result = input.nextInt(); } while (!(0 <= result && result <= 4)); if(result == 0){ break; } else { constructPlayer(result); } } } public static void constructPlayer(int id){ System.out.println("What's the name of this player?"); String str = input.next(); switch(id){ case 1: players.add(new LivePlayer(str)); break; case 2: players.add(new RecklessBot(str)); break; case 3: players.add(new ConservativeBot(str)); break; case 4: players.add(new ReasonableBot(str)); break; default: break; } } public static void cleanUp(){ fillCup(); setCurrent.clear(); setTemp.clear(); for(int i = 0; i < players.size(); i++){ Player player = players.get(i); player.score = 0; } } public static void main(String[] args){ /* players.add(new ResonableBot("Steve")); players.add(new RecklessBot("Bill")); players.add(new ConservativeBot("Paul")); */ /* addPlayers(); playGame(); declareWinner(); */ ///* players.add(new LivePlayer("Test")); playGame(); //*/ //cleanUp(); //System.out.println(players.get(0)+ " won " +recklessWins + " times."); } }
50f80fe3a89dbec17fbc9d38549ceaad8ab40e19
[ "Java" ]
3
Java
Approxiam/ZombieDice
da4f0f823213b305958577d387796f715f58c32a
198eb909e5a543a276151c00d8917ade8885d54c
refs/heads/master
<file_sep><?php /** * Copyright © 2015 YourCompanyName . All rights reserved. */ namespace YourCompanyName\YourModuleName\Block\HelloWorld; use YourCompanyName\YourModuleName\Block\BaseBlock; class Index extends BaseBlock { } <file_sep><?php namespace YourCompanyName\YourModuleName\Block\Adminhtml\ModelName\Edit; class Tabs extends \Magento\Backend\Block\Widget\Tabs { protected function _construct() { parent::_construct(); $this->setId('checkmodule_modelname_tabs'); $this->setDestElementId('edit_form'); $this->setTitle(__('ModelName Information')); } }<file_sep><?php /** * Copyright © 2015 YourCompanyName. All rights reserved. */ namespace YourCompanyName\YourModuleName\Model\ResourceModel; /** * ModelName resource */ class ModelName extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { /** * Initialize resource * * @return void */ public function _construct() { $this->_init('yourmodulename_modelname', 'id'); } }
e046957e9c72b4b43661be4717cccc464a2e5bc5
[ "PHP" ]
3
PHP
FullStack-web-dev/Magento2
14428d1f681e1ecdd9d336461fddb7b9f6442519
53c5f3466128634a055e7fbb173d1387f663c595
refs/heads/master
<file_sep>package fr.doranco.wineo.middleware.objetmetier; import java.util.Map; import java.util.UUID; public class CaveBis { private Map<String, Bouteille> bouteilles; private Integer capaciteMax; private UUID reference; private String proprietaire; //constructeur public CaveBis() { super(); } //getter Setter public Map<String, Bouteille> getBouteilles() { return bouteilles; } public void setBouteilles(Map<String, Bouteille> bouteilles) { this.bouteilles = bouteilles; } public Integer getCapaciteMax() { return capaciteMax; } public void setCapaciteMax(Integer capaciteMax) { this.capaciteMax = capaciteMax; } public UUID getReference() { return reference; } public void setReference(UUID reference) { this.reference = reference; } public String getProprietaire() { return proprietaire; } public void setProprietaire(String proprietaire) { this.proprietaire = proprietaire; } } <file_sep>package fr.doranco.wineo.middleware.objetmetier; import java.util.HashSet; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; public class Cave { private HashSet<Bouteille> listeBouteille; private Integer bouteilleMax; private String proprietaire; //Getter Setter public HashSet<Bouteille> getListeBouteille() { return listeBouteille; } public void setListeBouteille(HashSet<Bouteille> listeBouteille) { this.listeBouteille = listeBouteille; } public Integer getBouteilleMax() { return bouteilleMax; } public void setBouteilleMax(Integer bouteilleMax) { this.bouteilleMax = bouteilleMax; } public String getProprietaire() { return proprietaire; } public void setProprietaire(String proprietaire) { this.proprietaire = proprietaire; } //ToString HashCode Equals @Override public String toString() { return new ToStringBuilder(this) .append("Liste bouteille", listeBouteille) .append("nombre max de bouteille", bouteilleMax) .append("proprietaire", proprietaire) .build(); } @Override public int hashCode() { return new HashCodeBuilder() .append(this.listeBouteille) .append(this.bouteilleMax) .append(this.proprietaire) .build(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; Cave autre = (Cave) obj; return new EqualsBuilder() .append(this.listeBouteille, autre.listeBouteille) .append(this.bouteilleMax, autre.bouteilleMax) .append(this.proprietaire, autre.proprietaire) .build(); } }
ca1eded67b8dfdfdbf0c9594263b44bef23919f7
[ "Java" ]
2
Java
Ireyeb/MiddleWineo
efd4eeffd5e8069d551ab8cca4b6dc33cce6f5d7
8f7674032d60419eafa9e35c7f3f1cb72f77b603
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 tugaspenggantipert7; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * * @author Axce29 */ public class TugasPenggantiPert7 { /** * @param args the command line arguments */ public static void main(String[] args) { olahData od = new olahData(); dataMHS data = new dataMHS(); Scanner masukan = new Scanner (System.in); int input; int in =0; int jml; do{ do{ System.out.println("=========Menu=========="); System.out.println("1.Masukan data"); System.out.println("2.Menampilkan data"); System.out.println("3.Sorting data"); System.out.println("4.Keluar"); System.out.print("Masukan pilihan Anda : "); input = masukan.nextInt(); if(input<=0){ System.out.print("Harap pilih menu 1-4"); } else if(input>4){ System.out.print("Harap pilih menu 1-4"); } }while(input>6); System.out.print("---------------------------------\n\n"); switch(input){ case 1: do{ System.out.print("Jumlah data mahasiswa yang dimasukan [1-100] : "); jml = masukan.nextInt(); od.getIndeks(jml); if(jml>100){ System.out.print("\nJumlah data mahasiswa yang dimasukan \nmelebihi kapasitas yang ditentukan\n\n"); } }while(jml>100); for(int i = 0; i<jml; i++){ System.out.println("Data mahasiswa ke- "+(i+1)); System.out.print("NIM : "); String nim = masukan.next(); data.setNim(nim); System.out.print("Nama : "); String nam = masukan.next(); data.setNama(nam); System.out.print("IPK : "); double ip = masukan.nextDouble(); data.setIpk(ip); System.out.print("\n"); od.set(i, data); } break; case 2: for(int i = 0; i<i; i++){ System.out.print("\n---------------------------------\n"); System.out.print("Data mahasiswa"+(i+1)+"\n"); od.get(i); } break; case 3: System.out.println("---------------------------------"); System.out.println("Sorting data :"); System.out.println("1.Sorting by NIM"); System.out.println("2.Sorting by Nama"); System.out.println("3.Sorting by IPK");; System.out.print("Pilih : "); System.out.print("\n---------------------------------\n"); int car = masukan.nextInt(); switch(car){ case 1: System.out.print("\n---------------------------------\n"); break; case 2: System.out.print("Masukan NIM mahasiswa yang dicari : "); break; case 3: System.out.print("Masukan IPK mahasiswa yang dicari : "); break; } break; case 4: System.out.println("Terima Kasih"); System.exit(0); break; } }while(in==0); } }
02c3299f62ad838567ea67ea6bb19964b36391cc
[ "Java" ]
1
Java
ArifHermanto29/PemrogramanJavaPraktikum5160411314
13c284812edd2bc263e2529ab450add238198bd5
34818b845007830efcb20f6c5c6d8218bb866f61
refs/heads/master
<repo_name>SamridiNanda/Music-player-cum-streamer<file_sep>/ProjMusicLib.java package projmusiclib; public class ProjMusicLib { public static void main(String[] args) { SplaasshFrame o=new SplaasshFrame(); o.setDefaultCloseOperation(2); o.setVisible(true); o.setSize(1390, 770); } } <file_sep>/SigninupFrame.java package projmusiclib; import java.awt.Graphics; import java.awt.Image; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; public class SigninupFrame extends javax.swing.JFrame { Image backgroundImage=null; public SigninupFrame() { initComponents(); try { backgroundImage = ImageIO.read(getClass().getResource("BB.png")); } catch (IOException ex) { Logger.getLogger(SigninupFrame.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void paint( Graphics g ) { super.paint(g); g.drawImage(backgroundImage, 0, 0, null); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jButton2.setBackground(new java.awt.Color(255, 255, 255)); jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton2.setForeground(new java.awt.Color(255, 255, 255)); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projmusiclib/stop-button-md_1.png"))); // NOI18N jButton2.setBorder(null); jButton2.setBorderPainted(false); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton1.setBackground(new java.awt.Color(255, 255, 255)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 255, 255)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projmusiclib/playbutton_1.png"))); // NOI18N jButton1.setBorder(null); jButton1.setBorderPainted(false); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("<NAME>", 0, 18)); // NOI18N jLabel1.setText("SIGN IN"); jLabel2.setFont(new java.awt.Font("<NAME>", 0, 18)); // NOI18N jLabel2.setText("SIGN UP"); jButton3.setBackground(new java.awt.Color(255, 255, 255)); jButton3.setFont(new java.awt.Font("G<NAME>", 1, 18)); // NOI18N jButton3.setText("SIGN UP"); jButton3.setBorder(null); jButton3.setBorderPainted(false); jButton4.setBackground(new java.awt.Color(255, 255, 255)); jButton4.setFont(new java.awt.Font("G<NAME>", 1, 18)); // NOI18N jButton4.setText("SIGN IN"); jButton4.setBorder(null); jButton4.setBorderPainted(false); jButton4.setContentAreaFilled(false); 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(16, Short.MAX_VALUE) .addComponent(jButton1) .addGap(27, 27, 27) .addComponent(jButton2) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton4) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(16, 16, 16)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(72, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(21, 21, 21)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(463, 463, 463) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(524, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(279, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(163, 163, 163)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: ProjFrame1 obj=new ProjFrame1(); obj.setDefaultCloseOperation(2); obj.setVisible(true); obj.setSize(1390, 770); // this.getParent().setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed SignupFrame obj=new SignupFrame(); obj.setDefaultCloseOperation(2); obj.setVisible(true); obj.setSize(1390, 770); }//GEN-LAST:event_jButton2ActionPerformed public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SigninupFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables } <file_sep>/MainFrame3.java package projmusiclib; import java.awt.FlowLayout; public class MainFrame3 extends javax.swing.JFrame { public MainFrame3() { initComponents(); jComboBox4.setVisible(false); jComboBox3.setVisible(false); jLabel3.setVisible(false); jLabel6.setVisible(false); setLayout(new FlowLayout()); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jComboBox4 = new javax.swing.JComboBox(); jComboBox3 = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(0, 0, 0)); jLabel2.setFont(new java.awt.Font("Mistral", 3, 36)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 0)); jLabel2.setText(" BASS BOOST"); jLabel4.setBackground(new java.awt.Color(255, 255, 51)); jLabel4.setFont(new java.awt.Font("Trebuchet MS", 0, 11)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 0)); jLabel4.setText("_/***/_"); jLabel5.setBackground(new java.awt.Color(255, 255, 51)); jLabel5.setFont(new java.awt.Font("Trebuchet MS", 0, 11)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 0)); jLabel5.setText("_/***/_"); jPanel5.setBackground(new java.awt.Color(255, 255, 51)); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 16, Short.MAX_VALUE) ); jPanel6.setBackground(new java.awt.Color(255, 255, 51)); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 17, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(207, 207, 207) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addContainerGap(263, Short.MAX_VALUE)) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(33, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26)) ); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jButton1.setBackground(new java.awt.Color(255, 0, 0)); jButton1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 255, 0)); jButton1.setText("UPLOAD"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Traditional Arabic", 3, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(204, 0, 0)); jLabel1.setText("SELECT CATEGORY TO UPLOAD LATEST SONGS"); jComboBox4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jComboBox4.setForeground(new java.awt.Color(0, 0, 153)); jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "BLUES", "COUNTRY", "POP", "ROCK" })); jComboBox4.setOpaque(false); jComboBox3.setForeground(new java.awt.Color(0, 0, 153)); jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EMINEM", "KATY PERRY", "IMAGINE DRAGONS", "COLDPLAY", "ENRIQUE" })); jComboBox3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox3ActionPerformed(evt); } }); jLabel3.setForeground(new java.awt.Color(204, 51, 0)); jLabel3.setText("SELECT GENRE"); jLabel6.setForeground(new java.awt.Color(204, 0, 0)); jLabel6.setText("SELECT ARTIST"); jButton2.setBackground(new java.awt.Color(255, 255, 102)); jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jButton2.setForeground(new java.awt.Color(153, 0, 0)); jButton2.setText("UPLOAD BY GENRE"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setBackground(new java.awt.Color(255, 255, 51)); jButton3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jButton3.setForeground(new java.awt.Color(153, 0, 0)); jButton3.setText("UPLOAD BY ARTIST"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(131, 131, 131) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jComboBox3, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jComboBox4, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(124, 124, 124) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(240, 240, 240)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 642, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(55, 55, 55)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(284, 284, 284)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(70, 70, 70) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(73, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed }//GEN-LAST:event_jButton1ActionPerformed private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed }//GEN-LAST:event_jComboBox3ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed jComboBox4.setVisible(true); jLabel3.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed jComboBox3.setVisible(true); jLabel6.setVisible(true); }//GEN-LAST:event_jButton3ActionPerformed public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame3().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JComboBox jComboBox3; private javax.swing.JComboBox jComboBox4; 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.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; // End of variables declaration//GEN-END:variables }
aaeaa22e4746ce8637e99ee423677b3dd901ca49
[ "Java" ]
3
Java
SamridiNanda/Music-player-cum-streamer
8388cf3facfb285b060c3d76a7b5a2305b1a6c8b
b4f64a96bb6430eff0c8e42ce5894811fedd68dc
refs/heads/master
<file_sep># CIS50_SpaceShooter Space Shooter game for final <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PhaserFire : MonoBehaviour { public float moveSpeed = 10.0f; void Update() { transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyAsteroid : MonoBehaviour { public GameManager gameManager; public GameObject explosion = null; public int enemyHealth = 1; public int scoreValue = 5; public int spawnSide; public float moveSpeed = 2.5f; public float timer = 0.0f; void Awake() { //determine which side of the screen enemy will spawn spawnSide = Random.Range(0, 2); GameObject gameManagerObject = GameObject.Find("GameManager"); if (gameManagerObject != null) { gameManager = gameManagerObject.GetComponent<GameManager>(); } if (spawnSide == 0) { transform.rotation = Quaternion.Euler(0, 0, -140); transform.position = new Vector3(-10.75f, Random.Range(8.5f, 17.0f), 0); } else if (spawnSide == 1) { transform.rotation = Quaternion.Euler(0, 0, -220); transform.position = new Vector3(10.75f, Random.Range(8.5f, 17.0f), 0); } } void Update() { transform.Translate(Vector3.up * moveSpeed * Time.deltaTime); if (enemyHealth <= 0) { gameManager.AddToScore(scoreValue); Instantiate(explosion, transform.position, transform.rotation); Destroy(gameObject); } } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Phaser") { Destroy(other.gameObject); enemyHealth--; } if (other.gameObject.tag == "PhotonTorpedo") { enemyHealth -= 5; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public List<GameObject> enemies = new List<GameObject>(); //0 = asteroid, 1 = Klingon, 2 = Romulan, 3 = defense station public List<float> spawnTimes = new List<float>(); //match above index values public List<float> timers = new List<float>(); //match above index values public GameObject bossBorgCube = null; public GameObject explosion = null; public GameObject[] livesLeft; public GameObject player = null; public GameObject playerPrefab = null; public Text scoreTextLabel = null; public bool bossIsActive = false; public bool screenCleared = false; public int livesRemaining = 3; public int score = 0; public float bossTimer = 0.0f; public float spawnBoss = 120.0f; public float spawnPlayer = 4.0f; public float spawnTimer = 0.0f; public string[] enemiesForScreenClear = { "Enemy", "Disruptor" }; void Update() { bossTimer += Time.deltaTime; //begin normal level enemy spawning and count down until boss time if (bossTimer <= spawnBoss) { for (int i = 0; i < timers.Count; i++) { timers[i] += Time.deltaTime; } for (int i = 0; i < timers.Count; i++) { if (timers[i] >= spawnTimes[i]) { Instantiate(enemies[i]); timers[i] = 0.0f; } } } //destroy all enemies, stop their spawning, and activate boss else if (bossTimer >= spawnBoss && screenCleared == false) { screenCleared = true; foreach (string tag in enemiesForScreenClear) { GameObject[] enemiesToDestroy = GameObject.FindGameObjectsWithTag(tag); foreach (GameObject enemy in enemiesToDestroy) { Instantiate(explosion, enemy.transform.position, enemy.transform.rotation); Destroy(enemy); } } enemies.Clear(); spawnTimes.Clear(); timers.Clear(); bossBorgCube.SetActive(true); bossIsActive = true; } if (bossIsActive == true) { bossBorgCube = GameObject.Find("BossBorgCube"); } //give player a couple seconds to recover before spawning character again if (player == null && (livesLeft[0].activeSelf == true || livesLeft[1].activeSelf == true)) { spawnTimer += Time.deltaTime; } //remove a life and clear screen when player spawns a new life if (player == null && spawnTimer >= spawnPlayer) { foreach (string tag in enemiesForScreenClear) { GameObject[] enemiesToDestroy = GameObject.FindGameObjectsWithTag(tag); foreach (GameObject enemy in enemiesToDestroy) { Instantiate(explosion, enemy.transform.position, enemy.transform.rotation); Destroy(enemy); } } Instantiate(playerPrefab); player = GameObject.FindGameObjectWithTag("Player"); spawnTimer = 0.0f; livesRemaining--; if (livesLeft[0].activeSelf == true) { livesLeft[0].SetActive(false); } else if (livesLeft[1].activeSelf == true) { livesLeft[1].SetActive(false); } } if (player == null && livesRemaining == 1) { StartCoroutine(WaitForNewScreen("GameOverScreen")); } if (bossBorgCube == null) { bossIsActive = false; StartCoroutine(WaitForNewScreen("WinScreen")); } } //change to appropriate scene for game end public IEnumerator WaitForNewScreen(string sceneName) { yield return new WaitForSecondsRealtime(3.0f); SceneManager.LoadSceneAsync(sceneName); } //add and update score as necessary public void AddToScore (int scoreValue) { score += scoreValue; UpdateScore(); } public void UpdateScore() { scoreTextLabel.text = "Score: " + score; } } //final assignment parameters //1. 2 unique weapons //2. 2 unique enemies (boss doesn't count) //3. Boss encounter //4. Special ability (warp drive/blink ability, thruster) //5. Score System //6. Life system //7. Win/loss (beat boss, lose lives)<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossBorgCube : MonoBehaviour { public List<GameObject> aimedWeaponPlacements = new List<GameObject>(); public List<GameObject> staticWeaponPlacements = new List<GameObject>(); public GameObject bossHealthBar = null; public GameObject bossHealthText = null; public GameObject disruptorPrefab = null; public GameObject explosion = null; public GameObject player = null; public AudioSource weAreBorgSFX; public int bossCurrentHealth = 120; public int bossMaxHealth = 120; public float aimedWeaponFire = 1.50f; public float aimedWeaponTimer = 0.0f; public float staticWeaponFire = 1.1f; public float staticWeaponTimer = 0.0f; void Awake() { player = GameObject.FindWithTag("Player"); weAreBorgSFX = GetComponent<AudioSource>(); bossHealthBar.SetActive(true); bossHealthText.SetActive(true); } void Start() { //play Borg SFX after all enemy explosion sounds have ended weAreBorgSFX.PlayDelayed(0.50f); for (int i = 0; i < aimedWeaponPlacements.Count; i++) { aimedWeaponPlacements[i].transform.LookAt(player.transform.position); } } void Update() { aimedWeaponTimer += Time.deltaTime; staticWeaponTimer += Time.deltaTime; bossHealthBar.transform.localScale = new Vector3((float)bossCurrentHealth / (float)bossMaxHealth, 1.0f, 1.0f); player = GameObject.FindWithTag("Player"); if (player != null) { for (int i = 0; i < aimedWeaponPlacements.Count; i++) { aimedWeaponPlacements[i].transform.LookAt(player.transform.position); } } if (aimedWeaponTimer >= aimedWeaponFire) { aimedWeaponTimer = 0; for (int i = 0; i < aimedWeaponPlacements.Count; i++) { Instantiate(disruptorPrefab, aimedWeaponPlacements[i].transform.position, aimedWeaponPlacements[i].transform.rotation); } } if (staticWeaponTimer >= staticWeaponFire) { staticWeaponTimer = 0; for (int i = 0; i < staticWeaponPlacements.Count; i++) { Instantiate(disruptorPrefab, staticWeaponPlacements[i].transform.position, staticWeaponPlacements[i].transform.rotation); } } if (bossCurrentHealth <= 0) { bossCurrentHealth = 0; bossHealthBar.transform.localScale = new Vector3(0, 0, 0); for (int i = 0; i < aimedWeaponPlacements.Count; i++) { Instantiate(explosion, transform.position, transform.rotation); Destroy(aimedWeaponPlacements[i]); } for (int i = 0; i < staticWeaponPlacements.Count; i++) { Instantiate(explosion, transform.position, transform.rotation); Destroy(staticWeaponPlacements[i]); } Instantiate(explosion, transform.position, transform.rotation); Destroy(gameObject); } } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Phaser") { Destroy(other.gameObject); bossCurrentHealth--; } if (other.gameObject.tag == "PhotonTorpedo") { bossCurrentHealth -= 10; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyDefenseStationRotate : MonoBehaviour { public int rotateDirection; public float rotateSpeed = 75.0f; void Start() { //randomly choose clockwise or counterclockwise direction for enemy to spin rotateDirection = Random.Range(0, 2); } void Update() { if (rotateDirection == 0) { transform.Rotate(Vector3.forward, rotateSpeed * Time.deltaTime); } if (rotateDirection == 1) { transform.Rotate(Vector3.back, rotateSpeed * Time.deltaTime); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PhotonTorpedo : MonoBehaviour { public KeyCode manualExplosion = KeyCode.Mouse1; public float explosionSize = 3.75f; public float moveSpeed = 5.0f; public bool isExploding = false; void Update() { //move torpedo up before it is triggered to explode if (isExploding == false) { transform.Translate(Vector3.up * moveSpeed * Time.deltaTime); } //if torpedo hits enemy or is triggered by player, stop moving and increase size if (Input.GetKeyDown(manualExplosion)) { isExploding = true; transform.localScale = new Vector3(explosionSize, explosionSize, explosionSize); Destroy(gameObject, 2.0f); } } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Enemy") { isExploding = true; transform.localScale = new Vector3(explosionSize, explosionSize, explosionSize); Destroy(gameObject, 2.5f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyDefenseStation : MonoBehaviour { public GameManager gameManager; public List<GameObject> disruptorPlacements = new List<GameObject>(); public GameObject disruptorPrefab = null; public GameObject explosion = null; public int enemyHealth = 3; public int scoreValue = 20; public int shotPosition1; public int shotPosition2; public float moveSpeed = 1.75f; public float timeBetweenShots = 1.25f; public float timer = 0.0f; void Awake() { GameObject gameManagerObject = GameObject.Find("GameManager"); if (gameManagerObject != null) { gameManager = gameManagerObject.GetComponent<GameManager>(); } transform.position = new Vector3(Random.Range(-8.75f, 8.75f), 10.4f, 0.0f); //determine which 2 of the 5 weapon placements will fire first shotPosition1 = Random.Range(0, 5); do { shotPosition2 = Random.Range(0, 5); } while (shotPosition2 == shotPosition1); } void Update() { timer += Time.deltaTime; transform.Translate(Vector3.up * moveSpeed * Time.deltaTime); //shoot weapon at 2 of 5 weapon placements if (timer >= timeBetweenShots) { timer = 0; Instantiate(disruptorPrefab, disruptorPlacements[shotPosition1].transform.position, disruptorPlacements[shotPosition1].transform.rotation); Instantiate(disruptorPrefab, disruptorPlacements[shotPosition2].transform.position, disruptorPlacements[shotPosition2].transform.rotation); //determine which 2 of the 5 weapon placements will fire after cooldown shotPosition1 = Random.Range(0, 5); do { shotPosition2 = Random.Range(0, 5); } while (shotPosition2 == shotPosition1); } if (enemyHealth <= 0) { gameManager.AddToScore(scoreValue); Instantiate(explosion, transform.position, transform.rotation); Destroy(gameObject); } } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Phaser") { Destroy(other.gameObject); enemyHealth--; } if (other.gameObject.tag == "PhotonTorpedo") { enemyHealth -= 5; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyKlingonController : MonoBehaviour { public GameManager gameManager; public List<GameObject> disruptorPlacements = new List<GameObject>(); public GameObject disruptorPrefab = null; public GameObject explosion = null; public int enemyHealth = 3; public int scoreValue = 10; public Vector3 evadeValue; public float moveSpeed = 2.0f; public float timeBetweenShots; public float timer = 0.0f; void Awake() { GameObject gameManagerObject = GameObject.Find("GameManager"); if (gameManagerObject != null) { gameManager = gameManagerObject.GetComponent<GameManager>(); } //spawn at random point along X axis above playing field transform.position = new Vector3(Random.Range(-8.75f, 8.75f), Random.Range(10.25f, 10.45f), 0.0f); } void Start() { timeBetweenShots = Random.Range(0.85f, 1.5f); //determine diagonal flight path destination evadeValue = new Vector3(Random.Range(-9.0f, 9.0f), -4.5f, 0.0f); } void Update() { timer += Time.deltaTime; if (timer >= timeBetweenShots) { timer = 0; timeBetweenShots = Random.Range(0.85f, 1.5f); for (int i = 0; i < disruptorPlacements.Count; i++) { Instantiate(disruptorPrefab, disruptorPlacements[i].transform.position, disruptorPlacements[i].transform.rotation); } } //float straight down to Y position before beginning diagonal movement if (transform.position.y > 7.5) { transform.Translate(Vector3.up * 0.75f * moveSpeed * Time.deltaTime); } //start diagonal "evasive" movement if (transform.position.y <= 10.5) { transform.position = Vector3.MoveTowards(transform.position, evadeValue, moveSpeed * 1.1f * Time.deltaTime); } if (enemyHealth <= 0) { gameManager.AddToScore(scoreValue); Instantiate(explosion, transform.position, transform.rotation); Destroy(gameObject); } } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Phaser") { Destroy(other.gameObject); enemyHealth--; Debug.Log(other.gameObject + " hit Klingon!"); } if (other.gameObject.tag == "PhotonTorpedo") { enemyHealth -= 5; Debug.Log("Hit by torpedo"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class DestroyByTime : MonoBehaviour { public float destroyDelay = 1.5f; void Start() { //cause non-moving instantiated objects such as explosions to be removed from memory Destroy(gameObject, destroyDelay); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameOverManager : MonoBehaviour { public GameObject restartButton = null; public GameObject quitButton = null; public void OnRestartButtonClicked() { SceneManager.LoadSceneAsync("MainScene"); } public void OnQuitButtonClicked() { Application.Quit(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TorpedoAnimator : MonoBehaviour { //animate torpedos by cycling through array of images private Material mat; public Texture2D[] frames; public float animateSpeed = 10.0f; void Awake() { mat = GetComponent<Renderer>().material; } void Update() { int index = (int)(Time.time * animateSpeed); index = index % frames.Length; mat.mainTexture = frames[index]; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class TitleScreenManager : MonoBehaviour { //show title screen and how to play before players begin public GameObject howToPlayButton = null; public GameObject howToPlayCanvas = null; public GameObject mainGameButton = null; public GameObject mainScreenCanvas = null; public AudioSource warpSFX; void Awake() { warpSFX = GetComponent<AudioSource>(); } public void HowToPlayButtonClicked() { warpSFX.Play(); mainScreenCanvas.SetActive(false); howToPlayCanvas.SetActive(true); } public void MainGameButtonClicked() { howToPlayCanvas.SetActive(false); SceneManager.LoadSceneAsync("MainScene"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class IntroAnimation : MonoBehaviour { public GameObject gameManager = null; public AudioSource spockGreetings; public AudioSource spockUnpleasantSituation; public Text spockTextOne = null; public Text spockTextTwo = null; void Start() { //get audio for "cinematic" GUI opening AudioSource[] spockClips = GetComponents<AudioSource>(); spockGreetings = spockClips[0]; spockUnpleasantSituation = spockClips[1]; spockGreetings.Play(); } public void NextTextActive() { //change text dialogue in GUI spockTextOne.gameObject.SetActive(false); spockTextTwo.gameObject.SetActive(true); spockUnpleasantSituation.Play(); } public void ActivateGameManager() { //begin game gameManager.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public GameObject explosion = null; public GameObject healthBar = null; public GameObject[] phaserPlacements; public GameObject phaserPrefab = null; public GameObject photonTorpedoPlacement = null; public GameObject photonTorpedoPrefab = null; public GameObject shield = null; public GameObject shieldBar = null; public AudioSource phaserFireSFX; public AudioSource screenClearBombSFX; public KeyCode upInput = KeyCode.W; public KeyCode downInput = KeyCode.S; public KeyCode leftInput = KeyCode.A; public KeyCode rightInput = KeyCode.D; public KeyCode shootPhaser = KeyCode.Mouse0; public KeyCode activateShield = KeyCode.Space; public KeyCode shootPhotonTorpedo = KeyCode.Mouse1; public KeyCode screenClearBomb = KeyCode.Q; public KeyCode warpDrive = KeyCode.LeftShift; public bool isPhotonTorpedoAway = false; public bool screenClearBombUsed = false; public bool shieldActive = false; public bool shieldDestroyed = false; public int currentHealth = 50; public int currentShield = 50; public int phaserRotation = 0; public int maxHealth = 50; public int maxShield = 50; public float moveSpeed = 5.0f; public float torpedoCooldown = 2.5f; public float torpedoTimer = 0.0f; public float warpDriveCooldown = 1.5f; public float warpDriveTimer = 0.0f; public float xPosMin = -9.25f; public float xPosMax = 9.25f; public float yPosMin = -1.25f; public float yPosMax = 8.0f; public string[] enemiesForScreenClear = { "Enemy", "Disruptor" }; void Start() { healthBar = GameObject.Find("PlayerHealthBar"); shieldBar = GameObject.Find("ShieldBar"); healthBar.transform.localScale = new Vector3(1, 1, 1f); shieldBar.transform.localScale = new Vector3(1, 1, 1); Mathf.Clamp(currentHealth, 0, 50); AudioSource[] SFX = GetComponents<AudioSource>(); screenClearBombSFX = SFX[0]; phaserFireSFX = SFX[1]; shield.SetActive(false); warpDriveTimer = 1.5f; } void Update() { //start timers for abilities and ensure health and shield bars deplete as damage is taken torpedoTimer += Time.deltaTime; warpDriveTimer += Time.deltaTime; shieldBar.transform.localScale = new Vector3((float)currentShield / (float)maxShield, 1.0f, 1.0f); healthBar.transform.localScale = new Vector3((float)currentHealth / (float)maxHealth, 1.0f, 1.0f); if (Input.GetKey(upInput)) { //keep player inside the playing field if (transform.position.y < yPosMax) { transform.Translate(Vector3.up * Time.deltaTime * moveSpeed); //allow player to use blink ability if not on cooldown if (Input.GetKeyDown(warpDrive) && warpDriveTimer > warpDriveCooldown) { transform.position += Vector3.up * 3.0f; warpDriveTimer = 0; } } } if (Input.GetKey(downInput)) { if (transform.position.y > yPosMin) { transform.Translate(Vector3.down * Time.deltaTime * moveSpeed); if (Input.GetKeyDown(warpDrive) && warpDriveTimer > warpDriveCooldown) { transform.position += Vector3.down * 3.0f; warpDriveTimer = 0; } } } if (Input.GetKey(leftInput)) { if (transform.position.x > xPosMin) { transform.Translate(Vector3.left * Time.deltaTime * moveSpeed); if (Input.GetKeyDown(warpDrive) && warpDriveTimer > warpDriveCooldown) { transform.position += Vector3.left * 3.0f; warpDriveTimer = 0; } } } if (Input.GetKey(rightInput)) { if (transform.position.x < xPosMax) { transform.Translate(Vector3.right * Time.deltaTime * moveSpeed); if (Input.GetKeyDown(warpDrive) && warpDriveTimer > warpDriveCooldown) { transform.position += Vector3.right * 3.0f; warpDriveTimer = 0; } } } if (Input.GetKeyDown(shootPhaser)) { //play phaser SFX when shot is fired phaserFireSFX.Play(); //cycle through different weapon placements as shots are fired Instantiate(phaserPrefab, phaserPlacements[phaserRotation].transform.position, phaserPlacements[phaserRotation].transform.rotation); phaserRotation++; if (phaserRotation == 3) { phaserRotation = 0; } } if (Input.GetKeyDown(shootPhotonTorpedo) && torpedoTimer >= torpedoCooldown) { //launch torpedo if not on cooldown and one has not already been fired if (isPhotonTorpedoAway == false) { Instantiate(photonTorpedoPrefab, photonTorpedoPlacement.transform.position, photonTorpedoPlacement.transform.rotation); isPhotonTorpedoAway = true; torpedoTimer = 0.0f; } //detonate torpedo in torpedo controller script else if (isPhotonTorpedoAway == true) { isPhotonTorpedoAway = false; } } //use ultimate ability once per life to clear the screen of all hazards if (Input.GetKeyDown(screenClearBomb) && screenClearBombUsed == false) { screenClearBombSFX.Play(); screenClearBombUsed = true; foreach (string tag in enemiesForScreenClear) { GameObject[] enemiesToDestroy = GameObject.FindGameObjectsWithTag(tag); foreach (GameObject enemy in enemiesToDestroy) { Instantiate(explosion, enemy.transform.position, enemy.transform.rotation); Destroy(enemy); } } } if (Input.GetKey(activateShield) && shieldDestroyed == false) { shieldActive = true; shield.SetActive(true); } if (Input.GetKeyUp(activateShield)) { shieldActive = false; shield.SetActive(false); } if (currentShield <= 0) { currentShield = 0; shieldDestroyed = true; } if (currentHealth <= 0) { currentHealth = 0; healthBar.transform.localScale = new Vector3(0, 0, 0); Instantiate(explosion, transform.position, transform.rotation); } } void LateUpdate() { if (currentHealth == 0) { Destroy(gameObject); } } //damage triggers public void OnTriggerEnter(Collider other) { if ((other.gameObject.tag == "Disruptor" || other.gameObject.tag == "Enemy") && shieldActive == true) { currentShield -= 10; Destroy(other.gameObject); Instantiate(explosion, other.gameObject.transform.position, other.gameObject.transform.rotation); } if (other.gameObject.tag == "Disruptor" && shieldActive == false) { currentHealth -= 9; Destroy(other.gameObject); Instantiate(explosion, other.gameObject.transform.position, other.gameObject.transform.rotation); } if (other.gameObject.tag == "Enemy" && shieldActive == false) { currentHealth -= 14; Destroy(other.gameObject); Instantiate(explosion, other.gameObject.transform.position, other.gameObject.transform.rotation); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyRomulanController : MonoBehaviour { public GameManager gameManager; public GameObject disruptorPlacement = null; public GameObject disruptorPrefab = null; public GameObject explosion = null; public GameObject player = null; public Vector3 currentDestination; public int enemyHealth = 2; public int scoreValue = 15; public float moveSpeed = 2.0f; public float timeBetweenShots; public float timer = 0.0f; void Awake() { GameObject gameManagerObject = GameObject.Find("GameManager"); if (gameManagerObject != null) { gameManager = gameManagerObject.GetComponent<GameManager>(); } //find player to make weapon placements aim shots player = GameObject.FindWithTag("Player"); //spawn at random point along X axis above playing field transform.position = new Vector3(Random.Range(-8.75f, 8.75f), 10.4f, 0.0f); } void Start() { disruptorPlacement.transform.LookAt(player.transform.position); currentDestination = new Vector3(Random.Range(-9.0f, 9.0f), 7.5f, 0.0f); timeBetweenShots = Random.Range(0.9f, 1.75f); } void Update() { timer += Time.deltaTime; //continue to aim at player if (player != null) { disruptorPlacement.transform.LookAt(player.transform.position); } //float from spawn into static Y position if (transform.position.y > 7.5) { transform.Translate(Vector3.up * moveSpeed * Time.deltaTime); } //move randomly along X axis if (transform.position.y <= 7.5) { transform.position = Vector3.MoveTowards(transform.position, currentDestination, moveSpeed * Time.deltaTime); if (Vector3.Distance(transform.position, currentDestination) <= 0.05f) { currentDestination = new Vector3(Random.Range(-8.5f, 8.5f), 7.5f, 0.0f); } } if (timer >= timeBetweenShots) { timer = 0; timeBetweenShots = Random.Range(0.9f, 1.75f); Instantiate(disruptorPrefab, disruptorPlacement.transform.position, disruptorPlacement.transform.rotation); } if (enemyHealth <= 0) { gameManager.AddToScore(scoreValue); Instantiate(explosion, transform.position, transform.rotation); Destroy(gameObject); } } public void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Phaser") { Destroy(other.gameObject); enemyHealth--; } if (other.gameObject.tag == "PhotonTorpedo") { enemyHealth -= 5; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayingField : MonoBehaviour { //ensure enemies and projectiles are destroyed when they leave the playing field void OnTriggerExit(Collider other) { Destroy(other.gameObject); } }
e725a9972b3b69de171c15de832193b6e8282cf2
[ "Markdown", "C#" ]
17
Markdown
Folrig/CIS50_SpaceShooter
8397776aff6383075ac76d4bd31e925ce7cbc65c
0564a5a1ad1f228b0cbd8fe85fedd52306c5bec8
refs/heads/master
<file_sep>import React from 'react'; export function dynamic(c) { return class dy extends React.Component { state= { l: null } componentDidMount(){ this.mounted = true; c() .then(r => r.default) .then((e) => { if(this.mounted) { this.setState({ l: e }, () => { if(this.props.componentIsMounted) { this.props.componentIsMounted(this.l); } if(this.setCountAndLoad) this.setCountAndLoad(); }) } }) } componentWillUnmount() { this.mounted = false; } setCountAndLoad = () => { } render() { const { l: L } = this.state; if (L) { return <L ref={(e) => this.l}/> } else { return <div>1</div> } } } }<file_sep>const demo = ( state = { name: "初始化" }, action ) => { switch (action.type) { case "demo/setName": return { ...state, ...action.subreddit }; default: return state; } }; export { demo }; <file_sep># hzw-boilerplate a simple react project boilerlate <file_sep>const config = require("./webpack.config.common"); const webpack = require("webpack"); const commomConfig = Object.assign( { devtool: "inline-source-map", //源码调试 mode: "development", devServer: { contentBase: "./dist", //设置热加载的文件访问路径 port: 9998, //端口 quiet: false, clientLogLevel: "error", hot: true } }, config ); module.exports = commomConfig; <file_sep>import React from 'react' import { connect } from 'react-redux' import { setName } from 'Actions/demo'; import styles from './demo_redux.css'; @connect(state => ({ name: state.demo.name, })) export default class Demo extends React.Component { changeName() { this.props.dispatch(setName({name:'a23'})); } render() { return <h1 className={styles.index} onClick={() => this.changeName()}>is demo2, {this.props.name}</h1>; } }<file_sep>import Header from "./layouts/header"; // const registerModel = (app, model) => { // // eslint-disable-next-line // if (!(app._models.filter(m => m.namespace === model.namespace).length === 1)) { // app.model(model); // } // }; export default [ { path: "/", components: Header, indexRoute: { onEnter: (nextState, replace) => replace("/index") }, childRoutes: [ { path: "index", getComponent(next, cb) { require.ensure([], reqiure => { cb(null, require("./routes/blog/")); }); } }, { path: "demo", getComponent(next, cb) { require.ensure([], reqiure => { cb(null, require("./routes/demo/")); }); } }, { path: "demo1", getComponent(next, cb) { require.ensure([], reqiure => { cb(null, require("./routes/demo/demo.js")); }); } }, { path: "demo_redux", getComponent(next, cb) { require.ensure([], reqiure => { cb(null, require("./routes/demo/demo_redux")); }); } } ] } ]; <file_sep>const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); //installed via npm const CleanWebpackPlugin = require("clean-webpack-plugin"); const webpack = require("webpack"); //to access built-in plugins const fs = require("fs"); const cwd = process.cwd(); const appDirectory = fs.realpathSync(cwd); module.exports = { entry: { index: `${appDirectory}/src/index.js` }, output: { path: `${appDirectory}/dist`, filename: "[name].js" }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: `${appDirectory}/src/index.html`, title: "我的博客" }) ], resolve: { alias: { Actions: `${appDirectory}/src/actions/`, root: `${appDirectory}/src` } }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: "babel-loader" } }, { test: /\.md$/, use: [ { loader: "html-loader" }, { loader: "markdown-loader", options: { pedantic: true } } ] }, { test: /\.css$/, use: [ "style-loader", { loader: "css-loader", options: { modules: true, localIdentName: "[local]_[hash:base64:5]" } } ] }, { test: /\.less$/, use: [ { loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader", options: { modules: true, localIdentName: "[local]_[hash:base64:5]" } }, { loader: "less-loader" } ] }, { test: /\.(png|svg|jpg|gif|woff|woff2|eot|ttf|otf)$/, use: ["file-loader"] }, { test: /\.(csv|tsv)$/, use: ["csv-loader"] }, { test: /\.xml$/, use: ["xml-loader"] } ] } }; <file_sep>import React from 'react'; import { dynamic } from 'root/utils/dynamic' import img from 'root/assets/img1.png'; import styles from './demo.less'; function a(t) { return dynamic(t); } export default class Demo extends React.Component { render() { return <div className={styles.index}> is index, <img src={img} /> </div>; } }
8dc6c9dd981f16935bdbe7873d81cb26c7915ed1
[ "JavaScript", "Markdown" ]
8
JavaScript
hanangjie/hzw-boilerplate
ec03333726c89afdf6ead4c8253277931eb2311c
d741f449a275ed54a226b561396bc2c84dcbdb0b
refs/heads/master
<repo_name>m-ahmedy/upload-service<file_sep>/README.md # Upload Service ## Required exports from src/backend.js - **uploadHandler** Express handler function for the `POST /upload` route - **middleware** Array of the middlewares used with Express app by calling `app.use()` ## How to start - Clone the repository to your **development** machine by `git clone ` - After developing the upload handler logic copy the handler function - the one inside `app.post("/upload", <This function>)` - and assign it to the `uploadHandler` export. - Be sure to require all the dependencies in the response handler and add them to `package.json`. - Copy the whole folder to the server on which the IP of the host will be called, using `scp` command or any other method. - From the terminal on the server cd to the directory and run '`sh script.sh 8000`' where 8080 is the port on which the service will be listening, can be changed if required just run the command again. - The script would do all the infrastructure handling and starts the upload service on every reboot. - You can check service status with `systemctl status upload.service`<file_sep>/lib/remove-service.sh systemctl stop upload.service systemctl disable upload.service rm /etc/systemd/system/upload.service rm /etc/systemd/system/upload.service # and symlinks that might be related rm /usr/lib/systemd/system/upload.service rm /usr/lib/systemd/system/upload.service # and symlinks that might be related systemctl daemon-reload systemctl reset-failed<file_sep>/script.sh #!/bin/bash export UPLOAD_SERVICE_ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )" >> ~/.bashrc echo echo "Opening port on $1" echo if [ "$1" != "" ]; then echo "UPLOAD_SERVICE_PORT=$1" > $UPLOAD_SERVICE_ROOT_DIR/.env firewall-cmd --permanent --add-port=$1/tcp else echo "UPLOAD_SERVICE_PORT=8080" > $UPLOAD_SERVICE_ROOT_DIR/.env firewall-cmd --permanent --add-port=8080/tcp fi firewall-cmd --reload echo echo "Opened port successfully" echo echo "Installing Node" echo npm cache clean --force curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash - sudo yum install nodejs -y echo echo "Installed Node Successfully" echo echo "Installing dependencies" echo npm install echo "Installed dependencies successfully" echo echo "Writing a service to run at startup" echo /bin/bash $UPLOAD_SERVICE_ROOT_DIR/lib/remove-service.sh echo "#!/bin/bash" > /var/tmp/upload_service.sh echo "cd $UPLOAD_SERVICE_ROOT_DIR && npm start" >> /var/tmp/upload_service.sh chmod +x /var/tmp/upload_service.sh cp $UPLOAD_SERVICE_ROOT_DIR/lib/upload.service /etc/systemd/system/ systemctl daemon-reload systemctl enable upload.service systemctl start upload.service echo echo "Writing a service to run at startup successfuly" echo
c2b7dc14c99e72cc6d95fe644085d696080007f4
[ "Markdown", "Shell" ]
3
Markdown
m-ahmedy/upload-service
ce6a713ef9c592563e79c9639a4f790c355bd541
7d2f4ba7daa33c97643ef23cdc16724357048047
refs/heads/main
<file_sep># Initial steps for using pybind11 Clone the pybind11-initial steps repo: ``` git clone --recursive <EMAIL>:winksaville/pybind11-initialsteps cd pybind11-initialsteps/ ``` If you forget `--resusive` or `--recurse-submodules` you can use `submodule update` to update after cloning, see [git-tools-submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules): for additional information. ``` git clone <EMAIL>:winksaville/pybind11-initialsteps cd pybind11-initialsteps git submodule update --init --recursive ``` ## First step Navigate into the firststep directory: ``` $ cd firststep ``` ### The source code for a simple C++ module A very simple c++ file that uses pybind11 to create a python extension that makes the add method usable by python code: ``` $ cat example.cpp #include <pybind11/pybind11.h> namespace py = pybind11; int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; // optional module docstring m.def("add", &add, "A function which adds two numbers"); } ``` ### The python file that uses example.add to add 2 + 5 ``` $ cat example.py import example print(f"result={example.add(2, 5)}") ``` ### The bash script that compiles the extension and runs the python example: ``` $ cat build-run.sh #!/usr/bin/env bash set -x # Get from pybind11 for the -I parameters it needs INCLUDES=`python3 -m pybind11 --includes` # Get from python the extension needed for this platform DOT_EXT=`python3-config --extension-suffix` # Compile g++ -O3 -Wall -shared -std=c++11 -fPIC -o example$DOT_EXT $INCLUDES example.cpp # Run python example.py``` ## Install, build and run ``` ### Install pybind11 Note: with later steps it's not necessary to install pybind11 so you might consider just looking at the code. ``` pip install pybind11 ``` ### Run ``` $ ./build-run.sh ++ python3 -m pybind11 --includes + INCLUDES='-I/opt/miniconda3/envs/x/include/python3.8 -I/opt/miniconda3/envs/x/lib/python3.8/site-packages/pybind11/include' ++ python3-config --extension-suffix + DOT_EXT=.cpython-38-x86_64-linux-gnu.so + g++ -O3 -Wall -shared -std=c++11 -fPIC -o example.cpython-38-x86_64-linux-gnu.so -I/opt/miniconda3/envs/x/include/python3.8 -I/opt/miniconda3/envs/x/lib/python3.8/site-packages/pybind11/include example.cpp + python example.py result=7 ``` ## Second step A more realistic example where a C library is going to be converted to a python extension using cmake. Navigate into the second directory from pybind11-initialsteps: ``` $ cd secondstep ``` ### TODO: Add details for each of the files ``` wink@3900x:~/prgs/python/projects/pybind11-initialsteps (main) $ tree -L 3 secondstep secondstep ├── arith │   ├── CMakeLists.txt │   ├── inc │   │   └── arith.hxx │   └── src │   └── add.cxx ├── CMakeLists.txt ├── example │   ├── CMakeLists.txt │   ├── pybind11 │   └── src │   └── example.cxx └── useexample.py ``` ### Commands to prepare, build, install and run ``` wink@3900x:~/prgs/python/projects/pybind11-initialsteps/secondstep (main) cmake -S . -B build -G Ninja -DCMAKE_INSTALL_PREFIX=~/opt/secondstep cmake --build build cmake --install build export PYTHONPATH="$HOME/opt/secondstep/lib" ./useexample.py ``` ### The resultsComple ``` wink@3900x:~/prgs/python/projects/pybind11-initialsteps/secondstep (main) $ cmake -S . -B build -G Ninja -DCMAKE_INSTALL_PREFIX=~/opt/secondstep -- The C compiler identification is GNU 10.2.0 -- The CXX compiler identification is GNU 10.2.0 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: /usr/bin/cc - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: /usr/bin/c++ - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done -- pybind11 v2.6.1 dev1 -- Found PythonInterp: /usr/bin/python3.8 (found version "3.8.6") -- Found PythonLibs: /usr/lib/libpython3.8.so -- Performing Test HAS_FLTO -- Performing Test HAS_FLTO - Success -- Configuring done -- Generating done -- Build files have been written to: /home/wink/prgs/python/projects/pybind11-initialsteps/secondstep/build wink@3900x:~/prgs/python/projects/pybind11-initialsteps/secondstep (main) $ cmake --build build [5/5] Linking CXX shared module example/example.cpython-38-x86_64-linux-gnu.so wink@3900x:~/prgs/python/projects/pybind11-initialsteps/secondstep (main) $ cmake --install build -- Install configuration: "" -- Installing: /home/wink/opt/secondstep/lib/libarith.so.0.2.0 -- Up-to-date: /home/wink/opt/secondstep/lib/libarith.so.1 -- Up-to-date: /home/wink/opt/secondstep/lib/libarith.so -- Installing: /home/wink/opt/secondstep/include/arith.hxx -- Installing: /home/wink/opt/secondstep/lib/example.cpython-38-x86_64-linux-gnu.so -- Set runtime path of "/home/wink/opt/secondstep/lib/example.cpython-38-x86_64-linux-gnu.so" to "/home/wink/opt/secondstep/lib" wink@3900x:~/prgs/python/projects/pybind11-initialsteps/secondstep (main) $ export PYTHONPATH="$HOME/opt/secondstep/lib" wink@3900x:~/prgs/python/projects/pybind11-initialsteps/secondstep (main) $ ./useexample.py result=7 ``` <file_sep>cmake_minimum_required(VERSION 3.13) project(secondstep VERSION 0.3.0 DESCRIPTION "second step") add_subdirectory(arith) add_subdirectory(example) <file_sep>#!/usr/bin/env python3 import example print(f"result={example.add(2, 5)}") <file_sep># RPATHs for finding dynamic libraries, RPATHS?=/home/wink/opt/lib:/home/wink/lib # Get from pybind11 for the -I parameters it needs INCLUDES=$(shell python3 -m pybind11 --includes) # Get from python the extension needed for this platform DOT_EXT=$(shell python3-config --extension-suffix) .PHONY: help help: @echo targets: @echo "run: build and run example.py," @echo " optional param: RPATHS=xxx where xxx is path to libraries" @echo " default RPATHS=$(RPATHS)" @echo "buildit: Build example$(DOT_EXT)" @echo "clean: Clean artificats" .PHONY: run run: buildit python useexample.py .PHONY: buildit buildit: example$(DOT_EXT) example$(DOT_EXT): build/example.obj build/libadd.so g++ -shared -fPIC -o $@ $< -L./build -ladd -Wl,-rpath=$(RPATHS) build: mkdir -p build build/example.obj: example.cxx inc/add.hxx | build g++ -O3 -Wall -std=c++11 -fPIC -I inc $(INCLUDES) -o $@ -c $< build/add.obj: src/add.cxx inc/add.hxx | build g++ -O3 -Wall -std=c++11 -fPIC -I inc -o $@ -c $< build/libadd.so: build/add.obj g++ -shared -fPIC -o $@ $^ .PHONY: clean clean: rm -rf example$(DOT_EXT) build <file_sep>#include <pybind11/pybind11.h> #include "add.hxx" PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example plugin"; // optional module docstring m.def("add", &add, "A function which adds two numbers"); } <file_sep>cmake_minimum_required(VERSION 3.13) project(example VERSION 0.1.0 DESCRIPTION "Example cpython extension") # Below we set RPATH for the example.xxx.so so that when it is loaded # the arith library can be found. But, for this example.xxx.so to be found # PYTHONPATH needs to be set! HOPEFULLY, we can solve this when we # add setup.py. # Set the install RPATH so after installing example can find the arth library set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib) # Set the build RPATH so tests or while developing example can find the arth library set(CMAKE_BUILD_RPATH ${CMAKE_BINARY_DIR}/arith) # Add pybind11 so we can use the pybind11_add_module add_subdirectory(pybind11) pybind11_add_module(example src/example.cxx) # Specify example has the arith library as a dependency target_link_libraries(example PUBLIC arith) # Specify where example can find arith library include while building target_include_directories(example PRIVATE ${CMAKE_SOURCE_DIR}/arith/inc) # Install exampe.*.so into the install library directory install(TARGETS example LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) <file_sep>import example print(f"result={example.add(2, 5)}") <file_sep>// add header // #ifndef ADD_HXX #define ADD_HDD 1 int add(int i, int j); #endif <file_sep>#!/usr/bin/env bash set -x # Get from pybind11 for the -I parameters it needs INCLUDES=`python3 -m pybind11 --includes` # Get from python the extension needed for this platform DOT_EXT=`python3-config --extension-suffix` # Compile g++ -O3 -Wall -shared -std=c++11 -fPIC -o example$DOT_EXT $INCLUDES example.cpp # Run python example.py
4b6a9663b0ae5ae950eee91ccf4c78a2ef2934a6
[ "CMake", "Markdown", "Makefile", "Python", "C++", "Shell" ]
9
Markdown
winksaville/pybind11-initialsteps
363c0cf0bc2694d4301182708ba64140fec78592
4452b2a323b46e6726dcc899bb124d1914f9faf5
refs/heads/main
<repo_name>BlueWhaleKo/docker-utils<file_sep>/go.mod module github.com/BlueWhaleKo/docker-utils go 1.16 require ( github.com/containerd/containerd v1.5.5 // indirect github.com/docker/docker v20.10.8+incompatible // indirect github.com/docker/go-connections v0.4.0 // indirect google.golang.org/grpc v1.40.0 // indirect ) <file_sep>/pkg/util/push.go package util import ( "context" "io" "github.com/docker/docker/api/types" "github.com/docker/docker/client" ) func PushImage(c *client.Client, image string, opt types.ImagePushOptions) (io.ReadCloser, error) { return c.ImagePush(context.Background(), image, opt) } <file_sep>/README.md # docker-util docker utility library <file_sep>/pkg/util/dockerfile.go package util import ( "fmt" "strings" ) type Dockerfile struct { inner []string } func NewDockerfile() *Dockerfile { return &Dockerfile{} } func (d *Dockerfile) From(from string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("FROM %s", from)) return d } func (d *Dockerfile) Entrypoint(entrypoint string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("ENTRYPOINT %s", entrypoint)) return d } func (d *Dockerfile) Cmd(cmd string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("CMD %s", cmd)) return d } func (d *Dockerfile) WORKDIR(dir string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("WORKDIR %s", dir)) return d } func (d *Dockerfile) Run(cmd string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("RUN %s", cmd)) return d } func (d *Dockerfile) Add(source, target string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("ADD %s %s", source, target)) return d } func (d *Dockerfile) Copy(source, target string) *Dockerfile { d.inner = append(d.inner, fmt.Sprintf("COPY %s %s", source, target)) return d } func (d *Dockerfile) Build() string { return strings.Join(d.inner, "\n") } <file_sep>/pkg/util/build.go package util import ( "archive/tar" "bytes" "context" "io" "io/ioutil" "github.com/docker/docker/api/types" "github.com/docker/docker/client" ) func BuildImage(c *client.Client, dockerfile io.Reader, opt types.ImageBuildOptions) (types.ImageBuildResponse, error) { buf := new(bytes.Buffer) tw := tar.NewWriter(buf) defer tw.Close() readall, err := ioutil.ReadAll(dockerfile) if err != nil { return types.ImageBuildResponse{}, err } err = tw.WriteHeader(&tar.Header{ Name: "Dockerfile", Size: int64(len(readall)), }) if err != nil { return types.ImageBuildResponse{}, err } _, err = tw.Write(readall) if err != nil { return types.ImageBuildResponse{}, err } tarReader := bytes.NewReader(buf.Bytes()) res, err := c.ImageBuild(context.Background(), tarReader, opt) if err != nil { return types.ImageBuildResponse{}, err } return res, nil }
5d45b7667fe242ab3a7473bb9b85b4e903f6a625
[ "Go", "Go Module", "Markdown" ]
5
Go Module
BlueWhaleKo/docker-utils
86552bb27bd0f0f5403a80a4b38bb1b6a81f62c8
f857c4f129b4e95b467056604a656a87028c9e3b
refs/heads/master
<repo_name>InnaSmir/3.1.Radio<file_sep>/src/test/java/ru/netology/RadioTest.java package ru.netology; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RadioTest { Radio radio = new Radio(); @Test public void shouldGetAndSetCurrentRadioStation() { radio.setCurrentRadioStation(0); assertEquals(0, radio.getCurrentRadioStation()); radio.setCurrentRadioStation(4); assertEquals(4, radio.getCurrentRadioStation()); radio.setCurrentRadioStation(9); assertEquals(9, radio.getCurrentRadioStation()); radio.setCurrentRadioStation(10); assertEquals(9, radio.getCurrentRadioStation()); radio.setCurrentRadioStation(-1); assertEquals(9, radio.getCurrentRadioStation()); } @Test public void shouldGetAndSetCurrentVolumeSound() { radio.setCurrentVolumeSound(0); assertEquals(0, radio.getCurrentVolumeSound()); radio.setCurrentVolumeSound(5); assertEquals(5, radio.getCurrentVolumeSound()); radio.setCurrentVolumeSound(9); assertEquals(9, radio.getCurrentVolumeSound()); radio.setCurrentVolumeSound(10); assertEquals(10, radio.getCurrentVolumeSound()); radio.setCurrentVolumeSound(-1); assertEquals(10, radio.getCurrentVolumeSound()); radio.setCurrentVolumeSound(11); assertEquals(10, radio.getCurrentVolumeSound()); } @Test public void shouldGetAndSetMaxVolumeSound() { radio.setMaxVolumeSound(10); assertEquals(10, radio.getMaxVolumeSound()); radio.setMaxVolumeSound(9); assertEquals(9, radio.getMaxVolumeSound()); } @Test public void shouldGetAndSetMinVolumeSound() { radio.setMinVolumeSound(0); assertEquals(0, radio.getMinVolumeSound()); radio.setMinVolumeSound(1); assertEquals(1, radio.getMinVolumeSound()); } @Test public void shouldGetAndSetMaxNumberRadioStation() { radio.setMaxNumberRadioStation(9); assertEquals(9, radio.getMaxNumberRadioStation()); radio.setMaxNumberRadioStation(8); assertEquals(8, radio.getMaxNumberRadioStation()); } @Test public void shouldGetAndSetMinNumberRadioStation() { radio.setMinNumberRadioStation(9); assertEquals(9, radio.getMinNumberRadioStation()); radio.setMinNumberRadioStation(8); assertEquals(8, radio.getMinNumberRadioStation()); } @Test public void shouldIncreaseCurrentVolumeSound() { radio.setCurrentVolumeSound(10); radio.increaseCurrentVolumeSound(); assertEquals(10,radio.getCurrentVolumeSound()); } @Test public void shouldDecreaseCurrentVolumeSound() { radio.setCurrentVolumeSound(0); radio.decreaseCurrentVolumeSound(); assertEquals(0,radio.getCurrentVolumeSound()); } //возможность выставлять номер радиостанции с цифрового пульта (вводя числа 0 - 9) @Test public void shouldRemoteNumberRadioStation() { int [] possibleNumberRadioStation = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; radio.setCurrentRadioStation(possibleNumberRadioStation[0]); assertEquals(possibleNumberRadioStation[0], radio.getCurrentRadioStation()); radio.setCurrentRadioStation(possibleNumberRadioStation[9]); assertEquals(9, radio.getCurrentRadioStation()); radio.setCurrentRadioStation(possibleNumberRadioStation[1]); assertEquals(1, radio.getCurrentRadioStation()); radio.setCurrentRadioStation(possibleNumberRadioStation[4]); assertEquals(4, radio.getCurrentRadioStation()); } }
fe5e1a8e3a59f733875575e8d9260fab80f2da50
[ "Java" ]
1
Java
InnaSmir/3.1.Radio
e36a871a293b568d22bf5cd6c5d10560813c86e1
b959302d61d80a38824033d3d96d7a883d1acf73
refs/heads/master
<repo_name>Masoumeh/recogito2<file_sep>/app/views/help/tutorial/tutorial_fa.scala.html @()(implicit request: RequestHeader, webJarsUtil: org.webjars.play.WebJarsUtil) @views.html.help._layout("Recogito in 10 Minutes", "A quick tutorial of Recogito's most important features. Learn how to create annotations, map places and share your work with others.", "en", "tutorial.css") { <h1>10 Minute Tutorial</h1> <span class="sub-title"><span class="icon">&#xf017;</span> A Quick Introduction to Recogito</span> } { <div class="toc-wrapper" dir="rtl"> <div class="toc"> <ul class="internal"> <li><a href="#what">ریکوگیتو چیست؟</a></li> <li><a href="#upload">کلیک سند جدید </a></li> <li><a href="#annotations">حاشیه‌نویسی</a></li> <li><a href="#map">شناسایی و نگاشت مکان‌ها</a></li> <li><a href="#export">دریافت داده‌ها</a></li> <li><a href="#invite">دعوت از کاربران</a></li> </ul> <div class="localized-versions"> <h3>This tutorial in</h3> <ul> <li> <a href="@controllers.help.routes.HelpController.localizedTutorial("de")"> <img src="@routes.Assets.versioned("images/flags/de.png")"> Deutsch </a> </li> <li> <a href="@controllers.help.routes.HelpController.tutorial()"> <img src="@routes.Assets.versioned("images/flags/en_uk.png")"> English </a> </li> <li> <a href="@controllers.help.routes.HelpController.localizedTutorial("es")"> <img src="@routes.Assets.versioned("images/flags/es.png")"> Espa&ntilde;ol </a> </li> <li> <a href="@controllers.help.routes.HelpController.localizedTutorial("it")"> <img src="@routes.Assets.versioned("images/flags/it.png")"> Italiano </a> </li> <li> <a href="@controllers.help.routes.HelpController.localizedTutorial("nl")"> <img src="@routes.Assets.versioned("images/flags/nl.png")"> Nederlands </a> </li> </ul> </div> </div> </div> <div class="article has-sidebar" dir="rtl"> <div class="inner"> <p> این آموزش کوتاه خلاصه‌ای از مهمترین قابلیت‌های ریکوگیتو را در اختیار شما می‌گذارد. یاد خواهید گرفت که چگونه: </p> <ul> <li>متن و عکس بارگذاری کنید.</li> <li>حاشیه‌نویسی کنید.</li> <li>نام مکان‌ها را در متن خود شناسایی و روی نقشه مشخص کنید.</li> <li>برای استفادهٔ دوباره از داده‌های خود در محیطی خارج از ریکوگیتو آنها را دریافت (export) کنید.</li> <li>کاربران دیگر را برای مشارکت دعوت کنید.</li> </ul> <h2 id="what">ریکوگیتو چیست؟</h2> <p> ریکوگیتو سکویی آنلاین برای حاشیه‌نویسی مشارکتی متن و اسناد است که توسط <a href="http://commons.pelagios.org" target="_blank">Pelagios Commons</a> نگهداری و مدیریت می‌شود. در ریکوگیتو برای کاربران محیط کاری شخصی ایجاد می‌شود که آنان را قادر به جمع آوری و سازماندهی منابع خود—متن، عکس و داده‌هایی در قالب جدول—و مشارکت در حاشیه‌نویسی و تفسیر منابع می‌کند. ریکوگیتو به شما کمک می‌کند تا به‌ راحتی کارهای خود را در وب در معرض دید عموم قرار دهید و نتایج تحقیقات خود را به‌ عنوان داده‌باز (Open Data) ارائه کنید. </p> <p> این آموزش مهمترین نکات لازم دربارۀ کار با ریکوگیتو را در اختیار شما قرار می‌دهد. برای تکمیل این آموزش نیاز به ایجاد حساب کاربری و همچنین دو سند نمونه دارید: یک فایل متنی در قالب txt و یک تصویر. </p> <p> نکته: این متن آموزشی را در پنجره جداگانه‌ای در مرورگر خود باز کنید تا در زمان پیشرفت کار قادر به دیدن و دنبال‌کردن مراحل آن باشید. </p> <p class="tip rtl"> در ریکوگیتو اسناد برای سازماندهی منابع شما بکار می‌روند. هر سند می‌تواند شامل چندین فایل باشد. در این قسمت از آموزش, ما سندی را با تنها یک فایل متنی بارگذاری می‌کنیم. </p> <h2 id="upload">کلیک سند جدید </h2> <p> <img src="@routes.Assets.versioned("images/help/new-document.png")"> </p> <p> کلیک سند جدید </p> <h3>برای بارگذاری سند جدید</h3> <ol> <li>عنوانی برای سند خود وارد کرده و دکمه «بعدی» را کلیک کنید.</li> <li>فایل متنی خود را بارگذاری کنید. می‌توانید این کار را از طریق «انتخاب فایل» و «پیوست» متن و یا با کشیدن و رها‌کردن فایل توسط موس در محدوده بارگذاری انجام دهید.</li> <li>می‌توانید شناسایی موجودیت‌های نامدار (Named Entity Recognition) را بر روی متن اجرا کنید. در این صورت خواهید توانست مکان‌ها و افراد را به صورت خودکار در متن شناسایی کنید و حاشیه‌نویسی اولیه‌ای را انجام دهید. برای اینکار گزینه «حاشیه‌نویسی خودکار» را انتخاب کرده و «بعدی» را کلیک کنید.</li> </ol> <p> این مرحله, زمانی متناسب با طول متن شما نیاز خواهد داشت. پس از پایان اجرا، ,<strong>پایان</strong> را کلیک کنید. تبریک می‌گوییم! شما اولین سند خود را وارد محیط کاری خود کرده‌اید. </p> <h3>بارگذاری تصویر جدید</h3> <p> برای ایجاد سند جدیدی از تصویر مورد نظر خود, مراحل بالا را طی کنید. در مرحله پایانی، تبدیل تصویر بارگذاری شده به تصویری با قابلیت بزرگنمایی زمان کوتاهی به طول می‌انجامد. در این مورد توضیحات بیشتری در ادامه ارائه می‌شود. </p> <h2 id="annotations">مرحله ۲. حاشیه‌نویسی</h2> <p> بر روی سند خود در لیست دوبار کلیک کنید. با این کار وارد نمای حاشیه‌نویسی می‌شوید. </p> <h3>ایجاد حاشیه‌نویسی</h3> <p> متن موردنظر خود را همانگونه که در هر ویرایشگر متن دلخواهی باز کنید: می‌توانید این کار را با کشیدن و رها کردن موس و یا دوبار کلیک انجام دهید. می‌توانید توضیحات و برچسب‌هایی را به متن اضافه کنید. همچنین می‌توانید بخشی از متن را را بعنوان مکان، فرد یا رویداد شناسایی کنید. (در ادامه در مورد چگونگی کار با مکان بیشتر خواهیم آموخت.) </p> <p> <img src="@routes.Assets.versioned("images/help/annotation-view.png")"> </p> <p> حاشیه‌نویسی با ویرایشگر را تجربه کنید. پس از ایجاد حاشیه‌نویسی‌ها می‌توانید هر بخشی را جداگانه تغییر داده یا پاک کنید. (برای پاک کردن یک برچسب بر روی آن کلیک کنید تا دکمه پاک کردن ظاهر شود.) پاک کردن تمام بخش‌های یک حاشیه‌نویسی رنگ پس زمینه متن موردنظر را نیز پاک خواهد کرد. </p> <h3>ایجاد حاشیه‌نویسی برای تصویر</h3> <p> <img src="@routes.Assets.versioned("images/help/image-controls.png")" class="inline right"> تصویر خود را باز کنید. در ریکوگیتو می‌توانید حتی تصاویر با وضوح بالا را از طریق نمای قابل بزرگنمایی (zoomable view) به آسانی حرکت دهید. با بکاربردن چرخ موس یا دکمه‌های <span class="key">+</span> و <span class="key">-</span> در گوشه سمت راست بالایی می‌توانید بزرگنمایی را تغییر دهید. در دستگاه‌های لمسی همچنین می‌توانید از حرکت "نیشگون" استفاده کنید. با کشیدن و رها کردن تصویر می‌توانید pan کنید. </p> <p> می‌توانید تصویر را در درجات دلخواه بچرخانید. در کامپیوترهای رومیزی کلید SHIFT + Alt را همزمان با کشیدن موس نگه دارید. در دستگاه‌های لمسی می‌توانید از حرکت "نیشگون" استفاده کنید. با بکاربردن دکمه‌ای که حاوی یک فلش است به سرعت تصویر را به حالت اولیه باز گردانید. </p> <p> در اینجا اولین حاشیه‌نویسی برای تصویر را ایجاد می‌کنیم. در منوی ابزار یک منوی کرکر‌ه‌ای وجود دارد که با استفاده از آن می‌توانید حالت‌های مختلف انتخاب بخشی از تصویر در ریکوگیتو را تغییر دهید: نقطه، مستطیل و جعبه عنوان گذاری شده. نقط‌ه‌ای را انتخاب کرده و سپس با کلیک بر روی تصویر یادداشتی را ایجاد کنید. با بازگشت به گزینه حرکت (Move) می‌توانید ناوش اولیه تصویر را بازیابی کنید. </p> <p> حالا ناحیه‌ای از تصویر را حاشیه‌نویسی کنید: ابزار مستطیل را انتخاب کنید. برای انتخاب نقطه شروع ناحیه انتخابی یک بار کلیک کنید و سپس در نقطه پایانی دوباره کلیک کنید. </p> <p> <img src="@routes.Assets.versioned("images/help/tilted-box.gif")"> </p> <p id="tilted-box"> جعبه عنوان گذاری شده ممکن است تمرین بیشتری نیاز داشته باشد: از منو آن را انتخاب کنید. دکمه موس را کلیک کرده و نگه دارید تا خطوط اصلی جعبه را بکشید. سپس موس را رها کنید. برای تعیین ارتفاع جعبه، موس را حرکت دهید و زمانی که به ارتفاع دلخواه رسیدید کلیک کنید. </p> <p class="tip rtl"> نکته: جعبه عنوان گذاری شده بطور خاص برای حاشیه‌نویسی برچسب‌ها در نقشه پرکاربرد است. از آنجا که خطوط اصلی مشخصی وجود دارد، داده‌هایی که تولید می‌کنید اطلاعاتی درمورد جهت قرارگیری برچسب را نیز شامل می‌شود. </p> <p id="linked-box"> <img src="@routes.Assets.versioned("images/help/linked-box.jpg")" class="inline right"> The <strong>Linked Box</strong><span class="linked-box"></span> is a modified version of the Tilted Box, designed specifically for maps containing symbols and labels. </p> <p> Click once to mark the symbol, then continue to annotate the label as you would with the Tilted Box: click to start the baseline, click again to end it, click once more to set the height. You can modify all points afterwards, by clicking and dragging them. </p> <h2 id="map">مرحله ۳: شناسایی و نگاشت مکان‌ها</h2> <p> تا این مرحله چگونگی حاشیه‌نویسی یک کلمه یا عبارت در یک سند و شناسایی آن بعنوان مرجعی به یک مکان را آموخته‌اید اکنون می‌خواهیم این مرجع را به یک فرهنگ جغرافیایی (gazetteer) ارجاع دهیم بطوریکه ریکوگیتو قادر یه کشیدن و نشان دادن آن مکان بر روی نقشه باشد. </p> <p> مکانی را در ویرایشگر حاشیه‌نویسی کلیک کنید. ریکوگیتو تلاش خواهد کرد تا بطور خودکار پیشنهاداتی را فرهنگ‌های جغرافیایی (gazetteers) مورد پشتیبان خود ارائه کند. شما می‌توانید این پیشنهادها را تائید کنید یا گزینه مناسب تری را در جستجو کنید. در صورتی که مورد مناسبی برای انطباق پیدا نکردید، می‌توانید این مرجع را—بعنوان نشانه‌ای که با هیچ مکانی مطابقت ندارد—با پرچمی‌ علامت گذاری کنید. </p> <p> <img src="@routes.Assets.versioned("images/help/create-text-annotation.gif")"> </p> <p> برای تسریع کار، ریکوگیتو متن موردنظر را برای عبارات یکسان جستجو کرده و امکان ارجاع دوباره این عبارت به فرهنگ جغرافیایی را برای موارد دیگر فراهم می‌کند. </p> <h2 id="export">مرحله ۴: دریافت داده‌ها</h2> <p> شکلک … را در نوار راهبری انتخاب کنید تا گزینه‌های موجود برای دریافت سند را مشاهده کنید. علاوه بر گزینه‌های لیست شده در این صفحه، می‌توایند بسته پشتیبان کار خود را از صفحه تنظیمات سند بارگیری کنید. توصیه می‌کنیم نسخه‌های پشتیبان را جهت بایگانی و بعنوان یک اقدام امنیتی بارگیری کنید. </p> <p> <img src="@routes.Assets.versioned("images/help/export.png")"> </p> <h2 id="invite">مرحله ۵: دعوت از کاربران</h2> <p> در این مرحله پایانی، چگونگی به اشتراک گذاشتن اسناد با سایر کاربران ریکوگیتو را خواهیم آموخت، بطوریکه بتوان در قالب یک تیم همکاری کرد. با اتخاب شکلک … در نوار راهبری اصلی به صفحه تنظیمات سند هدایت می‌شوید. در نوار کناری سمت چپ گزینه «اشتراک گذاری» را انتخاب کنید. </p> <p> <img src="@routes.Assets.versioned("images/help/share.gif")"> </p> <p> برای اختصاص دسترسی اسناد خود به یک کاربر از ابزار جستجو در پایین جعبه <strong>مشارکت کنندگان</strong> استفاده کنید. می‌تواند سطوح مختلف دسترسی را انتخاب کنید: </p> <ul> <li>«خواندن» اجازه مشاهده سند و حاشیه‌نویسی‌ها مربوطه را صادر می‌کند ولی اجازه اضافه کردن حاشیه‌نویسی‌ها و نظرات را به آنها نمی‌دهد.</li> <li>«نوشتن» اجازه مشاهده و همچنین حاشیه‌نویسی سند را به کاربران می‌دهد.</li> <li>«مدیریت» اجازه نوشتن را بهمراه ویرایش فراداده، دعوت از سایر مشارکت‌کنندگان و انجام اعمال مدیریتی مانند بارگیری نسخه‌های پشتیبان را صادر می‌کند. </li> </ul> <h2>تبریک می‌گوییم!</h2> <p> شما مراحل آموزش مهمترین قابلیت‌های ریکوگیتو را با موفقیت پشت سر گذاشتید. با به پایان رساندن این دوره آموزشی شما آموختید که: </p> <ul> <li>سندی را بارگذاری کنید</li> <li>حاشیه‌نویسی روی متون و تصاویر را انجام دهید</li> <li>مکان‌ها را به فرهنگ‌های جغرافیایی ارجاع دهید</li> <li>داده‌های خود را در قالب‌های متفاوت دریافت و بارگیری کنید</li> <li>از کاربران دیگر برای همکاری دعوت بعمل آورید</li> </ul> <p> درصورت تمایل به یادگیری بیشتر و تماس با انجمن کاربران، خواهشمند است از انجمن کاربران ریکوگیتو دیدن فرمایید. </p> </div> </div> @Html(webJarsUtil.script("1.12.0/jquery.min.js")) @Html(webJarsUtil.requireJs(routes.Assets.versioned("javascripts/help/tutorial.js"))) } <file_sep>/app/assets/javascripts/common/annotationView.js define([ 'common/utils/annotationUtils' ], function(Utils) { var Annotations = function(initial) { var annotations = (initial) ? initial : [], contributors = [], uniqueTags = [], /** Checks if an array is undefined or empty **/ isEmpty = function(maybeArr) { if (maybeArr && maybeArr.length > 0) return false; else return true; }, /** Shorthand to add to an array of distinct elements, since we're lacking a decent set **/ addIfNotExists = function(element, array) { if (array.indexOf(element) < 0) array.push(element); }, /** * Utility function to collect values into an array of distinct elements. * * Implements the functionality common to building the uniqueTags, contributor etc. sets. */ collectIntoIfEmpty = function(fn, arr) { if (isEmpty(arr)) annotations.forEach(function(a) { fn(a).forEach(function(value) { addIfNotExists(value, arr); }); }); }, /** Resets the derived sets (uniqueTags, contributors etc.) **/ resetDerivedSets = function() { contributors = []; uniqueTags = []; }, /** Add an annotation or array of annotations to the view **/ add = function(a) { var newAnnotations = (jQuery.isArray(a)) ? a : [ a ]; annotations = annotations.concat(newAnnotations); // This could be optimized. We could just add to the existing. // But before that, we'd need to check if empty (i.e. not a one-liner, and // performance increase might be minimal unless for really long lists of // annotations resetDerivedSets(); }, /** Removes an annotatoin or array of annotations to the view **/ remove = function(a) { var idx = annotations.indexOf(a); if (idx > -1) { annotations.splice(idx, 1); resetDerivedSets(); } }, getFiltered = function(filter) { return annotation.filter(filter); }, listContributors = function() { var getContributors = function(a) { return a.contributors; }; collectIntoIfEmpty(getContributors, contributors); return contributors; }, listUniqueTags = function() { var getTags = function(a) { return Utils.getTags(a); }; collectIntoIfEmpty(getTags, uniqueTags); return uniqueTags; }, listAnnotations = function() { return annotations; }; this.add = add; this.remove = remove; // This way we can hand out a 'read-only' reference to other UI components. // Note that the annotation array as such is mutable, so we can't actually prevent // write access. But returning new copies every time seems too costly. this.readOnly = function() { return { getFiltered : getFiltered, listContributors : listContributors, listUniqueTags : listUniqueTags, listAnnotations : listAnnotations }; }; }; return Annotations; });
71b968adf5647a5dcc45d6be2a4bb9b1ef530fe0
[ "JavaScript", "HTML" ]
2
HTML
Masoumeh/recogito2
bf6b222f0c1b669b4ef8f0dbb1ae8df945d30f5d
8f2e89c278c6c1ea3b8fec2f707d23f121c5aec4
refs/heads/master
<file_sep>package com.example.Coll_3; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Alex on 27.12.13. */ public class DataBaseOptionalTargetHelper extends SQLiteOpenHelper { public static final String NAME_DATABASE = "db_opt_target"; public static final int VERSION_DATABASE = 1; public static final String NAME_TABLE = "table_opt_target"; public static final String TARGET = "target"; public static final String PRIORY = "priory"; public DataBaseOptionalTargetHelper(Context context) { super(context, NAME_DATABASE, null, VERSION_DATABASE); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + NAME_TABLE + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + TARGET + " TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE " + NAME_TABLE); onCreate(db); } } <file_sep>package com.example.Coll_3; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.*; import android.widget.*; import java.util.ArrayList; import java.util.List; public class MyActivity extends Activity { /** * Called when the activity is first created. */ public SQLiteDatabase main_db; public SQLiteDatabase opt_db; public DataBaseMainTargetHelper dbMainHelper; public DataBaseOptionalTargetHelper dbOptHeler; public ListView listTarget; public Cursor cursor; public ArrayAdapter<String> adapter; public int TABLE_SHOW = 0; private void install_db() { dbMainHelper = new DataBaseMainTargetHelper(this); dbOptHeler = new DataBaseOptionalTargetHelper(this); main_db = dbMainHelper.getWritableDatabase(); opt_db = dbOptHeler.getWritableDatabase(); } private boolean update_listTarget(int num_db) { List<String> from = new ArrayList<String>(); if (num_db == 0) { cursor = main_db.query(dbMainHelper.NAME_DATABASE,null,null,null,null,null,null); } else { cursor = opt_db.query(dbMainHelper.NAME_DATABASE,null,null,null,null,null,null); } while (cursor.moveToNext()) { String text = cursor.getString(cursor.getColumnIndex("target")); from.add(text); } adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,from); cursor.close(); listTarget.setAdapter(adapter); return true; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listTarget = (ListView) findViewById(R.id.listView); install_db(); update_listTarget(0); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.main_target: TABLE_SHOW = 0; return update_listTarget(0); case R.id.optional_target: TABLE_SHOW = 1; return update_listTarget(1); } return true; } public void onClickButtonAdd(View v) { EditText text = (EditText) findViewById(R.id.editText); String s = text.getText().toString(); ContentValues cv = new ContentValues(); if (TABLE_SHOW == 0) { cv.put(DataBaseMainTargetHelper.TARGET,s); main_db.insert(DataBaseMainTargetHelper.NAME_TABLE,null,cv); } else { cv.put(DataBaseOptionalTargetHelper.TARGET,s); main_db.insert(DataBaseOptionalTargetHelper.NAME_TABLE,null,cv); } } }
c080ec08c51c00c2a0dce3443f84a122aba7b376
[ "Java" ]
2
Java
Aleks-Z/colloquium3
3c3b1ea292bf494d4ddcc1f6d53474d63f9fc0a1
c5abf16c6b1ad4d9186c5a19a58c42af7b136c70
refs/heads/master
<repo_name>gingsi/rl-continuouscartpole<file_sep>/src/performance_list.py """Evaluate performance for a list of experiments (mean CPU/GPU time per step)""" import argparse import logging import os import shutil from collections import OrderedDict from pathlib import Path from src.rl.eval_exp import read_experiment_list from src.rl.experiment import Experiment from src.rl.get_filenames import get_exp_dir from src.utils.config_mapping import load_experiment_config from src.utils.jsonencoder import to_json from src.utils.logger import get_logger from src.utils.stats import Stats def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "multi_file_name", help="file with list of experiments in config/lists/*.txt") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--performance_dir", type=str, default="performance") parser.add_argument("--cuda", action="store_true", help="use cuda") parser.add_argument( "--save", action="store_true", help="save performance list to file") parser.add_argument( "--cleanup", action="store_true", help="delete performance runs") args = parser.parse_args() # read list of experiments run_name = "test-perf" experiments = read_experiment_list( args.multi_file_name, config_dir=args.config_dir) # disable logging logger = get_logger(".", "perf", with_file=False) logger.setLevel(logging.ERROR) # loop experiments steps = 10000 trials = 5 for exp_name in experiments: print("{:30}...".format(exp_name), end=" ") config_file = Path(args.config_dir) / "experiments" / "{}.json".format( exp_name) config = load_experiment_config(config_file) # disable eval (1 eval done at the end for all experiments) config["evaluation"]["eval_every_n_steps"] = steps * 2 ms_per_step = [] for t in range(trials): # run experiment exp = Experiment( config, exp_name, run_name, logger=logger, log_dir=args.log_dir, run_number=t, reset=True, reload=False, use_cuda=args.cuda, verbose=False, max_steps=steps) exp.run_training() # calculate time spent time_total = exp.current_time_total ms_per_step.append(1000 * time_total / steps) # cleanup if args.cleanup: exp_dir = get_exp_dir( exp_name, run_name, t, log_dir=args.log_dir) shutil.rmtree(exp_dir, ignore_errors=True) # calculate stats over N trials s = Stats(ms_per_step) print("{:7.3f} +- {:7.3f} ms/step".format( s.mean, s.stddev)) # save to file if args.save: infos = OrderedDict() infos["ms"] = ms_per_step infos["ms_mean"] = s.mean infos["ms_std"] = s.stddev infos["cuda"] = args.cuda infos["steps"] = steps infos["trials"] = trials os.makedirs(args.performance_dir, exist_ok=True) filename = Path(args.performance_dir) / "{}_{}.json".format( "gpu" if args.cuda else "cpu", exp_name) with filename.open("wt", encoding="utf8") as fh: fh.write(to_json(infos)) if __name__ == '__main__': main() <file_sep>/README.md # Solving the Continuous Cartpole problem <NAME>., <NAME>., <NAME>. -- 3 week project for the Reinforcement Learning course at the University of Freiburg. [Overview (2 slides)](./slides_overview.pdf) [Full slide set](./slides_full.pdf) ## Problem Description Environment: Continuous Cartpole - Start with pole at the bottom - `1` reward for the pole being at the top, `-1` reward and termination when off the screen, `0` reward else - Max `500` steps per episode - Observation space: Cart position, cart velocity, pole angle, pole velocity at tip - Action space: continuous in [-1, 1] - Discretized for DQN ## Algorithm DQN as proposed in [1] with - Soft target network update as in [2] - Double Q Learning as in [3] - Dueling Network Architecture as in [4] Our best configuration solves the problem in ~190K steps (~800 episodes) tested with 15 different random seeds. Best agent ([video](./_media/agent.mp4)): ![Best Agent](./_media/agent.gif) ## Installation ### Environment Tested with Win10: `Python==3.8.6 PyTorch==1.6.0 CUDA==10.1 TorchVision==0.7.0 Pillow==7.2.0` ### Latex Installing a Latex distribution is recommended for better plots. If you get Latex errors, run the script with `--disable_tex` to disable it. ### Setup steps ```bash git clone https://github.com/gingsi/rl-continuouscartpole.git cd rl-continuouscartpole # change the torch installation command below depending on your GPU pip install torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html pip install -r requirements.txt ``` ## Evaluation We provide the agent models for 2 selected experiments (best config with eval and train metric) with 15 different runs. All logged metrics are provided so all plots can be recreated. All created plots and data are also provided in `test_results/`. ### Run agent ```bash # watch highest quality agent (highest eval score: 426.500 +- 0.842 over 1000 evaluation episodes) python -m src.eval vanilla-v6-baseline-step-eval5k run1 --log_dir runs_best --run_number 7 --render # watch fastest converging agent (converged after 150k steps, 834 episodes) python -m src.eval vanilla-v6-baseline-step-eval5k run1 --log_dir runs_best --run_number 1 --render # watch random agent python -m src.tests.run_cartpole_random # watch untrained agent python -m src.eval vanilla-v6-baseline-step-eval5k run_untrained --run_number 0 --render # create video of highest quality agent python -m src.eval vanilla-v6-baseline-step-eval5k run1 --log_dir runs_best --run_number 7 --render --video # do agent quality test for 100 episodes of highest quality agent python -m src.eval vanilla-v6-baseline-step-eval5k run1 --eval_episodes 100 --log_dir runs_best --overwrite --run_number 7 # run best agent for 100K steps to see if he ever falls down python -m src.eval vanilla-v6-baseline-step-eval5k run1 --eval_episodes 1 --num_steps 100000 --log_dir runs_best --run_number 7 --overwrite ``` ### Analysis and plots ```bash # create txt/csv analysis of all experiments python -m src.eval_list all run1 --log_dir runs_no_models --no_plots --performance_dir performance_saved # ---------- evaluate scores: recreate plots/csv/text information # the 5 experiments presented in slides python -m src.eval_list presented run1 --log_dir runs_no_models --performance_dir performance_saved # the 3 good experiments presented python -m src.eval_list presented-good run1 --log_dir runs_no_models --performance_dir performance_saved # all experiments, no single runs, sorted by steps until convergence python -m src.eval_list all run1 --log_dir runs_no_models --no_single_plots --sort --performance_dir performance_saved # top10 experiments (lowest steps) python -m src.eval_list all run1 --log_dir runs_no_models --no_single_plots --sort --topk 10 --performance_dir performance_saved # for meaningful training score comparison plots: only shaped python -m src.eval_list all-shaped run1 --log_dir runs_no_models --no_single_plots --performance_dir performance_saved # for meaningful training score comparison plots: only sparse python -m src.eval_list all-sparse run1 --log_dir runs_no_models --no_single_plots --performance_dir performance_saved # plot epsilon scheduler + hardcoded results from the presented experiments python -m src.tests.test_eps_scheduler # ---------- single agent quality evaluation # recreate agent quality plots over all runs from existing data (tested 1000 episodes) # also recreates the evaluation data used in slide 2, performance table, column Evaluation (1000 ep) python -m src.eval vanilla-v6-baseline-step-eval5k run1 --eval_episodes 1000 --log_dir runs_no_models python -m src.eval vanilla-v6-baseline-step-eval20k run1 --eval_episodes 1000 --log_dir runs_no_models python -m src.eval vanilla-v6-baseline-step-train run1 --eval_episodes 1000 --log_dir runs_no_models python -m src.eval vanilla-v6-baseline-time-eval5k run1 --eval_episodes 1000 --log_dir runs_no_models python -m src.eval vanilla-v0 run1 --eval_episodes 1000 --log_dir runs_no_models ``` ## Training All experiment configurations are provided. Please note that GPU training is not necessarily faster than CPU training due to small models. It all depends on your setup. ### Sequential training Running one experiment at a time either on GPU or CPU. ```bash # ---------- train # train best experiment, 1 runs, CUDA python -m src.run vanilla-v6-baseline-step-eval5k run2 --reset --cuda # train best experiment, 4 more runs, CPU python -m src.run vanilla-v6-baseline-step-eval5k run2 --reset --run_start 1 --run_end 5 # ---------- evaluate # evaluate all 5 runs of the experiment for 100 episodes python -m src.eval vanilla-v6-baseline-step-eval5k run2 --eval_episodes 100 --overwrite # create plots / more extensive analysis for this single experiment with 5 runs python -m src.eval_list best-single run2 ``` ### Multiprocessing Running multiple experiments in parallel on the CPU. Since PyTorch internally does multiprocessing when CPU training, it's important to limit the number of threads per worker to avoid locks. This example works for 8 cores (4 workers with 2 threads each). Formula: `num_cores >= num_workers * num_threads`. To run single experiments in multiprocessing, create a new list in `config/lists/` containing only a single experiment name. ```bash export OMP_NUM_THREADS=2 export MKL_NUM_THREADS=2 # train the 5 experiments in the slides, 5 runs each, multiprocessing (will take a while) python -m src.submit presented run2 --run_end 5 --num_workers 4 --num_threads 2 --reset # evaluate the presented runs trained with the command before python -m src.eval_list presented run2 # clean up everything except best and last checkpoints/metrics files for all experiments python -m src.cleanup_list presented run2 --delete ``` ### Further evaluation To evaluate your results more deeply, use the code from chapter **Evaluation**, change `run1` to `run2` and remove the `--log_dir` argument. ## Other code ```bash # re-evaluate performance of the presented experiments (approx cpu/gpu time per step) python -m src.performance_list presented --save --cleanup python -m src.performance_list presented --save --cleanup --cuda # time profile the best configuration for 10000 steps on CPU python -m cProfile -s cumtime -o profiling/dqnprofile.pstats src\run.py vanilla-v6-baseline-step-eval5k test-profile --reset --max_steps 10000 python -m src.read_profiler profiling/dqnprofile.pstats ``` ## Other environments For this part, we ran our algorithm on other gym environments. No code, config or evaluation is provided, only a short qualitative analysis. ### LunarLander-v2 [video](./_media/lander.mp4) The best config works off-the-shelf on this problem which has a discrete action space. Problem solved after 520k steps (2419 episodes): ![Lander](./_media/lander.gif) ### BipedalWalker-v2 [video](./_media/walker.mp4) In this problem, the agent gets punished more for applying stronger torque to the joints, the action space is 4-dimensional and continuous. So either the discretization (we chose 3) is too coarse and the agent applies too much torque or the curse of dimensionality hits (`num_actions = num_discretization ^ 4`) and the agent has problems learning. Our algorithm does not solve this problem well, at least not off-the-shelf. Performance after 980k steps (3345 episodes): ![Lander](./_media/walker.gif) ## Training / evaluation curves For more visualizations, see the full slide set or the folder `test_results/`. ### Best config (least steps) #### Evaluation curve ![Eval](./_media/best_eval.png) #### Training curve ![Eval](./_media/best_train.png) ## Repository content details - `_media` images / videos for the readme - `_misc` open source courier new font for video creation - `config/experiments/` single experiment configuration - `config/lists/` experiment list for evaluations - `performance/` experiment performance (mean CPU/GPU time per step for 5 trials with 10k steps) - `performance_saved/` profiled experiment performance to recreate plots - `profiling/` empty directory to be used by python cProfile - `runs/` folder to store models and metrics, initially not existing - `runs_best/` the 15 runs of the best experiment including agent weights - `runs_no_models/` all metrics of all runs of all experiments, without agent weights - `src/` the code - `test/` output folder of created plots, initially not existing - `test_results/` all plots and metrics: - `_LISTNAME_run1/` plots of multiple experiments. - `csv/` metrics evaluation as raw data. - `eps_schedulers/` epsilon schedulers + hardcoded experiment results in a plot. - `eval/` agent quality evaluation per experiment. - `step/`, `time_cpu/`, `time_gpu/` single experiment plots over different x-axis metrics. - `txt/` metrics evaluation as human-readable data. ## References - [1] <NAME>. et al (2015), Human Level Control Through Deep Reinforcement Learning ([pdf](https://web.stanford.edu/class/psych209/Readings/MnihEtAlHassibis15NatureControlDeepRL.pdf)) - [2] <NAME>. et al (2015), Continuous control with deep reinforcement learning ([arxiv](https://arxiv.org/abs/1509.02971)) - [3] <NAME>. et al (2016), Deep Reinforcement Learning with Double Q-learning ([arxiv](https://arxiv.org/abs/1509.06461)) - [4] <NAME>. et al (2015), Dueling Network Architectures for Deep Reinforcement Learning ([arxiv](https://arxiv.org/abs/1511.06581)) - [5] <NAME>. et al (2017), Rainbow: Combining Improvements in Deep Reinforcement Learning ([arxiv](https://arxiv.org/abs/1710.02298)) - [6] <NAME>., RBED: Reward Based Epsilon Decay ([arxiv](https://arxiv.org/abs/1910.13701)) <file_sep>/src/rl/observ_transform.py """Sincos transform for the observation space""" import numpy as np from gym.spaces import Box class ObservTransformer(object): """Transform observation space (sincos-transform)""" def __init__(self, observ_space: Box, transform_type="none"): self.transform_type = transform_type if self.transform_type == "sincos": # add fields cos, sin of theta high = np.concatenate([observ_space.high, [1., 1.]]) low = np.concatenate([observ_space.low, [-1., -1.]]) self.observ_space = Box(low, high, dtype=np.float32) elif self.transform_type == "none": # leave input space as is self.observ_space = observ_space else: raise ValueError("Input Transform {} not recognized.".format( self.transform_type)) # save original input space self.observ_space_orig = observ_space # print("Setup input transformer, from {} to {}".format( # self.input_space_orig.shape, self.input_space.shape)) def transform_observ(self, observ): """Transform given observation""" assert observ.shape == self.observ_space_orig.shape if self.transform_type == "sincos": theta = observ[2] observ = np.concatenate( [observ, [np.cos(theta), np.sin(theta)]]) return observ <file_sep>/src/read_profiler.py """Reads the output from a profiling scripts. First run the profiler: python -m cProfile -s cumtime -o profiling/dqnprofile.pstats \ -m src.run dqn-baseline test1 --cpu --reset --max_steps 200 Then this script: python -m src.read_profiler profiling/dqnprofile.pstats """ import argparse import pstats def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("file", type=str) args = parser.parse_args() file = args.file p = pstats.Stats(file) # p.strip_dirs() p.sort_stats("cumtime") p.print_stats(20) if __name__ == '__main__': main() <file_sep>/src/rl/experiment.py """Experiment class""" import glob import json import os from timeit import default_timer as timer from typing import Dict import numpy as np import shutil import time import torch from gym import Env from gym.spaces import Box, Space, Discrete from src.agent.dqn_agent import create_dqn_agent from src.rl.epsilon_scheduler import get_eps_scheduler from src.rl.eval_exp import find_last_step, find_best_step_eval from src.rl.get_filenames import get_exp_dir, get_filename_config, \ get_filename_infos, get_exp_id, get_filename_agent from src.rl.observ_transform import ObservTransformer from src.utils.action_quantization import Quantizer1D, QuantizerND from src.utils.config_mapping import get_reward_fn, get_env from src.utils.jsonencoder import to_json from src.utils.logger import get_logger, close_logger from src.utils.stats import Stats class Config(object): """Holds experiment configuration""" def __init__(self, config: dict): # ***** Load config # quantizer cfg_quant = config["quantizer"] self.quantize_flag = cfg_quant["quantize_flag"] self.quantize_num = cfg_quant.get("quantize_num") # optional field for lists (at some point all should be) self.quantize_nums = cfg_quant.get("quantize_nums") # training cfg_train = config["training"] self.max_steps = cfg_train["max_steps"] self.batch_size = cfg_train["batch_size"] self.discount_factor = cfg_train["discount_factor"] self.reward_function_name = cfg_train["reward_function"] self.max_steps_per_episode = cfg_train["max_steps_per_episode"] self.max_steps_per_episode_eval = cfg_train[ "max_steps_per_episode_eval"] self.avg_score_episodes = cfg_train["avg_score_episodes"] # optimizer self.cfg_optimizer = config["optimizer"] # epsilon scheduler: allow not existing (optional) for continuous # methods self.cfg_eps_scheduler = config.get("eps_scheduler") # algorithm / agent self.cfg_agent = config["algorithm"] # evaluation cfg_eval = config["evaluation"] self.eval_every_n_steps = cfg_eval["eval_every_n_steps"] self.eval_n_episodes = cfg_eval["eval_n_episodes"] self.solve_score = cfg_eval["solve_score"] # special case: this field overrides solve_score but is optional # for convenience so not all configs have to be modified. self.solve_score_train = cfg_eval.get("train_solve_score") # saving cfg_saving = config["saving"] self.save_every_n_steps = cfg_saving["save_every_n_steps"] self.save_last = cfg_saving["save_last"] self.save_best = cfg_saving["save_best"] # environment cfg_env = config["environment"] self.env_name = cfg_env["env"] self.env_observ_transform = cfg_env["env_observ_transform"] class Experiment(object): def __init__( self, config: Dict, exp_name, run_name, logger=None, log_dir="runs", run_number=0, reset=False, reload=False, reload_step=-1, reload_best=False, use_cuda=True, verbose=True, print_every=1, num_threads=0, max_steps=-1): """ Args: config (dict): configuration (see config/experiments/dqn_baseline.json) for an example run_name (str): name the run logger (logging.Logger, optional): pass a logger object or if None, will create a new logger log_dir (str, optional): base directory to save logs, models etc. run_number (int, optional): run number to be able to run the same experiment multiple times reset (bool, optional): reset and delete the old experiment reload (bool, optional): reload stats and models from checkpoint reload_step (int, optional): which step to reload (default -1 = reload latest step) reload_best (bool, optional): if reload == True and reload_step == -1, loads the best instead of last episode use_cuda (bool, optional): use cuda if available (default True) verbose (bool, optional): disable some of the logging print_every (int, optional): only print some of the training steps (default 1 = print all steps) num_threads (int, optional): how many threads to use, (default 0= let torch decide) max_steps (int, optional): overwrite max steps manually for e.g. performance test. default -1 = dont overwrite """ # ---------- initalize blank variables ---------- self.current_episode = 0 self.current_time_eval = 0 # total time (sec) spent evaluating self.current_time_total = 0 # total time for everything self.current_step = 0 # total step counter self.is_solved = False # is already solved self.metrics = { "episodes": [], # list of int: episodes trained "scores": [], # list of float: total rewards "avg_scores": [], # list of float: average total rewards over last # X episodes "time_total": [], # list of float: total time spent "time_eval": [], # list of float: eval time spent "step": [], # current total step "other": [] # list of tuple: with other info (currently epsilon) } self.metrics_eval = { "episodes": [], # list of int: episodes evaluated "steps": [], # list of int: steps evaluated "scores_list": [], # list per episode evaluated: # list of total rewards gained over N evaluations in this episode "avg_scores": [] # list of float: average over the N evaluations # done this episode } self.best_eval_score = -np.finfo(np.float32).max self.best_train_avg_score = -np.finfo(np.float32).max # ---------- read arguments, setup directories ---------- self.exp_name = exp_name self.run_name = run_name self.run_number = run_number self.log_dir = log_dir self.exp_id = get_exp_id(self.exp_name, self.run_name, self.run_number) self.exp_dir = get_exp_dir( self.exp_name, self.run_name, self.run_number, log_dir=self.log_dir) self.use_cuda = use_cuda self.verbose = verbose self.print_every = print_every # make sure folder exists if reset or not self.exp_dir.is_dir(): # on reset, delete previous experiment shutil.rmtree(str(self.exp_dir), ignore_errors=True) time.sleep(.1) os.makedirs(str(self.exp_dir), exist_ok=False) elif self.exp_dir.is_dir() and not reload: raise ValueError( "Experiment already exists in {}. " "Use either --reset or --reload".format( self.exp_dir )) # create logger if logger is None: self.logger = get_logger(self.exp_dir, self.exp_id) self.logger_is_external = False else: self.logger = logger self.logger_is_external = True # output device info if self.verbose: self.logger.info("cuda available: {} use it: {}".format( torch.cuda.is_available(), use_cuda)) # load config self.cfg = Config(config) # overwrite max steps if max_steps > -1: self.cfg.max_steps = max_steps # save config to file with open(str(get_filename_config( self.exp_name, self.run_name, self.run_number, log_dir=self.log_dir)), "wt", encoding="utf8") as fh: json.dump(config, fh, indent=4, sort_keys=True) # load reward function self.reward_function = get_reward_fn(self.cfg.reward_function_name) if num_threads > 0: torch.set_num_threads(num_threads) self.logger.info("Set num threads to {}".format(num_threads)) # ---------- setup environment, quantizer ---------- # get environment class env_class = get_env(self.cfg.env_name) if self.cfg.env_name == "default_cartpole": # create training environment with shaped reward (if requested) self.env = env_class( reward_function=self.reward_function) # type: Env # create evaluation environment, always with sparse reward self.env_eval = env_class(reward_function=None) else: # gym envs don't have this reward function keyword self.env = env_class self.env_eval = env_class self.action_space = self.env.action_space # create input transformer self.observ_transformer = ObservTransformer( self.env.observation_space, transform_type=self.cfg.env_observ_transform) self.observ_space = self.observ_transformer.observ_space # type: Box self.observ_size = self.observ_space.shape[0] # check action space type if type(self.action_space) is Box: # box - continuous actions if self.cfg.quantize_flag: # check action space is 1D if self.action_space.shape == (1,): # regular behaviour, quantize actions self.action_size = self.cfg.quantize_num self.quantizer = Quantizer1D( self.action_space, self.action_size) self.action_dim = 1 else: # multiple dim actions self.action_size = self.cfg.quantize_num self.action_dim = self.action_space.shape[0] self.quantizer = QuantizerND( self.action_space, self.cfg.quantize_num) self.eps_scheduler = get_eps_scheduler( config["eps_scheduler"], self.cfg.max_steps) self.do_quantization = True else: raise NotImplementedError( "Continuous actions without quantizer not implemented") elif type(self.action_space) is Discrete: # discrete action space, no quantizer self.action_size = self.action_space.n self.action_dim = 1 self.quantizer = None self.do_quantization = False self.eps_scheduler = get_eps_scheduler( config["eps_scheduler"], self.cfg.max_steps) else: # unknown action space raise NotImplementedError( "unknown gym.Space: {}".format(type(self.action_space))) if self.verbose: self.logger.info( "Created experiment {} #{} environment {} {} " "observs {} actions {}".format( self.exp_id, self.run_number, self.cfg.env_name, self.env, self.observ_space, self.action_space)) # ---------- create agent ---------- # create agent self.algo_name = self.cfg.cfg_agent["name"] if self.algo_name == "dqn": # create DQN agent self.agent = create_dqn_agent( self.cfg.cfg_agent, self.cfg.cfg_optimizer, self.observ_size, self.action_size, self.action_dim, self.cfg.batch_size, self.cfg.discount_factor, self.quantizer, use_cuda=self.use_cuda, verbose=self.verbose) if self.verbose: self.logger.info("---------- Optimizer: {}".format( self.agent.optimizer)) else: raise NotImplementedError( "algorithm {} not implemented".format( self.algo_name)) # reload agent state dict if needed if reload: if reload_step == -1: # find last episode reload_step = find_last_step( self.exp_name, self.run_name, self.run_number, log_dir=self.log_dir) if reload_step == -1: # nothing found - start from scratch self.logger.warning("*" * 20) self.logger.warning( "Reloading experiment but no files found in {} - " "Starting from scratch".format( self.exp_dir)) self.logger.warning("*" * 20) elif reload_best: # something found but requested to load best instead of # last best_step, _, _ = find_best_step_eval( self.exp_name, self.run_name, self.run_number, log_dir=self.log_dir) # self.logger.info( # "Reloading BEST step {} instead of " # "LAST step {}".format( # best_step, reload_step)) reload_step = best_step if reload_step > -1: # reload infos only if models exist self.logger.info("{}_{}_{} RELOADING step {}".format( self.exp_name, self.run_name, self.run_number, reload_step)) self.load_infos(reload_step) self.load_agent(reload_step) def run_training(self): """ Train agent on environment with given settings. Returns: metrics dictionary, metrics_eval dictionary """ if self.cfg.quantize_flag: # epsilon scheduler is only relevant for quantized actions eps = self.eps_scheduler.reset(start_step=self.current_step) else: eps = 0 start_episode = self.current_episode start_step = self.current_step # setup timing time_start = self.current_time_total time_lap = timer() # start training self.logger.info("Training from {} to {}".format( self.current_step, self.cfg.max_steps)) # loop over episodes while self.current_step < self.cfg.max_steps and not self.is_solved: # reset observation and score observ = self.env.reset() # transform observation observ = self.observ_transformer.transform_observ(observ) score = 0 n_steps = 0 for t in range(0, self.cfg.max_steps_per_episode): if self.verbose and t % 20 == 0: print("step {} / {}\r".format(t, self.cfg.max_steps_per_episode), end="") # get action from environment if self.cfg.quantize_flag: # agents in discrete environment need epsilon parameter # to sample actions action = self.agent.act(observ, eps=eps) # step epsilon scheduler for quantized actions eps = self.eps_scheduler.step() else: # sample continuous action action = self.agent.act(observ) # do one step in the environment next_observ, reward, done, _ = self.env.step(action) # transform observation next_observ = self.observ_transformer.transform_observ( next_observ) # do one optimization step of the agent self.agent.step( observ, action, reward, next_observ, done, self.current_step) # accumulate score, change observation, break if done score += reward observ = next_observ self.current_step += 1 n_steps += 1 # ---------- eval, saving etc ---------- # evaluate: evaluation steps have one higher episode step count # (looks nicer to have train (0,1,2,3,4) and eval (5) is_best = False if (self.current_step % self.cfg.eval_every_n_steps == 0 and self.cfg.eval_every_n_steps > -1): is_best_eval = self.eval_step() # only use eval score for is_best if train solve score # is not set if self.cfg.solve_score_train is None: is_best = is_best_eval self.save_infos() self.save_agent() # save at every n steps and the best configurations if (self.current_step % self.cfg.save_every_n_steps == 0 and self.cfg.save_every_n_steps > -1) or ( is_best and self.cfg.save_best): self.logger.info( "***** SAVING: step {} is_best {} " "best eval score {:.3f} " "best train score {:.3f}".format( self.current_step, is_best, self.best_eval_score, self.best_train_avg_score )) # if save every n steps is -1 we want to delete all the old # saves that are not the best anymore if self.cfg.save_every_n_steps == -1 and is_best: old_agents = glob.glob(str(self.exp_dir / "*.pth")) for f in old_agents: agent_num = int(f.split("_")[-1].split(".pth")[0]) if agent_num == self.current_step: continue os.remove(f) self.logger.info("Removing {}".format(f)) self.save_infos() self.save_agent() # check if problem is solved if (is_best and self.best_eval_score >= self.cfg.solve_score): self.logger.info( "\nProblem solved (eval metric)! " "eval score {:.3f}\n".format( self.best_eval_score)) self.is_solved = True # stop episode if reward is terminal if done: break # ---------- episode is done ---------- # calculate training metrics for this episode time_now = timer() time_deff = time_now - time_lap self.current_time_total += time_deff time_lap = time_now # print("time diff", time_deff, "total", self.current_time_total) self.metrics["episodes"].append(self.current_episode) self.metrics["scores"].append(score) avg_score = np.mean(self.metrics["scores"][ -self.cfg.avg_score_episodes:]) if avg_score > self.best_train_avg_score: # train score is the metric for is_best self.best_train_avg_score = avg_score if self.cfg.solve_score_train is not None: # solve train score is the metric if avg_score >= self.cfg.solve_score_train: # done self.logger.info( "\nProblem solved (train metric)! " "train score {:.3f} " "best eval score {:.3f}\n".format( avg_score, self.best_eval_score)) self.is_solved = True self.metrics["avg_scores"].append(avg_score) self.metrics["time_total"].append(self.current_time_total) self.metrics["time_eval"].append(self.current_time_eval) self.metrics["step"].append(self.current_step) # field for additional metrics (tuple) self.metrics["other"].append((eps,)) # output episode info if self.current_episode % self.print_every == 0 or \ self.current_step >= self.cfg.max_steps - 1: # determine some additional log information depending on # quantized action environment or not if self.cfg.quantize_flag: # add epsilon to log other_info = "eps {:.3f}".format(eps) else: # nothing (yet) other_info = "" self.logger.info( "{}-{}-{} E{:4} S{:7}/{:7} ({:3}) {} score {:8.3f} " "avg_score {:8.3f}".format( self.exp_name, self.run_name, self.run_number, self.current_episode, self.current_step, self.cfg.max_steps, n_steps, other_info, score, avg_score)) # increase episode step count self.current_episode += 1 # check if training is done: then do another eval and save if self.current_step >= self.cfg.max_steps or self.is_solved: is_best = self.eval_step() if self.cfg.save_last or self.cfg.save_best and is_best: if self.verbose: self.logger.info( "***** SAVING: step {} is_best {}".format( self.current_step, is_best)) # if save every n steps is -1 AND the last agent is the # best, we want to delete all the old # saves that are not the best anymore if self.cfg.save_every_n_steps == -1 and is_best: old_agents = glob.glob(str(self.exp_dir / "*.pth")) for f in old_agents: if f == "agent_{}.pth".format(self.current_step): continue os.remove(f) if self.verbose: self.logger.info("Removing {}".format(f)) self.save_infos() self.save_agent() self.logger.info("Done training.") # output time deltas delta_ep = self.current_episode - start_episode delta_step = self.current_step - start_step delta_time = self.current_time_total - time_start if delta_step > 0: self.logger.info( "{}-{}-{} training {} episodes {} step took {:.3f}s," " {:.3f}ms per step, cuda {}, eval time {:.3f}s".format( self.exp_name, self.run_name, self.run_number, delta_ep, delta_step, delta_time, 1000 * delta_time / delta_step, self.use_cuda, self.current_time_eval)) return self.metrics, self.metrics_eval def eval_step(self): """Do one step of evaluation and metrics update Returns: is_best (bool) whether this is the best agent """ # evaluate time_lap = timer() eval_scores = self.run_evaluation() eval_score = np.mean(eval_scores) is_best = False if eval_score >= self.best_eval_score: is_best = True self.best_eval_score = eval_score time_delta = timer() - time_lap self.current_time_eval += time_delta self.metrics_eval["episodes"].append(self.current_episode) self.metrics_eval["steps"].append(self.current_step) self.metrics_eval["scores_list"].append(eval_scores) self.metrics_eval["avg_scores"].append(eval_score) return is_best def run_evaluation(self, num_ep=-1, num_steps=-1, print_steps=False): """Evaluate agent in the eval environment (always sparse reward). Args: num_ep: How many episodes to evaluate (default -1 use experiment settings) num_steps: Max steps to terminate episode (default -1 use experiment settings) Returns: list of score (total reward) per episode """ if num_ep == -1: num_ep = self.cfg.eval_n_episodes if num_steps == -1: num_steps = self.cfg.max_steps_per_episode_eval scores = [] for ep in range(0, num_ep): if self.verbose: print("eval {:4}/{:4}".format(ep, num_ep), end="\r") observ = self.env_eval.reset() # transform observation observ = self.observ_transformer.transform_observ(observ) score = 0 for t in range(0, num_steps): if print_steps and t % 50 == 0: print("step {}/{}".format(t, num_steps), end="\r") if self.cfg.quantize_flag: # set epsilon to 0 for evaluation of quantized action # space methods action = self.agent.act(observ, eps=0) else: # sample action in continuous environment action = self.agent.act(observ) # step environment next_observ, reward, done, _ = self.env_eval.step(action) # transform observation next_observ = self.observ_transformer.transform_observ( next_observ) # do NOT step the agent # update scores, change observation and break if done score += reward observ = next_observ if done: break # collect scores over episodes scores.append(score) # print some stats on the evaluation s = Stats(scores) self.logger.info( "{}-{}-{} E{:4} S{:7}/{:7} Eval {:7.3f} +- {:7.3f}".format( self.exp_name, self.run_name, self.run_number, self.current_episode, self.current_step, self.cfg.max_steps, s.mean, s.stddev)) # return total scores over episodes return scores def save_agent(self): """Save state dict of agent """ filename_agent = get_filename_agent( self.exp_name, self.run_name, self.run_number, self.current_step, log_dir=self.log_dir) # save agent state dict (model, optimizer etc) agent_dict = self.agent.get_state_dict() with filename_agent.open("wb") as fh: torch.save(agent_dict, fh) # if self.verbose: # self.logger.info("Saved agent to {}".format(filename_agent)) def save_infos(self): # save infos to json filename_infos = get_filename_infos( self.exp_name, self.run_name, self.run_number, self.current_step, log_dir=self.log_dir) info_dict = { "episode": self.current_episode, "metrics": self.metrics, "metrics_eval": self.metrics_eval, "current_time_eval": self.current_time_eval, "current_time_total": self.current_time_total, "current_step": self.current_step, "best_eval_score": float(self.best_eval_score), "best_train_avg_score": float(self.best_train_avg_score), "is_solved": self.is_solved } with filename_infos.open("wt", encoding="utf8") as fh: # json.dump(info_dict, fh, indent=4, sort_keys=True) fh.write(to_json(info_dict)) # if self.verbose: # self.logger.info("Saved stats to {}".format(filename_infos)) def load_agent(self, step): """Load state dict of agent Args: step(int, optional): what step to load, default -1: current step """ if step == -1: step = self.current_step filename_agent = get_filename_agent( self.exp_name, self.run_name, self.run_number, step, log_dir=self.log_dir) # load agent if self.verbose: self.logger.info("Loading agent from {}".format(filename_agent)) try: with filename_agent.open("rb") as fh: agent_dict = torch.load(fh) self.agent.set_state_dict(agent_dict) except FileNotFoundError: self.logger.info( "WARNING: {}_{}_{} Could not load agent model.\n{}\n" "Weights are not loaded. If you only read the " "stats of this experiment, this is fine.".format( self.exp_name, self.run_name, self.run_number, filename_agent)) def load_infos(self, step): """Load info (stats etc.) Args: step(int, optional): what step to load, default -1: current step """ # load infos try: filename_infos = get_filename_infos( self.exp_name, self.run_name, self.run_number, step, log_dir=self.log_dir) with filename_infos.open("rt", encoding="utf8") as fh: info_dict = json.load(fh) except FileNotFoundError: # ---------- HACK for accidentally deleting too many scores.json last_step = find_last_step( self.exp_name, self.run_name, self.run_number, self.log_dir) filename_infos = get_filename_infos( self.exp_name, self.run_name, self.run_number, last_step, log_dir=self.log_dir) with filename_infos.open("rt", encoding="utf8") as fh: info_dict = json.load(fh) if self.verbose: self.logger.warning( "WARNING: {}_{}_{} Reloading agent episode {} but scores episode " "{}, probably some files are missing. do NOT train.".format( self.exp_name, self.run_name, self.run_number, step, last_step)) if self.verbose: self.logger.info("Loading infos from {}".format(filename_infos)) self.current_episode = info_dict["episode"] self.current_time_eval = info_dict["current_time_eval"] self.current_time_total = info_dict["current_time_total"] self.current_step = step # info_dict["current_step"] self.metrics = info_dict["metrics"] self.metrics_eval = info_dict["metrics_eval"] self.best_eval_score = info_dict["best_eval_score"] self.best_train_avg_score = info_dict["best_train_avg_score"] self.is_solved = info_dict["is_solved"] def close(self): """Close the experiment. It is important to close the logger between multiple experiments since otherwise problems may occur: - same message printed multiple times - folders/files stay locked We do not want to close external loggers that have been passed to the __init__, since they will be closed by the caller. """ if not self.logger_is_external: close_logger(self.logger) <file_sep>/src/agent/dqn_model.py """Networks for DQN""" from typing import List import torch.nn as nn from torch.nn import functional as F import torch def create_network(observ_size, action_size, action_dim, config_net, verbose=True) \ -> nn.Module: net_name = config_net["name"] if net_name == "qnet1": net = DQNModule( observ_size, action_size, action_dim, config_net["nonlinearity"], config_net["encoder_fc_units"], config_net["batchnorm"], config_net["use_dueling"], verbose=verbose) else: raise NotImplementedError("network {} not implemented".format( net_name)) return net class DQNModule(nn.Module): """Use DQNEncoder to encode observation to hidden state, then encode hidden state to action (Q-values)""" def __init__( self, observ_size=4, action_size=2, action_dim=1, nonlinearity="selu", encoder_fc_units=(64, 64), batchnorm=False, use_dueling=True, verbose=True): """ Args: observ_size: size of observation space action_size: size of action space nonlinearity: "relu", "selu" or "leakyrelu" for the encoder encoder_fc_units: list of neurons per linear layer for the encoder batchnorm: use batchnorm in the encoder use_dueling: networks verbose: print network graph """ super().__init__() # setup encoder to map from observation space to hidden space self.net_encoder = DQNEncoderModule( observ_size, nonlinearity, encoder_fc_units, batchnorm) # get size of hidden state vector hidden_size = encoder_fc_units[-1] if verbose: print("---------- network ----------") print("Encoder: {}".format(self.net_encoder)) # map from encoding to output self.use_dueling = use_dueling self.action_size = action_size self.action_dim = action_dim if not self.use_dueling: # no dueling networks - simply map from hidden space to action # with a linear layer self.net_output = nn.Linear(hidden_size, action_size ** action_dim) if verbose: print("Output: {}".format(self.net_output)) else: # ---------- dueling networks ---------- # state-value network self.state_value_stream = nn.Linear(hidden_size, 1) # action advantage network self.advantage_stream = nn.Linear( hidden_size, action_size ** action_dim) if verbose: print("State value stream: {}".format( self.state_value_stream)) print("Advantage stream: {}".format(self.advantage_stream)) def forward(self, x): # encode observation space to hidden space x = self.net_encoder(x) if not self.use_dueling: # no dueling, compute q values x = self.net_output(x) # print("net out", x.shape) # x = torch.reshape(x, [-1] + [self.action_size for _ in # range(self.action_dim)]) # print("net out reshaped", x.shape) return x # ---------- dueling networks forward pass ---------- state_value = self.state_value_stream(x) # shape (batch, 1) advantage_value = self.advantage_stream(x) # shape (batch, n_actions) advantage_sum = 1 / (self.action_size ** self.action_dim) * ( advantage_value.sum(-1)).unsqueeze(1) # shape (batch, 1) total_sum = state_value + advantage_value - advantage_sum return total_sum class DQNEncoderModule(nn.Module): """Encode observation space to hidden space. Network graph: observation -> [linear, nonlinearity, optional, batchnorm] * N -> hidden state Args: observ_size (int): Dimension of observations nonlinearity (str): nonlinearity "relu", "selu" or "leakyrelu" encoder_fc_units (List[int]): list of neurons per linear layer batchnorm (bool): Use batchnorm """ def __init__( self, observ_size: int, nonlinearity: str, encoder_fc_units: List[int], batchnorm: bool): """Initialize parameters and build model. """ super().__init__() # define nonlinearity class if nonlinearity == "selu": nonlin_class = nn.SELU elif nonlinearity == "relu": nonlin_class = nn.ReLU elif nonlinearity == "leakyrelu": nonlin_class = nn.LeakyReLU else: raise ValueError("Nonlinearity {} not found".format(nonlinearity)) # define batchnorm class def bn_class(_): return nn.Sequential() if batchnorm: bn_class = nn.BatchNorm1d # loop over the encoder num units list and create the network modules = [] in_shape = observ_size for num_fc_units in encoder_fc_units: modules += [ nn.Linear(in_shape, num_fc_units), nonlin_class(), bn_class(num_fc_units)] in_shape = num_fc_units self.encoder = nn.ModuleList(modules) def forward(self, x): for module in self.encoder: x = module(x) return x <file_sep>/src/rl/epsilon_scheduler.py """Epsilon decay schedulers: multiplicate, cosine, constant""" import numpy as np def get_eps_scheduler(config, max_steps): name = config["name"] if name == "mult_decay": return MultiplicativeEpsilonDecay( max_steps, config["eps_start"], config["eps_end"], config["eps_decay"], config["warmup"]) elif name == "cos_decay": return CosineEpsilonDecay( max_steps, config["eps_start"], config["eps_end"], config["warmup"]) elif name == "none": return ConstantEpsilon(config["eps_start"]) else: raise ValueError("Epsilon Scheduler {} unknown".format( name)) class MultiplicativeEpsilonDecay(object): """Multiplicatively decay epsilon. Args: max_steps (int): Total number of steps eps_start (float): maximum (starting) epsilon value eps_end (float): minimum (end) epsilon value, epsilon can never go below that eps_decay (float): multiplicative decay per episode warmup (float): percentage of the episodes to run with start eps in [0, 1] """ def __init__( self, max_steps, eps_start=1.0, eps_end=0.01, eps_decay=0.9995, warmup=0.0): self.max_steps = max_steps self.eps_start = eps_start self.eps_end = eps_end self.eps_decay = eps_decay self.current_epsilon = 0 self.current_step = 0 self.warmup_steps = int(max_steps * warmup) def reset(self, start_step=0): self.current_step = start_step step_after_warmup = max(0, self.current_step - self.warmup_steps) self.current_epsilon = max(self.eps_end, ( self.eps_decay ** step_after_warmup) * self.eps_start) return self.current_epsilon def step(self): self.current_step += 1 if self.current_step >= self.warmup_steps: self.current_epsilon = max( self.eps_end, self.eps_decay * self.current_epsilon) return self.current_epsilon def get_epsilon(self): return self.current_epsilon class CosineEpsilonDecay(object): """Cosine epsilon decay. Args: max_steps (int): Total number of steps eps_start (float): maximum (starting) epsilon value eps_end (float): minimum (end) epsilon value, epsilon can never go below that warmup (float): percentage of the episodes to run with start eps in [0, 1] """ def __init__( self, max_steps, eps_start=1.0, eps_end=0.01, warmup=0.0): assert 0 <= warmup <= 1, "Epsilon decay warmup must be in " \ "[-1, 1]" self.max_steps = max_steps self.eps_start = eps_start self.eps_end = eps_end self.current_epsilon = 0 self.current_step = 0 self.warmup_steps = int(max_steps * warmup) def reset(self, start_step=0): self.current_step = start_step self.current_epsilon = self.get_epsilon() return self.current_epsilon def step(self): self.current_step += 1 self.current_epsilon = self.get_epsilon() return self.current_epsilon def get_epsilon(self): step_after_warmup = max(0, self.current_step - self.warmup_steps) total_steps_after_warmup = max(0, self.max_steps - self.warmup_steps) cos_factor = (np.cos(np.pi * ( step_after_warmup / total_steps_after_warmup)) + 1) / 2 self.current_epsilon = self.eps_end + ( self.eps_start - self.eps_end) * cos_factor return self.current_epsilon class ConstantEpsilon(object): """Constant epsilon""" def __init__(self, eps_start=1.0): self.eps_start = eps_start def reset(self): return self.eps_start def step(self): return self.eps_start def get_epsilon(self): return self.eps_start <file_sep>/src/tests/run_cartpole_random.py import numpy as np from gym import Env from tqdm import tqdm from src.rl.continuous_cartpole import ContinuousCartPoleEnv from src.utils.stats import Stats def main(): env = ContinuousCartPoleEnv() policy_fn = RandomPolicy(env).get_action run_env(env, policy_fn, do_print=True, do_render=True) env.close() print("Done running environment with rendering\n") n_runs = 500 max_steps = 500 print("Calculate total rewards for {} runs...".format(n_runs)) discount_factor = 1. total_rewards = [] for n in tqdm(range(n_runs)): experience = run_env(env, policy_fn, max_steps=max_steps) len_experience = len(experience) observs, actions, rewards, is_dones = zip(*experience) rewards = np.array(rewards) discounted_rewards = rewards * get_discount_array( len_experience, discount_factor) total_reward = discounted_rewards.sum() total_rewards.append(total_reward) # get statistics of total rewards per run print("Rewards:") print(Stats(total_rewards)) def get_discount_array(len_array, discount_factor): """ Returns 1D array of shape (Len_array) with discount factors per step, element 0: 1.0 element 1: discount_factor element 2: discount_factor ^ 2 ... element k: discount_factor ^ k """ return (np.ones(len_array) * discount_factor) ** np.arange(len_array) class RandomPolicy(object): """Random Policy: Sample action from environment action space. """ def __init__(self, env: Env): self.env = env def get_action(self, _): return self.env.action_space.sample() def run_env(env: Env, policy, max_steps=500, do_print=False, do_render=False): """Run given environment and policy function""" old_observ = env.reset() total_reward = 0 experience = [] for i in range(max_steps): if do_render: env.render() action = policy(old_observ) new_observ, reward, done, _ = env.step(action) total_reward += reward experience.append((old_observ, action, reward, done)) old_observ = new_observ if do_print: print("{:4}/{:4} S: {} A: {} R: {}".format( i, max_steps, old_observ, action, reward)) if done: break if do_print: print("Last observation: {}".format(old_observ)) print("Total reward: {}".format(total_reward)) return experience if __name__ == '__main__': main() <file_sep>/src/utils/action_quantization.py """Quantize (map) between continuous and discrete action space""" import numpy as np from gym.spaces import Box, Space, Discrete from typing import List class Quantizer1D(object): """Works on numpy objects and quantizes/dequantizes actions. For simplicity only works with action spaces of length 1. """ def __init__(self, space: Box, num_quant: int): self.space = space self.num_quant = num_quant if type(space) is Box: if self.space.shape != (1,): print(self.space) raise NotImplementedError("action spaces > 1 not supported.") self.high = self.space.high[0] self.low = self.space.low[0] elif type(space) is Discrete: raise ValueError("No quantizer for discrete action space needed") self.space_int_to_float = np.linspace( self.low, self.high, num=num_quant, endpoint=True) def int_to_float(self, action_int): """Convert integer action to float action Args: action_int (int): quantized action Returns: float action """ return self.space_int_to_float[action_int] def float_to_int(self, action_float): """Convert float action to int action Args: action_float (float): float action Returns: quantized action """ assert self.low <= action_float <= self.high, ( "action {} out of range [{}, {}]".format( action_float, self.low, self.high)) # scale to [0, 1] flt = (action_float - self.low) / (self.high - self.low) # scale to [0, num_quant-1] flt *= (self.num_quant - 1) # round to integer action_int = np.round(flt).astype(np.int) return action_int class QuantizerND(object): """Extension to work with arbitary boxes """ def __init__(self, space: Box, num_quant: int): self.space = space self.num_quant = num_quant if type(space) is Box: assert len(self.space.shape) == 1, "multi-dim actions not support" self.highs = self.space.high self.lows = self.space.low elif type(space) is Discrete: raise ValueError("No quantizer for discrete action space needed") self.dim_action = self.space.shape[0] print("NUM QUANT", num_quant) self.lows = np.array([-4, -6, -9, -1]) self.spaces_int_to_float = np.linspace( self.lows, self.highs, num=num_quant, endpoint=True) def int_to_float(self, action_int): """Convert integer action to float action Args: action_int (int): quantized action Returns: float action """ action_float = np.diag(self.spaces_int_to_float[action_int, :]) return action_float def float_to_int(self, action_float): """Convert float action to int action Args: action_float (float): float action Returns: quantized action """ # assert self.low <= action_float <= self.high, ( # "action {} out of range [{}, {}]".format( # action_float, self.low, self.high)) # scale to [0, 1] flt = (action_float - self.lows) / (self.highs - self.lows) # scale to [0, num_quant-1] flt *= (self.num_quant - 1) # round to integer action_int = np.round(flt).astype(np.int) return action_int def test_quantizer(): # create box box = Box(np.array([-1]), np.array([1])) # create quantizer num_quant = 16 q = Quantizer1D(box, num_quant) # quantize int to float for n in range(num_quant): print("{} -> {:.3f}".format(n, q.int_to_float(n))) # quantize float to int for flt in np.linspace(-1, 1, 50): print("{:.3f} -> {}".format(flt, q.float_to_int(flt))) <file_sep>/src/submit.py """Submit Experiments in a multiprocessing queue. Make sure (num_cores >= num_workers * num_threads) to avoid locks. Example for 8 Cores (4 workers with 2 threads each), 5 experiments with 5 runs each: export OMP_NUM_THREADS=2 export MKL_NUM_THREADS=2 python -m src.submit presented run2 --num_workers 4 --num_threads 2 """ import argparse from pathlib import Path from src.rl.eval_exp import check_experiment, read_experiment_list from src.rl.experiment import Experiment from src.utils.config_mapping import load_experiment_config from src.utils.multiproc import MultiProcessor from src.utils.torchutils import set_seed def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "multi_file_name", help="file with list of experiments in config/*.txt") parser.add_argument("multi_run_name", help="name of multi run") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--cuda", action="store_true", help="use cuda") parser.add_argument("--run_start", type=int, default=0, help="start of the range (first run)") parser.add_argument("--run_end", type=int, default=5, help="end of the range (last run +1)") parser.add_argument("--seed", type=int, default=-1, help="seed") parser.add_argument("--num_workers", type=int, default=0, help="amount of workers") parser.add_argument( "--num_threads", type=int, default=0, help="number of threads per experiment") parser.add_argument( "--eval", help="check status only (don't run anything)", action="store_true") parser.add_argument( "--reset", action="store_true", help="force reset (delete existing experiments). without this flag " "the code is capable of continuing stopped runs.") args = parser.parse_args() if args.num_threads == 0: print("WARNING: No limit on threads (--num_threads=0). This will " "probably end in a deadlock unless --num_workers=1. " "See --help.") if args.seed != -1: set_seed(args.seed) # read list of experiments multi_run_name = args.multi_run_name experiments = read_experiment_list(args.multi_file_name, config_dir=args.config_dir) # setup multiprofessor mp = MultiProcessor(num_workers=args.num_workers, sleep=10) # loop experiments completed_list = [] for exp_name in experiments: # loop nruns print(exp_name) for n in range(args.run_start, args.run_end): # load config config_file = (Path(args.config_dir) / "experiments" / "{}.json".format(exp_name)) config = load_experiment_config(config_file) is_done = check_experiment( exp_name, multi_run_name, n, log_dir=args.log_dir) if not is_done: # submit experiment task = TaskExperiment( config, exp_name, multi_run_name, n, use_cuda=args.cuda, log_dir=args.log_dir, reset=args.reset) mp.add_task(task) else: completed_list.append((exp_name, multi_run_name, n)) print("Is already done") print("Tasks: {}".format(mp.get_num_tasks())) if args.eval: mp.close() return # run all experiments results = mp.run() # check results print("analyzing results...") emptys = 0 for result in results: if result is None: # experiment failed (stacktrace is somewhere in the log / stdout) emptys += 1 continue # # don't need to process results here, use src/eval_list.py # metrics, metrics_eval = result print("{} empty results AKA errors".format(emptys)) class TaskExperiment(object): """Run experiment in multitask""" def __init__( self, config, exp_name, run_name, run_number, use_cuda=False, log_dir="runs", num_threads=0, reset=False): self.use_cuda = use_cuda self.run_number = run_number self.run_name = run_name self.exp_name = exp_name self.config = config self.log_dir = log_dir self.num_threads = num_threads self.reset = reset def __call__(self): exp = Experiment( self.config, self.exp_name, self.run_name, logger=None, log_dir=self.log_dir, run_number=self.run_number, reset=self.reset, reload=not self.reset, use_cuda=self.use_cuda, print_every=100, verbose=False, num_threads=self.num_threads) metrics, metrics_eval = exp.run_training() exp.close() return metrics, metrics_eval if __name__ == '__main__': main() <file_sep>/requirements.txt gym tqdm jupyter matplotlib opencv-python numpy nltk <file_sep>/src/run.py """Run 1 (default) or N runs for a given experiment.""" import argparse from pathlib import Path from pprint import pprint from src.rl.experiment import Experiment from src.utils.config_mapping import load_experiment_config from src.utils.torchutils import set_seed def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("exp_name") parser.add_argument("run_name") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--cuda", action="store_true", help="use cuda") parser.add_argument("--run_start", type=int, default=0, help="number of the first run") parser.add_argument("--run_end", type=int, default=1, help="number of the last run") parser.add_argument("--reset", action="store_true", help="delete old experiment") parser.add_argument("--reload", action="store_true", help="reload old experiment") parser.add_argument("--reload_episode", type=int, default=-1, help="which episode to reload " "(default -1=last episode)") parser.add_argument("--base_seed", type=int, default=0, help="offset the seeds") parser.add_argument("--max_steps", type=int, default=-1, help="overwrite max steps for debugging " "(default -1=don't)") args = parser.parse_args() exp_name = args.exp_name run_name = args.run_name config_file = Path(args.config_dir) / "experiments" / "{}.json".format( exp_name) config = load_experiment_config(config_file) print("LOADED CONFIG {}".format(config_file)) pprint(config) # exp = Experiment( # config, reset=args.reset, reload=args.reload, # reload_episode=args.reload_episode, max_steps=args.max_steps, # use_cuda=not args.cpu) # run multiple experiments with different seeds print("Running {} runs".format(args.run_end - args.run_start)) for n in range(args.run_start, args.run_end): set_seed(n + args.base_seed) exp = Experiment( config, exp_name, run_name, logger=None, log_dir=args.log_dir, run_number=n, reset=args.reset, reload=args.reload, reload_step=args.reload_episode, use_cuda=args.cuda, verbose=True, max_steps=args.max_steps) metrics, metrics_eval = exp.run_training() exp.close() # watch untrained agent # test_agent(exp.env, exp.agent) # train DQN # exp.train_quantized() if __name__ == '__main__': main() <file_sep>/src/tests/test_input_transform.py import matplotlib.pyplot as plt import numpy as np from src.rl.continuous_cartpole import ContinuousCartPoleEnv from src.rl.observ_transform import ObservTransformer def main(): env = ContinuousCartPoleEnv() space = env.observation_space n = 10000 samp_angle = [] for i in range(n): samp = space.sample() samp_angle.append(samp[2]) samp_angle = np.array(samp_angle) print(samp_angle.min(), samp_angle.max()) # run env tf = ObservTransformer(env.observation_space, "sincos") angle_hist, c, s = [], [], [] old_observ = env.reset() old_observ = tf.transform_observ(old_observ) while True: angle_hist.append(old_observ[2]) c.append(old_observ[4]) s.append(old_observ[5]) action = np.random.random(1) * 2 - 1 new_observ, reward, done, _ = env.step(action) new_observ = tf.transform_observ(new_observ) if done: break old_observ = new_observ plt.plot(np.arange(len(angle_hist)), angle_hist) plt.plot(np.arange(len(angle_hist)), c) plt.plot(np.arange(len(angle_hist)), s) plt.show() # test epsilon schedulers if __name__ == '__main__': main() <file_sep>/src/rl/get_filenames.py """Utilities to get folders / filenames / find last episode / find last runs, etc. """ from pathlib import Path def get_exp_id(exp_name, run_name, run_number): """Given experiment, get unique experiment id (full experiment name).""" return "{}_{}_{}".format( exp_name, run_name, run_number) def get_exp_dir(exp_name, run_name, run_number, log_dir="runs"): """Given experiment, get experiment directory.""" return Path(log_dir) / get_exp_id(exp_name, run_name, run_number) def get_filename_infos( exp_name, run_name, run_number, step, log_dir="runs"): """Given experiment and step, get filename of the train infos. These also contain evaluation done during training.""" exp_dir = get_exp_dir(exp_name, run_name, run_number, log_dir=log_dir) return exp_dir / "scores_{}.json".format(step) def get_filename_eval( exp_name, run_name, run_number, log_dir="runs"): """Given experiment and episode, get filename of the evaluation infos. These only contain the evaluations done at the end of training, with the eval.py script. """ exp_dir = get_exp_dir(exp_name, run_name, run_number, log_dir=log_dir) return exp_dir / "eval.json".format() def get_filename_agent( exp_name, run_name, run_number, step, log_dir="runs"): """Given experiment and step, get filename of the agent weights.""" exp_dir = get_exp_dir(exp_name, run_name, run_number, log_dir=log_dir) return exp_dir / "agent_{}.pth".format(step) def get_filename_config( exp_name, run_name, run_number, log_dir="runs"): """Given experiment, get name of experiment config file.""" exp_dir = get_exp_dir(exp_name, run_name, run_number, log_dir=log_dir) return exp_dir / "config.json" <file_sep>/src/rl/eval_exp.py """Utilities to get folders / filenames / find last episode / find last runs, check experiment status, ...""" import copy import glob import json from collections import OrderedDict from pathlib import Path import numpy as np from src.rl.get_filenames import get_exp_dir, get_filename_infos, \ get_filename_config from src.utils.config_mapping import load_experiment_config def find_last_step(exp_name, run_name, run_number, log_dir="runs"): """ Given experiment, find last saved episode. Return -1 if no episode is found.""" exp_dir = get_exp_dir(exp_name, run_name, run_number, log_dir=log_dir) files = glob.glob(str(exp_dir / "scores*.json")) if len(files) == 0: return -1 else: return sorted([ int(file.replace(".json", "").split("_")[-1]) for file in files])[-1] def load_infos(exp_name, run_name, run_number, step, log_dir="runs"): result_file = get_filename_infos( exp_name, run_name, run_number, step, log_dir=log_dir) infos = json.load(result_file.open("rt", encoding="utf8")) return infos def find_best_step_eval(exp_name, run_name, run_number, log_dir="runs", verbose=False, config_dir="config"): last_step = find_last_step(exp_name, run_name, run_number, log_dir=log_dir) infos = load_infos( exp_name, run_name, run_number, last_step, log_dir=log_dir) avg_scores = infos["metrics_eval"]["avg_scores"] best_score = infos["best_eval_score"] best_idx = np.argsort(avg_scores)[-1] best_step = infos["metrics_eval"]["steps"][best_idx] if verbose: print("step {} scores {} best {} / {}".format( last_step, avg_scores, best_score, best_idx)) return best_step, best_idx, best_score def get_available_runs(exp_name, run_name, log_dir="runs"): """Given experiment name and run name, find available run numbers.""" glob_str = str(Path(log_dir) / "{}_{}_*".format(exp_name, run_name)) dirs = glob.glob(glob_str) run_numbers = sorted([int(a.split(run_name)[-1][1:]) for a in dirs]) if len(run_numbers) == 0: print("glob return nothing: {}".format(glob_str)) return run_numbers def check_experiment( exp_name, run_name, run_number, log_dir="runs", config_dir="config", verbose=True, use_unfinished=False, ignore_agent=False): if verbose: print("***** Checking exp {} run {}".format(exp_name, run_number)) # check experiment already exists exp_dir = get_exp_dir( exp_name, run_name, run_number, log_dir=log_dir) is_done = False if exp_dir.is_dir(): # load experiment config config_file = (Path(config_dir) / "experiments" / "{}.json".format(exp_name)) config = load_experiment_config(config_file) max_steps = config["training"]["max_steps"] # check last info file last_step = find_last_step( exp_name, run_name, run_number, log_dir=log_dir) result_file = exp_dir / "scores_{}.json".format(last_step) agent_file = exp_dir / "agent_{}.pth".format(last_step) if last_step == -1: print("Did not find any experiments") elif (agent_file.is_file() or ignore_agent) and result_file.is_file(): infos = json.load(result_file.open("rt", encoding="utf8")) if last_step >= max_steps: is_done = True else: if verbose: print("Not enough steps, checking if it is done") if infos["is_solved"]: is_done = True else: if use_unfinished: is_done = True if verbose: print( "Experiment {}_{}_{} trained {}/{} steps and " "is not solved.".format( exp_name, run_name, run_number, last_step, max_steps)) else: if verbose: print("Agent {} / results {} missing".format( agent_file, result_file)) else: if verbose: print("Directory does not exist: {}".format(exp_dir)) return is_done def check_all_experiments( exp_list, run_name, log_dir="runs", use_unfinished=False, ignore_agent=False, config_dir="config", sort=False, topk=-1, lowk=-1): exps = OrderedDict() print("Checking experiments...") sort_scores = [] sort_keys = [] for n_exp, exp_name in enumerate(exp_list): print("{}_{} ".format(exp_name, run_name), end=" ") # find runs that have this name runs = get_available_runs( exp_name, run_name, log_dir=log_dir) best_scores = [] print("runs", runs) for n in runs: # print("---------- {}_{}_{}".format(exp_name, multi_run_name, n), # end=" ") is_done = check_experiment( exp_name, run_name, n, log_dir=log_dir, verbose=False, use_unfinished=use_unfinished, ignore_agent=ignore_agent, config_dir=config_dir) # print(is_done) if not is_done: continue if exps.get(exp_name) is None: exps[exp_name] = OrderedDict() last_step = find_last_step( exp_name, run_name, n, log_dir=log_dir) best_step, best_idx, best_score = find_best_step_eval( exp_name, run_name, n, log_dir=log_dir, config_dir=config_dir) infos = load_infos( exp_name, run_name, n, last_step, log_dir=log_dir) # print("best step {} with {}".format(best_step, best_score)) exps[exp_name][n] = { "last_step": last_step, "best_step": best_step, "best_idx": best_idx, "best_score": best_score, "infos": infos, "config": load_experiment_config(get_filename_config( exp_name, run_name, n, log_dir=log_dir)) } best_scores.append(best_step) try: print("found {} completed runs".format(len(exps[exp_name]))) except KeyError: print("found nothing. if the experiment is not converged, consider" " using flag --use_unfinished") mean_score = np.mean(best_scores) sort_scores.append(float(mean_score)) sort_keys.append(exp_name) print() if sort: new_dict = OrderedDict() new_index = np.argsort(sort_scores) maxi = len(new_index) for i, idx in enumerate(new_index): if topk != -1 and lowk == -1: if i >= topk: continue elif topk == -1 and lowk != -1: if maxi - i - 1 >= lowk: continue elif topk != -1 and lowk != -1: if not (i < topk or maxi - i - 1 < lowk): continue key = sort_keys[idx] new_dict[key] = copy.deepcopy(exps[key]) return new_dict return exps def read_experiment_list(exp_list, config_dir="config"): exp_list_file = Path(config_dir) / "lists" / "{}.txt".format( exp_list) file_content = exp_list_file.open("rt", encoding="utf8").read().splitlines() experiments = [] for a in file_content: if a.strip() == "": continue if a[0] == "#": continue experiments.append(a) return experiments <file_sep>/src/eval.py """Evaluate single experiment with multiple runs. Features: - render agent / create video - evaluate agent for N episodes, save results, create plot """ import argparse import json import logging import os from pathlib import Path import matplotlib.pyplot as plt import numpy as np from src.rl.eval_exp import get_available_runs from src.rl.experiment import Experiment from src.rl.get_filenames import get_filename_eval from src.rl.render import render_agent from src.utils.config_mapping import load_experiment_config from src.utils.jsonencoder import to_json from src.utils.logger import get_logger from src.utils.plots import setup_latex_return_str_formatter, FIGSIZE, \ get_color_adaptive, COLOR_SUCCESS, NAME_MAP, ALPHA_LEGEND from src.utils.stats import Stats def main(): parser = argparse.ArgumentParser() parser.add_argument("exp_name") parser.add_argument("run_name") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--test_dir", type=str, default="test") parser.add_argument("--cuda", action="store_true", help="use cuda") parser.add_argument("--run_number", type=int, default=-1, help="number of single run " "(default -1 = all available runs)") parser.add_argument("--reload_step", type=int, default=-1, help="which step to reload " "(default -1=last step)") parser.add_argument("--reload_last", action="store_true", help="reload last instead of best step") parser.add_argument("--render", action="store_true", help="render agent") parser.add_argument("--video", action="store_true", help="capture rendering on video") parser.add_argument("--render_num", type=int, default=1, help="how many times to render agent") parser.add_argument("--overwrite", action="store_true", help="force overwriting old eval results") parser.add_argument("--eval_episodes", type=int, default=200) parser.add_argument("--num_steps", type=int, default=500) parser.add_argument("--video_dir", type=str, default="test_videos") parser.add_argument("--disable_tex", action="store_true", help="disable latex") args = parser.parse_args() exp_name = args.exp_name run_name = args.run_name # disable logging to file for notebooks logger = get_logger(".", "stats", with_file=False) # ä logger.setLevel(logging.ERROR) # find runs if args.run_number != -1: run_start = args.run_number run_end = args.run_number + 1 runs = list(range(run_start, run_end)) else: runs = get_available_runs( exp_name, run_name, log_dir=args.log_dir) print("experiment: {}_{}, runs to be evaluated: {}".format( exp_name, run_name, runs)) # ---------- rendering ---------- if args.render: for n in runs: # create experiment config_file = Path( args.config_dir) / "experiments" / "{}.json".format( exp_name) config = load_experiment_config(config_file) exp = Experiment( config, exp_name, run_name, logger=logger, log_dir=args.log_dir, run_number=n, reset=False, reload=True, reload_step=args.reload_step, reload_best=not args.reload_last, use_cuda=args.cuda, verbose=False) logger.info("Reloaded step {}".format(exp.current_step)) # render agent for m in range(args.render_num): video_id = "vid_{}_{}_{}".format(n, m, exp.current_step) video_dir = "" if args.video: video_dir = Path(args.video_dir) / "{}_{}".format( exp_name, run_name) logger.info( "Run {:2} trial {:2} rendering agent...".format( n, m)) render_agent( exp.env, exp.agent, exp.observ_transformer, num_steps=args.num_steps, video_dir=video_dir, video_name=video_id) # done rendering, exit return # ---------- evaluation ---------- eval_scores, steps = evaluate_all_runs( exp_name, run_name, run_number=args.run_number, log_dir=args.log_dir, config_dir=args.config_dir, use_cuda=args.cuda, reload_best=not args.reload_last, reload_step=args.reload_step, eval_episodes=args.eval_episodes, overwrite=args.overwrite, num_steps=args.num_steps) # plot format_text = setup_latex_return_str_formatter(disable_tex=args.disable_tex) plt.figure(figsize=FIGSIZE) for i, n in enumerate(runs): run_scores = eval_scores[i] step = steps[i] stats = Stats(run_scores) color = get_color_adaptive(i, len(runs)) # capsize=CAPSIZE_ERRORBAR capsize = 5 ms = 20 plt.errorbar( i, stats.mean, stats.stddev, color=color, label=format_text("#{} step {:.0f}K mean {:.3f}".format( n, step / 1000, stats.mean)), capsize=capsize, marker='x', lw=1, ms=10) plt.plot( [i], [stats.min_], color=color, ms=ms, marker=6, fillstyle='none') plt.plot([i], [stats.max_], marker=7, color=color, ms=ms, fillstyle='none') plt.xlabel("Agent Number") plt.ylabel(format_text( "Eval Score ($\epsilon=0$, {} episodes)".format( args.eval_episodes))) name = NAME_MAP.get(exp_name) plt.title( format_text("{} Agent Quality: Mean, stddev, min, max of eval " "score".format(name if name else exp_name))) plt.plot([-.5, len(runs) - .5], [400, 400], "--", c=COLOR_SUCCESS, label="success") plt.xlim([-.5, len(runs) - .5]) plt.grid() plt.legend(framealpha=ALPHA_LEGEND) dir_ = Path(args.test_dir) / "eval" os.makedirs(str(dir_), exist_ok=True) fn = str(dir_ / "{}_{}_eval{}ep.png".format( exp_name, run_name, args.eval_episodes)) plt.savefig(fn) plt.close() print("Plot saved to {}".format(fn)) def evaluate_all_runs( exp_name, run_name, run_number=-1, log_dir="runs", config_dir="config", use_cuda=False, reload_best=True, reload_step=-1, eval_episodes=200, overwrite=False, num_steps=500): scores_collector = [] steps_collector = [] if run_number >= 0: runs = [run_number] else: runs = get_available_runs( exp_name, run_name, log_dir=log_dir) for n in runs: scores, step = evaluate_run( exp_name, run_name, n, log_dir=log_dir, config_dir=config_dir, use_cuda=use_cuda, reload_best=reload_best, reload_step=reload_step, eval_episodes=eval_episodes, overwrite=overwrite, num_steps=num_steps) scores_collector.append(scores) single_stats = Stats(scores) print("{}_{}_{} x{}: {:8.3f} +- {:8.3f} range [{} {}]".format( exp_name, run_name, n, len(scores), single_stats.mean, single_stats.stddev, single_stats.min_, single_stats.max_)) steps_collector.append(step) if len(scores_collector) > 1: s = Stats(np.mean(scores_collector, axis=1)) print("Stats of mean results per run:\n {}".format(s)) s2 = Stats(np.reshape(scores_collector, -1)) print("Stats of all concatenated results:\n {}".format(s2)) else: print("Need at least 2 runs to compute stddev etc.") return scores_collector, steps_collector def evaluate_run( exp_name, run_name, run_number, log_dir="runs", config_dir="config", use_cuda=False, reload_best=True, reload_step=-1, eval_episodes=200, overwrite=False, num_steps=500): """Evaluate a run. returns list of eval scores""" # disable logging logger = get_logger(".", "stats_{}_{}_{}".format( exp_name, run_name, run_number), with_file=False) logger.setLevel(logging.ERROR) # load experiment config_file = Path(config_dir) / "experiments" / "{}.json".format( exp_name) config = load_experiment_config(config_file) exp = Experiment( config, exp_name, run_name, logger=logger, log_dir=log_dir, run_number=run_number, reset=False, reload=True, reload_step=reload_step, reload_best=reload_best, use_cuda=use_cuda, verbose=False) # read old evaluation file if exists eval_dict = {} eval_file = get_filename_eval( exp_name, run_name, run_number, log_dir=log_dir) if eval_file.is_file(): with eval_file.open("rt", encoding="utf8") as fh: eval_dict = json.load(fh) else: print("Old eval file {} not found".format(eval_file)) # check if there already is evaluation for this episode and # print a warning that we will overwrite it now current_step = exp.current_step current_step_str = str(current_step) old_eval = eval_dict.get(current_step_str) eval_episodes_str = str(eval_episodes) if old_eval is not None: old_scores = old_eval.get(eval_episodes_str) if old_scores is None: print( "Old scores for step {} episodes {} not found, creating new" "".format(current_step_str, eval_episodes)) elif overwrite: print( "Run {:2} Overwriting evaluation for step " "{} because of --overwrite flag".format( run_number, current_step)) else: print("Reloading existing eval:", end=" ") # logger.info("Reloading existing evaluation") eval_dict = json.load( eval_file.open("rt", encoding="utf8")) return eval_dict[current_step_str][eval_episodes_str], current_step else: print("Current step {} not found in eval dict: {}".format( current_step_str, eval_dict.keys() )) eval_dict[current_step_str] = {} # evaluate exp.verbose = True scores = exp.run_evaluation( num_ep=eval_episodes, num_steps=num_steps, print_steps=num_steps > 10000) # print("{} tries, mean: {}".format(len(scores), np.mean(scores))) # update evaluation dictionary eval_dict[current_step_str][eval_episodes_str] = scores # write evaluation to file with eval_file.open("wt", encoding="utf8") as fh: fh.write(to_json(eval_dict)) return scores, current_step if __name__ == '__main__': main() <file_sep>/src/agent/dqn_agent.py """DQN Agent class and creator method""" import random import numpy as np import torch from torch import nn from torch.optim.optimizer import Optimizer from src.agent.base_agent import AbstractAgent from src.agent.replay_buffer import ReplayMemory from src.agent.dqn_model import create_network from src.opt.optimizers import get_optimizer from src.utils.action_quantization import Quantizer1D from src.utils.torchutils import get_device def create_dqn_agent( config_agent: dict, config_optimizer: dict, observ_size: int, action_size: int, action_dim: int, batch_size: int, discount_factor: float, action_quantizer: Quantizer1D, use_cuda: bool = True, verbose: bool = True): """Given configuration dictionaries and parameters, create networks, optimizer and DQN agent.""" # create networks device = get_device(use_cuda) config_net = config_agent["net"] net_online = create_network( observ_size, action_size, action_dim, config_net, verbose=verbose).to( device) net_target = create_network( observ_size, action_size, action_dim, config_net, verbose=verbose).to( device) # create optimizer optimizer = get_optimizer(config_optimizer, net_online.parameters()) # create agent agent = RainbowDQNAgent( observ_size, action_size, action_dim, action_quantizer, net_online, net_target, optimizer, buffer_size=config_agent["buffer_size"], batch_size=batch_size, discount_factor=discount_factor, tau=config_agent["tau"], update_every=config_agent["update_every"], use_cuda=use_cuda, use_double_q_loss=config_agent["use_double_q"] ) return agent class RainbowDQNAgent(AbstractAgent): """ DQN Agent to act and learn in a gym environment with some rainbow implementations completed (paper arxiv 1710.02298): - double q learning: yes - prioritized replay: no - dueling networks: yes - multi-step learning: no - distributional rl: no - noisy nets: no """ def __init__( self, observ_size: int, action_size: int, action_dim: int, action_quantizer: Quantizer1D, net_online: nn.Module, net_target: nn.Module, optimizer: Optimizer, buffer_size: int = 100000, batch_size: int = 64, discount_factor: float = .99, tau: float = 1e-3, update_every: int = 4, use_cuda: bool = True, use_double_q_loss: bool = True): """ Args: observ_size: size of observation space action_size: number of actions action_quantizer: quantizer object to quantize continuous actions net_online: online network (used to act) net_target: target network optimizer: optimizer to update online network buffer_size: size of the replay buffer batch_size: batch size discount_factor: discount (gamma) tau: parameter for soft update of target network update_every: how often to update target network use_cuda: use gpu if available use_double_q_loss: use double q learning loss instead of normal q learning loss """ self.use_double_q_loss = use_double_q_loss # type:bool self.observ_size = observ_size # type: int self.action_size = action_size # type: int self.action_dim = action_dim # type: int self.action_quantizer = action_quantizer # type: Quantizer1D self.net_online = net_online # type: nn.Module self.net_target = net_target # type: nn.Module self.optimizer = optimizer # type: Optimizer self.buffer_size = buffer_size # type: int self.batch_size = batch_size # type: int self.discount_factor = discount_factor # type: float self.tau = tau # type: float self.update_every = update_every # type: int self.use_cuda = use_cuda # type: bool self.device = get_device(use_cuda) # type: str self.is_training = True self.loss_fn = nn.MSELoss() # create replay buffer self.memory = ReplayMemory( self.buffer_size, self.action_size, self.batch_size, self.action_quantizer, use_cuda=use_cuda) # start in training mode self.set_train() def set_eval(self): self.net_online.eval() self.net_target.eval() self.is_training = False def set_train(self): self.net_online.train() self.net_target.train() self.is_training = True def get_state_dict(self): """Return state dict required for saving.""" return { "model": self.net_online.state_dict(), "optimizer": self.optimizer.state_dict() } def set_state_dict(self, agent_dict): """Set state dict from given dictionary""" self.net_online.load_state_dict(agent_dict["model"]) self.optimizer.load_state_dict(agent_dict["optimizer"]) def step(self, observ, action, reward, next_observ, done, total_step): """One optimization step of the agent.""" if not self.is_training: raise ValueError( "Agent is set to evaluation mode but .step() has been called.") # update replay buffer self.memory.add(observ, action, reward, next_observ, done) if (total_step + 1) % self.update_every != 0: # this is not a learn step return if len(self.memory.buffer) <= self.batch_size: # not enough memory in the replay buffer return # ---------- learning ---------- experiences = self.memory.sample() observs, actions, rewards, next_observs, dones = experiences # dirty hack for handling Box shape batch, 1 and Discrete shape batch if len(actions.shape) == 1: actions = actions.unsqueeze(1) if not self.use_double_q_loss: # regular loss net_target_out = self.net_target(next_observs) q_targets_next = net_target_out.detach() q_targets_next = q_targets_next.max(-1)[0] q_targets_next = q_targets_next.unsqueeze(-1) else: # double q loss q_local_argmax = self.net_online( next_observs).detach().max(1)[1].unsqueeze(1) target_out = self.net_target(next_observs) q_targets_next = target_out.gather(1, q_local_argmax) # compute q targets for current observations q_targets = rewards + (self.discount_factor * q_targets_next * ( 1 - dones)) # compute expect q for current observations # print("actions", actions.shape, actions.dtype) actions = torch_base2int( actions, self.action_size, self.action_dim, use_cuda=self.use_cuda) actions = actions.unsqueeze(-1) # print("actions", actions.shape) local_out = self.net_online(observs) # print("local out", local_out.shape) q_expected = local_out.gather(1, actions) # print("expected", q_expected.shape) # td-Loss (MSE) loss = self.loss_fn(q_expected, q_targets) # optimize self.optimizer.zero_grad() loss.backward() self.optimizer.step() # soft update target network for target_param, local_param in zip( self.net_target.parameters(), self.net_online.parameters()): target_param.data.copy_( self.tau * local_param.data + (1.0 - self.tau) * target_param.data) def act(self, observ, eps=0.): """Act given some observation and epsilon""" # check epsilon-greedy action selection if random.random() > eps: # model action (no gradients, eval mode) observ = np.expand_dims(np.array(observ, dtype=np.float32), axis=0) observ = torch.from_numpy(observ).to(self.device) self.net_online.eval() with torch.no_grad(): action_values = self.net_online(observ) self.net_online.train() action = np.argmax(action_values.cpu().data.numpy()) # base DIM representation gives back the action action = np_int2base( action, self.action_size, size=self.action_dim) else: # random action action = np.random.choice( self.action_size, size=self.action_dim) if self.action_quantizer is not None: # environment expects continuous actions # dequantize action (int to float) action = self.action_quantizer.int_to_float(action) # env expects action to be a length 1 numpy array return action # return np.array([action]) else: # these envs expect no dimension i guess? # better would be some flag on what to actually return return np.squeeze(action,axis=-1) def np_int2base(x, base, size=None, decreasing=True): x = np.asarray(x) if size is None: size = int(np.ceil(np.log(np.max(x)) / np.log(base))) if decreasing: powers = base ** np.arange(size - 1, -1, -1) else: powers = base ** np.arange(size) digits = (x.reshape(x.shape + (1,)) // powers) % base return digits def np_base2int(x_list, base, size=None, decreasing=True): x_list = np.asarray(x_list) if size is None: size = x_list.shape[-1] if decreasing: powers = base ** np.arange(size - 1, -1, -1) else: powers = base ** np.arange(size) contents = x_list * powers contents = contents.sum(axis=-1) return contents def torch_int2base(x, base, size=None, decreasing=True, use_cuda=False): device = get_device(use_cuda) if size is None: size = int(torch.ceil(torch.log(torch.max(x)) / torch.log(base))) if decreasing: powers = base ** torch.arange(size - 1, -1, -1).float().to(device) else: powers = base ** torch.arange(size).float().to(device) digits = (x.reshape(x.shape + (1,)) // powers) % base return digits def torch_base2int(x_list, base, size=None, decreasing=True, use_cuda=False): device = get_device(use_cuda) if size is None: size = x_list.shape[-1] if decreasing: powers = base ** torch.arange(size - 1, -1, -1).long().to(device) else: powers = base ** torch.arange(size).long().to(device) contents = x_list * powers contents = contents.sum(dim=-1) return contents<file_sep>/src/tests/test_cfg_renamers.py import glob from pathlib import Path if __name__ == '__main__': data = glob.glob( "*/*/config.json") # (Path("src") / "tests" / "list.txt").open("rt").read().splitlines() print(len(data), "files") for f in data: print(f) file_content = Path(f).open("rt").read() file_content = file_content.replace( "env_state_transform", "env_observ_transform") # Path(f).open("wt").write(file_content) <file_sep>/src/utils/plots.py """Matplotlib setup / parameters / helper functions""" import errno import os import subprocess import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import colors from matplotlib import style STYLE = "default" COLOR_MAP = "hsv" FIGSIZE = (17, 12) FONTSIZE = 16 FONTSIZE_LEGEND = 14 ALPHA_LEGEND = 0.2 COLOR_MEAN = 'black' COLOR_SUCCESS = 'red' CAPSIZE_ERRORBAR = 10 style.use(STYLE) mpl.rcParams.update({ 'font.size': FONTSIZE}) color_cycle = plt.rcParams['axes.prop_cycle'].by_key()['color'] NAME_MAP = { "vanilla-v0": "Baseline", "vanilla-v6-baseline-step-eval5k": "Best (eval @5K)", "vanilla-v6-baseline-step-eval20k": "Best (eval @20K)", "vanilla-v6-baseline-step-train": "Best (train score >= 400)", "vanilla-v6-baseline-time-eval5k": "Best + shaped reward (eval @5K)", } def get_color(num): # cycle colors from standard matplotlib color list return color_cycle[num % len(color_cycle)] def reduce_lightness(color_, lightness=1): color_ = colors.to_rgba(color_, alpha=1) color_ = [a * lightness if m < 3 else a for m, a in enumerate(color_)] return color_ def get_color_gradient(num, max_num): # cycle colors uniformly in a gradient colormap cmap = plt.get_cmap(COLOR_MAP) denom = (max_num - 1) if max_num > 1 else 1 factor = 0.95 # for repeating color maps to not repeat too much lightness = 0.8 # also a little darker return reduce_lightness(cmap(num / denom * factor), lightness) def get_color_adaptive(num, max_num): # color cycle if few runs, gradient if more runs. this avoids reusing # the same color for different runs if max_num < len(color_cycle): return get_color(num) else: return get_color_gradient(num, max_num) def setup_latex_return_str_formatter(disable_tex=False): # check latex available if disable_tex: print("LATEX deactivated.") tex = False else: tex = True try: devnull = open(os.devnull, 'w') subprocess.call(["latex", "-version"], stdout=devnull, stderr=devnull) except OSError as e: if e.errno == errno.ENOENT: print("Latex not found, deactivating...") tex = False else: # Something else went wrong while trying to run latex raise if tex: mpl.rc('text', usetex=tex) def format_text(text: str): if tex: escapees = ["_", "#", "&"] for escapee in escapees: text = text.replace(escapee, "\\{}".format(escapee)) ds = [(">=", "$\\geq$")] for d1, d2 in ds: text = text.replace(d1, d2) return text return text return format_text <file_sep>/src/opt/optimizers.py from torch import optim from torch.optim.rmsprop import RMSprop from src.opt.adamw import AdamW def get_optimizer(config_opt, parameters): name = config_opt["name"] if name == "adam": opt = optim.Adam( parameters, lr=config_opt["lr"], betas=(config_opt["momentum"], config_opt["beta2"]), eps=config_opt["eps"], weight_decay=config_opt["weight_decay"], amsgrad=config_opt["amsgrad"]) elif name == "adamw": opt = AdamW( parameters, lr=config_opt["lr"], betas=(config_opt["momentum"], config_opt["beta2"]), eps=config_opt["eps"], weight_decay=config_opt["weight_decay"], amsgrad=config_opt["amsgrad"]) elif name == "sgd": opt = optim.SGD( parameters, lr=config_opt["lr"], momentum=config_opt["momentum"], dampening=config_opt["dampening"], weight_decay=config_opt["weight_decay"], nesterov=config_opt["nesterov"]) elif name == "rmsprop": opt = RMSprop( parameters, lr=config_opt["lr"], alpha=config_opt["alpha"], eps=config_opt["eps"], weight_decay=config_opt["weight_decay"], momentum=config_opt["momentum"], centered=config_opt["centered"]) else: raise NotImplementedError("optimizer {} not implemented".format(name)) return opt <file_sep>/src/agent/base_agent.py """Abstract agent class template.""" import numpy as np class AbstractAgent(object): """Agent can act and learn in a gym environment.""" def step(self, observ, action, reward, next_observ, done, total_step): """Do one step, e.g. save experiences and update networks Args: observ (np.ndarray): current observation action (np.ndarray): current action reward (float): reward next_observ (np.ndarray): next observation done (bool): next_observ is terminal or not total_step (int): total training step """ raise NotImplementedError def act(self, observ, eps=0.): """Take observation and act epsilon-greedily. Args: observ (np.ndarray): observation eps (float): epsilon, for epsilon-greedy action selection """ raise NotImplementedError def set_eval(self): """Set all neural networks to evaluation mode""" raise NotImplementedError def set_train(self): """Set all neural networks to train mode""" raise NotImplementedError def get_state_dict(self): """Return a dictionary with all relevant state dictionaries: State dicts of all networks and state dict of the optimizer. This dict will be saved to file.""" raise NotImplementedError def set_state_dict(self, agent_dict): """Update all relevant state dicts (networks, optimizer) from the input dictionary.""" raise NotImplementedError <file_sep>/src/rl/reward_functions.py import numpy as np def angle_normalize(x): """Makes sure all values of the input array are in the range [-pi, pi), by adding or subtracting 2*pi until they are. Copied from continuous cartpole env. """ return ((x + np.pi) % (2 * np.pi)) - np.pi def reward_default(cart_pole): if (cart_pole.state[0] < - cart_pole.x_threshold or cart_pole.state[0] > cart_pole.x_threshold): return -1 return 1 if -0.1 <= angle_normalize( cart_pole.state[2]) <= 0.1 else 0 def reward_shaped_v1(cart_pole): # -1000 for falling off if (cart_pole.state[0] < - cart_pole.x_threshold or cart_pole.state[0] > cart_pole.x_threshold): return -1000 # +10000 - very high reward for being in the good range ang_norm = angle_normalize(cart_pole.state[2]) if -0.1 <= ang_norm <= 0.1: return 1000 else: # shaped reward for going up on either side # up factor should be 1 when up and 0 when down up_factor = 1 - np.abs(ang_norm) / np.pi return up_factor * 2 - 1 def reward_shaped_v2(cart_pole): # -1 for falling off if (cart_pole.state[0] < - cart_pole.x_threshold or cart_pole.state[0] > cart_pole.x_threshold): return -1 # +1000 - very high reward for being in the good range ang_norm = angle_normalize(cart_pole.state[2]) if -0.1 <= ang_norm <= 0.1: return 100 else: # shaped reward for going up on either side # up factor should be 1 when up and 0 when down up_factor = 1 - np.abs(ang_norm) / np.pi return (np.exp(up_factor) - 1) / (np.e - 1) def new_reward_v1(cart_pole): return +1 <file_sep>/src/utils/jsonencoder.py """More beautiful JSON encoder than the default json.dump. Does indents and newlines but keeps lists on single line. """ import numpy import collections def to_json(obj, lvl=0, indent=4, space=" ", newline="\n"): json_str = "" if isinstance(obj, collections.Mapping): json_str += "{" + newline comma = "" for key, val in obj.items(): json_str += comma comma = ",\n" json_str += space * indent * (lvl + 1) json_str += '"' + str(key) + '":' + space json_str += to_json(val, lvl + 1) json_str += newline + space * indent * lvl + "}" elif isinstance(obj, str): json_str += '"' + obj + '"' elif isinstance(obj, collections.Iterable): json_str += "[" + ",".join([to_json(e, lvl + 1) for e in obj]) + "]" elif isinstance(obj, bool): json_str += "true" if obj else "false" elif isinstance(obj, int): json_str += str(obj) elif isinstance(obj, float): json_str += '%.7g' % obj elif isinstance(obj, numpy.ndarray) and numpy.issubdtype( obj.dtype, numpy.integer): json_str += "[" + ','.join(map(str, obj.flatten().tolist())) + "]" elif isinstance(obj, numpy.ndarray) and numpy.issubdtype( obj.dtype, numpy.inexact): json_str += "[" + ','.join( map(lambda x: '%.7g' % x, obj.flatten().tolist())) + "]" elif obj is None: json_str += 'null' else: raise TypeError( "Unknown type '%s' for json serialization" % str(type(obj))) return json_str <file_sep>/src/utils/stats.py """Stats class to calculate mean/stddev on the fly""" import numpy as np class Stats(object): # noinspection PyArgumentList def __init__(self, array: np.ndarray, axis: int = -1): self.array = np.array(array) self.axis = axis self.dims = len(self.array.shape) self.mean = self.array.mean(axis=self.axis) # self.var = self.array.var(axis=self.axis) # statistically correct: divide by N-1 self.var = ((self.array - np.expand_dims(self.mean, axis=self.axis) ) ** 2).sum(self.axis) / (self.array.shape[axis] - 1) self.stddev = np.sqrt(self.var) self.min_ = self.array.min(axis=self.axis) self.max_ = self.array.max(axis=self.axis) def __str__(self): if self.dims == 1: return ( "Array mean {:.3f} stddev {:.3f} valuerange {:.3f}/{:.3f} " "var {:.3f} num_values {} ".format( self.mean, self.stddev, self.min_, self.max_, self.var, self.array.shape)) else: return ( "Array {} mean {} ...\n" "fields: mean, var, stddev, min_, max".format( self.array.shape, self.mean.shape) ) def average_last(x, n=100): """Calculate average of the axis of the last N elements""" assert len(x.shape) == 1, "currently only implemented for length 1 axis" axis_length = x.shape[0] if axis_length < n: # trying to average over a length longer than the actual array dims # just use the simple mean of all elements up to this point out = np.zeros_like(x) for i in range(axis_length): out[i] = x[: i + 1].mean() else: # there are points where we can calculate average for last N points # faster version as soon as 100 examples are available cumsum = np.cumsum(np.insert(x, np.ones((100,)) * x[0], 0)) out = (cumsum[n:] - cumsum[:-n]) / float(n) # correct the first i as running mean of only the first i for i in range(n): out[i] = x[:i + 1].mean() return out <file_sep>/src/tests/test_std.py """Test whether standard deviation calculation is correct""" import numpy as np from src.utils.stats import Stats def main(): data = [9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4] true_var = 9.368 true_std = 3.061 print("***** TRUE") print("std", true_std) print("var", true_var) # 1D arrays s = Stats(data) print("***** STATS") print("std", s.stddev) print("var", s.var) # n-D print("***** N-D") data = np.array(data) data = np.expand_dims(data, 0) data = np.repeat(np.expand_dims(data, -1), 3, axis=-1) print(data.shape) s = Stats(data, axis=1) print("std", s.stddev, s.stddev.shape) print("var", s.var, s.var.shape) if __name__ == '__main__': main() <file_sep>/src/cleanup_list.py """Clean up experiment folders: - delete all models.pth/scores.json except best and last model Will not delete anything unless run with --delete """ import argparse import glob import os from pathlib import Path from src.rl.eval_exp import check_all_experiments, get_exp_dir def main(): parser = argparse.ArgumentParser() parser.add_argument( "multi_file_name", help="file with list of experiments in config/lists/*.txt") parser.add_argument("multi_run_name", help="name of multi run") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--delete", action="store_true") args = parser.parse_args() log_dir = args.log_dir # read list of experiments multi_run_name = args.multi_run_name exp_list_file = Path(args.config_dir) / "lists" / "{}.txt".format( args.multi_file_name) experiments = exp_list_file.open("rt", encoding="utf8").read().splitlines() # find all relevant experiments exps = check_all_experiments( experiments, multi_run_name, log_dir=log_dir, use_unfinished=True, ignore_agent=True, config_dir=args.config_dir) for n_exp, (exp_name, content) in enumerate(exps.items()): print("---------- {}: {} runs".format(exp_name, len(content))) for run_num, run_info in content.items(): last_step = run_info["last_step"] best_step = run_info["best_step"] # print( "run {} last {} best {}".format( # run_num, last_step, best_step)) # get score files exp_dir = get_exp_dir( exp_name, multi_run_name, run_num, log_dir=args.log_dir) score_files = sorted(glob.glob(str(exp_dir / "scores_*.json"))) for score_file in score_files: step = int(score_file.split("scores_")[-1].split(".json")[0]) if step == last_step or step == best_step: # save best and last step infos continue if args.delete: print("deleting {}".format(score_file)) os.remove(score_file) else: print("use --delete to remove {}".format(score_file)) # get agent files agent_files = sorted(glob.glob(str(exp_dir / "agent_*.pth"))) for agent_file in agent_files: step = int(agent_file.split("agent_")[-1].split(".pth")[0]) if step == last_step or step == best_step: # save both best and last agent continue if args.delete: print("deleting {}".format(agent_file)) os.remove(agent_file) else: print("use --delete to remove {}".format(agent_file)) if __name__ == '__main__': main() <file_sep>/src/tests/test_eps_scheduler.py """Epsilon scheduler test / plot""" import argparse import os from pathlib import Path import matplotlib.pyplot as plt import numpy as np from src.rl.epsilon_scheduler import get_eps_scheduler from src.utils.plots import FIGSIZE, setup_latex_return_str_formatter, \ NAME_MAP, get_color_adaptive, CAPSIZE_ERRORBAR def main(): # test epsilon schedulers parser = argparse.ArgumentParser() parser.add_argument("--test_dir", type=str, default="test") parser.add_argument("--disable_tex", action="store_true", help="disable latex") args = parser.parse_args() test_path = Path(args.test_dir) / "eps_schedulers" os.makedirs(str(test_path), exist_ok=True) exps = ["vanilla-v6-baseline-step-eval5k", "vanilla-v6-baseline-step-eval20k", "vanilla-v6-baseline-step-train", "vanilla-v6-baseline-time-eval5k"] means = [189.02, 197.41, 512.08, 256.03] stds = [28.414, 35.292, 162.597, 54.989] max_steps = 1000000 opts = { "eps_start": 1.0, "eps_end": 0.01, "eps_decay": 0.99995, "warmup": 0.05 } names = ["mult_decay", "cos_decay"] pretty_names = ["Exponential Decay", "Cosine Decay"] scheds = [] for n in names: scheds.append(get_eps_scheduler({ "name": n, **opts}, max_steps)) xr = np.arange(max_steps) every = 10 xss = [] epsss = [] format_text = setup_latex_return_str_formatter(disable_tex=args.disable_tex) def plot_exps(epss_): for k, (exp, mean, std) in enumerate(zip(exps, means, stds)): color = get_color_adaptive(k + 1, len(exps) + 1) eps_ = int(mean * 1000 / every) plt.errorbar( mean, epss_[eps_], yerr=0, xerr=std, c=color, marker='x', linestyle='-', ms=15, capsize=CAPSIZE_ERRORBAR, alpha=1, label=format_text(NAME_MAP[exp])) for name, sched, pretty_name in zip(names, scheds, pretty_names): sched.reset() epss = [] xs = [] print("---------- {}".format(name)) print("Accumulate stats") for i in range(max_steps): eps = sched.get_epsilon() sched.step() if i % every == 0: epss.append(eps) xs.append(xr[i] / 1000) xss.append(xs) epsss.append(epss) print("Plot") plt.figure(figsize=FIGSIZE) plt.plot(xs, epss, label=format_text(pretty_name)) plt.grid() plt.title(format_text( "{} $\epsilon$-scheduler and mean+std " "experiment convergence step".format(pretty_name))) plt.xlabel("K steps") plt.ylabel("$\epsilon$") plot_exps(epss) plt.legend() plt.savefig(str(test_path / "{}.png".format(name))) plt.close() plt.figure(figsize=FIGSIZE) for name, xs, epss in zip(names, xss, epsss): plt.plot(xs, epss, label=format_text(name)) plt.grid() plt.legend() plt.xlabel("K steps") plt.ylabel("$\epsilon$") plt.title("$\epsilon$-scheduler comparison") filename = str(test_path / "all.png") plt.savefig(filename) plt.close() print("Epsilon scheduler plotted to {}".format(filename)) if __name__ == '__main__': main() <file_sep>/src/utils/logger.py """Easy logging to stdout and file simultanously""" import datetime import logging import sys from pathlib import Path def get_logger(logdir, name, filename="run", with_file=True) -> logging.Logger: logger = logging.getLogger(name) logger.setLevel(logging.INFO) formatter = logging.Formatter( # "%(name)s %(asctime)s %(levelname)s %(message)s", # datefmt="%m%d %H%M%S") "%(asctime)s %(levelname)s %(message)s", datefmt="%m-%d %H:%M:%S") ts = str(datetime.datetime.now()).split(".")[0].replace(" ", "_") ts = ts.replace(":", "_").replace("-", "_") if with_file: file_path = str(Path(logdir) / "{}_{}.log".format(filename, ts)) file_hdlr = logging.FileHandler(file_path) file_hdlr.setFormatter(formatter) logger.addHandler(file_hdlr) strm_hdlr = logging.StreamHandler(sys.stdout) strm_hdlr.setFormatter(formatter) logger.addHandler(strm_hdlr) return logger def close_logger(logger: logging.Logger): x = list(logger.handlers) for i in x: logger.removeHandler(i) i.flush() i.close() def logger_info(logger: logging.Logger): print(logger.name) x = list(logger.handlers) for i in x: handler_str = "Handler {} Type {}".format(i.name, type(i)) print(handler_str) <file_sep>/src/agent/replay_buffer.py import random from collections import deque import numpy as np import torch from src.utils.action_quantization import Quantizer1D from src.utils.torchutils import get_device class ReplayMemory(object): """Memory for experience replay""" def __init__( self, buffer_size: int, action_size: int, batch_size: int, action_quantizer: Quantizer1D, use_cuda: bool = True): """Create the memory""" self.action_size = action_size self.batch_size = batch_size self.action_quantizer = action_quantizer self.buffer = deque(maxlen=buffer_size) self.device = get_device(use_cuda) def add(self, observ, action, reward, next_observ, done): """Append experience tuple to the buffer""" if self.action_quantizer is not None: # quantize the action action = self.action_quantizer.float_to_int(action) self.buffer.append((observ, action, reward, next_observ, done)) def sample(self): """Sample experience tuples from buffer""" # sample random experience tuples experiences = random.sample(self.buffer, k=self.batch_size) # collect data from tuples observs, actions, rewards, next_observs, dones = [], [], [], [], [] for e in experiences: observs.append(e[0]) actions.append(e[1]) rewards.append(e[2]) next_observs.append(e[3]) dones.append(e[4]) # transform data to tensors with correct data types, shapes, devices observs = torch.from_numpy(np.array(observs, dtype=np.float32)).to( self.device) actions = torch.from_numpy(np.array(actions, dtype=np.int64)).to( self.device) rewards = torch.from_numpy(np.expand_dims(np.array( rewards, dtype=np.float32), axis=-1)).to(self.device) next_observs = torch.from_numpy( np.array(next_observs, dtype=np.float32)).to(self.device) dones = torch.from_numpy(np.expand_dims(np.array( dones, dtype=np.float32), axis=-1)).to(self.device) return observs, actions, rewards, next_observs, dones <file_sep>/src/eval_list.py """Evaluate list of experiments. Creates plots and CSV/txt data.""" import argparse import json import os from pathlib import Path from typing import Dict import matplotlib.pyplot as plt import numpy as np from src.rl.eval_exp import check_all_experiments, read_experiment_list from src.utils.plots import setup_latex_return_str_formatter, FIGSIZE, \ get_color_adaptive, FONTSIZE_LEGEND, COLOR_MEAN, COLOR_SUCCESS, \ CAPSIZE_ERRORBAR, NAME_MAP, ALPHA_LEGEND from src.utils.stats import Stats def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "multi_file_name", help="file with list of experiments in config/lists/*.txt") parser.add_argument("multi_run_name", help="name of multi run") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--test_dir", type=str, default="test") parser.add_argument("--performance_dir", type=str, default="performance") parser.add_argument( "--use_unfinished", action="store_true", help="include unfinished runs in the analysis, i.e. not converged and " "step < max_step") parser.add_argument( "--no_plots", action="store_true", help="dont plot (only create text analysis)") parser.add_argument( "--no_single_plots", action="store_true", help="dont create single plots (only joined eval plot and text data)") parser.add_argument( "--sort", action="store_true", help="sort experiment by best step (only works correctly for " "eval metric)") parser.add_argument( "--topk", type=int, default=-1, help="only K best (default -1=all)") parser.add_argument( "--lowk", type=int, default=-1, help="only K worst (default -1=all)") parser.add_argument("--disable_tex", action="store_true", help="disable latex") args = parser.parse_args() log_dir = args.log_dir # ---------- setup plotting ---------- format_text = setup_latex_return_str_formatter(disable_tex=args.disable_tex) ms = 10 # setup different metrics to plot over for all plots x_metrics = "step", "time_cpu", "time_gpu" x_metrics_labels = ( "K Steps", "Approx Time on CPU (sec)", "Approx Time on GPU (sec)") y_metric_label_train = "Train total reward (avg last 100 epochs)" y_metric_label_eval = r"Eval total reward ($\epsilon$=0, " \ "evaluated for 25 epochs)" # ---------- setup experiments ---------- multi_run_name = args.multi_run_name experiments = read_experiment_list( args.multi_file_name, config_dir=args.config_dir) # find all relevant experiments (they have files, are converged etc.) exps = check_all_experiments( experiments, multi_run_name, log_dir=log_dir, use_unfinished=args.use_unfinished, ignore_agent=True, config_dir=args.config_dir, sort=args.sort, topk=args.topk, lowk=args.lowk) # directories plots_dir = Path(args.test_dir) / "_{}_{}".format( args.multi_file_name, multi_run_name) plots_dir_base = Path(args.test_dir) os.makedirs(str(plots_dir), exist_ok=True) # ---------- plot final evaluation results best epoch ---------- print("Plotting all experiments in one figure...") # this is an example how to create multiple plots at once # 6 plots: eval score of all / only solved runs over steps / # approx time CPU / approx time GPU # setup figures and axes figs = dict() # type: Dict[str, Dict[str, plt.Figure]] axs = dict() # type: Dict[str, Dict[str, plt.Axes]] for metric, metric_label in zip(x_metrics, x_metrics_labels): figs[metric] = dict() # type: Dict[str, plt.Figure] axs[metric] = dict() # type: Dict[str, plt.Axes] for p_name in "eval_all", "eval_solved", "train_all", "train_solved": fig, ax = plt.subplots(1, 1, figsize=FIGSIZE) if p_name.find("eval") > -1: ax.set_ylabel(y_metric_label_eval) else: ax.set_ylabel(y_metric_label_train) ax.set_xlabel(metric_label) figs[metric][p_name] = fig axs[metric][p_name] = ax # setup csv creation field_names = ["EvalScore", "TrainScore", "K Steps", "Time CPU", "Time GPU", "Episodes"] csv_dir = Path(args.test_dir) / "csv" txt_dir = Path(args.test_dir) / "txt" os.makedirs(str(csv_dir), exist_ok=True) os.makedirs(str(txt_dir), exist_ok=True) txt_file = txt_dir / "{}_{}.txt".format( args.multi_file_name, multi_run_name) csv_file = csv_dir / "{}_{}.csv".format( args.multi_file_name, multi_run_name) csv_file_means = csv_dir / "{}_{}_means.csv".format( args.multi_file_name, multi_run_name) csv_file_stddev = csv_dir / "{}_{}_stddev.csv".format( args.multi_file_name, multi_run_name) if args.topk != -1 or args.lowk != -1 or args.sort: # disable writing if not all data is used txt_file = os.devnull csv_file = os.devnull csv_file_means = os.devnull csv_file_stddev = os.devnull csv_handler = open(str(csv_file), "wt", encoding="utf8") csv_handler.write(";".join( ["ExpName", "RunNumber"] + field_names) + "\n") csv_handler_means = open(str(csv_file_means), "wt", encoding="utf8") csv_handler_means.write( ";".join(["ExpName", "RunAmount"] + field_names) + "\n") csv_handler_stddev = open(str(csv_file_stddev), "wt", encoding="utf8") csv_handler_stddev.write( ";".join(["ExpName", "RunAmount"] + field_names) + "\n") txt_file_handler = open(str(txt_file), "wt", encoding="utf8") # loop found experiments and infos exp_performance_cpu, exp_performance_gpu = dict(), dict() num_eval_ep = 0 for n_exp, (exp_name, content) in enumerate(exps.items()): s = "---------- {}: {} runs".format(exp_name, len(content)) print(s) print(s, file=txt_file_handler) (best_scores, best_steps, best_episodes, best_train_scores) = \ [], [], [], [] (best_scores_solved, best_steps_solved, best_episodes_solved, best_train_scores_solved) = [], [], [], [] color = get_color_adaptive(n_exp, len(exps)) # load performance metrics file_cpu = Path(args.performance_dir) / "cpu_{}.json".format(exp_name) file_gpu = Path(args.performance_dir) / "gpu_{}.json".format(exp_name) try: perf_dict_cpu = json.load(file_cpu.open("rt", encoding="utf8")) except FileNotFoundError as e: print(e, "CPU time plot will not work") perf_dict_cpu = dict([("ms_mean", 0)]) try: perf_dict_gpu = json.load(file_gpu.open("rt", encoding="utf8")) except FileNotFoundError as e: print(e, "GPU time plot will not work") perf_dict_gpu = dict([("ms_mean", 0)]) # # save to the experiment dict we are looping over for later exp_performance_cpu[exp_name] = perf_dict_cpu exp_performance_gpu[exp_name] = perf_dict_gpu best_times_cpu, best_times_gpu = [], [] best_times_cpu_solved, best_times_gpu_solved = [], [] for run_num, run_info in content.items(): infos = run_info["infos"] metrics = infos["metrics"] eval_episodes = infos["metrics_eval"]["episodes"] train_solve_score = run_info["config"]["evaluation"].get( "train_solve_score") if train_solve_score is None: # standard procedure best_step = run_info["best_step"] / 1000 best_idx = run_info["best_idx"] best_score = run_info["best_score"] best_episode = eval_episodes[best_idx] # find train avg scores try: best_train_score = metrics["avg_scores"][best_episode] except IndexError: best_train_score = metrics["avg_scores"][best_episode - 1] else: # training avg score metric # last step is always the best? because then the experiment # ends, unless not converged # if not converged we do not care about best step really # so always take last best_step = metrics["step"][-1] / 1000 # train scores are indexed by episodes best_episode = np.argmax(metrics["avg_scores"]) best_train_score = metrics["avg_scores"][best_episode] best_score = infos["metrics_eval"]["avg_scores"][-1] time_cpu = best_step * perf_dict_cpu["ms_mean"] time_gpu = best_step * perf_dict_gpu["ms_mean"] # append data for all runs best_scores.append(best_score) best_train_scores.append(best_train_score) best_steps.append(best_step) best_episodes.append(best_episode) best_times_cpu.append(time_cpu) best_times_gpu.append(time_gpu) # plot single run results for all runs alpha = 1. how = 'x' axs["step"]["eval_all"].plot( best_step, best_score, how, c=color, ms=ms, alpha=alpha) axs["time_cpu"]["eval_all"].plot( time_cpu, best_score, how, c=color, ms=ms, alpha=alpha) axs["time_gpu"]["eval_all"].plot( time_gpu, best_score, how, c=color, ms=ms, alpha=alpha) axs["step"]["train_all"].plot( best_step, best_train_score, how, c=color, ms=ms, alpha=alpha) axs["time_cpu"]["train_all"].plot( time_cpu, best_train_score, how, c=color, ms=ms, alpha=alpha) axs["time_gpu"]["train_all"].plot( time_gpu, best_train_score, how, c=color, ms=ms, alpha=alpha) # append data / plot only for solved runs if infos["is_solved"]: best_scores_solved.append(best_score) best_train_scores_solved.append(best_train_score) best_steps_solved.append(best_step) best_episodes_solved.append(best_episode) best_times_cpu_solved.append(time_cpu) best_times_gpu_solved.append(time_gpu) # plot only solved runs if infos["is_solved"]: axs["step"]["eval_solved"].plot( best_step, best_score, how, c=color, ms=ms, alpha=alpha) axs["time_cpu"]["eval_solved"].plot( time_cpu, best_score, how, c=color, ms=ms, alpha=alpha) axs["time_gpu"]["eval_solved"].plot( time_gpu, best_score, how, c=color, ms=ms, alpha=alpha) axs["step"]["train_solved"].plot( best_step, best_train_score, how, c=color, ms=ms, alpha=alpha) axs["time_cpu"]["train_solved"].plot( time_cpu, best_train_score, how, c=color, ms=ms, alpha=alpha) axs["time_gpu"]["train_solved"].plot( time_gpu, best_train_score, how, c=color, ms=ms, alpha=alpha) # find num eval episodes metrics_eval = infos["metrics_eval"] eval_scores_list = metrics_eval["scores_list"] for scores in eval_scores_list: num_eval_ep_new = len(scores) if num_eval_ep == 0: num_eval_ep = num_eval_ep_new assert num_eval_ep_new == num_eval_ep, "#eval_episodes unequal" # setup errorbar plot def plot_errbar(ax_, x_stat, y_stat, label_): ax_.errorbar( x_stat.mean, y_stat.mean, yerr=y_stat.stddev, xerr=x_stat.stddev, c=color, marker='^', linestyle='-', capsize=CAPSIZE_ERRORBAR, alpha=1, label=label_) # plot mean + stddev for all runs stats_scores = Stats(best_scores) stats_train_scores = Stats(best_train_scores) stats_steps = Stats(best_steps) stats_times_cpu = Stats(best_times_cpu) stats_times_gpu = Stats(best_times_gpu) stats_episodes = Stats(best_episodes) exp_nice_name = NAME_MAP.get(exp_name) if exp_nice_name is None: exp_nice_name = exp_name label = format_text("{} (#{})".format(exp_nice_name, len(best_scores))) plot_errbar( axs["step"]["eval_all"], stats_steps, stats_scores, label) plot_errbar( axs["time_cpu"]["eval_all"], stats_times_cpu, stats_scores, label) plot_errbar( axs["time_gpu"]["eval_all"], stats_times_gpu, stats_scores, label) plot_errbar( axs["step"]["train_all"], stats_steps, stats_train_scores, label) plot_errbar( axs["time_cpu"]["train_all"], stats_times_cpu, stats_train_scores, label) plot_errbar( axs["time_gpu"]["train_all"], stats_times_gpu, stats_train_scores, label) # plot mean + stddev only for solved runs if len(best_scores_solved) > 0: stats_scores_solved = Stats(best_scores_solved) stats_train_scores_solved = Stats(best_train_scores_solved) stats_steps_solved = Stats(best_steps_solved) stats_times_cpu_solved = Stats(best_times_cpu_solved) stats_times_gpu_solved = Stats(best_times_gpu_solved) if len(best_scores_solved) == len(best_scores): label = format_text("{} (#{})".format( exp_nice_name, len(best_scores))) else: label = format_text("{} (#{}/{})".format( exp_nice_name, len(best_scores_solved), len(best_scores))) plot_errbar(axs["step"]["eval_solved"], stats_steps_solved, stats_scores_solved, label) plot_errbar(axs["time_cpu"]["eval_solved"], stats_times_cpu_solved, stats_scores_solved, label) plot_errbar(axs["time_gpu"]["eval_solved"], stats_times_gpu_solved, stats_scores_solved, label) plot_errbar(axs["step"]["train_solved"], stats_steps_solved, stats_train_scores_solved, label) plot_errbar(axs["time_cpu"]["train_solved"], stats_times_cpu_solved, stats_train_scores_solved, label) plot_errbar(axs["time_gpu"]["train_solved"], stats_times_gpu_solved, stats_train_scores_solved, label) # ---------- print stats ---------- # write mean/stddev csv csv_handler_means.write(";".join([exp_name, str(len(content))])) csv_handler_stddev.write(";".join([exp_name, str(len(content))])) # print infos lines = [] for k in range(len(content)): lines.append("{};{}".format(exp_name, k)) for name, stats in zip( field_names, [stats_scores, stats_train_scores, stats_steps, stats_times_cpu, stats_times_gpu, stats_episodes]): s = ("{:10} range [{:8.2f}, {:8.2f}] mean {:8.2f} +- {:9.3f} " "values [{}]").format( name, stats.min_, stats.max_, stats.mean, stats.stddev, ", ".join(["{:8.2f}".format(a) for a in stats.array.tolist( )])) print(s) print(s, file=txt_file_handler) for k, v in enumerate(stats.array.tolist()): lines[k] += ";" + str(v) csv_handler_means.write(";" + str(stats.mean)) csv_handler_stddev.write(";" + str(stats.stddev)) csv_handler_means.write("\n") csv_handler_stddev.write("\n") for l in lines: csv_handler.write(l + "\n") csv_handler.close() csv_handler_means.close() csv_handler_stddev.close() txt_file_handler.close() if args.no_plots: return # finalize plots for score_name in "train", "eval": title_add2 = "" if args.topk != -1 and args.lowk != -1: title_add2 = ", only best {} & worst {}".format( args.topk, args.lowk) elif args.lowk != -1: title_add2 = ", only worst {}".format(args.lowk) elif args.topk != -1: title_add2 = ", only best {}".format(args.topk) if score_name == "eval": title_str = "Mean+stddev of final evaluation score over {}{}{}" else: title_str = "Mean+stddev of final training score over {}{}{}" for metric, metric_name in zip(x_metrics, x_metrics_labels): for title_add in "all", "solved": idx1, idx2 = metric, "{}_{}".format(score_name, title_add) ax = axs[idx1][idx2] title_add3 = "" if title_add == "solved": title_add3 = ", only solved" ax.set_title(format_text(title_str.format( metric_name, title_add2, title_add3))) ax.legend(fontsize=FONTSIZE_LEGEND, framealpha=ALPHA_LEGEND) ax.grid() fig = figs[idx1][idx2] fig.savefig(str( plots_dir / "{}{}{}{}_{}_scores_over_{}.png".format( "sorted_" if ( args.sort and args.topk == -1 and args.lowk == -1) else "", "top{}_".format(args.topk) if args.topk != -1 else "", "bot{}_".format(args.lowk) if args.lowk != -1 else "", score_name, title_add, metric))) plt.close(fig) if args.no_single_plots: return # ---------- plot eval score over metrics per run ---------- print("\nPlotting run eval scores...") # loop found experiments and infos for n_exp, (exp_name, content) in enumerate(exps.items()): print("{:2} {}".format(n_exp, exp_name)) # loop metrics for metric, metric_label in zip(x_metrics, x_metrics_labels): # setup plot plt.figure(figsize=FIGSIZE) plt.xlabel(metric_label) plt.ylabel(y_metric_label_eval) # for mean calculation, save the calculated x spaces x_spaces, y_spaces = [], [] min_x, max_x = 1e20, 0 has_metric = True # final plot will be in K steps / seconds not step / ms metric_correction = 1000 for i, (run_num, run_info) in enumerate(content.items()): infos = run_info["infos"] metrics_eval = infos["metrics_eval"] eval_scores = metrics_eval["avg_scores"] # [:best_idx+1] eval_steps = metrics_eval["steps"] # [:best_idx+1] best_idx = run_info["best_idx"] if infos["is_solved"]: train_solve_score = run_info["config"]["evaluation"].get( "train_solve_score") if train_solve_score is None: # regular procedure # skip all after best idx since we dont care about # those eval_scores = eval_scores[:best_idx + 1] eval_steps = eval_steps[:best_idx + 1] else: # don't skip anything pass # calculate x space for x metric perf = 1 x_space = np.array(eval_steps, dtype=np.float64) if metric == "time_cpu": perf = exp_performance_cpu[exp_name]["ms_mean"] x_space *= perf elif metric == "time_gpu": perf = exp_performance_gpu[exp_name]["ms_mean"] x_space *= perf min_x = min(min_x, x_space[0]) max_x = max(max_x, x_space[-1]) x_spaces.append(x_space) if perf == 0: # this means there is no performance evaluation for this # metric and experiment - skip has_metric = False break # calculate y space for y metric y_space = np.array(eval_scores) y_spaces.append(y_space) # plot single run results - eval color = get_color_adaptive(run_num, len(content)) label = format_text("#{}".format(run_num)) plt.plot( x_space / metric_correction, y_space, "x--", c=color, ms=15, alpha=1.0, label=label) # if there is no performance evaluation for this experiment and # metric, skip plot if not has_metric: print( "Skipping plot {} metric {} - no performance eval".format( exp_name, metric)) plt.close() continue # ----- calculate mean interval = 10 # accuracy, 1 = best and slowest start_point = int(min_x) - int(min_x) % interval end_point = int(max_x) - int(max_x) % interval + interval # create x space for mean and mask new_x_space = np.arange( start_point, end_point + 1, interval, dtype=np.float64) num_points = len(new_x_space) num_runs = len(x_spaces) mask = np.zeros_like(new_x_space) all_data = np.zeros((num_points, num_runs)) none_value = np.finfo(np.float64).min new_y_spaces = [] for i, (x_space, y_space) in enumerate( zip(x_spaces, y_spaces)): # interpolate the run eval data new_y_space = np.interp(new_x_space, x_space, y_space) # # this with all the mask code: ended runs are not taken into # # consideration for current mean/stddev # left=none_value, right=none_value) all_data[:, i] = new_y_space # add a 1 to the mask where the data is valid mask += new_y_space != none_value new_y_spaces.append(new_y_space) new_y_spaces = np.array(new_y_spaces) # check if there is invalid data at the end (where no more runs # where running) is_invalid = np.where(mask == 0)[0] if len(is_invalid > 0): # found invalid points - cut all data first_invalid_point = is_invalid[-1] all_data = all_data[:first_invalid_point] mask = mask[:first_invalid_point] new_x_space = new_x_space[:first_invalid_point] # set data to 0 where the value is invalid all_data[all_data == none_value] = 0 # get mean and stdev denominator and set it to 1 to avoid div by 0 mean_denom = np.maximum(mask, np.ones_like(mask)) stddev_denom = np.maximum(mask - 1, np.ones_like(mask)) # calculate mean and stddev finally mean = all_data.sum(axis=-1) / mean_denom # mean is correct stddev = all_data.std(axis=-1) mean_exp = np.expand_dims(mean, axis=-1) stddev2 = np.sqrt((np.sum( (all_data - mean_exp) ** 2, axis=-1)) / stddev_denom) # plot mean plt.plot( new_x_space / metric_correction, mean, label="mean".format(num_runs), lw=3, c=COLOR_MEAN) plt.fill_between( new_x_space / metric_correction, mean - stddev, mean + stddev, alpha=0.3, label="stddev", color=COLOR_MEAN) # stddev explodes the plot - yrange = datarange + 10% try: # noinspection PyArgumentList data_min = all_data.min() # noinspection PyArgumentList data_max = all_data.max() except ValueError: # happens when there are no performance measures for the metric # and the plot is invalid anyway data_min = 0 data_max = 1 data_range = data_max - data_min data_add = data_range * 0.02 plt.ylim(data_min - data_add, data_max + data_add) # x-y range is a little high x_min = new_x_space[0] / metric_correction x_max = new_x_space[-1] / metric_correction x_diff = x_max - x_min x_add = x_diff * 0.02 plt.xlim(x_min - x_add, x_max + x_add) # plot success line success = 400 plt.plot([x_min, x_max], [success, success], "-", c=COLOR_SUCCESS, lw=2, label="success") # finalize plot exp_nice_name = NAME_MAP.get(exp_name) if exp_nice_name is None: exp_nice_name = exp_name plt.title( "Experiment {} - Evaluation score over {} ".format( format_text(exp_nice_name), metric_label)) plt.legend(fontsize=FONTSIZE_LEGEND, framealpha=ALPHA_LEGEND) plt.grid() dir_ = plots_dir_base / metric os.makedirs(str(dir_), exist_ok=True) plt.savefig(str(dir_ / "run_eval_{}_over_{}.png".format( exp_name, metric))) plt.close() # ---------- plot train score over steps per run ---------- print("\nPlotting run train scores...") # loop found experiments and infos for max_k in [None, 100]: print("\nLimiting steps to {}k".format(max_k)) for n_exp, (exp_name, content) in enumerate(exps.items()): print("{:2} {}".format(n_exp, exp_name)) # loop metrics for metric, metric_label in zip(x_metrics, x_metrics_labels): # setup plot plt.figure(figsize=FIGSIZE) plt.xlabel(metric_label) plt.ylabel(y_metric_label_train) # for mean calculation, save the calculated x spaces x_spaces, y_spaces = [], [] min_x, max_x = 1e20, 0 has_metric = True # final plot will be in K steps / seconds not step / ms metric_correction = 1000 for i, (run_num, run_info) in enumerate(content.items()): infos = run_info["infos"] metrics = infos["metrics"] train_scores = metrics["avg_scores"] train_steps = metrics["step"] best_step = run_info["best_step"] if infos["is_solved"]: train_solve_score = run_info["config"][ "evaluation"].get("train_solve_score") if train_solve_score is None: # standard procedure pass else: # train metric - dont skip anything # overwrite best step with last step best_step = run_info["last_step"] if max_k is not None: best_step = min(max_k * 1000, best_step) # find index where step is > best step for the first # time where_arr = np.where(np.array( train_steps) > best_step)[0] if len(where_arr) > 0: best_idx = where_arr[0] # skip all after best idx since we dont care about # those train_scores = train_scores[:best_idx + 1] train_steps = train_steps[:best_idx + 1] else: # find index where step is > maxk for the first # time if max_k is not None: where_arr = np.where(np.array( train_steps) > max_k * 1000)[0] best_idx = where_arr[0] # skip all after best idx since we dont care about # those train_scores = train_scores[:best_idx + 1] train_steps = train_steps[:best_idx + 1] # calculate x space for x metric perf = 1 x_space = np.array(train_steps, dtype=np.float64) if metric == "time_cpu": perf = exp_performance_cpu[exp_name]["ms_mean"] x_space *= perf elif metric == "time_gpu": perf = exp_performance_gpu[exp_name]["ms_mean"] x_space *= perf min_x = min(min_x, x_space[0]) max_x = max(max_x, x_space[-1]) x_spaces.append(x_space) if perf == 0: # this means there is no performance evaluation for # this metric and experiment - skip has_metric = False break # calculate y space for y metric y_space = np.array(train_scores) y_spaces.append(y_space) # plot single run results - eval color = get_color_adaptive(run_num, len(content)) label = format_text("#{}".format(run_num)) plt.plot( x_space / metric_correction, y_space, "-", c=color, alpha=1.0, label=label) # plot finish indicator plt.plot( (x_space / metric_correction)[-1], y_space[-1], "|", c=color, alpha=1.0, ms=50) # if there is no performance evaluation for this experiment and # metric, skip plot if not has_metric: print( "Skip plot {} metric {} - no performance eval".format( exp_name, metric)) plt.close() continue # ----- calculate mean interval = 10 # accuracy, 1 = best and slowest start_point = int(min_x) - int(min_x) % interval end_point = int(max_x) - int(max_x) % interval + interval # create x space for mean and mask new_x_space = np.arange( start_point, end_point + 1, interval, dtype=np.float64) num_points = len(new_x_space) num_runs = len(x_spaces) mask = np.zeros_like(new_x_space) all_data = np.zeros((num_points, num_runs)) none_value = np.finfo(np.float64).min for i, (x_space, y_space) in enumerate( zip(x_spaces, y_spaces)): # interpolate the run eval data # for train, remove ended runs new_y_space = np.interp(new_x_space, x_space, y_space, left=none_value, right=none_value) all_data[:, i] = new_y_space # add a 1 to the mask where the data is valid mask += new_y_space != none_value # check if there is invalid data at the end (where no more runs # where running) is_invalid = np.where(mask == 0)[0] if len(is_invalid) > 0: # found invalid points - cut all data first_invalid_point = is_invalid[-1] all_data = all_data[:first_invalid_point] mask = mask[:first_invalid_point] new_x_space = new_x_space[:first_invalid_point] # dont plot mean sttdev if its only one run left is_only_one = np.where(np.logical_and( mask == 1, new_x_space > 100000))[0] if len(is_only_one) > 0: first_only_one_point = is_only_one[0] all_data = all_data[:first_only_one_point] mask = mask[:first_only_one_point] new_x_space = new_x_space[:first_only_one_point] # get mean and stdev denominator and set it to 1 to avoid # div by 0 mean_denom = np.maximum(mask, np.ones_like(mask)) stddev_denom = np.maximum(mask - 1, np.ones_like(mask)) # calculate mean and stddev finally # stddev is WRONG where there is less than full runs # because sum of differences is not 0 for done runs # calculate mean # set data to 0 where the value is invalid for mean calc all_data_mean = np.copy(all_data) all_data_mean[all_data == none_value] = 0 mean = all_data_mean.sum(axis=-1) / mean_denom # calculate stddev # set data to mean where the value is invalid for stddev calc # with the stddev_denom the math then works out mean_exp = np.expand_dims(mean, axis=-1).repeat( num_runs, axis=-1) all_data[all_data == none_value] = \ mean_exp[all_data == none_value] stddev = np.sqrt(np.sum((all_data - np.expand_dims( mean, axis=-1)) ** 2, axis=-1) / stddev_denom) # plot mean plt.plot( new_x_space / metric_correction, mean, label="mean", lw=3, c=COLOR_MEAN) plt.fill_between( new_x_space / metric_correction, mean - stddev, mean + stddev, alpha=0.3, label="stddev", color=COLOR_MEAN) # fix y limites y_spaces_flat = np.concatenate(y_spaces, axis=-1) # noinspection PyArgumentList data_min = y_spaces_flat.min() # noinspection PyArgumentList data_max = y_spaces_flat.max() data_range = data_max - data_min data_add = data_range * 0.02 plt.ylim(data_min - data_add, data_max + data_add) # x-y range is a little high x_min = min_x / metric_correction x_max = max_x / metric_correction x_diff = x_max - x_min x_add = x_diff * 0.02 plt.xlim(x_min - x_add, x_max + x_add) # finalize plot exp_nice_name = NAME_MAP.get(exp_name) if exp_nice_name is None: exp_nice_name = exp_name plt.title( "Experiment {} - Train score over {}{}".format( format_text(exp_nice_name), metric_label, ", max {}k steps".format(max_k) if max_k is not None else "")) plt.legend(fontsize=FONTSIZE_LEGEND, framealpha=ALPHA_LEGEND) plt.grid() dir_ = plots_dir_base / metric os.makedirs(str(dir_), exist_ok=True) plt.savefig(str(dir_ / "run_train_{}{}_over_{}.png".format( "max{}k_".format(max_k) if max_k is not None else "", exp_name, metric))) plt.close() if __name__ == '__main__': main() <file_sep>/src/submit_create_jobs.py """Create jobs for pool""" import argparse import os from pathlib import Path def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "multi_file_name", help="file with list of experiments in config/*.txt") parser.add_argument("multi_run_name", help="name of multi run") parser.add_argument("--config_dir", type=str, default="config") parser.add_argument("--log_dir", type=str, default="runs") parser.add_argument("--num_runs", type=int, default=5, help="amount of runs") args = parser.parse_args() # read list of experiments multi_run_name = args.multi_run_name exp_list_file = Path(args.config_dir) / "lists" / "{}.txt".format( args.multi_file_name) experiments = exp_list_file.open("rt", encoding="utf8").read().splitlines() os.makedirs("_jobs/logs", exist_ok=True) os.makedirs("_jobs/psingle", exist_ok=True) os.makedirs("_jobs/pmulti", exist_ok=True) # loop experiments for exp_name in experiments: # create job file = "_jobs/{}.sh".format(exp_name) content = """#!/bin/bash #PBS -N {0} #PBS -S /bin/bash #PBS -l nodes=1:ppn=8,mem=20gb,walltime=24:00:00 #PBS -q student #PBS -m aef #PBS -M <EMAIL> #PBS -j oe #PBS -t 1-1%1 #PBS -o _jobs/logs/{0} #PBS -e _jobs/logs/{0} cd /misc/lmbraid19/gings/repos/rlproject source ~/raid/venvs/venvcv/bin/activate python -m src.run --reset {1} {2} --run_start 0 --run_end {3} """.format(exp_name, exp_name, multi_run_name, args.num_runs) open(file, "wt").write(content) print("created {} with {} runs".format(file, args.num_runs)) # create another job file = "_jobs/psingle/{}.sh".format(exp_name) content = """#!/bin/bash cd ~/repos/rlproject source ~/venvpool/bin/activate python -m src.run --reset {1} {2} --run_start 0 --run_end {3} """.format(exp_name, exp_name, multi_run_name, args.num_runs) open(file, "wt").write(content) print("created {} with {} runs".format(file, args.num_runs)) # create multi job file = "_jobs/pmulti/{}.sh".format(exp_name) content = """#!/bin/bash cd ~/repos/rlproject source ~/venvpool/bin/activate export OMP_NUM_THREADS=2 export MKL_NUM_THREADS=2 echo "{1}" > config/lists/tmp_{1}.txt python -m src.submit tmp_{1} {2} --reset --run_start 0 --run_end {3} \\ --num_workers 4 --num_threads 2 """.format(exp_name, exp_name, multi_run_name, args.num_runs) open(file, "wt").write(content) print("created {} with {} runs".format(file, args.num_runs)) if __name__ == '__main__': main() <file_sep>/src/utils/torchutils.py """Save seed function (should be deterministic)""" import random import numpy as np import torch import torch.backends.cudnn as cudnn from torch import cuda def get_device(use_cuda): """Return torch device Args: use_cuda (bool): Use GPU if available """ return (torch.device( "cuda:0" if torch.cuda.is_available() and use_cuda else "cpu")) # noinspection PyUnresolvedReferences def set_seed(seed): torch.manual_seed(seed) cuda.manual_seed(seed) cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = False cudnn.deterministic = True <file_sep>/src/utils/config_mapping.py """Map config strings to objects for environments and reward functions""" import json import gym from src.rl.continuous_cartpole import ContinuousCartPoleEnv from src.rl.reward_functions import reward_default, reward_shaped_v1, \ reward_shaped_v2, new_reward_v1 ENVS = { "default_cartpole": ContinuousCartPoleEnv } REWARD_FUNCTIONS = { "none": None, "default": reward_default, "shaped_v1": reward_shaped_v1, # unused "shaped_v2": reward_shaped_v2, "new_v1": new_reward_v1 # unused } def load_experiment_config(config_json): with open(str(config_json), "rt", encoding="utf8") as fh: config = json.load(fh) return config def get_env(name): env = ENVS.get(name) if env is None: env = gym.make(name) return env def get_reward_fn(name): return REWARD_FUNCTIONS[name] <file_sep>/src/rl/render.py """Display agent / render video""" import glob import os from pathlib import Path import cv2 import numpy as np import shutil from PIL import Image, ImageDraw, ImageFont from gym import Env from gym.wrappers import Monitor from src.agent.base_agent import AbstractAgent from src.rl.observ_transform import ObservTransformer def render_agent( env_in: Env, agent: AbstractAgent, observ_transformer: ObservTransformer, num_steps=500, video_dir="", video_name=None): """ Watch agent do something Args: env_in: gym environment agent: instance of child of abstractagent (must be able to "act") observ_transformer: input transformer (e.g. sincos trick) num_steps: max episode steps video_dir: where to save the video, if "" no video is done. video_name: give a name to the video (optional) Returns: reward (float) """ # setup video dir monitor_dir = Path(video_dir) / video_name if video_dir != "": # with video env = Monitor(env_in, str(monitor_dir), force=True, uid=video_name) else: # no video env = env_in # watch an untrained agent observ = env.reset() observ = observ_transformer.transform_observ(observ) j = 0 sum_reward = 0 info = [] for j in range(num_steps): print("{:5}/{:5}\r".format(j, num_steps), end="") # render env.render() # save render info info.append((j, sum_reward)) # act / step / collect rewards action = agent.act(observ) observ, reward, done, _ = env.step(action) observ = observ_transformer.transform_observ(observ) sum_reward += reward if done: break print("Reward {} after {:5} steps".format(sum_reward, j)) env.close() env_in.close() if video_dir == "": return sum_reward # find video video_name += "_r{:.3f}".format(sum_reward) files = glob.glob(str(Path(monitor_dir) / "*.mp4")) assert len(files) == 1, "more than one/no video was created?! {}".format( files) vid_file = files[0] target_file = str(Path(video_dir) / "{}_raw.mp4".format(video_name)) # ***** post process (add step, max_step, reward) # read video input video_in = cv2.VideoCapture(vid_file) fps = video_in.get(cv2.CAP_PROP_FPS) w = int(video_in.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(video_in.get(cv2.CAP_PROP_FRAME_HEIGHT)) # create video writer fourcc = cv2.VideoWriter_fourcc(*'MP4V') video_out = cv2.VideoWriter(target_file, fourcc, fps, (w, h)) counter = 0 sum_reward_total = sum_reward step, sum_reward = 0, 0 while video_in.isOpened(): # read frame ret, frame = video_in.read() if not ret: break # read step and reward if counter <= j: step, sum_reward = info[counter] # # modify frame # # opencv has ugly fonts t1 = "S {:4}/{:4}".format( step, j + 1) t2 = "R {:.2f}/{:.2f}".format( sum_reward, sum_reward_total) # pillow has better fonts than opencv pil_frame = Image.fromarray(frame) draw = ImageDraw.Draw(pil_frame) monospace = ImageFont.truetype("_misc/cour.ttf", 32) t2w, t2h = draw.textsize(t2, font=monospace) bordered_text(draw,monospace,t1,5,5) bordered_text(draw,monospace,t2, pil_frame.width - t2w - 5, 5) # draw.text((5, 5), t1, (0, 0, 0), font=monospace) # draw.text((pil_frame.width - t2w - 5, 5), t2, (0, 0, 0), # font=monospace) frame = np.array(pil_frame) # write video video_out.write(frame) counter += 1 video_in.release() video_out.release() target_file_wa = str(Path(video_dir) / "{}.mp4".format(video_name)) # make whatsapp ready os.system( "ffmpeg -i \"{}\" -c:v libx264 -c:a aac -y -preset slow " "-crf 5 \"{}\"".format(target_file, target_file_wa)) # if it worked delete the non-whatsapp version if Path(target_file_wa).is_file(): print("removing raw video file...") os.remove(str(target_file)) print("removing gym monitor directory...") shutil.rmtree(str(monitor_dir)) print("\nWrote video to {}".format(target_file_wa)) else: print("Conversion failed somewhere") return sum_reward def bordered_text( draw, font, text, x, y, color = (0,0,0), bgcolor=(255,255,255)): # draw.text((x - 1, y), text, font=font, fill=bgcolor) # draw.text((x + 1, y), text, font=font, fill=bgcolor) # draw.text((x, y - 1), text, font=font, fill=bgcolor) # draw.text((x, y + 1), text, font=font, fill=bgcolor) # thicker border draw.text((x - 1, y - 1), text, font=font, fill=bgcolor) draw.text((x + 1, y - 1), text, font=font, fill=bgcolor) draw.text((x - 1, y + 1), text, font=font, fill=bgcolor) draw.text((x + 1, y + 1), text, font=font, fill=bgcolor) # main text draw.text((x,y), text, font=font, fill=color)<file_sep>/src/utils/multiproc.py """ Multiprocessing convenience classes for torch. Most importantly makes sure that error stacktraces do not get lost. """ import subprocess import traceback from timeit import default_timer as timer from typing import List import time import tqdm from torch import multiprocessing # import multiprocessing def systemcall(call): pipe = subprocess.PIPE process = subprocess.Popen(call, stdout=pipe, stderr=pipe, shell=True) out, err = process.communicate() retcode = process.poll() charset = 'utf-8' out = out.decode(charset) err = err.decode(charset) return out, err, retcode class Worker(multiprocessing.Process): def __init__(self, task_q, result_q, error_q, verbose=False): super().__init__() self.task_q = task_q self.result_q = result_q self.error_q = error_q self.verbose = verbose def run(self): proc_name = self.name while True: next_task = self.task_q.get() if next_task is None: # poison pill means shutdown if self.verbose: print("{:s}: exiting".format(proc_name)) self.task_q.task_done() break if self.verbose: print(str(next_task)) try: result = next_task() pass except Exception as e: self.error_q.put((e, traceback.format_exc())) result = None self.task_q.task_done() self.result_q.put(result) class MultiProcessor(object): """convenience class for multiprocessing jobs""" def __init__( self, num_workers=0, verbose=True, progressbar=True, sleep=1): self._num_workers = num_workers self.verbose = verbose self.progressbar = progressbar if self._num_workers == 0: self._num_workers = multiprocessing.cpu_count() self._tasks = multiprocessing.JoinableQueue() self._results = multiprocessing.Queue() self._errors = multiprocessing.Queue() self._workers = [] # type: List[Worker] self._num_tasks = 0 self.total_time = 0 self.sleep = sleep def get_num_tasks(self): return self._num_tasks def add_task(self, task): self._tasks.put(task) self._num_tasks += 1 def close(self): self._results.close() self._errors.close() for w in self._workers: w.terminate() def run(self): # start N _workers start = timer() if self.verbose: print('Creating {:d} workers'.format(self._num_workers)) self._workers = [Worker(self._tasks, self._results, self._errors) for _ in range(self._num_workers)] for w in self._workers: w.start() # add poison pills for _workers for i in range(self._num_workers): self._tasks.put(None) # write start message if self.verbose: print("Running {:d} enqueued tasks and {:d} stop signals".format( self._num_tasks, self._num_workers)) # check info on the queue, with a nice (somewhat stable) progressbar if self.progressbar: print("waiting for the task queue to be filled...") num_wait = 0 while self._tasks.empty(): time.sleep(1) num_wait += 1 if num_wait >= 5: break tasks_now = self._num_tasks + self._num_workers pbar = tqdm.tqdm(total=tasks_now) while not self._tasks.empty(): time.sleep(self.sleep) tasks_before = tasks_now tasks_now = self._tasks.qsize() resolved = tasks_before - tasks_now pbar.set_description( "~{:7d} tasks remaining...".format(tasks_now)) pbar.update(resolved) pbar.close() # join _tasks if self.verbose: print("waiting for all tasks to finish...") self._tasks.join() # check _errors if self.verbose: print("reading error queue... ") num_err = 0 while not self._errors.empty(): e, stacktrace = self._errors.get() num_err += 1 print() print(stacktrace) if num_err >= 0: print("{} errors, check the log.".format(num_err)) elif self.verbose: print("no errors found.") # read _results and return them if self.verbose: print("reading results...") results = [] # # this can lead to some results missing # while not self._results.empty(): while self._num_tasks > 0: result = self._results.get() results.append(result) self._num_tasks -= 1 stop = timer() self.total_time = stop - start if self.verbose: print("Operation took {:.3f}s".format(self.total_time)) return results
0dfa62a68c59f7d4233e3d5245a12a0233a7f10a
[ "Markdown", "Python", "Text" ]
35
Python
gingsi/rl-continuouscartpole
87026506467ea08ff9c349294897dd3d942b8e16
86a86c7d357a8ee57f1f6aed0926638d6c8275b1
refs/heads/main
<file_sep>import { parse, transform } from '@markdoc/markdoc' import { readFileSync } from 'fs' import { join } from 'path' export const loadMarkdownFile = (path: string) => { const content = readFileSync(join(process.cwd(), path), 'utf-8') return transform(parse(content)) } <file_sep>import axios from 'axios' export type ConnpassEvent = { event_id: number title: string catch: string description: string event_url: string started_at: string ended_at: string limit: number hash_tag: string event_type: string accepted: number waiting: number updated_at: string owner_id: number owner_nickname: string owner_display_name: string place: string address: string lat: string lon: string series: { id: number title: string url: string } } export type ConnpassEventResponse = { results_start: number results_returned: number results_available: number events: ConnpassEvent[] } export const listConnpassEvent = async (query: string) => { const { data: events } = await axios.get(`https://connpass.com/api/v1/event/?${query}`) return events as ConnpassEventResponse } export const listJPStripesConnpassEvents = async (query?: string) => { return listConnpassEvent(['series_id=12610', query].filter(Boolean).join('&')) }
fcc67f7e2581eb000aaa5ccc3c83cb3c16e1ab13
[ "TypeScript" ]
2
TypeScript
jp-stripes/jpstripes.com
48aa817dbf174f26fa3abfb0c7dfc006cc7d8d9a
df74b2cc4e45f21b36107340fedbb36db213b8d0
refs/heads/master
<file_sep>var app = angular.module("aniModule", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider.when("/cat", { templateUrl: "cat.html" }); $routeProvider.when("/dog", { templateUrl: "dog.html" }); $routeProvider.when("/catdog", { templateUrl: "catdog.html" }); $routeProvider.when("/catanddog", { templateUrl: "catanddog.html" }); $routeProvider.when("/", { template: "Welcome! Click an animal above" }); $routeProvider.otherwise({ template: "404 animals not found" }); });
ce24ba29439f135e9911b585eb6b3f7967140972
[ "JavaScript" ]
1
JavaScript
jcjoneskern/cat-dog
d3c0d0cfd756250a163e1582f2394d8b789239c0
2eae3b53d12a1b7e93694e5bd2fd8f1c6e5b4058
refs/heads/master
<repo_name>itskhushis1/javaprograms<file_sep>/fasno.java import java.util.*; public class FascinatingNumberExample1 { public static void main(String args[]) { int num, n2, n3; Scanner sc=new Scanner(System.in); System.out.print("Enter any Number: "); num = sc.nextInt(); n2 = num * 2; n3 = num * 3; //concatenating num, n2, and n3 String concatstr = num + "" + n2 + n3; boolean found = true; //checks all digits from 1 to 9 are present or not for(char c = '1'; c <= '9'; c++) { int count = 0; //loop counts the frequency of each digit for(int i = 0; i < concatstr.length(); i++) { char ch = concatstr.charAt(i); //compares the character of concatstr with i if(ch == c) //incerments the count by 1 if the specified condition returns true count++; } //returns true if any of the condition returns true if(count > 1 || count == 0) { found = false; break; } } if(found) System.out.println(num + " is a fascinating number."); else System.out.println(num + " is not a fascinating number."); } }
a567954649a907cfa21f0165c196170e16f67d76
[ "Java" ]
1
Java
itskhushis1/javaprograms
4487e3c397a2cfcce5abaf876c5e84fea5590344
d3850312c839b989162119e22d764afdd1dcfde7
refs/heads/master
<file_sep>React Antd 入門文件 ## 相關文件 - This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) - A UI Design Language and React UI library [antd](https://ant.design/components/card/) - A declarative, efficient, and flexible JavaScript library for building user interfaces [react](https://reactjs.org/) ## Demo - [preview](https://skycloud1030.github.io/react-antd/) - [code](https://github.com/skycloud1030/react-antd/blob/master/src/App.js) ## 安裝 - 需要安裝 Node.js - 需要安裝相關套件 ```sh npm install || yarn install ``` ## 網站啟動 - 會啟動 sever 做測試頁面 - http://localhost:5000/ - port 可在 .env 修改 ```sh npm start ``` ## 網站實際輸出 - 會壓縮 && 最小化程式碼 ```sh npm run build ``` <file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "0e5ed3ca4dfcd84d334b66e3d09a4024", "url": "/react-antd/index.html" }, { "revision": "39f6fe0d4cbc5e0b29f2", "url": "/react-antd/static/css/2.31686bb5.chunk.css" }, { "revision": "2d309446bb4a3e7e9766", "url": "/react-antd/static/css/main.4950a8de.chunk.css" }, { "revision": "39f6fe0d4cbc5e0b29f2", "url": "/react-antd/static/js/2.350fc8b3.chunk.js" }, { "revision": "bfc08a62983de46a4daec9f8c3c657d8", "url": "/react-antd/static/js/2.350fc8b3.chunk.js.LICENSE.txt" }, { "revision": "2d309446bb4a3e7e9766", "url": "/react-antd/static/js/main.054fb569.chunk.js" }, { "revision": "6e5825c9b0760a400233", "url": "/react-antd/static/js/runtime-main.1ea2b9b5.js" } ]);<file_sep>const repositories = [ "react-bootstrap-carousel", "array-includes-any", "react-shields-badge", "react-selectlist", "react-loadingmask" ]; export default repositories;
3577ffec1bb65b70f1daf74fbb56dc8ff4aa7e5f
[ "Markdown", "JavaScript" ]
3
Markdown
skycloud1030/react-antd
6d2b40831404700917106cc901cec1a7139671a1
e457aad987a7ba9b9fc4ca34618bd3b698fcf561
refs/heads/master
<file_sep>import blackjack.*; import cardgame.*; public class Runner { public static void main(String[] args) { Viewer viewer = new Viewer(); viewer.intro(); Playable game = new Game(viewer.getPlayerName(), "Dealer"); game.dealCards(); viewer.displayHand(game); game.nextPlayer(); viewer.displayHand(game); viewer.completeRound(game); } } <file_sep>puts "" system "cd bin && java Runner" <file_sep>import blackjack.*; import static org.junit.Assert.assertEquals; import org.junit.*; public class RankTest { private Rank ace, one, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king; @Before public void before() { ace = Rank.ACE; two = Rank.TWO; three = Rank.THREE; four = Rank.FOUR; five = Rank.FIVE; six = Rank.SIX; seven = Rank.SEVEN; eight = Rank.EIGHT; nine = Rank.NINE; ten = Rank.TEN; jack = Rank.JACK; queen = Rank.QUEEN; king = Rank.KING; } @Test public void aceHasCorrectName() { assertEquals("Ace", ace.getName()); } @Test public void aceHasCorrectScore() { assertEquals(11, ace.getScore()); } @Test public void twoHasCorrectName() { assertEquals("Two", two.getName()); } @Test public void twoHasCorrectScore() { assertEquals(2, two.getScore()); } @Test public void threeHasCorrectName() { assertEquals("Three", three.getName()); } @Test public void threeHasCorrectScore() { assertEquals(3, three.getScore()); } @Test public void fourHasCorrectName() { assertEquals("Four", four.getName()); } @Test public void fourHasCorrectScore() { assertEquals(4, four.getScore()); } @Test public void fiveHasCorrectName() { assertEquals("Five", five.getName()); } @Test public void fiveHasCorrectScore() { assertEquals(5, five.getScore()); } @Test public void sixHasCorrectName() { assertEquals("Six", six.getName()); } @Test public void sixHasCorrectScore() { assertEquals(6, six.getScore()); } @Test public void sevenHasCorrectName() { assertEquals("Seven", seven.getName()); } @Test public void sevenHasCorrectScore() { assertEquals(7, seven.getScore()); } @Test public void eightHasCorrectName() { assertEquals("Eight", eight.getName()); } @Test public void eightHasCorrectScore() { assertEquals(8, eight.getScore()); } @Test public void nineHasCorrectName() { assertEquals("Nine", nine.getName()); } @Test public void nineHasCorrectScore() { assertEquals(9, nine.getScore()); } @Test public void tenHasCorrectName() { assertEquals("Ten", ten.getName()); } @Test public void tenHasCorrectScore() { assertEquals(10, ten.getScore()); } @Test public void jackHasCorrectName() { assertEquals("Jack", jack.getName()); } @Test public void jackHasCorrectScore() { assertEquals(10, jack.getScore()); } @Test public void queenHasCorrectName() { assertEquals("Queen", queen.getName()); } @Test public void queenHasCorrectScore() { assertEquals(10, queen.getScore()); } @Test public void kingHasCorrectName() { assertEquals("King", king.getName()); } @Test public void kingHasCorrectScore() { assertEquals(10, king.getScore()); } } <file_sep>package blackjack; import java.util.*; public class Player { private Hand hand; private String name; public Player(String name) { this.hand = new Hand(); this.name = name; } public Hand getHand() { return this.hand; } public String getName() { return this.name; } public void takeCards(Deck deck, int numberToTake) { for (int i = 0; i < numberToTake; i++) { hand.add(deck.removeCard()); } } } <file_sep>import blackjack.*; import static org.junit.Assert.*; import org.junit.*; public class PlayerTest { Player player; Deck deck; @Before public void before() { player = new Player("Eoghan"); deck = new Deck(); } @Test public void hasname() { assertEquals("Eoghan", player.getName()); } @Test public void hasEmptyHandOnInit() { assertEquals(0, player.getHand().getCards().size()); } @Test public void canTakeCardFromDeck() { player.takeCards(deck, 1); assertEquals(1, player.getHand().getCards().size()); assertEquals(51, deck.cardCount()); } @Test public void canTakeMultipleCardsFromDeck() { player.takeCards(deck, 4); assertEquals(4, player.getHand().getCards().size()); assertEquals(48, deck.cardCount()); } } <file_sep>package blackjack; import java.util.*; public class Deck { ArrayList<Card> cards; public Deck() { this.cards = new ArrayList<Card>(); for (Suit suit : Suit.values()) { for (Rank rank : Rank.values()) { Card newCard = new Card(suit, rank); cards.add(newCard); } } this.shuffle(); } public ArrayList<Card> getCards() { return this.cards; } public int cardCount() { return this.getCards().size(); } public void shuffle(){ Collections.shuffle(this.cards); } public Card removeCard() { if (cardCount() > 0) { return this.cards.remove(0); } return null; } } <file_sep>import blackjack.*; import static org.junit.Assert.*; import org.junit.*; public class HandTest { Hand hand, hand2, hand3, hand4; Card card, card2, card3, card4; @Before public void before() { hand = new Hand(); hand2 = new Hand(); hand3 = new Hand(); hand4 = new Hand(); card = new Card(Suit.DIAMONDS, Rank.TWO); card2 = new Card(Suit.HEARTS, Rank.KING); card3 = new Card(Suit.CLUBS, Rank.ACE); card4 = new Card(Suit.HEARTS, Rank.KING); hand2.add(card); hand2.add(card2); hand3.add(card); hand3.add(card2); hand3.add(card3); hand4.add(card); hand4.add(card2); hand4.add(card4); } @Test public void isEmptyOnInit() { assertEquals(0, hand.getCards().size()); } @Test public void canAddCard() { hand.add(card); assertEquals(1, hand.getCards().size()); } @Test public void canCalculateValue() { assertEquals(12, hand2.calculateValue()); } @Test public void isBustreturnsFalse__valueUnderTwentyOne() { assertEquals(false, hand2.isBust()); } @Test public void isBustreturnsFalse__valueOverTwentyOne_withAceValueUnchanged() { assertEquals(false, hand3.isBust()); } @Test public void isBustreturnsTrue__valueOverTwentyOne_noAces() { assertEquals(true, hand4.isBust()); } @Test public void canChangeValuesOfAcesInHand() { hand3.changeAceValues(); assertEquals(13, hand3.calculateValue()); } } <file_sep>import blackjack.*; import static org.junit.Assert.assertEquals; import org.junit.*; public class SuitTest { Suit hearts, diamonds, clubs, spades; @Before public void before() { hearts = Suit.HEARTS; diamonds = Suit.DIAMONDS; clubs = Suit.CLUBS; spades = Suit.SPADES; } @Test public void heartsHasCorrectName() { assertEquals("Hearts", hearts.getName()); } @Test public void diamondsHasCorrectName() { assertEquals("Diamonds", diamonds.getName()); } @Test public void clubsHasCorrectName() { assertEquals("Clubs", clubs.getName()); } @Test public void spadesHasCorrectName() { assertEquals("Spades", spades.getName()); } } <file_sep>package blackjack; import cardgame.*; import java.util.*; public class Viewer { Scanner in; public Viewer() { in = new Scanner(System.in); } public void intro() { System.out.println("Thanks for choosing to play blackjack."); } public String getPlayerName() { System.out.println(""); System.out.println("What is your name?"); String name = in.nextLine(); System.out.println(""); System.out.println("Your name is " + name + "? (y/n)"); String nameConfirmation = in.nextLine(); if (nameConfirmation.equals("y")) { return name; } else { name = this.getPlayerName(); return name; } } public void displayHand(Playable game) { System.out.println(""); System.out.println(game.getCurrentPlayer().getName() + " has the following cards:"); for (Card card : game.getCurrentPlayer().getHand().getCards()) { System.out.println(card.getDescription()); } System.out.println(""); System.out.println("The total value of your hand is " + game.getCurrentPlayer().getHand().calculateValue()); } public void completeRound(Playable game) { Player winner = game.determineBestHand(); System.out.println(""); System.out.println(winner.getName() + " is the Winner."); } }
1ed0b79071d99921bbd6db63f78e6f9a8b16ce73
[ "Java", "Ruby" ]
9
Java
eoghanscrowley/BlackJack
5667c416dbaf85da776529869567f34e509c8ee6
6d01ffdee09d8418ff417f3ad47efc877038ea65
refs/heads/master
<file_sep>using System; using System.Collections.Generic; namespace averagepair { class Program { static void Main(string[] args) { var arr1 = new List<int>() { 1, 2, 3, 5, 6, 8, 9 }; var arr2 = new List<int>() { -1, 3, 5, 7, 9 }; var arr3 = new List<int>() { 2, 5, 7, 11 }; int target = 4; Console.WriteLine(AveragePair(arr1, target)); Console.WriteLine(AveragePair(arr2, target)); Console.WriteLine(AveragePair(arr3, target)); } static bool AveragePair(List<int> arr, int target) { if (arr.Count < 2) return false; int right = arr.Count - 1; int left = 0; int average = -1; do { average = (arr[right] + arr[left]); if (average == target * 2) { return true; } else if (average > target * 2) { right--; } else { left++; } } while (right > left); return false; } } }<file_sep>//write function that accepts two arrays //function should return true if every value in the array has its corresponding value squared in the second array //frequency of values must be the same, but order does not matter function same(arr1, arr2) { //checking to see if the length of both arrays are equal; if they're not, then automatically false if (arr1.length !== arr2.length) { return false; } let frequencyCounter1 = {}; let frequencyCounter2 = {}; //looping through first array and... for (let num of arr1) { //num is the key and we are finding the value at that key --> value in this case is the frequency that the num appears // the value will equal the frequency, otherwise if it's not in the object it will be zero //each time you are at that key, you will increment 1 (keeps tally of the frequency) frequencyCounter1[num] = (frequencyCounter1[num] || 0) + 1 } //repeat the loop with arr2 (these loops are separated, which is better than a nested loop) --> time complexity is O(N) for (let num of arr2) { frequencyCounter2[num] = (frequencyCounter2[num] || 0) + 1 } console.log(frequencyCounter1) console.log(frequencyCounter2) //looping through the keys in the first object and... for (let key in frequencyCounter1) { // if the key^2 (ie num^2) is not in the second object, return false because no matching number if (!(key ** 2 in frequencyCounter2)) { return false; } //if the frequency of the number in the second object is not equal to the frequency of the number in the first object we know it's not the same frequency in both objects so can return false if (frequencyCounter2[key ** 2] !== frequencyCounter1[key]) { return false; } } return true; } array1 = [1, 2, 3, 2, 2] array2 = [9, 1, 4, 4, 5] const isThere = same(array1, array2) console.log(isThere)<file_sep>/* M I N S U B A R R A Y L E N G T H This function should return the minimal length of a contiguous subarray of which the sum is greater than or equal to the integer passed to the function. If there isn't one, return 0 instead. Time: O(n) Space: O(1) */ const minSubArrayLen = (arr, target) => { if (arr.length < 1) return 0 // 1. Instantiate the beginning of the window let left = 0 let sum = arr[left] // 2. Instantiate our length variable at a high number to allow for lower matches let len = arr.length + 1 // 3. Check if first member meets the target by itself if (sum >= target) { return 1 } // 4. Iterate right pointer from 1 to the end. This will be the right boundary of the window. // The window may grow or shrink in size as the function progresses. for (let right = 1; right < arr.length; right++) { // 5. Add right pointer to cumulative sum and compare to target sum += arr[right] if (sum >= target) { // 6. If it's a match, start moving left pointer and subtracting values until it is no longer a match or equal to right pointer do { sum -= arr[left] left++ } while (sum >= target && left <= right) // 7. Record length of the previous match return if length === 1, or continue iterating through the remaining array members /* When we exit the while loop, the left pointer is one farther left than the last successful subarray, so add 1. Then, the number of elements is 1 greater than the raw difference between the left and right indices. Net result: add 2 to the difference between the two indices. */ len = Math.min(len, right - left + 2) // A positive match will never be less than one, so return if the length is 1 if (len === 1) return len } } // Since we instantiated len as (arr.length + 1), if this has not changed, no match was found. Return 0. return (len > arr.length) ? 0 : len } console.log(minSubArrayLen([2, 3, 1, 2, 4, 3], 7)) console.log(minSubArrayLen([3, 1, 7, 11, 2, 9, 8, 21, 62, 33, 19], 52)) console.log(minSubArrayLen([2, 1, 6, 5, 4], 9))<file_sep>/* F I B O N A C C I Find the nth degree in the Fibonacci sequence Time: O(2^n) Space: O(n) */ // 1. Take in an argument for the 'nth' degree function fib(deg) { //2. Establish a base case if (deg <= 2) return 1 //3. Establish answer via recursive calls return fib(deg - 1) + fib(deg - 2) } console.log(fib(4)) console.log(fib(10)) console.log(fib(28)) console.log(fib(35)) <file_sep>/* C O U N T U N I Q U E V A L U E S Count the number of unique values in a SORTED array. Space: O(1) Time: O(n) */ const countUniqueValues = (arr) => { // Set left counter at the beginning. It will increment as needed. let i = 0; // Set the right counter at the second index. It will traverse the full array. for (let j = 1; j < arr.length; j++) { // If the value at index j is not equal to the value at index i, a unique value has been found. // We will mutate the array to track the unique values. // For each match, increment i by one and replace the value at that index with the unique value at index j. if (arr[i] !== arr[j]) { i++ arr[i] = arr[j] } // If the values are equal, the value at index j is not unique. Continue the loop. j increments by 1 upon the next iteration. } // Since we have been tracking unique values with i, we can simply use its ending position to determine the count. Since i is // the index, add one for the total count. return i + 1 } console.log(countUniqueValues([1, 1, 1, 2, 2, 3, 3]))<file_sep>/* A R E T H E R E D U P L I C A T E S See if there are any duplicates in a set of arguments and return true if a duplicate pair is found. The function should accept any number of arguments. Time: O(n) Space: O(1) */ // The original problem states that it can be solved using frequency counters or multiple pointers. // This solution uses frequency counters. function areThereDuplicates() { // Instantiate an object to keep track of existing values. const counterObject = {} // Use the 'arguments' object to iterate through any arguments passed in to the function for (let i = 0; i < arguments.length; i++) { if (counterObject[arguments[i]]) { // If the value already exists as a key in counterObject, it is a duplicate. return true } else { // Create a key to represent the arguments value. The object value can be anything; we just need to show // that this key exists. counterObject[arguments[i]] = 1 } } // If we have made it this far, there are no duplicates. return false } console.log(areThereDuplicates(1, 2, 3)) console.log(areThereDuplicates(1, 2, 1, 1)) console.log(areThereDuplicates('a', 'b', 'hello', 'b')) /* Fun solution from the problem source. This does not incorporate either approach, but uses the Set object in JavaScript to create a duplicate-less set. It then compares that Set's size to the original argument set's length. If they are the same, there are no duplicates. Different sizes means there are duplicates. function areThereDuplicates() { return new Set(arguments).size !== arguments.length } */ <file_sep>/* A V E R A G E P A I R Given a SORTED array and a target average, determine if the average of any two members of the array equals the target. Return true/false. This is a 'multiple pointers' practice problem. Time: O(n) Space: O(1) */ function averagePair(arr, target) { //1. Check for empty array if (arr.length === 0) return false //2. Instantiate our two pointers at the beginning and end of the array let left = 0 let right = arr.length - 1 //3. Iterate through the array. If the two pointers meet, we have traversed the full array. while (left < right) { //4. Calculate the average of the two pointers. We will compare this to the target. const average = (arr[left] + arr[right]) / 2 //5. If it's a match, return true if (average === target) { return true } else if (average < target) { //6. If the current average is too low, move the left pointer, and vice versa left++ } else { right-- } } //7. If we make it to the end without a match, return false return false } console.log(averagePair([1, 2, 3], 2.5)) console.log(averagePair([1, 2, 3, 4, 5, 6, 7, 8], 1.5)) console.log(averagePair([-2, -1, 2, 3, 6], 7)) console.log(averagePair([], 0))<file_sep>/* A N A G R A M Frequency counter practice exercise. Check if two strings are anagrams of each other. For the purpose of this function, the strings contain a single word with no spaces or punctuation, and all the characters are lowercase. */ function validAnagram(str1, str2) { // 1. Compare lengths of two strings if (str1.length !== str2.length) { return false } // 2. Instantiate frequency counter objects const counterObject1 = {} const counterObject2 = {} // 3. Loop through each string and assign characters to counter objects as keys for (let i = 0; i < str1.length; i++) { const character = str1.charAt(i) // If the character is already present as a key, add 1 to its value. If not, the value is undefined, so set the value to 0 and add 1) counterObject1[character] = (counterObject1[character] || 0) + 1 } for (let i = 0; i < str2.length; i++) { const character = str2.charAt(i) counterObject2[character] = (counterObject2[character] || 0) + 1 } // 4. Use for/in on first counter object and compare keys to second counter object for (let key in counterObject1) { if (!key in counterObject2) { return false } if (counterObject1[key] !== counterObject2[key]) { return false } } return true } // Demonstration 1 - returns 'false' because the quantities of each character differ str1 = "aaz" str2 = "zza" console.log(validAnagram(str1, str2)) // Demonstration 2 - returns 'true' str3 = "texttwisttime" str4 = "timetwisttext" console.log(validAnagram(str3, str4))<file_sep>/* R E V E R S E S T R I N G Given a string, reverse the characters in the string so that it reads backwards from the given input. Time: O(N) Space: O(1) */ // SOLUTION 1: Slightly better performance (only iterates through the string once), harder to read const reverseString = (str) => { // 1. Create a new variable to hold the new string let newString = "" // 2. Iterate through the given string, starting at the end for (let i = str.length - 1; i >= 0; i--) { // 3. Add character at 'i' to new string variable newString += str[i] } return newString } // SOLUTION 2: Using built-in methods, easier to read. Much cleaner. Iterates through full string for each method. const reverseString2 = (str) => { // 'Split' string into an array of its characters, Reverse the array, than Join back into a string return str.split("").reverse().join("") } console.log(reverseString("abc")) console.log(reverseString("Tacocat")) console.log(reverseString("nam daed ,no em nruT"))<file_sep>/* R E C U R S I V E R A N G E Find the sum of all numbers from 0 to a given number using a recursive function. Time: O(n), Space: O(n)*/ function recursiveRange(num) { // 1. Establish a base case if (num === 0) return 0 // 2. Recursive call/different number return num + recursiveRange(num - 1) } // SAMPLE INPUT/OUTPUT console.log(recursiveRange(6)) // 21 console.log(recursiveRange(10)) // 55 <file_sep> function reverse(str) { // add whatever parameters you deem necessary - good luck! array = str.split("") reverseStr = [] function reverseArray(arr) { // 1. Base case if (arr.length === 0) return // 2. Recursive call reverseStr.unshift(arr[0]) return reverseArray(arr.slice(1)) } // 2.5 Call helper function reverseArray(array) // 3. Join reversed array and return the result return reverseStr.join("") } function reverse2(str) { if (str.length === 0) return "" return str[str.length - 1] + reverse2(str.substring(0, str.length - 1)) // Udemy answer: return reverse2(str.slice(1)) + str[0]) } console.log(reverse2('awesome')) // 'emosewa' console.log(reverse2('rithmschool')) // 'loohcsmhtir' <file_sep># Morning Algorithms ## Open to all students of Nashville Software School This is the public GitHub repo for Morning Algorithms at NSS. We meet every weekday at 8:00 am. All code that we work on in the sessions will be posted here for review. If you are a part of the sessions, feel free to push your own code and make/request changes. In particular, feel free to add any comments that you find helpful. ### Joining We have a Slack channel on NSS, Morning-Algorithms-C41. Feel free to message us there, or find me (<NAME>) on Slack. If you are brand new to algorithms and algorithm complexity, I strongly recommend that you watch some videos about complexity and "Big O" notation. This will help explain why we use many of the concepts we are learning. Slack me, and I can provide some additional resources. ### Concepts So far, this repo contains code for the following concepts: #### [Binary Search](https://github.com/dLars99/Morning-Algorithms/blob/master/binary-search/binarySearch.js) An optimized search to find a value in a sorted array. #### [Frequency Counter](https://github.com/dLars99/Morning-Algorithms/blob/master/frequencyCounter/frequencyCounter.js) Determine if the values in one array all correspond to squares of those values in a second array. Introduction to the concept of "Frequency Counters" #### [Anagram](https://github.com/dLars99/Morning-Algorithms/tree/master/anagram/anagram.js) Determine if two strings are anagrams of one another using frequency counters. #### [Binary Search](https://github.com/dLars99/Morning-Algorithms/tree/master/binary-search/binarySearch.js) Search method to find a value in a sorted array by dividing the array into resultant halves. #### [Count Unique Values](https://github.com/dLars99/Morning-Algorithms/tree/master/countUniqueValues/countUniqueValues.js) Count the number of unique values in a sorted array. Introduction to the concept of "Multiple Pointers." #### [Max Sum](https://github.com/dLars99/Morning-Algorithms/tree/master/maxSum-slidingWindow/maxSum.js) Given an array, find the subarray of a given size with the highest sum. Demo exercise for the "Sliding Window" concept. #### [Duplicates](https://github.com/dLars99/Morning-Algorithms/tree/master/duplicates/duplicates.js) Determine if any duplicates exist in a list of arguments. #### [Reverse String](https://github.com/dLars99/Morning-Algorithms/tree/master/reverseString/reverseString.js) Reverse the characters in a string. #### [Average Pair](https://github.com/dLars99/Morning-Algorithms/tree/master/averagePair/averagePair.js) See if the average of any pair of numbers in an array matches a target average. Also completed in [C#](https://github.com/dLars99/Morning-Algorithms/tree/master/csharp/averagepair) #### [Is A Subsequence](https://github.com/dLars99/Morning-Algorithms/tree/master/isSubsequence/isSubsequence.js) Determine if all the characters of the first string are present, in order, in a second string. #### [Min Subarray Length](https://github.com/dLars99/Morning-Algorithms/tree/master/minSubArrayLen/minSubArrayLen.js) Find the length of the smallest subarray within a given array whose members add to a total greater than or equal to a target integer. #### [Product of Array](https://github.com/dLars99/Morning-Algorithms/tree/master/productOfArray/productOfArray.js) Find the product of all numbers within an array using a recursive solution. #### [Fibonacci](https://github.com/dLars99/Morning-Algorithms/tree/master/fib/fib.js) Find the nth degree of the Fibonacci sequence using a recursive solution. #### [Recursive Range](https://github.com/dLars99/Morning-Algorithms/tree/master/recursiveRange/recursiveRange.js) Find the sum of all numbers from 0 to __n__ using a recursive solution. #### [Singly Linked Lists](https://github.com/dLars99/Morning-Algorithms/tree/master/linked-list/linked-list.js) Singly Linked List data structure. Constructor plus methods for push, pop, shift, unshift, get, set, insert, remove, and reverse. <file_sep>//Problem: Write a function that accepts an array of integers (arr) and a number (num) that calculates the maximum sum of num consecutive elements in the array //function taking in an array (positive and/or negative) and num, which is the number of consecutive numbers in the array that should be added together //ie if num is 3 we would be taking the sum of three consecutive numbers in the array function maxSubarraySum(arr, num) { //instanstiate maxSum which will keep track of the MAX sum of the numbers being added together let maxSum = 0; //instanstiate tempSum which will keep track of the sum of the number being added together with each iteration through the loops let tempSum = 0; //edge case - if the array length is less than the value of num, we will automatically know there are not enough numbers to sum //therefore, return null if (arr.length < num) return null; //iterate through the first three numbers to get our first sum, which will be added to tempSum //in the array below it would be summing up index 0, 1, and 2 (values 2, 6, 9 respectively) for (let i = 0; i < num; i++) { tempSum += arr[i]; } //maxSum will be assigned the value of tempSum maxSum = tempSum; //iterate through the same array NOW starting at index of num (ie in array below will be starting with index 3 with value of 2) for (let i = num; i < arr.length; i++) { // tempSum will be assigned value of tempSum (currently equal to 17) - arr[3-3] (i is equal to 3 and num is equal to 3) + arr[3] (the value at index 3 is 2): // this creates a 'sliding window', which takes the current tempSum and subtracts the value at the first index in the sum sequence and then "moves" the window // and adds the value at the new index (which will make up the next 3 consecutive numbers; in the array below that new index will be 3 with a value of 2) tempSum = tempSum - arr[i - num] + arr[i]; // Math.max will find the larger value between maxSum and current tempSum; if the maxSum is greater than tempSum, maxSum will just stay the same; // otherwise, maxSum will be assigned the current value tempSum maxSum = Math.max(maxSum, tempSum); } //after iterations finished whatever the maxSum is, return it return maxSum; } console.log(maxSubarraySum([2, 6, 9, 2, 1, 8, 5, 6, 3], 3)) <file_sep># Technical Interview Questions ## A compilation This list is a compilation of technical interview questions received by members of this cohort. Feel free to add to this list. I have attempted to classify the questions in a meaningful manner, though any suggestions are welcome. ### Vocabulary - Define Agile (vs. waterfall?) - Define Scrum ### Projects/Implementation - How would you build this project? - How would you handle user authentication (username/password)? (Answer: you don't!) <file_sep># Behavioral Interview Questions ## A compilation This list is a compilation of behavioral interview questions received by members of this cohort. Feel free to add to this list. I have attempted to classify the questions in a meaningful manner, though any suggestions are welcome. ### General - Tell me about yourself - Why development/NSS/software? - Where do you want to be in 1 year/5 years/10 years? ### Situational - Is there a type of team member you would not want to work with - If you had to work with that type of teammate above, how would you handle it? - What are your workplace stressors? How do you handle those? - How would you handle conflicting instructions from two different people? - If you have a full slate and are told to add another project, and another team member is currently assigned to one project but could work better with another, how would you handle that? ### Project-based - Tell me about a time when you had to get from A to B, and when you got to B, it turned out to me more than you anticipated - Tell me about the process on <project x> ### Company/Team-based - What kind of team/company are you hoping to look for? - Where do you see yourself on a team? <file_sep>/* <NAME> <NAME> L I S T Constructing the data structure of the singly linked list. So far, our list includes the following methods: - Constructor - Push - Pop */ // Node class - the linked list is built of member 'Nodes' // piece of data - val // reference to next node - next class Node{ constructor(val){ this.val = val; this.next = null; } } // The linked list itself, starting with a constructor to initialize an empty list // Head - the first item in the list // Tail - the last item in the list // Length - number of member Nodes class SinglyLinkedList{ constructor(){ this.head = null; this.tail = null; this.length = 0; } // 'push' to add a new value to the end of the list push(val){ /* Our solution if (this.length === 0) { this.head = new Node(val); this.tail = this.head; } else if (this.length === 1) { this.tail = new Node(val); this.head.next = this.tail; } else { let oldTail = this.tail; this.tail = new Node(val); oldTail.next = this.tail; } */ // Their solution // 1. Instantiate a new Node const newNode = new Node(val); if (!this.head) { // 2a. Set head and tail to new node if the list is empty this.head = newNode; this.tail = this.head; } else { // 2b. Connect the old tail to the new node and set it to the new tail this.tail.next = newNode; this.tail = newNode; } // 3. Increase the length this.length++; // 4. Return the list return this; } // 'pop' to remove the last item from the list pop() { // If no nodes, return undefined if (this.length === 0) return undefined; // Loop through until you reach the tail let current = this.head; let prev; while (current.next !== null) { prev = current; current = current.next; } // Set the next property of the 2nd to last node to be null prev.next = null; // Set the tail to the 2nd to last node this.tail = prev; // Decrement length this.length--; // If all items are removed... if (this.length === 0) { this.head = null; this.tail = null; } // Return the value of the removed node return current.val; } // Shift - removing a node from the beginning of the list shift() { // If no nodes, return undefined if (!this.head) return undefined; // Store the current head in a variable let currentHead = this.head; // Set the head to be the current head's next node this.head = currentHead.next; // Decrement length this.length--; // If all items are removed... if (this.length === 0) { this.head = null; this.tail = null; } // Return value of removed node return currentHead.val; } // Unshift - add to the beginning unshift(val) { // Create a new node using the value const newHead = new Node(val); // If there is no head, set the head and tail if (!this.head) { this.head = newHead; this.tail = newHead; } else { // Set new node's next propery to the current head newHead.next = this.head; // Set the head to the new node this.head = newHead; } // Increment length this.length++; // Return the linked list return this; } // Get - retrieve a node by its position get(idx) { // If index is less than zero, or greater than the length, return null if (idx < 0 || idx >= this.length ) return null; // Loop through list until you reach the index let currentNode = this.head; for (let i = 0; i < idx; i++) { currentNode = currentNode.next; } // Return node at that index return currentNode; } // Set - update the value at a given position set(idx, val) { // Use get to find the node const theNode = this.get(idx); // If the node is not found, return false if (!theNode) return false; // If found, update the value and return true theNode.val = val; return true; } // Insert - add a new node at a specific position insert(idx, val) { // If index is less than zero or greater than length, return false if (idx < 0 || idx > this.length) return false; // If index is same as length, push if (idx === this.length) return !!this.push(val); // If index is 0, unshift if (idx === 0) return !!this.unshift(val); // Otherwise, use get to retrieve index - 1 const prev = this.get(idx - 1); let newNode = new Node(val); // Set next node on the new node to be the next from the previous node indexNode = prev.next; newNode.next = indexNode; // Set the next property on the previous node to be the new node prev.next = newNode; // Increment length this.length++; // Return true return true; } // Remove - remove the node from a specific position remove(idx) { // If index is less than zero or greater than the length, return undefined if (idx < 0 || idx >= this.length) return null; // If index is same as length - 1, pop if (idx === this.length - 1) return this.pop(); // If index is zero, shift if (idx === 0) return this.shift(); // Otherwise, use get to find index - 1 const prev = this.get(idx - 1); // Set the next property to be the node after the indexed node const removedNode = prev.next; prev.next = removedNode.next; // Decrement length this.length--; // Return the value of the removed node return removedNode.val; } // Reverse - reverse the list in place reverse() { // Reassign the head -- it is now the tail this.tail = this.head; // SLIDING WINDOW // Create a current variable let current = this.tail; // Create a next variable let next; // Create a prev variable -- set to null so we can connect the new tail to it within the while loop let prev = null; // Loop while (current) { // Reverse the ".next" connections next = current.next; current.next = prev; // Move the window prev = current; current = next; } // Reassign the head property this.head = prev; return this; } // Print - display the linked list in the console print() { let current = this.head; console.log(current.val) while(current.next) { current=current.next; console.log(" --> " + current.val) } } /* Sample code to traverse the list, taken from the Udemy course traverse() { var current= this.head; while (current) { console.log(current.val); current = current.next; } } */ } var list = new SinglyLinkedList() list.push("HELLO") list.push("???") list.push("GOODBYE") list.push("!!!!") console.log(list.reverse()); list.print(); <file_sep>const binarySearch = (arr, target) => { let left = 0 let right = arr.length - 1 let middle // if (arr[left] === target || arr[right] === target) { // return true // } while (left <= right) { middle = Math.floor((left + right) / 2) if (target === arr[middle]) { return middle } else if (arr[middle] < target) { left = middle + 1 } else if (arr[middle] > target) { right = middle - 1 } } return false } const arr = [ -3, -1, 0, 3, 5, 16, 27, 33] console.log(binarySearch(arr, 57))
9db905b6a56974c2a81a1301711a33ca596a9489
[ "JavaScript", "C#", "Markdown" ]
17
C#
dLars99/Morning-Algorithms
14588db9892ab95335a304fb926f8ecbec0b891c
01ad584618234a098dcf5aad7317ed109631758e
refs/heads/master
<repo_name>iv-mexx/ReactiveAnimation<file_sep>/README.md # ReactiveAnimation [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) Declarative animations using [ReactiveCocoa](https://github.com/ReactiveCocoa/ReactiveCocoa) signals. See the [Mac demo](https://github.com/ReactiveCocoa/ReactiveAnimation-MacDemo) for an example of how the library works. ReactiveAnimation is released under the [MIT license](LICENSE.md). ### Getting Started To import the ReactiveAnimation framework, add `ReactiveAnimation.xcodeproj` as a subproject and add the appropriate framework target to your application. Alternatively, you can use [Carthage](https://github.com/Carthage/Carthage) to build the framework for you. <file_sep>/ReactiveAnimationDemo_iOS/ViewController.swift // // ViewController.swift // ReactiveAnimationDemo_iOS // // Created by <NAME> on 16/06/2017. // Copyright © 2017 Innovaptor OG. All rights reserved. // import UIKit import ReactiveSwift import ReactiveCocoa import ReactiveAnimation class ViewController: UIViewController { @IBOutlet weak var label: UILabel! private func randomPoint() -> CGPoint { let random: (CGFloat) -> CGFloat = { max in return CGFloat(arc4random_uniform(UInt32(max))) } let x = random(view.frame.size.width) let y = random(view.frame.size.height) return CGPoint(x: x, y: y) } override func viewDidLoad() { super.viewDidLoad() label.reactive.center <~ SignalProducer.timer(interval: .seconds(1), on: QueueScheduler.main) .map { _ in return self.randomPoint() } // In order to demonstrate different flatten strategies, // the animation duration is larger than the animation interval, // thus a new animation begins before the running animation is finished .animateEach(duration: 1.5, curve: .EaseInOut) // With the .concat flatten strategy, each animations are concatenated. // Each animation finisheds, before the next one starts. // This also means, that animations are queued .flatten(.concat) // With the .merge flatten strategy, each animation is performed immediately // If an animation is currently running, it is cancelled and the next animation starts from the current animation state // .flatten(.merge) } } <file_sep>/ReactiveAnimationTests/SwiftJunk.swift // // SwiftJunk.swift // ReactiveAnimation // // Created by <NAME> on 2015-03-22. // Copyright (c) 2015 ReactiveCocoa. All rights reserved. // import Foundation import LlamaKit import ReactiveCocoa import XCTest // Forces Xcode to link the Swift stdlib. final class SwiftJunkSpec: XCTestCase {} <file_sep>/ReactiveAnimation/Animation.swift // // Animation.swift // ReactiveAnimation // // Created by <NAME> on 2015-03-22. // Copyright (c) 2015 ReactiveCocoa. All rights reserved. // #if os(OSX) import AppKit public typealias AnimationCurveRawValue = Int #elseif os(iOS) import UIKit public typealias AnimationCurveRawValue = UIViewAnimationCurve.RawValue #endif import ReactiveSwift import ReactiveCocoa import enum Result.NoError /// Creates an animated SignalProducer for each value that arrives on /// `producer`. /// /// The `JoinStrategy` used on the inner producers will hint to /// ReactiveAnimation whether the animations should be interruptible: /// /// - `Concat` will result in new animations only beginning after all previous /// animations have completed. /// - `Merge` or `Latest` will start new animations as soon as possible, and /// use the current (in progress) UI state for animating. /// /// These animation behaviors are only a hint, and the framework may not be able /// to satisfy them. /// /// However the inner producers are joined, binding the resulting stream of /// values to a view property will result in those value changes being /// automatically animated. /// /// To delay an animation, use delay() or throttle() _before_ this function. /// Because the aforementioned operators delay delivery of `Next` events, /// applying them _after_ this function may cause values to be delivered outside /// of any animation block. /// /// Examples /// /// RAN(self.textField).alpha <~ alphaValues /// |> animateEach(duration: 0.2) /// /* Animate alpha without interruption. */ /// |> join(.Concat) /// /// RAN(self.button).alpha <~ alphaValues /// /* Delay animations by 0.1 seconds. */ /// |> delay(0.1) /// |> animateEach(curve: .Linear) /// /* Animate alpha, and interrupt for new animations. */ /// |> join(.Latest) /// /// Returns a producer of producers, where each inner producer sends one `next` /// that corresponds to a value from the receiver, then completes when the /// animation corresponding to that value has finished. Deferring the events of /// the returned producer or having them delivered on another thread is considered /// undefined behavior. extension Signal { public func animateEach(duration: TimeInterval? = nil, curve: AnimationCurve = .Default) -> Signal<SignalProducer<Value, NoError>, Error> { return self.map { value in return SignalProducer { observer, lifetime in OSAtomicIncrement32(&runningInAnimationCount) lifetime.observeEnded { OSAtomicDecrement32(&runningInAnimationCount) } #if os(OSX) NSAnimationContext.runAnimationGroup({ context in if let duration = duration { context.duration = duration } if curve != .Default { context.timingFunction = CAMediaTimingFunction(name: curve.mediaTimingFunction) } observer.send(value: value as! Value) // TODO: Why is the downcast necessary? }, completionHandler: { // Avoids weird AppKit deadlocks when interrupting an // existing animation. UIScheduler().schedule { observer.sendCompleted() } }) #elseif os(iOS) var options: UIViewAnimationOptions = [ UIViewAnimationOptions(rawValue: UInt(curve.rawValue)), .layoutSubviews, .beginFromCurrentState] if curve != .Default { options.formUnion(.overrideInheritedCurve) } UIView.animate(withDuration: duration ?? 0.2, delay: 0, options: options, animations: { observer.send(value: value as! Value) // TODO: Why is the downcast necessary? }, completion: { finished in if(finished) { observer.sendCompleted() } else { observer.sendInterrupted() } }) #endif } } } } extension SignalProducer { public func animateEach(duration: TimeInterval? = nil, curve: AnimationCurve = .Default) -> SignalProducer<SignalProducer<Value, NoError>, Error> { return self.lift { $0.animateEach(duration: duration, curve: curve) } } } /// The number of animated signals in the call stack. /// /// This variable should be manipulated with OSAtomic functions. private var runningInAnimationCount: Int32 = 0 /// Determines whether the calling code is running from within an animation /// definition. /// /// This can be used to conditionalize behavior based on whether a signal /// somewhere in the chain is supposed to be animated. /// /// This property is thread-safe. public var runningInAnimation: Bool { return runningInAnimationCount > 0 } /// Describes the curve (timing function) for an animation. public enum AnimationCurve: AnimationCurveRawValue, Equatable { /// The default or inherited animation curve. case Default = 0 /// Begins the animation slowly, speeds up in the middle, then slows to /// a stop. case EaseInOut case EaseIn case EaseOut case Linear // #if os(iOS) // case EaseInOut = UIViewAnimationCurve.EaseInOut.rawValue // #else // case EaseInOut // #endif // // /// Begins the animation slowly and speeds up to a stop. // case EaseIn // #if os(iOS) // = UIViewAnimationCurve.EaseIn // #endif // // /// Begins the animation quickly and slows down to a stop. // case EaseOut // #if os(iOS) // = UIViewAnimationCurve.EaseOut // #endif // // /// Animates with the same pace over the duration of the animation. // case Linear // #if os(iOS) // = UIViewAnimationCurve.Linear // #endif /// The name of the CAMediaTimingFunction corresponding to this curve. public var mediaTimingFunction: String { switch self { case .Default: return kCAMediaTimingFunctionDefault case .EaseInOut: return kCAMediaTimingFunctionEaseInEaseOut case .EaseIn: return kCAMediaTimingFunctionEaseIn case .EaseOut: return kCAMediaTimingFunctionEaseOut case .Linear: return kCAMediaTimingFunctionLinear } } } public func == (lhs: AnimationCurve, rhs: AnimationCurve) -> Bool { switch (lhs, rhs) { case (.Default, .Default), (.EaseInOut, .EaseInOut), (.EaseIn, .EaseIn), (.EaseOut, .EaseOut), (.Linear, .Linear): return true default: return false } } extension AnimationCurve: CustomStringConvertible { public var description: String { switch self { case .Default: return "Default" case .EaseInOut: return "EaseInOut" case .EaseIn: return "EaseIn" case .EaseOut: return "EaseOut" case .Linear: return "Linear" } } } <file_sep>/ReactiveAnimation/View.swift // // View.swift // ReactiveAnimation // // Created by <NAME> on 2015-03-22. // Copyright (c) 2015 ReactiveCocoa. All rights reserved. // #if os(OSX) import AppKit public typealias View = NSView #elseif os(iOS) import UIKit public typealias View = UIView #endif import ReactiveSwift import ReactiveCocoa import enum Result.NoError extension Reactive where Base: View { public var frame: BindingTarget<CGRect> { return makeBindingTarget { $0.frame = $1 } } public var bounds: BindingTarget<CGRect> { return makeBindingTarget { $0.bounds = $1 } } #if os(iOS) public var center: BindingTarget<CGPoint> { return makeBindingTarget { $0.center = $1 } } public var backgroundColor: BindingTarget<UIColor> { return makeBindingTarget { $0.backgroundColor = $1 } } public var transform: BindingTarget<CGAffineTransform> { return makeBindingTarget { $0.transform = $1 } } #endif public var alpha: BindingTarget<CGFloat> { return makeBindingTarget { #if os(OSX) $0.alphaValue = $1 #elseif os(iOS) $0.alpha = $1 #endif } } #if os(OSX) public var frameOrigin: BindingTarget<CGPoint> { return viewProperty { $0.setFrameOrigin($1) } } public var frameSize: BindingTarget<CGSize> { return viewProperty { $0.setFrameSize($1) } } public var boundsOrigin: BindingTarget<CGPoint> { return viewProperty { $0.setBoundsOrigin($1) } } public var boundsSize: BindingTarget<CGSize> { return viewProperty { $0.setBoundsSize($1) } } #endif }
ab7d2e46a020793c295e31f81af6e5462171e30a
[ "Markdown", "Swift" ]
5
Markdown
iv-mexx/ReactiveAnimation
eeee3b19dff603d230f185ad5fd97d556e6c9dfd
b9a7a64d4f0a2e3ef4e05b4f4b4332ca2f9db32b
refs/heads/master
<file_sep>import { CALL_API } from './enums'; export default () => { // eslint-disable-next-line no-restricted-globals self.addEventListener('message', e => { if (!e && e.data !== CALL_API) return; let { data } = e; fetch('https://jsonplaceholder.typicode.com/comments') .then(response => response.json()) .then(res => { console.log('res -> ', res) const list = res.filter( (item, idx) => { return item.email.includes(data); }); postMessage(list); }) .catch(error => postMessage(null)); }) }<file_sep>export const CALL_API = 'CALL_API'; export const JSON_DATA = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { } } ] }<file_sep> ## react-web-worker check example -> https://codesandbox.io/s/react-web-worker-9tiwj <file_sep>import React, { useEffect, useState } from 'react'; import worker from './worker'; import WebWorker from './workerSetup'; import { CALL_API } from './enums'; function App() { let [list, setList] = useState([]); let [value, setValue] = useState(); let ApiWorker = new WebWorker(worker); useEffect( () => { ApiWorker.addEventListener('message', event => { const { data } = event; setList(data); }); }); const onHandleChange = e => { let { value } = e.target; setValue(value); } const onHandleSubmit = e => { e.preventDefault(); console.log('value', value); ApiWorker.postMessage(value); } return ( <div className="App"> <div className={'search-input'}> <p>type me, info, com</p> <form onSubmit={onHandleSubmit}> <input type={'text'} onChange={onHandleChange} /> <input type={'submit'} /> </form> </div> <div> <ul> {list && list.map( (item, idx) => { return ( <li key={idx+item.email}>{item.email}</li> ) })} </ul> </div> </div> ); } export default App;
164ad891ef3a1c5fec67edb5cc2b0732414d45b7
[ "JavaScript", "Markdown" ]
4
JavaScript
davidkern13/react-web-worker
5dfd6a576aa3240c375724e35bfcea49742187ed
263492b2501f0a721d6b1b275e255eef736b0fa3
refs/heads/master
<repo_name>alistairkung/react-tutorial<file_sep>/src/Root.js import React from 'react'; import Counter from './module/Counter'; //use this component as it was the entry point of your dev server class Root extends React.Component { constructor(props) { super(props); this.state = {counters: [2,1,2]}; } increaseBy1=(index)=>{ this.setState({ counters: this.state.counters.map((val,i)=>{ if(i===index){ val = val+1; } return val; }) }); } increaseAll=()=>{ this.setState({ counters: this.state.counters.map((val)=>val + 1) }) } render(){ return( <div> {this.state.counters.map((value, i)=>{ return <Counter key={i} index={i} onIncrease= {this.increaseBy1} value = {value}/> })} <button onClick={this.increaseAll}>increase all</button> </div> ) } } export default Root;
8707f004ce0a476cd468ebdfc665a08e4f227ef0
[ "JavaScript" ]
1
JavaScript
alistairkung/react-tutorial
ff06bf8bd2a593933f9f2b069ccd7bcb7705d7db
329431dad68a2492887c37be89e4b5254fff6f00
refs/heads/main
<repo_name>tblaisot/k8s-image-autoproxy<file_sep>/pkg/mutate/image_proxy.go package mutate import ( "fmt" dockerparser "github.com/novln/docker-parser" dockerparserdocker "github.com/novln/docker-parser/docker" core "k8s.io/api/core/v1" ) func patchImageWithProxy(options Options, image string) (newimage string, err error) { newimage = image parsed, err := dockerparser.Parse(image) if err != nil { return } if dockerparserdocker.DefaultHostname == parsed.Registry() { newimage = fmt.Sprintf("%s/%s", options.proxy, parsed.Name()) } return } func proxyContainer(options Options, container core.Container, pathPrefix string, patches []map[string]string) []map[string]string { if options.enabled { s, _ := patchImageWithProxy(options, container.Image) if s != container.Image { patch := map[string]string{ "op": "replace", "path": fmt.Sprintf("%s/image", pathPrefix), "value": s, } patches = append(patches, patch) } } return patches } func proxyPodSpec(options Options, podSpec core.PodSpec, pathPrefix string, patches []map[string]string) []map[string]string { if options.enabled { for i, c := range podSpec.Containers { patches = proxyContainer(options, c, fmt.Sprintf("%s/containers/%d", pathPrefix, i), patches) } for i, c := range podSpec.InitContainers { patches = proxyContainer(options, c, fmt.Sprintf("%s/initContainers/%d", pathPrefix, i), patches) } } return patches } <file_sep>/scripts/gen-certs.sh #! /bin/bash WEBHOOK_NS=k8s-image-autoproxy WEBHOOK_NAME=k8s-image-autoproxy WEBHOOK_SVC=${WEBHOOK_NAME}.${WEBHOOK_NS}.svc K8S_OUT_CERT_FILE=./deploy/app-certs.yaml K8S_OUT_WEBBOK_FILE=./deploy/webhooks.yaml OUT_CERT="./ssl/${WEBHOOK_NAME}.pem" OUT_KEY="./ssl/${WEBHOOK_NAME}.key" # Create certs for our webhook #set -f #mkcert \ # --cert-file "${OUT_CERT}" \ # --key-file "${OUT_KEY}" \ # "${WEBHOOK_SVC}" #mv "${OUT_CERT}" "${OUT_CERT}.bak" #cat "${OUT_CERT}.bak" "$(mkcert -CAROOT)/rootCA.pem" > "${OUT_CERT}" #rm "${OUT_CERT}.bak" #set +f ./scripts/ssl.sh $WEBHOOK_NAME $WEBHOOK_NAME # Create certs secrets for k8s. rm ${K8S_OUT_CERT_FILE} kubectl -n ${WEBHOOK_NS} create secret generic \ ${WEBHOOK_NAME}-certs \ --from-file=key.pem=${OUT_KEY} \ --from-file=cert.pem=${OUT_CERT}\ --dry-run=client -o yaml > ${K8S_OUT_CERT_FILE} # Set the CABundle on the webhook registration. CA_BUNDLE=$(cat ${OUT_CERT} | base64 -w0) sed "s/CA_BUNDLE/${CA_BUNDLE}/" ./deploy/webhooks.yaml.tpl > ${K8S_OUT_WEBBOK_FILE} # Clean. rm "${OUT_CERT}" && rm "${OUT_KEY}" # Add note of autogenerated file. sed -i '1i# File autogenerated by ./scripts/gen-certs.sh' ${K8S_OUT_CERT_FILE} sed -i '1i# File autogenerated by ./scripts/gen-certs.sh' ${K8S_OUT_WEBBOK_FILE} <file_sep>/pkg/mutate/mutate_test.go package mutate import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" v1beta1 "k8s.io/api/admission/v1beta1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var clientset kubernetes.Interface = fake.NewSimpleClientset( &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "default", Annotations: map[string]string{ AnnotationEnabled: "true", }, }, }, &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "proxied", Annotations: map[string]string{ AnnotationEnabled: "true", AnnotationProxy: "proxy2.io", }, }, }, &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: "disabled", Annotations: map[string]string{ AnnotationEnabled: "false", }, }, }, ) var mutator = imageProxyMutator{config: Config{DefaultProxy: "proxy.io", DefaultEnable: false, Verbose: true}, clientset: clientset} func TestMutatesValidRequest(t *testing.T) { rawJSON := `{ "kind": "AdmissionReview", "apiVersion": "admission.k8s.io/v1beta1", "request": { "uid": "7f0b2891-916f-4ed6-b7cd-27bff1815a8c", "kind": { "group": "", "version": "v1", "kind": "Pod" }, "resource": { "group": "", "version": "v1", "resource": "pods" }, "requestKind": { "group": "", "version": "v1", "kind": "Pod" }, "requestResource": { "group": "", "version": "v1", "resource": "pods" }, "namespace": "default", "operation": "CREATE", "userInfo": { "username": "kubernetes-admin", "groups": [ "system:masters", "system:authenticated" ] }, "object": { "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "c7m", "namespace": "default", "creationTimestamp": null, "labels": { "name": "c7m" }, "annotations": { "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"name\":\"c7m\"},\"name\":\"c7m\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"args\":[\"-c\",\"trap \\\"killall sleep\\\" TERM; trap \\\"kill -9 sleep\\\" KILL; sleep infinity\"],\"command\":[\"/bin/bash\"],\"image\":\"centos:7\",\"name\":\"c7m\"}]}}\n" } }, "spec": { "volumes": [ { "name": "default-token-5z7xl", "secret": { "secretName": "default-token-5z7xl" } } ], "containers": [ { "name": "c7m", "image": "centos:7", "command": [ "/bin/bash" ], "args": [ "-c", "trap \"killall sleep\" TERM; trap \"kill -9 sleep\" KILL; sleep infinity" ], "resources": {}, "volumeMounts": [ { "name": "default-token-5z7xl", "readOnly": true, "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" } ], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File", "imagePullPolicy": "IfNotPresent" } ], "restartPolicy": "Always", "terminationGracePeriodSeconds": 30, "dnsPolicy": "ClusterFirst", "serviceAccountName": "default", "serviceAccount": "default", "securityContext": {}, "schedulerName": "default-scheduler", "tolerations": [ { "key": "node.kubernetes.io/not-ready", "operator": "Exists", "effect": "NoExecute", "tolerationSeconds": 300 }, { "key": "node.kubernetes.io/unreachable", "operator": "Exists", "effect": "NoExecute", "tolerationSeconds": 300 } ], "priority": 0, "enableServiceLinks": true }, "status": {} }, "oldObject": null, "dryRun": false, "options": { "kind": "CreateOptions", "apiVersion": "meta.k8s.io/v1" } } }` response, err := mutator.Mutate([]byte(rawJSON)) if err != nil { t.Errorf("failed to mutate AdmissionRequest %s with error %s", string(response), err) } r := v1beta1.AdmissionReview{} err = json.Unmarshal(response, &r) assert.NoError(t, err, "failed to unmarshal with error %s", err) rr := r.Response assert.Equal(t, `[{"op":"replace","path":"/spec/containers/0/image","value":"proxy.io/library/centos:7"}]`, string(rr.Patch)) assert.Contains(t, rr.AuditAnnotations, "k8s-image-autoproxy") } func TestMutatesNamespaceOverride(t *testing.T) { rawJSON := `{ "kind": "AdmissionReview", "apiVersion": "admission.k8s.io/v1beta1", "request": { "uid": "7f0b2891-916f-4ed6-b7cd-27bff1815a8c", "kind": { "group": "", "version": "v1", "kind": "Pod" }, "resource": { "group": "", "version": "v1", "resource": "pods" }, "requestKind": { "group": "", "version": "v1", "kind": "Pod" }, "requestResource": { "group": "", "version": "v1", "resource": "pods" }, "namespace": "proxied", "operation": "CREATE", "userInfo": { "username": "kubernetes-admin", "groups": [ "system:masters", "system:authenticated" ] }, "object": { "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "c7m", "namespace": "proxied", "creationTimestamp": null, "labels": { "name": "c7m" }, "annotations": { "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"name\":\"c7m\"},\"name\":\"c7m\",\"namespace\":\"proxied\"},\"spec\":{\"containers\":[{\"args\":[\"-c\",\"trap \\\"killall sleep\\\" TERM; trap \\\"kill -9 sleep\\\" KILL; sleep infinity\"],\"command\":[\"/bin/bash\"],\"image\":\"centos:7\",\"name\":\"c7m\"}]}}\n" } }, "spec": { "volumes": [ { "name": "default-token-5z7xl", "secret": { "secretName": "default-token-5z7xl" } } ], "containers": [ { "name": "c7m", "image": "centos:7", "command": [ "/bin/bash" ], "args": [ "-c", "trap \"killall sleep\" TERM; trap \"kill -9 sleep\" KILL; sleep infinity" ], "resources": {}, "volumeMounts": [ { "name": "default-token-<PASSWORD>", "readOnly": true, "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" } ], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File", "imagePullPolicy": "IfNotPresent" } ], "restartPolicy": "Always", "terminationGracePeriodSeconds": 30, "dnsPolicy": "ClusterFirst", "serviceAccountName": "default", "serviceAccount": "default", "securityContext": {}, "schedulerName": "default-scheduler", "tolerations": [ { "key": "node.kubernetes.io/not-ready", "operator": "Exists", "effect": "NoExecute", "tolerationSeconds": 300 }, { "key": "node.kubernetes.io/unreachable", "operator": "Exists", "effect": "NoExecute", "tolerationSeconds": 300 } ], "priority": 0, "enableServiceLinks": true }, "status": {} }, "oldObject": null, "dryRun": false, "options": { "kind": "CreateOptions", "apiVersion": "meta.k8s.io/v1" } } }` response, err := mutator.Mutate([]byte(rawJSON)) if err != nil { t.Errorf("failed to mutate AdmissionRequest %s with error %s", string(response), err) } r := v1beta1.AdmissionReview{} err = json.Unmarshal(response, &r) assert.NoError(t, err, "failed to unmarshal with error %s", err) rr := r.Response assert.Equal(t, `[{"op":"replace","path":"/spec/containers/0/image","value":"proxy2.io/library/centos:7"}]`, string(rr.Patch)) assert.Contains(t, rr.AuditAnnotations, "k8s-image-autoproxy") } func TestMutatesNamespaceDisabled(t *testing.T) { rawJSON := `{ "kind": "AdmissionReview", "apiVersion": "admission.k8s.io/v1beta1", "request": { "uid": "7f0b2891-916f-4ed6-b7cd-27bff1815a8c", "kind": { "group": "", "version": "v1", "kind": "Pod" }, "resource": { "group": "", "version": "v1", "resource": "pods" }, "requestKind": { "group": "", "version": "v1", "kind": "Pod" }, "requestResource": { "group": "", "version": "v1", "resource": "pods" }, "namespace": "disabled", "operation": "CREATE", "userInfo": { "username": "kubernetes-admin", "groups": [ "system:masters", "system:authenticated" ] }, "object": { "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "c7m", "namespace": "disabled", "creationTimestamp": null, "labels": { "name": "c7m" }, "annotations": { "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"name\":\"c7m\"},\"name\":\"c7m\",\"namespace\":\"disabled\"},\"spec\":{\"containers\":[{\"args\":[\"-c\",\"trap \\\"killall sleep\\\" TERM; trap \\\"kill -9 sleep\\\" KILL; sleep infinity\"],\"command\":[\"/bin/bash\"],\"image\":\"centos:7\",\"name\":\"c7m\"}]}}\n" } }, "spec": { "volumes": [ { "name": "default-token-5<PASSWORD>", "secret": { "secretName": "default-token-5z7xl" } } ], "containers": [ { "name": "c7m", "image": "centos:7", "command": [ "/bin/bash" ], "args": [ "-c", "trap \"killall sleep\" TERM; trap \"kill -9 sleep\" KILL; sleep infinity" ], "resources": {}, "volumeMounts": [ { "name": "default-token-5<PASSWORD>", "readOnly": true, "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" } ], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File", "imagePullPolicy": "IfNotPresent" } ], "restartPolicy": "Always", "terminationGracePeriodSeconds": 30, "dnsPolicy": "ClusterFirst", "serviceAccountName": "default", "serviceAccount": "default", "securityContext": {}, "schedulerName": "default-scheduler", "tolerations": [ { "key": "node.kubernetes.io/not-ready", "operator": "Exists", "effect": "NoExecute", "tolerationSeconds": 300 }, { "key": "node.kubernetes.io/unreachable", "operator": "Exists", "effect": "NoExecute", "tolerationSeconds": 300 } ], "priority": 0, "enableServiceLinks": true }, "status": {} }, "oldObject": null, "dryRun": false, "options": { "kind": "CreateOptions", "apiVersion": "meta.k8s.io/v1" } } }` response, err := mutator.Mutate([]byte(rawJSON)) if err != nil { t.Errorf("failed to mutate AdmissionRequest %s with error %s", string(response), err) } r := v1beta1.AdmissionReview{} err = json.Unmarshal(response, &r) assert.NoError(t, err, "failed to unmarshal with error %s", err) rr := r.Response assert.Equal(t, `[]`, string(rr.Patch)) assert.Contains(t, rr.AuditAnnotations, "k8s-image-autoproxy") } func TestErrorsOnInvalidJson(t *testing.T) { rawJSON := `Wut ?` _, err := mutator.Mutate([]byte(rawJSON)) if err == nil { t.Error("did not fail when sending invalid json") } } func TestErrorsOnInvalidPod(t *testing.T) { rawJSON := `{ "request": { "object": 111 } }` _, err := mutator.Mutate([]byte(rawJSON)) if err == nil { t.Error("did not fail when sending invalid pod") } } <file_sep>/pkg/mutate/mutate.go package mutate import ( "context" "encoding/json" "fmt" "log" admissionv1beta1 "k8s.io/api/admission/v1beta1" appsv1 "k8s.io/api/apps/v1" batchv1 "k8s.io/api/batch/v1" batchv1beta1 "k8s.io/api/batch/v1beta1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) const ( AnnotationEnabled = "k8s-image-autoproxy.enabled" AnnotationProxy = "k8s-image-autoproxy.proxy" ) type Config struct { DefaultProxy string DefaultEnable bool Verbose bool } type imageProxyMutator struct { config Config clientset kubernetes.Interface } type ImageProxyMutator interface { Mutate(body []byte) ([]byte, error) } func NewImageProxyMutator(config Config) ImageProxyMutator { log.Println(config) // creates the in-cluster config k8sConfig, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } // creates the clientset clientset, err := kubernetes.NewForConfig(k8sConfig) if err != nil { panic(err.Error()) } return imageProxyMutator{config: config, clientset: clientset} } type Options struct { enabled bool proxy string } func (m imageProxyMutator) GetNamespaceOptions(namespaceName string) (options Options, err error) { if m.config.Verbose { log.Printf("GetNamespaceOptions: %s", namespaceName) } namespace, err := m.clientset.CoreV1().Namespaces().Get(context.TODO(), namespaceName, metav1.GetOptions{}) if err != nil { return } annotationEnabled := m.config.DefaultEnable if val, ok := namespace.GetAnnotations()["k8s-image-autoproxy.enabled"]; ok { annotationEnabled = val != "false" } annotationProxy := m.config.DefaultProxy if val, ok := namespace.GetAnnotations()["k8s-image-autoproxy.proxy"]; ok && val != "" { annotationProxy = val } if m.config.Verbose { log.Printf("Namespace: %s, enabled: %t, proxy: %s\n", namespaceName, annotationEnabled, annotationProxy) // untested section } options = Options{enabled: annotationEnabled, proxy: annotationProxy} return } // Mutate mutates func (m imageProxyMutator) Mutate(body []byte) ([]byte, error) { if m.config.Verbose { log.Printf("recv: %s\n", string(body)) // untested section } // unmarshal request into AdmissionReview struct admReview := admissionv1beta1.AdmissionReview{} if err := json.Unmarshal(body, &admReview); err != nil { return nil, fmt.Errorf("unmarshaling request failed with %s", err) } responseBody := []byte{} ar := admReview.Request resp := admissionv1beta1.AdmissionResponse{} // the actual mutation is done by a string in JSONPatch style, i.e. we don't _actually_ modify the object, but // tell K8S how it should modifiy it p := []map[string]string{} if ar != nil { options, err := m.GetNamespaceOptions(ar.Namespace) if err != nil { return nil, err } switch ar.Kind.Kind { case "Pod": var pod *corev1.Pod if err := json.Unmarshal(ar.Object.Raw, &pod); err != nil { return nil, fmt.Errorf("unable unmarshal Pod json object %v", err) } p = proxyPodSpec(options, pod.Spec, "/spec", p) case "ReplicationController": var replicationController *corev1.ReplicationController if err := json.Unmarshal(ar.Object.Raw, &replicationController); err != nil { return nil, fmt.Errorf("unable unmarshal ReplicationController json object %v", err) } p = proxyPodSpec(options, replicationController.Spec.Template.Spec, "/spec/template/spec", p) case "Deployment": var deployment *appsv1.Deployment if err := json.Unmarshal(ar.Object.Raw, &deployment); err != nil { return nil, fmt.Errorf("unable unmarshal Deployment json object %v", err) } p = proxyPodSpec(options, deployment.Spec.Template.Spec, "/spec/template/spec", p) case "ReplicaSet": var replicaSet *appsv1.ReplicaSet if err := json.Unmarshal(ar.Object.Raw, &replicaSet); err != nil { return nil, fmt.Errorf("unable unmarshal ReplicaSet json object %v", err) } p = proxyPodSpec(options, replicaSet.Spec.Template.Spec, "/spec/template/spec", p) case "DaemonSet": var daemonSet *appsv1.DaemonSet if err := json.Unmarshal(ar.Object.Raw, &daemonSet); err != nil { return nil, fmt.Errorf("unable unmarshal DaemonSet json object %v", err) } p = proxyPodSpec(options, daemonSet.Spec.Template.Spec, "/spec/template/spec", p) case "StatefulSet": var statefulSet *appsv1.StatefulSet if err := json.Unmarshal(ar.Object.Raw, &statefulSet); err != nil { return nil, fmt.Errorf("unable unmarshal StatefulSet json object %v", err) } p = proxyPodSpec(options, statefulSet.Spec.Template.Spec, "/spec/template/spec", p) case "CronJob": var cronJob *batchv1beta1.CronJob if err := json.Unmarshal(ar.Object.Raw, &cronJob); err != nil { return nil, fmt.Errorf("unable unmarshal CronJob json object %v", err) } p = proxyPodSpec(options, cronJob.Spec.JobTemplate.Spec.Template.Spec, "/spec/jobTemplate/spec/template/spec", p) case "Job": var job *batchv1.Job if err := json.Unmarshal(ar.Object.Raw, &job); err != nil { return nil, fmt.Errorf("unable unmarshal Job json object %v", err) } p = proxyPodSpec(options, job.Spec.Template.Spec, "/spec/template/spec", p) default: return nil, fmt.Errorf("object not supported: %s", ar.Kind.Kind) } // set response options resp.Allowed = true resp.UID = ar.UID pT := admissionv1beta1.PatchTypeJSONPatch resp.PatchType = &pT // it's annoying that this needs to be a pointer as you cannot give a pointer to a constant? // add some audit annotations, helpful to know why a object was modified, maybe (?) resp.AuditAnnotations = map[string]string{ "k8s-image-autoproxy": "true", } // parse the []map into JSON resp.Patch, err = json.Marshal(p) if err != nil { return nil, err // untested section } // Success, of course ;) resp.Result = &metav1.Status{ Status: "Success", } admReview.Response = &resp // back into JSON so we can return the finished AdmissionReview w/ Response directly // w/o needing to convert things in the http handler responseBody, err = json.Marshal(admReview) if err != nil { return nil, err // untested section } } if m.config.Verbose { log.Printf("resp: %s\n", string(responseBody)) // untested section } return responseBody, nil } <file_sep>/README.md # k8s-image-autoproxy ## build ``` make build ``` ## test ``` make test ``` ## ssl/tls the `ssl/` dir will contain informations used to generate self signed certificates to deploy ## docker to create a docker image .. ``` make build-image ``` ### images [`tblaisot/k8s-image-autoproxy`](https://cloud.docker.com/repository/docker/tblaisot/k8s-image-autoproxy) ## Running in kind ```bash # spawn a Kind cluster make kind # generate certificates make gen-deploy-certs # build image make build-image # deploy make deploy # make sure it's running ... kubectl get pods -n k8s-image-autoproxy kubectl logs k8s-image-autoproxy-<POD> --follow -n k8s-image-autoproxy # create example pod to see it working kubectl apply -f integration-tests/pod.yaml kubectl get pod c7m -o yaml | grep image: # should be prefixed kubectl delete -f integration-tests/pod.yaml ``` ## kudos - [Writing a very basic kubernetes mutating admission webhook](https://medium.com/ovni/writing-a-very-basic-kubernetes-mutating-admission-webhook-398dbbcb63ec) - [https://github.com/alexleonhardt/k8s-mutate-webhook](https://github.com/alexleonhardt/k8s-mutate-webhook) <file_sep>/cmd/cmd.go package cmd import ( "fmt" "html" "io/ioutil" "log" "net/http" "os" "time" "github.com/spf13/cobra" m "github.com/tblaisot/k8s-image-autoproxy/pkg/mutate" ) var ( proxyByDefault string verbose bool enableByDefault bool mutator m.ImageProxyMutator ) func handleRoot(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello %q", html.EscapeString(r.URL.Path)) } func handleMutate(w http.ResponseWriter, r *http.Request) { log.Println("handle mutate ...") // read the body / request body, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { sendError(err, w) return } // mutate the request mutated, err := mutator.Mutate(body) if err != nil { sendError(err, w) return } // and write it back w.WriteHeader(http.StatusOK) _, err = w.Write(mutated) if err != nil { return } } func sendError(err error, w http.ResponseWriter) { log.Println(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "%s", err) } // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "k8s-image-autoproxy", Short: "Alter image name to replace docker.io to another repository", Long: `This tool alter container specs to prefix images from docker.io with a custom proxyByDefault url Usage: k8s-image-autoproxy --proxyByDefault proxyByDefault.io`, // Uncomment the following line if your bare application // has an action associated with it: Run: func(cmd *cobra.Command, args []string) { config := m.Config{DefaultProxy: proxyByDefault, Verbose: verbose, DefaultEnable: enableByDefault} mutator = m.NewImageProxyMutator(config) log.Println("Starting server ...") log.Println("Configuration") log.Printf("\tDefaultEnable: %t\n", config.DefaultEnable) log.Printf("\tDefaultProxy: %s\n", config.DefaultProxy) log.Printf("\tVerbose: %t\n", config.Verbose) mux := http.NewServeMux() mux.HandleFunc("/", handleRoot) mux.HandleFunc("/mutate", handleMutate) s := &http.Server{ Addr: ":8443", Handler: mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, // 1048576 } log.Fatal(s.ListenAndServeTLS("/etc/webhook/certs/cert.pem", "/etc/webhook/certs/key.pem")) }, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { log.Fatalln(err) os.Exit(1) } } func init() { rootCmd.Flags().StringVarP(&proxyByDefault, "proxyByDefault", "p", "", "Proxy hostname to prefix all docker.io images.") rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Print debug logs.") rootCmd.Flags().BoolVarP(&enableByDefault, "enableByDefault", "e", false, "Enable in all namespace by default.") _ = rootCmd.MarkFlagRequired("proxyByDefault") } <file_sep>/go.mod module github.com/tblaisot/k8s-image-autoproxy go 1.16 require ( github.com/novln/docker-parser v1.0.0 github.com/spf13/cobra v1.1.1 github.com/stretchr/testify v1.7.0 golang.org/x/tools v0.1.0 // indirect k8s.io/api v0.21.0 k8s.io/apimachinery v0.21.0 k8s.io/client-go v0.21.0 )
6e30330ff161daa0d13055beb44f44ed4833f414
[ "Markdown", "Go Module", "Go", "Shell" ]
7
Go
tblaisot/k8s-image-autoproxy
21de565780d9b2d2fe9048785b3e9940818afb3b
d068ec985c26694560af86d409d253f3fdb07938
refs/heads/master
<file_sep>require 'rspec' require './skynet_chasm' describe 'moto-terminator' do it 'knows when it fell into the gap' do expect(find_solution(0, 5, 5, [], 0, 2, false)).to be_nil end it 'knows when to jump' do solution = find_solution(1, 1, 5, [], 0, 2, false) expect(solution).to eq(['JUMP', 'SLOW', 'SLOW']) end it 'can speed up and jump' do solution = find_solution(3, 1, 5, [], 0, 1, false) expect(solution).to eq(['SPEED', 'JUMP', 'SLOW', 'SLOW']) end it 'can figure out to wait first' do solution = find_solution(4, 1, 5, [], 0, 1, false) expect(solution).to eq(['WAIT', 'SPEED', 'JUMP', 'SLOW', 'SLOW']) end it 'knows when to wait more than once' do solution = find_solution(5, 1, 2, [], 0, 2, false) expect(solution).to eq(['WAIT', 'WAIT', 'JUMP', 'SLOW', 'SLOW']) end it 'can do the real thing #1' do solution = find_solution(16, 2, 16, [], 0, 0, false) expected = ['SPEED'] * 5 + ['JUMP'] + ['SLOW'] * 5 expect(solution).to eq(expected) end it 'can do the real thing #2' do solution = find_solution(11, 3, 7, [], 0, 0, false) expected = ['SPEED'] * 4 + ['JUMP'] + ['SLOW'] * 4 expect(solution).to eq(expected) end end <file_sep>STDOUT.sync = true # DO NOT REMOVE # Don't let the machines win. You are humanity's last hope... require 'ostruct' DEBUG = false $start = Time.now def eputs(msg) return unless DEBUG STDERR.puts(msg) end def elap return #unless DEBUG eputs Time.now - $start end elap $width = gets.to_i # the number of cells on the X axis $height = gets.to_i # the number of cells on the Y axis $grid = [] $height.times do |row| $line = gets.chomp # width characters, each either 0 or . $grid << $line.split('') end eputs "grid is #{$grid}" def get_right_coords(x, y) eputs "get_right_coords(#{x}, #{y})" x += 1 while x < $width eputs "grid[x] is #{$grid[x]}" return "#{x} #{y}" if $grid[y][x] == '0' x += 1 end "-1 -1" end def get_bottom_coords(x, y) y += 1 while y < $height return "#{x} #{y}" if $grid[y][x] == '0' y += 1 end "-1 -1" end elap root_nodes = [] $grid.each_with_index do |row, y| root_nodes[y] = [] row.each_with_index do |char, x| next if char == '.' right_coords = get_right_coords(x, y) bottom_coords = get_bottom_coords(x, y) node = OpenStruct.new(coords: "#{x} #{y}", right: right_coords, bottom: bottom_coords) root_nodes[y] << node end end elap # Write an action using puts # To debug: STDERR.puts "Debug messages..." root_nodes.each do |nodes| elap nodes.each do |node| puts "#{node.coords} #{node.right} #{node.bottom}" #STDERR.puts "totall just printed something" end end #puts "0 0 1 0 0 1" # Three coordinates: a node, its right neighbor, its bottom neighbor <file_sep>require 'rspec' require './mars_lander_1' describe Lander do let(:lander) { Lander.new } it 'find the landing zone correctly' do points = [[0, 10], [100, 20], [500, 50], [1100, 40], [2500, 40], [3200, 80]] end end <file_sep>require "rspec" require "pry" require "./bender" describe Bender do let(:n) { "NORTH" } let(:s) { "SOUTH" } let(:e) { "EAST" } let(:w) { "WEST" } context 'simple movement' do let(:map) do ["#####".split(''), "#@ #".split(''), "# #".split(''), "#$ #".split(''), "#####".split(''),] end it "moves toward the goal" do bender = Bender.new(1, 1, 1, 3, map) expect(bender.go).to eq([s, s]) end end describe 'changing directions' do let(:map) do ["#####".split(''), "#@ #".split(''), "# #".split(''), "# $#".split(''), "#####".split(''),] end it "moves toward the goal" do bender = Bender.new(1, 1, 3, 3, map) expect(bender.go).to eq([s, s, e, e]) end end describe "#can_move?" do let(:map) do ["#####".split(''), "# #".split(''), "#@ #".split(''), "# #".split(''), "#####".split(''),] end context 'when on the left wall' do let(:bender) { Bender.new(1, 2, 0, 0, map) } it "can't move west" do expect(bender.can_move?(w)).to eq(false) end it "can move north, south, or east" do expect(bender.can_move?(n)).to eq(true) expect(bender.can_move?(s)).to eq(true) expect(bender.can_move?(e)).to eq(true) end end end describe "obstacles" do let(:map) do ["########".split(''), "# @ #".split(''), "# X#".split(''), "# XXX #".split(''), "# XX #".split(''), "# XX #".split(''), "# $#".split(''), "########".split(''),] end let(:bender) { described_class.new(2, 1, 6, 6, map) } it 'can change direction when encountering obstacles' do expect(bender.go).to eq([s, e, e, e, s, e, s, s, s]) end end describe "path modifiers" do let(:map) do ["#####".split(''), "#@$W#".split(''), "#E N#".split(''), "# #".split(''), "#####".split(''),] end let(:bender) { Bender.new(1, 1, 2, 1, map) } it "changes path based on lettered tiles" do expect(bender.go).to eq([s, e, e, n, w]) end end describe "breaker mode" do let(:map) do ["#####".split(''), "#@ #".split(''), "#B #".split(''), "#XXX#".split(''), "# $#".split(''), "#####".split(''),] end let(:bender) { Bender.new(1, 1, 3, 4, map) } it "breaks through barriers when in breaker mode" do expect(bender.go).to eq([s, s, s, e, e]) expect(bender.map[1][3]).to eq(' ') end context '2 breakers' do let(:map) do ["#####".split(''), "#@ #".split(''), "#B #".split(''), "#B #".split(''), "#$ #".split(''), "#####".split(''),] end let(:bender) { Bender.new(1, 1, 1, 4, map) } it 'flips back if bender hits another one' do expect(bender.go).to eq([s, s, s]) expect(bender.breaker_mode).to eq(false) end end end describe 'inverter' do let(:map) do ["#####".split(''), "#@ #".split(''), "#I #".split(''), "#$ #".split(''), "#####".split(''),] end let(:bender) { Bender.new(1, 1, 1, 3, map) } it 'flips the priorities of the directions' do expect(bender.dirs).to eq([s, e, n, w]) expect(bender.go).to eq([s, s]) expect(bender.dirs).to eq([w, n, e, s]) end end describe 'teleporter' do let(:map) do ["#####".split(''), "#@ T#".split(''), "#T #".split(''), "# $#".split(''), "#####".split(''),] end let(:bender) { Bender.new(1, 1, 3, 3, map) } it 'teleports to the other pad when encountered' do expect(bender.go).to eq([s, s, s]) end end describe 'broken walls?' do let(:map) do ["##########".split(''), "# #".split(''), "# @ #".split(''), "# B #".split(''), "# S W #".split(''), "# XXX #".split(''), "# B N #".split(''), "# XXXXXXX#".split(''), "# $#".split(''), "##########".split(''),] end let(:bender) { Bender.new(3, 2, 8, 8, map) } it 'handles this tricky case' do # SOUTH SOUTH SOUTH SOUTH EAST EAST EAST EAST NORTH NORTH WEST WEST WEST WEST SOUTH SOUTH SOUTH SOUTH EAST EAST EAST EAST EAST expect(bender.go).to eq([s, s, s, s, e, e, e, e, n, n, w, w, w, w, s, s, s, s, e, e, e, e, e]) end end end <file_sep>### # Bender class goes here ### $L, $C = gets.split(" ").collect {|x| x.to_i} $map = [] $x, $y, $sx, $sy = -1, -1, -1, -1 $L.times do |index| $row = gets.chomp $map << $row if $row.include?('@') $x = $row.index('@') $y = index end if $row.include?('$') $sx = $row.index('$') $sy = index end end # Write an action using puts # To debug: STDERR.puts "Debug messages..." bender = Bender.new($x, $y, $sx, $sy, $map) bender.eputs $map bender.go.each do |step| puts step end <file_sep>STDOUT.sync=true $nf,$w,$nr,$xf,$xp,$tc,$nae,$ne=gets.split(" ").collect{|x|x.to_i} $es=[] $ne.times do $ef,$ep=gets.split(" ").collect{|x|x.to_i} $es[$ef]=$ep end def l(pos) pos==0||pos==$w-1 end def b(p,d,f) if f==$xf tp=$xp elsif $es[f] tp=$es[f] else return false end (d=='LEFT')?tp>p :tp<p end loop do f,p,d=gets.split(" ") (l(p.to_i)||b(p.to_i,d,f.to_i))?puts("BLOCK"):puts("WAIT") end <file_sep>require 'ostruct' # $R = gets.to_i # the length of the road before the gap. # $G = gets.to_i # the length of the gap. # $L = gets.to_i # the length of the landing platform. def find_solution(r, g, l, solution, loc, speed, jumped) # puts "#{r} #{g}, #{l}, #{solution}, #{loc}, #{speed}, #{jumped} total: #{r+g+l}" return nil if fell_into_gap(r - loc - 1, jumped) || fell_off_platform(loc, r + g + l) return solution if jumped && speed == 0 # JUMP if !jumped && jumpable?(r - loc - 1, g, loc, speed) # puts "trying to jump..." prospective_solution = find_solution(r, g, l, solution + ['JUMP'], loc + speed, speed, true) return prospective_solution if prospective_solution end if jumped # SLOW new_speed = speed - 1 prospective_solution = find_solution(r, g, l, solution + ['SLOW'], loc + new_speed, new_speed, jumped) return prospective_solution if prospective_solution end # SPEED new_speed = speed + 1 prospective_solution = find_solution(r, g, l, solution + ['SPEED'], loc + new_speed, new_speed, jumped) return prospective_solution if prospective_solution # WAIT if speed != 0 prospective_solution = find_solution(r, g, l, solution + ['WAIT'], loc + speed, speed, jumped) return prospective_solution if prospective_solution end # SLOW if speed > 1 new_speed = speed - 1 prospective_solution = find_solution(r, g, l, solution + ['SLOW'], loc + new_speed, new_speed, jumped) return prospective_solution if prospective_solution end nil end def jumpable?(dist_to_gap, g, loc, speed) speed > dist_to_gap + g end def fell_into_gap(dist_to_gap, jumped) dist_to_gap < 0 && !jumped end def fell_off_platform(loc, total) loc >= total end <file_sep>class Bender attr_accessor :bx, :by, :startx, :starty, :goalx, :goaly, :map, :map_history, :north, :south, :east, :west, :dirs, :path, :current_dir, :breaker_mode def initialize(bx, by, goalx, goaly, map) @bx, @by = bx, by @startx, @starty = bx, by @goalx, @goaly = goalx, goaly @map = map @map_history = Array.new(map.size) { Array.new(map[0].size, 0) } @north = "NORTH" @south = "SOUTH" @east = "EAST" @west = "WEST" @path = [] @current_dir = south @breaker_mode = false end def go while bx != goalx || by != goaly moved = false if map_history[by][bx] > 100 eputs "already been to #{bx}, #{by} #{map_history[by][bx]} times" puts "LOOP" return [] end map_history[by][bx] += 1 ([current_dir] + dirs).each do |dir| if can_move?(dir) move(dir) moved = true break end end next if moved raise Exception, "Can't go anywhere" end path end def can_move?(dir) newx, newy = get_new_loc(dir) return false if boundary?(newx, newy) if obstacle?(newx, newy) if breaker_mode map[newy][newx] = ' ' return true end return false end # eputs "can move to #{newx}, #{newy}" true end def get_new_loc(dir) case dir when south return bx, by + 1 when east return bx + 1, by when north return bx, by - 1 when west return bx - 1, by end end def get_new_dir(x, y, dir) dir_map = { 'N' => north, 'S' => south, 'E' => east, 'W' => west } if dir_map.keys.include? map[y][x] dir_map[map[y][x]] else dir end end def get_other_teleport_loc(x, y) map.size.times do |row| map[0].size.times do |col| next if col == x && row == y return col, row if teleporter?(col, row) end end raise Exception, "No other teleporter found than #{x}, #{y}" end def dirs @dirs ||= [south, east, north, west] end def move(dir) # eputs "moving #{dir}" @bx, @by = get_new_loc(dir) @current_dir = get_new_dir(bx, by, dir) switch_breaker if breaker?(bx, by) flip_dirs if inverter?(bx, by) if teleporter?(bx, by) @bx, @by = get_other_teleport_loc(bx, by) end @path << dir end def switch_breaker @breaker_mode = !breaker_mode end def flip_dirs dirs.reverse! end def boundary?(x, y) map[y][x] == '#' end def obstacle?(x, y) map[y][x] == 'X' end def breaker?(x, y) map[y][x] == 'B' end def inverter?(x, y) map[y][x] == 'I' end def teleporter?(x, y) map[y][x] == 'T' end def eputs(msg) STDERR.puts(msg) end end <file_sep>class Lander def initialize(opts) @x = opts[:x] @y = opts[:y] @vx = opts[:vx] @vy = opts[:vy] @rot = opts[:rot] @thrust = opts[:thrust] @vx_max = 20 @vy_max = 40 end def instruction if over_landing_site new_rot = find_new_rot else # thrust to get over landing site new_rot = (x < @landing_xmin) ? -20 : 20 end new_thrust = find_new_thrust "#{new_rot} #{new_thrust}" end def over_landing_site x > landing_xmin - 500 && x < landing_xmax + 500 end def find_new_rot if y_dist_to_landing_site < 1000 && vx < vx_max 0 else (vx > 0) ? 30 : -30 end end def find_new_thrust if y_dist_to_landing_site < 750 || vy.abs > vy_max 4 else 3 end end def y_dist_to_landing_site y - landing_y end def find_landing_zone(points) prev_x = 0 prev_y = -1 flat_dist = 0 points.each do |x, y| #STDERR.puts "looking at #{x},#{y}" if y == prev_y flat_dist += x - prev_x if flat_dist >= 1000 @landing_y = prev_y @landing_xmax = x @landing_xmin = x - flat_dist return true end else prev_x = x prev_y = y flat_dist = 0 end end nil end attr_reader :x, :y, :vx, :vy, :rot, :thrust, :landing_y, :landing_xmin, :landing_xmax, :vx_max, :vy_max end
04e77270e6b6c4c1f1628e26291fda71c9f7429d
[ "Ruby" ]
9
Ruby
mikenichols/codingame
972c1c1ff5a006a56f53b47d5b8cb6bade057f1f
8e4fde87f7ff9c17b92e9beed7c1a1c3c0cf3ae2
refs/heads/main
<repo_name>bas001/intellij-pact-plugin<file_sep>/settings.gradle.kts rootProject.name = "intellij-pact-plugin" <file_sep>/src/main/kotlin/com/github/bas001/intellijpactplugin/services/MyApplicationService.kt package com.github.bas001.intellijpactplugin.services import com.github.bas001.intellijpactplugin.MyBundle class MyApplicationService { init { println(MyBundle.message("applicationService")) } }
90267a0183dfa089ec620abb02ae1d79740a750d
[ "Kotlin" ]
2
Kotlin
bas001/intellij-pact-plugin
b6f8d9e97ce06aae3fc53215ed54116685d73b15
18bf17471cc672408ff88e2aa37356911719b564
refs/heads/master
<repo_name>lczalh/learn<file_sep>/model/src/main/java/com/cz/model/code/CodeModel.java package com.cz.model.code; public final class CodeModel { /*成功*/ public final static String SUCCESS = "0000"; /*文件大小超出限制*/ public final static String FILESIZEEXCEEDEDLIMIT = "0001"; } <file_sep>/model/src/main/java/com/cz/model/message/MessageModel.java package com.cz.model.message; public final class MessageModel { /*文件大小超出限制*/ public final static String FILESIZEEXCEEDEDLIMIT = "上传文件大小超出限制!"; }
387110c911c43dd2ea03a1df320f161974d1f5c3
[ "Java" ]
2
Java
lczalh/learn
347d1a65d0f906c243b5cf1caa73ccc471324197
ea9c960d97a072a849a2b86490e2e3f09d03494e
refs/heads/master
<repo_name>MaximeBonnet27/DiamondSquareMap<file_sep>/DiamondSquareMap/src/com/github/maximebonnet27/Biomes.java package com.github.maximebonnet27; public enum Biomes { OCEAN, DEEP_OCEAN, SUBTROPICAL_DESERT, TEMPERATE_DESERT, GRASSLAND, TROPICAL_SEASONAL_FOREST, TROPICAL_RAIN_FOREST, TEMPERATE_RAIN_FOREST, TEMPERATE_DECIDUOUS_FOREST, TAIGA, SHRUBLAND, SCORCHED, BARE, TUNDRA, SNOW }<file_sep>/DiamondSquareMap/src/com/github/maximebonnet27/Terrain.java package com.github.maximebonnet27; public class Terrain { Biomes biome; double moisture; double height; public Terrain(Biomes biome, double moisture, double height) { super(); this.biome = biome; this.moisture = moisture; this.height = height; } }<file_sep>/DiamondSquareMap/readme.md # README Java implementation of the Diamond Square Algorithm (see [wiki](http://en.wikipedia.org/wiki/Diamond-square_algorithm)). The program uses the lwjgl to display the resulting map. # RESULTS Some screenshots : ![Screen1](screenshots/screen_1.png)
1f4cc645b4f17ee14dba1c2389ca00ce2d7689d2
[ "Markdown", "Java" ]
3
Java
MaximeBonnet27/DiamondSquareMap
3ee061c5e93182f2349a6b240393be7b97577170
8f483890f3926da2af1c4c4f430d53b3fa27e00c
refs/heads/master
<file_sep>const player = { x:1, y:1, path: [{x:1, y:1}] }; function placeHorizontal(thePlayer, command) { if(thePlayer.y >= 0 && thePlayer.y < 2){ if(command === "l"){ thePlayer.y--; } else { thePlayer.y++; } console.log(`Player has position: x=${thePlayer.x}, y=${thePlayer.y}`); let newPosition = {x: thePlayer.x, y: thePlayer.y}; thePlayer.path.push(newPosition); } else { console.log("You cant place player outside of the board!"); } } //for (let i=0; i< player.path.length; i++){ //console.log(`Path ${i} ==> x=${player.path[i].x}, y=${player.path[i].y}`) //} function placeVertical (thePlayer, command) { if(thePlayer.x >= 0 && thePlayer.x < 2){ if (command === "u"){ thePlayer.x--; } else { thePlayer.x++; } console.log(`The player has position: x=${thePlayer.x}, y=${thePlayer.y}`); let newPosition = {x: thePlayer.x, y: thePlayer.y}; thePlayer.path.push(newPosition); } else { console.log("Youu cant place player outside of the board!") } } function command(thePlayer, orders){ for (let i = 0; i< orders.length; i++){ let order = orders[i]; switch(order){ case "l": placeHorizontal(thePlayer, order); break; case "r": placeHorizontal(thePlayer, order); break; case "u": placeVertical(thePlayer, order); break; case "d": placeVertical(thePlayer, order); break; } } console.log(thePlayer.path); } command(player, "lurrddu"); <file_sep>let marsRover = { direction: "N", x : 0, y : 0, travelLog: [{x:0, y:0}] } function turnLeft(rover){ switch (rover.direction) { case "N": rover.direction = "W"; break; case "W": rover.direction = "S"; break; case "S": rover.direction = "E"; break; case "E": rover.direction = "N"; break; } console.log("turnLeft was called!"); } function turnRight(rover){ switch (rover.direction) { case "N": rover.direction = "E"; break; case "E": rover.direction = "S"; break; case "S": rover.direction = "W"; break; case "W": rover.direction = "N"; break; } console.log("turnRight was called!"); } function moveForward(rover){ if (rover.x >= 0 && rover.y >= 0 && rover.x < 10 && rover.y < 10){ switch(rover.direction) { case "N": marsRover.y++; break; case "E": marsRover.x++; break; case "S": marsRover.y--; break; case "W": marsRover.x--; break; } } else { console.log("You cant place player outside of the board!!!!!"); } console.log("moveForward was called"); console.log(`Rover has position: x=${rover.x}, y=${rover.y}`); let newPosition = {x: rover.x, y: rover.y}; marsRover.travelLog.push(newPosition); } function moveBackward(rover){ if (rover.x >= 0 && rover.y >= 0 && rover.x < 10 && rover.y < 10){ switch(rover.direction) { case "N": marsRover.y--; break; case "E": marsRover.x--; break; case "S": marsRover.y++; break; case "W": marsRover.x++; break; } } else { console.log("You cant place player outside of the board!!!!!"); } console.log("moveBackward was called"); console.log(`Rover has position: x=${rover.x}, y=${rover.y}`); let newPosition = {x: rover.x, y: rover.y}; marsRover.travelLog.push(newPosition); } function command(marsRover, orders){ for (let i = 0; i< orders.length; i++){ let order = orders[i]; switch(order){ case "l": turnLeft(marsRover, order); break; case "r": turnRight(marsRover, order); break; case "f": moveForward(marsRover, order); break; default: console.log("invalid command"); } } console.log(marsRover.travelLog); } <file_sep> let property = { owner: { firstName: "John", lastName: "Doe", age: 44 }, isForSale: true, sqrm: 120, address: { street: "Happy St", number: 123, city: "Miami", state: "FL", country: "US" }, amenities: ["pool", "tennis court", "private parking", "yard"] } function checkProperty(someProperty) { if (someProperty.isForSale === true) { console.log(`The owner, ${someProperty.owner.firstName} ${someProperty.owner.lastName} put the home for sale! The property has ${someProperty.amenities.length} amenities...`); } else { console.log(`The home in ${someProperty.address.street} ${someProperty.address.number} is not for sale`); } } property.isForSale = false; checkProperty(property); /*The output: if the property isForSale equals to true, the expected output to the console should be: The owner, <NAME> put the home for sale! The property has 4 amenities.. In the other case, we should see the following: The home in Happy St no. 123 is not for sale. */ //11-FUNCTIONS!!! Define a function getCredentials() that will receive the following object as argument and print the following result: let user = { username: "ironhacker", password: "<PASSWORD>" } let user2 = { username: "ironhacsdsker", password: "<PASSWORD>" } function getCredentials(anyUser) { console.log(`Username is: ${anyUser.username} and the password is: ${anyUser.password}`); } getCredentials(user); //al pasar un argumento como anyUser, se puede //poner cualquiera // => expected output: // Username is: ironhacker and the password is: <PASSWORD>. //10-FUNCTIONS!!! const arrAnimalites = ["perrite", "gatite", true, 47, 63, false, {name: "meme"}] arrAnimalites.forEach( elem => { let theType = typeof elem; console.log(`The variable ${elem} is type of ${theType}.`)} ); //9- FUNCTIONS!!! Define a function that will: count from 1 to 100, on numbers divisible with 4 print “Hey”, on numbers divisible with 6 print “There”, on numbers divisible with both 4 and 6 print “Ironhack”, skip numbers divisible with 7, on the number that represents your age add ! (ex. 34!). function fizzBuzz() { for (let i = 0; i <= 100; i++) { if (i%4 === 0){ console.log("Hey!"); } if (i%6 === 0) { console.log("There"); } if (i%4 === 0 && i%6 === 0) { console.log("Ironhack"); } if (i%7 === 0){ continue; } if (i === 24){ console.log(i + "!"); } } } fizzBuzz(); //8- FUNCTIONS!! let arr = []; function stringToLetters(letter) { for (let i = 0; i < letter.length; i++) { arr.push(letter[i]); } console.log(arr); } stringToLetters("hello"); */ //7- FUNCTIONSS!!! Define a function that will receive an array as an argument and calculate a sum of all its elements. Example, if we pass the following array to that function: const prices = [5, 7.99, 9.99, 0.99, 21], it should return 44.97 as output. How would you concatenate $ sign in front of the sum? const prices = [5, 7.99, 9.99, 0.99, 21]; let sum = 0; function sumOfPrices(prices) { for (let i = 0; i<prices.length; i++) { sum += prices[i]; } console.log(`$ ${sum}`) } sumOfPrices(prices); //6- FUNCTIONSS!!! let favCities = ["Amsterdam", "Barcelona", "Berlin", "Lisbon", "Madrid", "Mexico City", "Miami", "Paris", "Sao Paulo"]; function printEvens(favCities) { for (let i=0; i<favCities.length; i++){ if((i%2) === 0) { console.log(favCities[i]); } } } printEvens(favCities); //5- FUNCTIONSS!!! //let favCities = ["Rio de Janeiro", "Buenos Aires", //"Paris", "Ibiza", "Barcelona"]; function printFavCities (favCities) { for (let i=0; i<favCities.length; i++){ console.log(favCities[i]); } } printFavCities(favCities); ---------- let favFood = ["Pasta", "Beyond Burguer", "Quesito Vegano", "Banana Vegan Pancakes", "Vermouth"]; function printFavFood (favFood) { for (let i=0; i<favFood.length; i++){ console.log(favFood[i]); } } printFavFood(favFood); //- FUNCTIONSS!!! function printArrElements(ironCities) { for (let i=0; i<ironCities.length; i++){ console.log(ironCities[i]); } } printArrElements(["Amsterdam", "Barcelona", "Berlin", "Lisbon", "Madrid", "Mexico City", "Miami", "Paris", "Sao Paulo"]); */ //- FUNCTIONSS!!! Define a function printNumbers() that receives one argument and prints the numbers from 0 to whatever number we pass to it as an argument function printNumbers(number) { for(let i = 0; i<=number; i++) { console.log(i); } } printNumbers(16); //- FUNCTIONSS!!! Define a function printToTwenty() that will print the numbers from 0 to 20 to the console (don’t forget we have to invoke/call the function to see it working ) function printToTwenty() { for (let i = 0; i <= 20; i++){ console.log(i); } } printToTwenty(); //1- FUNCTIONSS!!! function welcome(name) { console.log(`Hello ${name}`); } welcome("Sofia");<file_sep>//5-OBJECTS Y ARRAYSS let basic = { language: "JavaScript", frameworks: [ { end: "back", list: [ { name: "ExpressJS", released: 2010 }, { name: "MeteorJS", released: 2012 } ] }, { end: "front", list: [ { name: "ReactJS", released: 2013 }, { name: "VueJS", released: 2014 } ] } ] }; console.log(basic.frameworks[0].list[0].name); // => ExpressJS console.log("In Ironhack, I'll learn " + basic.frameworks[0].list[0].name + " and " + basic.frameworks[1].list[0].name ); // => In Ironhack, I'll learn ExpressJS and ReactJS. //4- OBJECTS Y ARRAYSS //Given a 2D array, print the following: const ironCampuses = [ ["Mexico City", "Miami", "Sao Paulo"], ["Amsterdam", "Barcelona", "Berlin", "Lisbon", "Madrid", "Paris"] ]; console.log(ironCampuses[0][1]); // => Miami console.log(ironCampuses[1][0]); // => Amsterdam console.log(ironCampuses[1][5]); // => Paris //3- OBJECTS Y ARRAYSS //Given the object with nested objects in it, print: let student = { firstName: "Ana", lastName: "Blair", course: { name: "Web Development", type: "part-time" }, attendedIn: "Madrid", address: { street: "Happy Street", number: 123, city: "Barcelona", zip: 08015, country: "Spain" } }; console.log(student.course.name); // => Web Development console.log(student.address.street); // => Happy Street console.log(student.firstName + " moved from " + student.address.city + " to " + student.attendedIn + " to take " + student.course.type + " " + student.course.name + " course."); // => Ana moved from Barcelona to Madrid to take part-time Web Development course. //2- OBJECTS Y ARRAYSS /*Given the array, print: your course type (full-time or part-time) the most familiar topic the least familiar topic*/ let course = { name: "Web Development", type: ["full-time", "part-time"], topics: ["HTML/CSS & Responsive Design", "JavaScript", "MongoDB", "Node", "Express", "React"] }; console.log(course.type[0]); console.log(course.topics[1]); console.log(course.topics[2]); //1- OBJECTS Y ARRAYS!! //Using the given array of objects: //display price of iPhone, //display both phones’ names, //add a new phone at the beginning of the array, //remove the last element of the array let products = [ { name: "iPhone", price: 799.99 }, { name: "Samsung Galaxy S10", price: 900.00 } ] let newProduct = { name: "Xiaomi", price: 560 }; products.unshift(newProduct); products.pop(products[0]); console.log(products); console.log(products[0].price); console.log(products[0].name); console.log(products[1].name); //2-OBJECTS //Find the value of the price property and if it //is greater than 100, discount it by 10%. //If that’s not the case, discount it by 7%. //Update the object with : //the new property - discount and the //corresponding value (7% or 10%) and //the new price. let product = { name: "headphones", price: 100 }; product.discount = ""; if (product.price > 100){ product.discount = "10%" ; product.updatedPrice = product.price - (product.price * 0.1); } else if (product.price <= 100) { product.discount = "7%"; product.updatedPrice = product.price - (product.price * 0.07); } console.log("Updated product:", product); //--------------------------------------- //1- OBJECTS! SEGUNDA PARTE let produc = { name: "headphones", price: 77.7, //discount: "7%" }; for (let key in produc) { if (key === "discount") { console.log("Already discounted by ", produc.discount); } else if (produc.price > 100) { produc.discount = "10%"; produc.price = produc.price - (produc.price * 0.1); } else if (produc.price <= 100){ produc.discount = "7%"; produc.price = produc.price - (produc.price * 0.07); } console.log(produc); } //1- OBJECTSlet student = { name: "Max", age: 27 } console.log(student.name); //4- ARRAYS REVISAR!!!!!!!!!! //Given array of numbers, calculate the sum: // start value for the sum const prices = [10.99, 44.56, 112.79, 3, 5]; let sum = 0; for (let i = 0; i < prices.length; i++){ sum += prices[i]; } console.log(sum.toFixed()); //3- ARRAYS (check how can i make it with for o forEach) /*Check if the word appears in given array and print out if it does or doesn’t:*/ let word = "miami"; let arr = ["bcn", "mia", "sao", "mex", "par", "miami", "ams", "ber", "paris", "lis", "mad"]; if (arr.includes(word)) { console.log(word); } else { console.log("does not include") } //2- ARRAYS /*Create an array with 6 of your favorite foods. With the loop of your choice, iterate through the array, but only print out the foods with an even index.*/ const favoriteFoods = ["soup", "fajitas", "pastel de papa", "arrocito de milton", "guiso de lentejas de Milton", "melanzzane parmigiana"]; for (let i = 0; i < favoriteFoods.length; i++){ if (i % 2 === 0){ console.log(favoriteFoods[i]); } } //1- ARRAYS const animalArray = ["dog", "cat", "fish"]; console.log(`Before: ${animalArray}`); animalArray.push("cow"); console.log(`After: ${animalArray}`); */
57c0d084447a82d1d986dfdb2158dc6cb284b0ad
[ "JavaScript" ]
4
JavaScript
yolaresofia/javascript-practice
6e7b4a49fc21e4ca18bb786399e3e93cc18ab0f9
1252d02f1872ac1771148789883f3bcccbf05cd5